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
import Primes answer = last $ takeWhile (<1000000) $ scanl1 (*) primes
arekfu/project_euler
p0069/p0069.hs
mit
72
0
8
13
31
17
14
2
1
module P024Spec where import qualified P024 as P import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "solveBasic" $ do it "与えられた数値でできるN番目の順列 - 1" $ P.solveBasic [0] 1 `shouldBe` 0 it "与えられた数値でできるN番目の順列 - 2" $ map (P.solveBasic [1, 2]) [1..2] `shouldBe` [12, 21] it "与えられた数値でできるN番目の順列 - 3" $ map (P.solveBasic [0, 1, 2]) [1..6] `shouldBe` [12, 21, 102, 120, 201, 210] describe "permutations" $ do it "空リストなら空リストのみ" $ P.permutations ([]::[Int]) `shouldBe` ([[]]::[[Int]]) it "順列 - 1" $ P.permutations [1::Int] `shouldBe` [[1]] it "順列 - 2" $ P.permutations "ab" `shouldBe` ["ab", "ba"] it "順列 - 3" $ P.permutations [0::Int, 1, 2] `shouldBe` [[0,1,2], [0,2,1], [1,0,2], [1,2,0], [2,0,1], [2,1,0]] describe "solve1" $ do it "与えられた数値でできるN番目の順列 - 1" $ P.solve1 [0] 1 `shouldBe` 0 it "与えられた数値でできるN番目の順列 - 2" $ map (P.solve1 [1, 2]) [1..2] `shouldBe` [12, 21] it "与えられた数値でできるN番目の順列 - 3" $ map (P.solve1 [0, 1, 2]) [1..6] `shouldBe` [12, 21, 102, 120, 201, 210] describe "solve2" $ do it "与えられた数値でできるN番目の順列 - 1" $ P.solve2 [0] 1 `shouldBe` 0 it "与えられた数値でできるN番目の順列 - 2" $ map (P.solve2 [1, 2]) [1..2] `shouldBe` [12, 21] it "与えられた数値でできるN番目の順列 - 3" $ map (P.solve2 [0, 1, 2]) [1..6] `shouldBe` [12, 21, 102, 120, 201, 210]
yyotti/euler_haskell
test/P024Spec.hs
mit
1,709
0
15
349
696
387
309
37
1
{-# LANGUAGE DeriveDataTypeable #-} -- | Tor error types, inspired by System.IO.Error module Network.Anonymous.Tor.Error where import Data.Typeable (Typeable) import Control.Monad.IO.Class import Control.Exception (throwIO) import Control.Exception.Base (Exception) -- | Error type used type TorError = TorException -- | Exception that we use to throw. It is the only type of exception -- we throw, and the type of error is embedded within the exception. data TorException = TorError { toreType :: TorErrorType -- ^ Our error type } deriving (Show, Eq, Typeable) -- | Derives our Tor exception from the standard exception, which opens it -- up to being used with all the regular try/catch/bracket/etc functions. instance Exception TorException -- | An abstract type that contains a value for each variant of 'TorError' data TorErrorType = Timeout | Unreachable | ProtocolError String | PermissionDenied String deriving (Show, Eq) -- | Generates new TorException mkTorError :: TorErrorType -> TorError mkTorError t = TorError { toreType = t } -- | Tor error when a timeout has occurred timeoutErrorType :: TorErrorType timeoutErrorType = Timeout -- | Tor error when a host was unreachable unreachableErrorType :: TorErrorType unreachableErrorType = Unreachable -- | Tor error when communication with the SAM bridge fails protocolErrorType :: String -> TorErrorType protocolErrorType = ProtocolError -- | Tor error when communication with the SAM bridge fails permissionDeniedErrorType :: String -> TorErrorType permissionDeniedErrorType = PermissionDenied -- | Raise an Tor Exception in the IO monad torException :: (MonadIO m) => TorException -> m a torException = liftIO . throwIO -- | Raise an Tor error in the IO monad torError :: (MonadIO m) => TorError -> m a torError = torException
solatis/haskell-network-anonymous-tor
src/Network/Anonymous/Tor/Error.hs
mit
1,869
0
8
350
265
160
105
35
1
-- ghci -- :load C:\Users\Thomas\Documents\GitHub\haskell.practice\PE\Problem0026.hs -- :r -- :set +s for times --http://www.computing.surrey.ac.uk/personal/ext/R.Knott/Fractions/FractionsCalc.html --http://www.computing.surrey.ac.uk/personal/ext/R.Knott/Fractions/fractions.html#section2.2 --If λ is the smallest power of 10 that leaves a remainder of 1 when divided by n, then there are λ digits in the period of 1/n: --λ is the smallest number for which 10λ mod n = 1 module Problem0026 where import Data.List import Data.Ord reciprocalCycleLength n | even n = 0 | n `mod` 5 == 0 = 0 | n == 1 = 0 | otherwise = lengthOfCycle where lengthOfCycle = (length $ takeWhile (\elem -> isLengthOfCycle elem == False) [1..]) + 1 isLengthOfCycle p = (10^p) `mod` n == 1 findLongestReciprocalCycleInList list = maximumBy (comparing snd) $ zip list $ map reciprocalCycleLength list answer = findLongestReciprocalCycleInList [2..999] findLongestReciprocalCycleInListTests = and [ findLongestReciprocalCycleInList [2..10] == (7,6), findLongestReciprocalCycleInList [2..21] == (19,18) ] reciprocalCycleLengthTests = and [ reciprocalCycleLength 4 == 0, reciprocalCycleLength 6 == 0, reciprocalCycleLength 3 == 1, reciprocalCycleLength 2 == 0, reciprocalCycleLength 5 == 0, reciprocalCycleLength 6 == 0, reciprocalCycleLength 7 == 6, reciprocalCycleLength 8 == 0, reciprocalCycleLength 9 == 1, reciprocalCycleLength 10 == 0, reciprocalCycleLength 21 == 6, reciprocalCycleLength 9801 == 198 ] --tests tests = and [ reciprocalCycleLengthTests, findLongestReciprocalCycleInListTests ]
Sobieck00/practice
pe/nonvisualstudio/haskell/OldWork/Implementation/Problem0026.hs
mit
1,720
46
14
349
431
226
205
36
1
module Main where import Game.Internal import Test.Tasty import qualified Test.Tasty.HUnit as HU import qualified Test.Tasty.QuickCheck as QC main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [unitTests, props] unitTests :: TestTree unitTests = testGroup "Unit Tests" [ HU.testCase "isFinished start == False" $ isFinished start HU.@?= False , HU.testCase "isFinished sample == True" $ isFinished sample HU.@?= True , HU.testCase "-1 `elem` bounds == False" $ -1 `elem` bounds HU.@?= False ] props :: TestTree props = testGroup "Properties" [qcProps] qcProps :: TestTree qcProps = testGroup "QuickCheck" [ QC.testProperty "game starts empty" propGameStartsEmpty , QC.testProperty "one move doesn't finish a game" propOneMoveGameUnfinished , QC.testProperty "first move claims a cell for X" propFirstMoveForX , QC.testProperty "second turn for O" propSecondTurnForO , QC.testProperty "can't move to claimed cell" propNoMoveToClaimed ] propGameStartsEmpty :: QC.Property propGameStartsEmpty = QC.forAll pos $ \p -> playerAt p start == Just Unclaimed propOneMoveGameUnfinished :: QC.Property propOneMoveGameUnfinished = QC.forAll pos $ not . isFinished . (start >>=) . move propFirstMoveForX :: QC.Property propFirstMoveForX = QC.forAll pos $ \p -> playerAt p (start >>= move p) == Just (Claimed X) propSecondTurnForO :: QC.Property propSecondTurnForO = QC.forAll pos $ \p -> (\(Right (Unfinished _ m)) -> m == O) (start >>= move p) propNoMoveToClaimed :: QC.Property propNoMoveToClaimed = QC.forAll pos $ \p -> let Right (Unfinished _ pl) = start >>= move p >>= move p in pl == O coord :: QC.Gen Coordinate coord = QC.choose (lower, upper) pos :: QC.Gen Position pos = (,) <$> coord <*> coord player :: QC.Gen Player player = QC.elements [X, O] cell :: QC.Gen Cell cell = QC.oneof [pure Unclaimed, Claimed <$> player] straight :: QC.Gen Straight straight = QC.listOf cell board :: QC.Gen Board board = boardFromCells <$> QC.infiniteListOf cell unfinished :: QC.Gen Unfinished unfinished = Unfinished <$> board <*> player outcome :: QC.Gen Outcome outcome = QC.oneof [pure Draw, Won <$> player] finished :: QC.Gen Finished finished = Finished <$> board <*> outcome game :: QC.Gen Game game = QC.oneof [Left <$> finished, Right <$> unfinished]
amar47shah/NICTA-TicTacToe
test/Spec.hs
mit
2,360
0
13
428
766
401
365
59
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} module PostgREST.PgStructure where import Control.Applicative import Control.Monad (join) import Data.Functor.Identity import Data.List (elemIndex, find) import Data.Maybe (fromMaybe, isJust, mapMaybe) import Data.Monoid import Data.Text (Text, split) import qualified Hasql as H import qualified Hasql.Postgres as P import PostgREST.PgQuery () import PostgREST.Types import GHC.Exts (groupWith) import Prelude doesProcExist :: Text -> Text -> H.Tx P.Postgres s Bool doesProcExist schema proc = do row :: Maybe (Identity Int) <- H.maybeEx $ [H.stmt| SELECT 1 FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_proc p ON pronamespace = n.oid WHERE nspname = ? AND proname = ? |] schema proc return $ isJust row tableFromRow :: (Text, Text, Bool, Maybe Text) -> Table tableFromRow (s, n, i, a) = Table s n i (parseAcl a) where parseAcl :: Maybe Text -> [Text] parseAcl str = fromMaybe [] $ split (==',') <$> str columnFromRow :: (Text, Text, Text, Int, Bool, Text, Bool, Maybe Int, Maybe Int, Maybe Text, Maybe Text) -> Column columnFromRow (s, t, n, pos, nul, typ, u, l, p, d, e) = Column s t n pos nul typ u l p d (parseEnum e) Nothing where parseEnum :: Maybe Text -> [Text] parseEnum str = fromMaybe [] $ split (==',') <$> str relationFromRow :: (Text, Text, [Text], Text, [Text]) -> Relation relationFromRow (s, t, cs, ft, fcs) = Relation s t cs ft fcs Child Nothing Nothing Nothing pkFromRow :: (Text, Text, Text) -> PrimaryKey pkFromRow (s, t, n) = PrimaryKey s t n addParentRelation :: Relation -> [Relation] -> [Relation] addParentRelation rel@(Relation s t c ft fc _ _ _ _) rels = Relation s ft fc t c Parent Nothing Nothing Nothing:rel:rels allTables :: H.Tx P.Postgres s [Table] allTables = do rows <- H.listEx $ [H.stmt| SELECT n.nspname AS table_schema, c.relname AS table_name, c.relkind = 'r' OR (c.relkind IN ('v','f')) AND (pg_relation_is_updatable(c.oid::regclass, FALSE) & 8) = 8 OR (EXISTS ( SELECT 1 FROM pg_trigger WHERE pg_trigger.tgrelid = c.oid AND (pg_trigger.tgtype::integer & 69) = 69) ) AS insertable, array_to_string(array_agg(r.rolname), ',') AS acl FROM pg_class c CROSS JOIN pg_roles r JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('v','r','m') AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND ( pg_has_role(r.rolname, c.relowner, 'USAGE'::text) OR has_table_privilege(r.rolname, c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.rolname, c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'::text) ) GROUP BY table_schema, table_name, insertable ORDER BY table_schema, table_name |] return $ map tableFromRow rows allRelations :: H.Tx P.Postgres s [Relation] allRelations = do rels <- H.listEx $ [H.stmt| WITH table_fk AS ( SELECT ns.nspname AS table_schema, tab.relname AS table_name, column_info.cols AS columns, other.relname AS foreign_table_name, column_info.refs AS foreign_columns FROM pg_constraint, LATERAL (SELECT array_agg(cols.attname) AS cols, array_agg(cols.attnum) AS nums, array_agg(refs.attname) AS refs FROM unnest(conkey, confkey) AS _(col, ref), LATERAL (SELECT * FROM pg_attribute WHERE attrelid = conrelid AND attnum = col) AS cols, LATERAL (SELECT * FROM pg_attribute WHERE attrelid = confrelid AND attnum = ref) AS refs) AS column_info, LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = connamespace) AS ns, LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = conrelid) AS tab, LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = confrelid) AS other WHERE confrelid != 0 ORDER BY (conrelid, column_info.nums) ) SELECT * FROM table_fk UNION ( SELECT vcu.table_schema, vcu.view_name AS table_name, array_agg(vcu.column_name::text) AS columns, table_fk.foreign_table_name, table_fk.foreign_columns FROM information_schema.view_column_usage as vcu JOIN table_fk ON table_fk.table_schema = vcu.view_schema AND table_fk.table_name = vcu.table_name AND vcu.column_name = ANY (table_fk.columns) WHERE vcu.view_schema NOT IN ('pg_catalog', 'information_schema') AND columns = table_fk.columns GROUP BY vcu.table_schema, vcu.view_name, table_fk.foreign_table_name, table_fk.foreign_columns ) UNION ( SELECT vcu.view_schema as table_schema, table_fk.table_name, table_fk.columns, vcu.view_name as foreign_table_name, array_agg(vcu.column_name::text) as foreign_columns FROM information_schema.view_column_usage as vcu JOIN table_fk ON table_fk.table_schema = vcu.view_schema AND table_fk.foreign_table_name = vcu.table_name AND vcu.column_name = ANY (table_fk.foreign_columns) WHERE vcu.view_schema NOT IN ('pg_catalog', 'information_schema') AND foreign_columns = table_fk.foreign_columns GROUP BY vcu.view_schema, table_fk.table_name, vcu.view_name, table_fk.columns ) |] let simpleRelations = foldr (addParentRelation.relationFromRow) [] rels let links = filter ((==2).length) $ groupWith groupFn $ filter ( (==Child). relType) simpleRelations return $ simpleRelations ++ mapMaybe link2Relation links where groupFn :: Relation -> Text groupFn (Relation{relSchema=s, relTable=t}) = s<>"_"<>t link2Relation [ Relation{relSchema=sc, relTable=lt, relColumns=lc1, relFTable=t, relFColumns=c}, Relation{ relColumns=lc2, relFTable=ft, relFColumns=fc} ] = Just $ Relation sc t c ft fc Many (Just lt) (Just lc1) (Just lc2) link2Relation _ = Nothing allColumns :: [Relation] -> H.Tx P.Postgres s [Column] allColumns rels = do cols <- H.listEx $ [H.stmt| SELECT info.table_schema AS schema, info.table_name AS table_name, info.column_name AS name, info.ordinal_position AS position, info.is_nullable::boolean AS nullable, info.data_type AS col_type, info.is_updatable::boolean AS updatable, info.character_maximum_length AS max_len, info.numeric_precision AS precision, info.column_default AS default_value, array_to_string(enum_info.vals, ',') AS enum FROM ( SELECT table_schema, table_name, column_name, ordinal_position, is_nullable, data_type, is_updatable, character_maximum_length, numeric_precision, column_default, udt_name FROM information_schema.columns WHERE table_schema NOT IN ('pg_catalog', 'information_schema') ) AS info LEFT OUTER JOIN ( SELECT n.nspname AS s, t.typname AS n, array_agg(e.enumlabel ORDER BY e.enumsortorder) AS vals FROM pg_type t JOIN pg_enum e ON t.oid = e.enumtypid JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace GROUP BY s,n ) AS enum_info ON (info.udt_name = enum_info.n) ORDER BY schema, position |] return $ map (addFK . columnFromRow) cols where addFK col = col { colFK = fk col } fk col = join $ relToFk (colName col) <$> find (lookupFn col) rels lookupFn :: Column -> Relation -> Bool lookupFn (Column{colSchema=cs, colTable=ct, colName=cn}) (Relation{relSchema=rs, relTable=rt, relColumns=rc, relType=rty}) = cs==rs && ct==rt && cn `elem` rc && rty==Child lookupFn _ _ = False relToFk cName (Relation{relFTable=t, relColumns=cs, relFColumns=fcs}) = ForeignKey t <$> c where pos = elemIndex cName cs c = (fcs !!) <$> pos allPrimaryKeys :: H.Tx P.Postgres s [PrimaryKey] allPrimaryKeys = do pks <- H.listEx $ [H.stmt| WITH table_pk AS ( SELECT kc.table_schema, kc.table_name, kc.column_name FROM information_schema.table_constraints tc, information_schema.key_column_usage kc WHERE tc.constraint_type = 'PRIMARY KEY' AND kc.table_name = tc.table_name AND kc.table_schema = tc.table_schema AND kc.constraint_name = tc.constraint_name AND kc.table_schema NOT IN ('pg_catalog', 'information_schema') ) SELECT table_schema, table_name, column_name FROM table_pk UNION ( SELECT vcu.view_schema, vcu.view_name, vcu.column_name FROM information_schema.view_column_usage AS vcu JOIN table_pk ON table_pk.table_schema = vcu.view_schema AND table_pk.table_name = vcu.table_name AND table_pk.column_name = vcu.column_name WHERE vcu.view_schema NOT IN ('pg_catalog','information_schema') ) |] return $ map pkFromRow pks
pap/postgrest
src/PostgREST/PgStructure.hs
mit
10,207
0
15
3,250
1,384
763
621
77
2
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.MediaList (item, item_, itemUnsafe, itemUnchecked, deleteMedium, appendMedium, setMediaText, getMediaText, getLength, MediaList(..), gTypeMediaList) 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/MediaList.item Mozilla MediaList.item documentation> item :: (MonadDOM m, FromJSString result) => MediaList -> Word -> m (Maybe result) item self index = liftDOM ((self ^. jsf "item" [toJSVal index]) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.item Mozilla MediaList.item documentation> item_ :: (MonadDOM m) => MediaList -> Word -> m () item_ self index = liftDOM (void (self ^. jsf "item" [toJSVal index])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.item Mozilla MediaList.item documentation> itemUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => MediaList -> Word -> m result itemUnsafe self index = liftDOM (((self ^. jsf "item" [toJSVal index]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.item Mozilla MediaList.item documentation> itemUnchecked :: (MonadDOM m, FromJSString result) => MediaList -> Word -> m result itemUnchecked self index = liftDOM ((self ^. jsf "item" [toJSVal index]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.deleteMedium Mozilla MediaList.deleteMedium documentation> deleteMedium :: (MonadDOM m, ToJSString oldMedium) => MediaList -> oldMedium -> m () deleteMedium self oldMedium = liftDOM (void (self ^. jsf "deleteMedium" [toJSVal oldMedium])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.appendMedium Mozilla MediaList.appendMedium documentation> appendMedium :: (MonadDOM m, ToJSString newMedium) => MediaList -> newMedium -> m () appendMedium self newMedium = liftDOM (void (self ^. jsf "appendMedium" [toJSVal newMedium])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.mediaText Mozilla MediaList.mediaText documentation> setMediaText :: (MonadDOM m, ToJSString val) => MediaList -> val -> m () setMediaText self val = liftDOM (self ^. jss "mediaText" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.mediaText Mozilla MediaList.mediaText documentation> getMediaText :: (MonadDOM m, FromJSString result) => MediaList -> m result getMediaText self = liftDOM ((self ^. js "mediaText") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaList.length Mozilla MediaList.length documentation> getLength :: (MonadDOM m) => MediaList -> m Word getLength self = liftDOM (round <$> ((self ^. js "length") >>= valToNumber))
ghcjs/jsaddle-dom
src/JSDOM/Generated/MediaList.hs
mit
3,843
0
14
615
944
534
410
-1
-1
module ParameterizedEntity.Schema ( module ParameterizedEntity.Schema , module ParameterizedEntity.Schema.Virus ) where import qualified Database.Orville.PostgreSQL as O import ParameterizedEntity.Schema.Virus schema :: O.SchemaDefinition schema = [O.Table virusTable]
flipstone/orville
orville-postgresql/test/ParameterizedEntity/Schema.hs
mit
278
0
7
33
56
36
20
7
1
module Test.Hspec.Core.Formatters.V2Spec (spec) where import Prelude () import Helper import qualified Control.Exception as E import qualified Test.Hspec.Core.Spec as H import qualified Test.Hspec.Core.Spec as Spec import qualified Test.Hspec.Core.Runner as H import Test.Hspec.Core.Format import Test.Hspec.Core.Formatters.V2 testSpec :: H.Spec testSpec = do H.describe "Example" $ do H.it "success" (H.Result "" Spec.Success) H.it "fail 1" (H.Result "" $ Spec.Failure Nothing $ H.Reason "fail message") H.it "pending" (H.pendingWith "pending message") H.it "fail 2" (H.Result "" $ Spec.Failure Nothing H.NoReason) H.it "exceptions" (undefined :: Spec.Result) H.it "fail 3" (H.Result "" $ Spec.Failure Nothing H.NoReason) formatConfig :: FormatConfig formatConfig = FormatConfig { formatConfigUseColor = False , formatConfigOutputUnicode = True , formatConfigUseDiff = True , formatConfigPrettyPrint = True , formatConfigPrintTimes = False , formatConfigHtmlOutput = False , formatConfigPrintCpuTime = False , formatConfigUsedSeed = 0 , formatConfigExpectedTotalCount = 0 } runSpecWith :: Formatter -> H.Spec -> IO [String] runSpecWith formatter = captureLines . H.hspecWithResult H.defaultConfig {H.configFormat = Just $ formatterToFormat formatter} spec :: Spec spec = do describe "indentChunks" $ do context "with Original" $ do it "does not indent single-line input" $ do indentChunks " " [Original "foo"] `shouldBe` [PlainChunk "foo"] it "indents multi-line input" $ do indentChunks " " [Original "foo\nbar\nbaz\n"] `shouldBe` [PlainChunk "foo\n bar\n baz\n "] context "with Modified" $ do it "returns the empty list on empty input" $ do indentChunks " " [Modified ""] `shouldBe` [] it "does not indent single-line input" $ do indentChunks " " [Modified "foo"] `shouldBe` [ColorChunk "foo"] it "indents multi-line input" $ do indentChunks " " [Modified "foo\nbar\nbaz\n"] `shouldBe` [ColorChunk "foo", PlainChunk "\n ", ColorChunk "bar", PlainChunk "\n ", ColorChunk "baz", PlainChunk "\n "] it "colorizes whitespace-only input" $ do indentChunks " " [Modified " "] `shouldBe` [ColorChunk " "] it "colorizes whitespace-only lines" $ do indentChunks " " [Modified "foo\n \n"] `shouldBe` [ColorChunk "foo", PlainChunk "\n ", ColorChunk " ", PlainChunk "\n "] it "colorizes whitespace at the end of the input" $ do indentChunks " " [Modified "foo\n "] `shouldBe` [ColorChunk "foo", PlainChunk "\n ", ColorChunk " "] it "splits off whitespace-only segments at the end of a line so that they get colorized" $ do indentChunks " " [Modified "foo \n"] `shouldBe` [ColorChunk "foo", ColorChunk " ", PlainChunk "\n "] context "with empty lines" $ do it "colorizes indentation" $ do indentChunks " " [Original "foo", Modified "\n\n", Original "bar"] `shouldBe` [PlainChunk "foo", PlainChunk "\n", ColorChunk " ", PlainChunk "\n", ColorChunk " ", PlainChunk "bar"] describe "progress" $ do let item = ItemDone ([], "") . Item Nothing 0 "" describe "formatterItemDone" $ do it "marks succeeding examples with ." $ do formatter <- formatterToFormat progress formatConfig captureLines (formatter $ item Success) `shouldReturn` ["."] it "marks failing examples with F" $ do formatter <- formatterToFormat progress formatConfig captureLines (formatter . item $ Failure Nothing NoReason) `shouldReturn` ["F"] it "marks pending examples with ." $ do formatter <- formatterToFormat progress formatConfig captureLines (formatter . item $ Pending Nothing Nothing) `shouldReturn` ["."] describe "checks" $ do let formatter = checks config = H.defaultConfig { H.configFormat = Just $ formatterToFormat formatter } it "" $ do r <- captureLines . H.hspecWithResult config $ do H.it "foo" True normalizeSummary r `shouldBe` [ "" , "foo [✔]" , "" , "Finished in 0.0000 seconds" , "1 example, 0 failures" ] it "" $ do r <- captureLines . H.hspecWithResult config { H.configUnicodeMode = H.UnicodeNever } $ do H.it "foo" True normalizeSummary r `shouldBe` [ "" , "foo [v]" , "" , "Finished in 0.0000 seconds" , "1 example, 0 failures" ] describe "specdoc" $ do let runSpec = runSpecWith specdoc it "displays a header for each thing being described" $ do _:x:_ <- runSpec testSpec x `shouldBe` "Example" it "displays one row for each behavior" $ do r <- runSpec $ do H.describe "List as a Monoid" $ do H.describe "mappend" $ do H.it "is associative" True H.describe "mempty" $ do H.it "is a left identity" True H.it "is a right identity" True H.describe "Maybe as a Monoid" $ do H.describe "mappend" $ do H.it "is associative" True H.describe "mempty" $ do H.it "is a left identity" True H.it "is a right identity" True normalizeSummary r `shouldBe` [ "" , "List as a Monoid" , " mappend" , " is associative" , " mempty" , " is a left identity" , " is a right identity" , "Maybe as a Monoid" , " mappend" , " is associative" , " mempty" , " is a left identity" , " is a right identity" , "" , "Finished in 0.0000 seconds" , "6 examples, 0 failures" ] it "outputs an empty line at the beginning (even for non-nested specs)" $ do r <- runSpec $ do H.it "example 1" True H.it "example 2" True normalizeSummary r `shouldBe` [ "" , "example 1" , "example 2" , "" , "Finished in 0.0000 seconds" , "2 examples, 0 failures" ] it "displays a row for each successful, failed, or pending example" $ do r <- runSpec testSpec r `shouldSatisfy` any (== " fail 1 FAILED [1]") r `shouldSatisfy` any (== " success") it "displays a '#' with an additional message for pending examples" $ do r <- runSpec testSpec r `shouldSatisfy` any (== " # PENDING: pending message") context "with an empty group" $ do it "omits that group from the report" $ do r <- runSpec $ do H.describe "foo" $ do H.it "example 1" True H.describe "bar" $ do return () H.describe "baz" $ do H.it "example 2" True normalizeSummary r `shouldBe` [ "" , "foo" , " example 1" , "baz" , " example 2" , "" , "Finished in 0.0000 seconds" , "2 examples, 0 failures" ] describe "formatterDone" $ do it "recovers unicode from ExpectedButGot" $ do formatter <- formatterToFormat failed_examples formatConfig { formatConfigOutputUnicode = True } _ <- formatter . ItemDone ([], "") . Item Nothing 0 "" $ Failure Nothing $ ExpectedButGot Nothing (show "\955") (show "\956") (fmap normalizeSummary . captureLines) (formatter $ Done []) `shouldReturn` [ "" , "Failures:" , "" , " 1) " , " expected: \"λ\"" , " but got: \"μ\"" , "" , " To rerun use: --match \"//\"" , "" , "Randomized with seed 0" , "" , "Finished in 0.0000 seconds" , "1 example, 1 failure" ] context "when actual/expected contain newlines" $ do it "adds indentation" $ do formatter <- formatterToFormat failed_examples formatConfig _ <- formatter . ItemDone ([], "") . Item Nothing 0 "" $ Failure Nothing $ ExpectedButGot Nothing "first\nsecond\nthird" "first\ntwo\nthird" (fmap normalizeSummary . captureLines) (formatter $ Done []) `shouldReturn` [ "" , "Failures:" , "" , " 1) " , " expected: first" , " second" , " third" , " but got: first" , " two" , " third" , "" , " To rerun use: --match \"//\"" , "" , "Randomized with seed 0" , "" , "Finished in 0.0000 seconds" , "1 example, 1 failure" ] context "without failures" $ do it "shows summary in green if there are no failures" $ do formatter <- formatterToFormat failed_examples formatConfig _ <- formatter . ItemDone ([], "") . Item Nothing 0 "" $ Success (fmap normalizeSummary . captureLines) (formatter $ Done []) `shouldReturn` [ "" , "Finished in 0.0000 seconds" , "1 example, 0 failures" ] context "with pending examples" $ do it "shows summary in yellow if there are pending examples" $ do formatter <- formatterToFormat failed_examples formatConfig _ <- formatter . ItemDone ([], "") . Item Nothing 0 "" $ Pending Nothing Nothing (fmap normalizeSummary . captureLines) (formatter $ Done []) `shouldReturn` [ "" , "Finished in 0.0000 seconds" , "1 example, 0 failures, 1 pending" ] context "same as failed_examples" $ do failed_examplesSpec specdoc describe "getExpectedTotalCount" $ do let formatter = silent { formatterStarted = fmap show getExpectedTotalCount >>= writeLine } runSpec = runSpecWith formatter it "returns the total number of spec items" $ do result:_ <- runSpec testSpec result `shouldBe` "6" failed_examplesSpec :: Formatter -> Spec failed_examplesSpec formatter = do let runSpec = runSpecWith formatter context "displays a detailed list of failures" $ do it "prints all requirements that are not met" $ do r <- runSpec testSpec r `shouldSatisfy` any (== " 1) Example fail 1") it "prints the exception type for requirements that fail due to an uncaught exception" $ do r <- runSpec $ do H.it "foobar" (E.throw (E.ErrorCall "baz") :: Bool) r `shouldContain` [ " 1) foobar" , " uncaught exception: ErrorCall" , " baz" ] it "prints all descriptions when a nested requirement fails" $ do r <- runSpec $ H.describe "foo" $ do H.describe "bar" $ do H.it "baz" False r `shouldSatisfy` any (== " 1) foo.bar baz") context "when a failed example has a source location" $ do it "includes that source location above the error message" $ do let loc = H.Location "test/FooSpec.hs" 23 4 addLoc e = e {Spec.itemLocation = Just loc} r <- runSpec $ H.mapSpecItem_ addLoc $ do H.it "foo" False r `shouldContain` [" test/FooSpec.hs:23:4: ", " 1) foo"]
hspec/hspec
hspec-core/test/Test/Hspec/Core/Formatters/V2Spec.hs
mit
11,398
0
26
3,686
2,835
1,394
1,441
257
1
-- Helpers/tests/SortingSpec.hs import Test.Hspec import Data.List import Helpers.Sorting main :: IO() main = hspec $ do describe "Quicksort" $ do it "Should sort a list of Ints" $ do quicksort [4,1,3,2] `shouldBe` [1,2,3,4] it "Should sort a list of chars" $ do quicksort ["c","r","s","b"] `shouldBe` ["b","c","r","s"] it "Should sort a string" $ do quicksort "hithere" `shouldBe` "eehhirt" it "Should sort a one item list" $ do quicksort [4] `shouldBe` [4]
Sgoettschkes/learning
haskell/ProjectEuler/Helpers/tests/SortingSpec.hs
mit
545
0
16
156
188
100
88
14
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Bot.Slack ( SlackMessage (..) , SlackPostInfo (..) , SlackPostData (..) , SlackConfig (..) , postToSlack , sendSlackMessage ) where import Control.Monad import Control.Monad.Catch import Control.Monad.Trans import Control.Monad.Trans.Resource import Data.Aeson import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.Text (Text) import qualified Data.Text as T import Network.HTTP.Conduit data SlackMessage = SlackMessage { getIcon :: !Text , getText :: !Text } deriving (Show, Eq) data SlackPostInfo = SlackPostInfo { getChannel :: !Text , getUserName :: !Text } deriving (Show, Eq) data SlackPostData = SlackPostData { getInfo :: !SlackPostInfo , getMessage :: !SlackMessage } deriving (Show, Eq) instance ToJSON SlackPostData where toJSON SlackPostData{..} = object [ "channel" .= getChannel getInfo , "username" .= getUserName getInfo , "text" .= getText getMessage , "icon_emoji" .= getIcon getMessage ] data SlackConfig = SlackConfig { webhookUrl :: !Text } deriving (Show, Eq) getPostRequest :: MonadThrow m => [(BS.ByteString, BS.ByteString)] -> Text -> m Request getPostRequest pdata = return . urlEncodedBody pdata <=< parseUrl . T.unpack postToSlack :: SlackConfig -> SlackPostData -> IO BSL.ByteString postToSlack c d = runResourceT $ do req <- getPostRequest [("payload", BSL.toStrict . encode $ d)] $ webhookUrl c manager <- liftIO $ newManager tlsManagerSettings res <- httpLbs req manager return $ responseBody res sendSlackMessage :: MonadIO m => SlackConfig -> SlackPostInfo -> SlackMessage -> m () sendSlackMessage c i m = void $ liftIO $ postToSlack c $ SlackPostData i m
uecmma/LTSHaskell-slack-bot
src/Bot/Slack.hs
mit
1,939
0
15
472
534
292
242
-1
-1
{-# LANGUAGE PackageImports #-} import "swaggy-jenkins" Application (develMain) import Prelude (IO) main :: IO () main = develMain
cliffano/swaggy-jenkins
clients/haskell-yesod/generated/app/devel.hs
mit
132
0
6
19
34
20
14
5
1
module CommandList (commands) where import Command.Attach import Command.Categories import Command.Envelope import Command.Help import Command.Init import Command.Migrate import Command.Pull import Command.Rule import Command.Summary import Command.Transfer import CommandType commands :: [Command] commands = [ Command { name="init" , function=initCommand , docSummary="Initialize manila project in the current directory" , doc="manila init\n\nInitialize manila project in the current directory." } , Command { name="migrate" , function=migrateCommand , docSummary="Migrate the database to a newer version of manila" , doc="manila migrate\n\nMigrate the database to a newer version of manila." } , Command { name="help" , function=helpCommand , docSummary="Print this list" , doc="manila help\n\nPrint this list." } , Command { name="pull" , function=pullCommand , docSummary="Download and import data from Mint.com" , doc="manila pull\n\nDownload and import transactions and account balances from Mint.com." } , Command { name="summary" , function=summaryCommand , docSummary="Summary of envelope and account balances" , doc="manila summary\n\nSummary of envelope and account balances." } , Command { name="envelope" , function=envelopeCommand , docSummary="Add an envelope" , doc="manila envelope <name>\n\nAdd an envelope. Use the 'summary' command to see current envelopes." } , Command { name="transfer" , function=transferCommand , docSummary="Transfer money to an envelope" , doc="manila transfer <amount> <envelope>\n\nTransfer money to an envelope. Use a negative amount to transfer from envelope." } , Command { name="attach" , function=attachCommand , docSummary="Attach Mint.com category to envelope" , doc="manila attach <envelope> <category>\n\nAttach Mint.com category to envelope. This means that all transactions from <category> will come out of (or go into) <envelope>." } , Command { name="categories" , function=categoriesCommand , docSummary="List the categories that are attached to an envelope" , doc="manila categories\n\nList the categories that are attached to an envelope." } , Command { name="rule" , function=addRuleCommand , docSummary="Add a rule" , doc="manila rule -c <envelope> <category> <percentage> <amount> [start_date]\nmanila rule -t <envelope> <frequence> <amount> [start_date]\n\nAdd a rule." } , Command { name="rules" , function=listRulesCommand , docSummary="List all rules" , doc="manila rules\n\nList all rules." } ]
jpotterm/manila-hs
src/CommandList.hs
cc0-1.0
3,513
0
7
1,359
394
255
139
57
1
{- | Module : $Header$ - Description : Implementation of logic formula parser - Copyright : (c) Georgel Calin & Lutz Schroeder, DFKI Lab Bremen - License : GPLv2 or higher, see LICENSE.txt - Maintainer : g.calin@jacobs-university.de - Stability : provisional - Portability : portable - - Provides the implementation of the generic parser for the L formula datatype -} module GMP.Parser where import GMP.Generic import Text.ParserCombinators.Parsec data ModalOperator = Sqr | Ang | None deriving Eq -- | Main parser par5er :: ModalOperator -> GenParser Char st a -> GenParser Char st (L a) par5er flag pa = implFormula flag pa -- | Parser which translates all implications in disjunctions & conjunctions implFormula :: ModalOperator -> GenParser Char st a -> GenParser Char st (L a) implFormula flag pa = do f <- orFormula flag pa option f (do string "->" spaces i <- implFormula flag pa return $ Or (Neg f) i <|> do try(string "<->") spaces i <- implFormula flag pa return $ And (Or (Neg f) i) (Or f (Neg i)) <|> do string "<-" spaces i <- implFormula flag pa return $ Or f (Neg i) <|> do return f <?> "GMPParser.implFormula") -- | Parser for disjunction - used for handling binding order orFormula :: ModalOperator -> GenParser Char st a -> GenParser Char st (L a) orFormula flag pa = do f <- andFormula flag pa option f $ do string "\\/" spaces g <- orFormula flag pa return $ Or f g <?> "GMPParser.orFormula" -- | Parser for conjunction - used for handling the binding order andFormula :: ModalOperator -> GenParser Char st a -> GenParser Char st (L a) andFormula flag pa = do f <- primFormula flag pa option f $ do string "/\\" spaces g <- andFormula flag pa return $ And f g <?> "GMPParser.andFormula" {- | Parse a primitive formula: T, F, ~f, <i>f, [i]f, p*, - where i stands for an index, f for a formula and - * for a series of digits i.e. and integer -} primFormula :: ModalOperator -> GenParser Char st a -> GenParser Char st (L a) primFormula flag pa = do string "T" spaces return T <|> do string "F" spaces return F <|> do f <- parenFormula flag pa return f <|> do string "~" spaces f <- primFormula flag pa return $ nneg f <|> do char '<' spaces i <- pa spaces char '>' spaces f <- primFormula flag pa -- restrict to the default modal operator case flag of Ang -> return $ M i f Sqr -> return $ Neg (M i (nneg f)) _ -> return $ M i f <|> do char '[' spaces i <- pa spaces char ']' spaces f <- primFormula flag pa -- restrict to the default modal operator case flag of Sqr -> return $ M i f Ang -> return $ Neg (M i (nneg f)) _ -> return $ M i f <|> do char 'p' i <- atomIndex return $ Atom (fromInteger i) <?> "GMPParser.primFormula" -- | Parser for un-parenthesizing a formula parenFormula :: ModalOperator -> GenParser Char st a -> GenParser Char st (L a) parenFormula flag pa = do char '(' spaces f <- par5er flag pa spaces char ')' spaces return f <?> "GMPParser.parenFormula" -- | Parse integer number natural :: GenParser Char st Integer natural = fmap read $ many1 digit -- | Parse the possible integer index of a variable atomIndex :: GenParser Char st Integer atomIndex = do i <- try natural spaces return $ i <?> "GMPParser.atomIndex" -- | Parsers for the different modal logic indexes parseCindex :: Parser C parseCindex = do -- checks whether there are more numbers to be parsed let stopParser = do char ',' return False <|> do char '}' return True <?> "Parser.parseCindex.stop" -- checks whether the index is of the for x1,..,x& let normalParser l = do x <- natural let n = fromInteger x spaces q <- stopParser spaces case q of False -> normalParser (n:l) _ -> return (n:l) <?> "Parser.parseCindex.normal" char '{' res <- try(normalParser []) return $ C res <|> do -- checks whether the index is of the form "n..m" let shortParser = do x <- natural let n = fromInteger x spaces string ".." spaces y <- natural let m = fromInteger y return $ [n..m] <?> "Parser.parseCindex.short" res <- try(shortParser) return $ C res <?> "Parser.parseCindex" parseGindex :: Parser G parseGindex = do n <- natural return $ G (fromInteger n) parseHMindex :: Parser HM parseHMindex = do c <- letter return $ HM c <?> "Parser.parseHMindex" parseKindex :: Parser K parseKindex = return K parseKDindex ::Parser KD parseKDindex = return KD parsePindex :: Parser P parsePindex = do x <- natural let auxP n = do char '/' m<-natural return $ toRational (fromInteger n/fromInteger m) <|> do char '.' m<-natural let noDig n | n<10 = 1 | n>=10 = 1 + noDig (div n 10) let rat n = toRational(fromInteger n / fromInteger (10^(noDig n))) let res = toRational n + rat m return res <|> do return $ toRational n <?> "Parser.parsePindex.auxP" aux <- auxP x return $ P aux parseMindex :: Parser Mon parseMindex = return Mon
nevrenato/Hets_Fork
GMP/versioning/gmp-coloss-0.0.2/GMP/Parser.hs
gpl-2.0
7,478
0
25
3,642
1,712
770
942
163
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} import Control.SessionTypes import Control.SessionTypes.Visualize import Data.Proxy (Proxy (..)) -- This test requires visual verification. -- Run the following to generate a diagram: -- > stack build -- > stack exec test-visualizer -- -o output.svg -w 600 -h 600 -- Adjust the height and width if necessary main = visualizeP p p :: Proxy (R ( Int :!> Sel '[ Bool :?> Off [Wk Eps, V], R (Sel '[Char :!> V, Wk V])])) p = Proxy
Ferdinand-vW/sessiontypes
test/Test/Visualize/Main.hs
gpl-3.0
487
0
18
86
118
67
51
8
1
{-# LANGUAGE BangPatterns #-} module Main where -- | Ïîäêëþ÷åíèå ìîäóëåé ðàáîòû ñî ñïèñêàìè (Data.List) è ñ ìîíàäàìè (Control.Monad). -- Ìîäóëè ïîäêëþ÷àþòñÿ ïîä èìåíàìè L è M ñîîòâåòñòâåííî. -- Èç ìîäóëÿ Control.Monad áåðåòñÿ òîëüêî ôóíêöèÿ guard. import qualified Data.List as L import qualified Control.Monad as M (guard) import qualified Data.Map as Map -- | Èñïîëüçóåìûå â ïðîãðàììå òèïû äàííûõ. type DeviceData = (Char, Float) -- ^ Äàííûå ïî óñòðîéñòâó: ñèìâîë è âåðîÿòíîñòü âûõîäà èç ñòðîÿ. type DevicesData = [DeviceData] -- ^ Ñïèñîê äàííûõ ïî óñòðîéñòâàì. type FailureCostData = [Float] -- ^ Ñóììû óáûòêîâ êàæäîãî èç îòêàçîâ. type ProblemData = (DevicesData, FailureCostData) -- | Äàííûå çàäà÷è. type VariantProbability = (String, Float) -- | Òèïû ñëîâàðåé. type ProbMapKey = (Char, Int) -- ^ Êëþ÷ ñëîâàðÿ "Òàáëèöà âåðîÿòíîñòåé". type ProbabilityMap = Map.Map ProbMapKey Float -- ^ Òàáëèöà âåðîÿòíîñòåé äëÿ óñòðîéñòâ íà ïîçèöèÿõ. type DeviceCostMap = Map.Map Char Float -- ^ Òàáëèöà ñòîèìîñòè óñòðîéñòâ. -- | Ñîçäàþò ïóñòûå ñëîâàðè íóæíîãî òèïà. emptyProbMap :: ProbabilityMap emptyProbMap = Map.empty emptyDeviceCostMap :: DeviceCostMap emptyDeviceCostMap = Map.empty -- | Äàííûå ïî óñòðîéñòâàì. devices1, devices2 :: DevicesData devices1 = [ ('A', 0.37) , ('B', 0.43) , ('C', 0.2) ] devices2 = [ ('A', 0.17) , ('B', 0.13) , ('C', 0.20) , ('D', 0.09) , ('E', 0.40) , ('F', 0.01) ] devices3 = [ ('A', 0.10) , ('B', 0.11) , ('C', 0.05) , ('D', 0.04) , ('E', 0.14) , ('F', 0.10) , ('G', 0.10) , ('H', 0.09) , ('I', 0.15) , ('J', 0.12) ] -- | Ñóììû óáûòêîâ èç-çà îòêàçîâ. failureCost1, failureCost2 :: FailureCostData failureCost1 = [20, 20, 30, 30] failureCost2 = [ 8, 12, 20, 60] failureCost3 = [ 1, 3, 11, 34, 51] -- | Ïîëíûå äàííûå ïî ïðèìåðàì 1, 2, 3. problem1, problem2, problem3 :: ProblemData problem1 = (devices1, failureCost1) problem2 = (devices2, failureCost2) problem3 = (devices3, failureCost3) -- | Âîçâðàùàåò ñóììó âåðîÿòíîñòåé óñòðîéñòâ. probabilitySum [] = 0 probabilitySum ((_,pa):aas) = pa + probabilitySum aas -- | Âûñ÷èòûâàåò âåðîÿòíîñòü äëÿ âàðèàíòà ïåðåñòàíîâêè. -- Íàïðèìåð, âåðîÿòíîñòü âàðèàíòà "BACD", åñëè åñòü âñåãî 4 óñòðîéñòâà. -- Ïðèíèìàåò ñóììó âåðîÿòíîñòåé âñåõ óñòðîéñòâ (êîòîðàÿ âñåãäà îäíà è òà æå). -- Ðåêóðñèâíî âû÷èñëÿåò ïðîèçâåäåíèå âåðîÿòíîñòåé êîíêðåòíîãî óñòðîéñòâà: -- (Pa / (Pa + Pb + Pc + ...)) * (Pb / (Pb + Pc + ...)) * ... * Pn / Pn -- Ïîñëåäíåå ÷àñòíîå âû÷èñëÿòü íå íóæíî, îíî âñåãäà 1. -- Ñóììû â çíàìåíàòåëå êàæäûé ðàç âû÷èñëÿòü òîæå íå íóæíî. Ïðîùå ïåðåäàâàòü -- íà ñëåäóþùèé øàã óìåíüøåííóþ ñóììó âåðîÿòíîñòåé. variantProbability :: Float -> DevicesData -> VariantProbability variantProbability _ [] = ([], 1) variantProbability _ ((dev,_):[]) = ([dev], 1) variantProbability varSum devicesData = let ((dev, p):xs) = devicesData (devs, probs) = variantProbability (varSum - p) xs prob = (p / varSum) in (dev : devs, prob * probs) -- | Âûñ÷èòûâàåò âåðîÿòíîñòè âñåõ âàðèàíòîâ ïåðåñòàíîâîê. -- Ñëîæíîñòü äàííîé ôóíêöèè ñîñòàâëÿåò íå ìåíåå n!. variantProbabilities :: DevicesData -> [VariantProbability] variantProbabilities devices = let varSum = probabilitySum devices perms = L.permutations devices in map (variantProbability varSum) perms -- | Âûñ÷èòûâàåò òàáëèöó âåðîÿòíîñòè äëÿ óñòðîéñòâ ïî ïîçèöèÿì. -- Ïåðâàÿ ñâåðòêà ïðîáåãàåòñÿ ïî âåðîÿòíîñòÿì âàðèàíòîâ, -- è íà êàæäîì øàãó ñ ïîìîùüþ âòîðîé ñâåðòêè çàíîñèò âåðîÿòíîñòü âàðèàíòà -- â òàáëèöó íà ïîçèöèþ (óñòðîéñòâî, èíäåêñ). -- Ïðèìåð. -- let varProbs = [("ABC",0.2525397),("BAC",0.27912283),("CBA",0.10750001),("BCA",0.1508772),("CAB",9.25e-2),("ACB",0.117460325)] -- Ïåðâàÿ ñâåðòêà ñîáèðàåò âåðîÿòíîñòè âàðèàíòîâ: -- (varString, prob) <- varProbs -- Âòîðàÿ ñâåðòêà ñîáèðàåò íàçâàíèÿ óñòðîéñòâ âàðèàíòà ñ îäíîâðåìåííîé àêêóìóëÿöèåé èíäåêñà: -- dev <- varString -- idx <- [0..] -- Íà êàæäîé èòåðàöèè çíà÷åíèå ñîîòâåòñòâóþùåé ÿ÷åéêè òàáëèöû ñêëàäûâàåòñÿ ñ âåðîÿòíîñòüþ -- òåêóùåãî âàðèàíòà: probabilityMap[dev, idx] += prob probabilityTable :: [VariantProbability] -> ProbabilityMap probabilityTable varProbs = L.foldl' f emptyProbMap varProbs where f :: ProbabilityMap -> VariantProbability -> ProbabilityMap f' :: Float -> (Int, ProbabilityMap) -> Char -> (Int, ProbabilityMap) f dataMap (varString, prob) = snd $ L.foldl' (f' prob) (0, dataMap) varString f' prob (idx, dataMap) dev = let key = (dev, idx) in case Map.lookup key dataMap of Just x -> (idx + 1, Map.insert key (prob + x) dataMap) Nothing -> (idx + 1, Map.insert key prob dataMap) -- | Âûñ÷èòûâàåò ñòîèìîñòü ïîëîìêè óñòðîéñòâ. -- Ñâîðà÷èâàåò òàáëèöó âåðîÿòíîñòè â òàáëèöó ñòîèìîñòè óñòðîéñòâ -- ñ ïîìîùüþ ôóíêöèè f. deviceCosts :: FailureCostData -> ProbabilityMap -> DeviceCostMap deviceCosts failureCost dataMap = result where result = Map.foldrWithKey (f infFailCost) emptyDeviceCostMap dataMap infFailCost = failureCost ++ repeat 0 -- Áåñêîíå÷íûé ñïèñîê äëÿ îõâàòà âñåõ èíäåêñîâ idx f :: FailureCostData -> ProbMapKey -> Float -> DeviceCostMap -> DeviceCostMap f fCost (ch, idx) prob m = let producted = prob * (fCost !! idx) in case Map.lookup ch m of Just p -> Map.insert ch (p + producted) m Nothing -> Map.insert ch producted m -- | Òî÷êà âõîäà â ïðîãðàììó. main = do let (devices, failureCost) = problem2 let !varProbs = variantProbabilities devices let probTable = probabilityTable varProbs let devCosts = deviceCosts failureCost probTable putStrLn . show $ devCosts putStrLn "Ok."
graninas/Haskell-Algorithms
Tests/FailureProbability/FailureProbability.hs
gpl-3.0
6,073
0
15
1,501
1,205
706
499
87
2
module PPA.Lang.While.Util (Block (..), init, final, blocks, blockMap, labels, fv, fvA, fvB, flow, aExp, aExpA, aExpB) where import Prelude hiding (init) import qualified Data.Set as Set import qualified Data.Map.Strict as Map import qualified Data.Maybe as Maybe import PPA.Lang.While.Internal hiding (aExp) data Block = BAssign Var AExp Lab | BSkip Lab | BBExp BExp Lab deriving (Eq, Ord) instance Show Block where show (BAssign x a l) = "(" ++ (show l) ++ ") " ++ show (SAssign x a l) show (BSkip l) = "(" ++ (show l) ++ ") " ++ show (SSkip l) show (BBExp b l) = "(" ++ (show l) ++ ") " ++ (show b) -- 2.1, p. 36 init :: Stmt -> Lab init (SAssign _ _ l) = l init (SSkip l) = l init (SSeq ss) = init s_1 where s_1 :: Stmt s_1 = head ss init (SIf _ l _ _) = l init (SWhile _ l _) = l -- 2.1, p. 36 final :: Stmt -> Set.Set Lab final (SAssign _ _ l) = Set.singleton l final (SSkip l) = Set.singleton l final (SSeq ss) = final s_n where s_n :: Stmt s_n = last ss final (SIf _ _ s1 s2) = Set.unions [(final s1), (final s2)] final (SWhile _ l _) = Set.singleton l -- 2.1, p. 36 blocks :: Stmt -> Set.Set Block blocks (SAssign x a l) = Set.singleton $ BAssign x a l blocks (SSkip l) = Set.singleton $ BSkip l blocks (SSeq ss) = Set.unions bs where bs :: [Set.Set Block] bs = map blocks ss blocks (SIf b l s1 s2) = Set.unions [Set.singleton $ BBExp b l, blocks s1, blocks s2] blocks (SWhile b l s) = Set.unions [Set.singleton $ BBExp b l, blocks s] getLabel :: Block -> Lab getLabel (BAssign _ _ l) = l getLabel (BSkip l) = l getLabel (BBExp _ l) = l blockMap :: Set.Set Block -> Lab -> Block blockMap bs l = Maybe.fromJust $ Map.lookup l bm where bm :: Map.Map Lab Block bm = Set.foldl (\ acc x -> Map.insert (getLabel x) x acc) Map.empty bs -- 2.1, p. 37 labels :: Stmt -> Set.Set Lab labels s = Set.map getLabel $ blocks s -- 2.1, p. 37 flow :: Stmt -> Set.Set (Lab, Lab) flow SAssign{} = Set.empty flow (SSkip _) = Set.empty flow (SSeq ss) = Set.unions [subflows, seqflows] where subflows :: Set.Set (Lab, Lab) subflows = Set.unions $ map flow ss seqflows :: Set.Set (Lab, Lab) seqflows = Set.unions $ mapPair flowPair ss where flowPair :: Stmt -> Stmt -> Set.Set (Lab, Lab) flowPair s1 s2 = Set.map (\ l -> (l, init s2)) $ final s1 mapPair :: (Stmt -> Stmt -> Set.Set (Lab, Lab)) -> [Stmt] -> [Set.Set (Lab, Lab)] mapPair f ([x, y]) = [(f x y)] mapPair f (x:(tail@(y:_))) = (f x y):(mapPair f tail) flow (SIf _ l s1 s2) = Set.unions [subflows, branchflows] where subflows :: Set.Set (Lab, Lab) subflows = Set.unions [flow s1, flow s2] branchflows :: Set.Set (Lab, Lab) branchflows = Set.unions [Set.singleton (l, init s1), Set.singleton (l, init s2)] flow (SWhile _ l s) = Set.unions [subflows, bodyflows] where subflows :: Set.Set (Lab, Lab) subflows = flow s bodyflows :: Set.Set (Lab, Lab) bodyflows = Set.unions [Set.singleton (l, init s), Set.map (\ l' -> (l', l)) $ final s] -- 2.1, p. 38 flowReverse :: Stmt -> Set.Set (Lab, Lab) flowReverse s = Set.map (\ (l, l') -> (l', l)) $ flow s fvA :: AExp -> Set.Set Var fvA (AVar x) = Set.singleton x fvA (ANum _) = Set.empty fvA (AOpA _ a1 a2) = Set.unions [fvA a1, fvA a2] fvB :: BExp -> Set.Set Var fvB (BTrue) = Set.empty fvB (BFalse) = Set.empty fvB (BNot b) = fvB b fvB (BOpB _ b1 b2) = Set.unions [fvB b1, fvB b2] fvB (BOpR _ a1 a2) = Set.unions [fvA a1, fvA a2] -- 2.1, p. 38 -- NOTE: Referenced, but not defined fv :: Stmt -> Set.Set Var fv (SAssign x a _) = Set.unions [Set.singleton x, fvA a] fv (SSkip _) = Set.empty fv (SSeq ss) = Set.unions $ map fv ss fv (SIf b _ s1 s2) = Set.unions [fvB b, fv s1, fv s2] fv (SWhile b _ s) = Set.unions [fvB b, fv s] aExpA :: AExp -> Set.Set AExp aExpA (AVar _) = Set.empty aExpA (ANum _) = Set.empty aExpA a@(AOpA _ a1 a2) = Set.unions [Set.singleton a, aExpA a1, aExpA a2] aExpB :: BExp -> Set.Set AExp aExpB (BTrue) = Set.empty aExpB (BFalse) = Set.empty aExpB (BNot b) = aExpB b aExpB (BOpB _ b1 b2) = Set.unions [aExpB b1, aExpB b2] aExpB (BOpR _ a1 a2) = Set.unions [aExpA a1, aExpA a2] -- 2.1, p. 39 -- NOTE: Referenced, but not defined aExp :: Stmt -> Set.Set AExp aExp (SAssign _ a _) = aExpA a aExp (SSkip _) = Set.empty aExp (SSeq ss) = Set.unions $ map aExp ss aExp (SIf b _ s1 s2) = Set.unions [aExpB b, aExp s1, aExp s2] aExp (SWhile b _ s) = Set.unions [aExpB b, aExp s]
Isweet/ppa
src/PPA/Lang/While/Util.hs
gpl-3.0
4,727
0
15
1,296
2,352
1,216
1,136
102
2
{-# LANGUAGE GeneralizedNewtypeDeriving, TypeFamilies #-} {-| This module defines the main 'Application' type, as well as the associated monad for manipulating it. -} module Blog.Core ( module Xport , AppState(..) , App , runApp , execAppAction , appBlobStore , appUsers , appPosts , appTemplate , appTemplateDirectory , setLoggedIn', forwardAfterLogin' , requireLoggedIn', refreshLoggedIn' , setLoggedOut', loginData' , isLoggedIn ) where import Blog.Users.Core as Xport (Users(..), UserId(..), emptyUsers, User(..)) import Blog.Posts.Core as Xport (Posts(..), emptyPosts, PostInsert(..), PostId, Post(..), postDay, postTz) import Blog.Sitemap as Xport ( Sitemap(..) , PostSite(..) , UserSite(..) , PathDay(..) ) import Control.Applicative (Alternative, Applicative, (<$>)) import Control.Monad.Reader import Database.BlobStorage import Database.BlobStorage as Xport (BlobId) import Data.Acid import Data.Maybe (isJust) import Happstack.Server (ServerPartT, mapServerPartT, ServerMonad, FilterMonad, Response, WebMonad, HasRqData) import Happstack.Server.TinyAuth import Text.Templating.Heist (TemplateState) import Text.Templating.Heist.TemplateDirectory (TemplateDirectory, getDirectoryTS) import Web.Routes import Web.Routes.Happstack() -- | Shared for all requests data AppState = MkAppState { app_blobstore :: BlobStorage , app_users :: AcidState Users , app_posts :: AcidState Posts , app_template :: TemplateDirectory App } -- Woo! newtype App a = App { unApp :: RouteT Sitemap (ServerPartT (ReaderT AppState IO)) a } deriving (ServerMonad, FilterMonad Response, WebMonad Response, HasRqData, Monad, Functor, Applicative, Alternative, MonadPlus, MonadIO, MonadReader AppState) -- I dream of a future happstack where 'ServerMonad, FilterMonad Response, -- WebMonad Response, HasRqData' are all summed up with 'ServerMonad' instance MonadRoute App where type URL App = Sitemap askRouteFn = App askRouteFn instance AuthMonad App where type Session App = UserId getAuthConfig = do loginUrl <- showURL $ User UserLogin return $ defaultAuthConfig {loginForm = loginUrl} runApp :: AppState -> App a -> RouteT Sitemap (ServerPartT IO) a runApp appState (App m) = mapRouteT mapFn m where mapFn = mapServerPartT $ flip runReaderT appState -- | Used to resolve smart URL using functions -- outside of a routing context. execRouteT :: Site url x -> RouteT url m a -> m a execRouteT site route = let fn url q1 = case formatPathSegments site url of (path,q2) -> encodePathInfo path (q1 ++ q2) in unRouteT route fn -- | Whereas 'runApp' is meant to be used in the context of routing, -- 'execAppAction' can be used outside of routing. The 'Site' -- parameter is only used for URL resolution. execAppAction :: Site Sitemap x -> AppState -> App a -> ServerPartT IO a execAppAction site appState = execRouteT site . runApp appState appBlobStore :: App BlobStorage appBlobStore = asks app_blobstore appUsers :: App (AcidState Users) appUsers = asks app_users appPosts :: App (AcidState Posts) appPosts = asks app_posts appTemplate :: App (TemplateState App) appTemplate = asks app_template >>= getDirectoryTS appTemplateDirectory :: App (TemplateDirectory App) appTemplateDirectory = asks app_template -- | Is there currently a logged-in user isLoggedIn :: App Bool isLoggedIn = isJust <$> loginData'
aslatter/blog
Blog/Core.hs
gpl-3.0
3,538
0
14
700
859
491
368
82
1
-- given two numbers -- find primes in that range p39 :: Int -> Int -> [Int] p39 a b = takeWhile (<=b) . dropWhile (<a) $ primes where primes = sieve [2..] where sieve (x:xs) = x : sieve [ z | z <- xs, mod z x /= 0 ]
yalpul/CENG242
H99/31-41/p39.hs
gpl-3.0
244
0
14
79
112
59
53
4
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE TemplateHaskell #-} module Infsabot.Strategy.Random.Logic ( complexity, cRandom, getDeltas, applyDeltas, constantToParameter, simplify, complicate, getPartition ) where import Infsabot.RobotAction.Interface import Infsabot.Strategy.ExprTree.Interface import Infsabot.Base.Interface import Infsabot.Debug import Control.Monad.State.Lazy import Data.Ratio import System.Random import Math.Combinat.Partitions.Integer import Infsabot.Strategy.Random.Templates type HistoricalStates = [KnownState] class ComplexityRandom a where complexity :: a -> Int cRandom :: (RandomGen g) => Int -> g -> (a, g) instance {-# OVERLAPPABLE #-} (ComplexityRandom a) => Random a where randomR (a, b) = runState $ do c <- state $ randomR (ca, cb) state $ cRandom c where ca = complexity a cb = complexity b random = runState $ do val <- state $ randomR (1, 1000) state $ cRandom val class (Random a) => Expr a where getDeltas :: Ratio Int -> a -> [a] applyDeltas :: [Ratio Int] -> a -> a constantToParameter :: HistoricalStates -> a -> StdGen -> (a, StdGen) simplify :: HistoricalStates -> a -> StdGen -> (a, StdGen) complicate :: Int -> a -> StdGen -> (a, StdGen) instance Random RDirection where randomR = const random random gen= (case val of 0 -> N; 1 -> E; 2 -> W; _ -> S, gen') where (val, gen') = randomR (0 :: Int, 3) gen {- instance ComplexityRandom ExprDir where complexity (ConstDir _) = 1 complexity (IfDir a b c) = 1 + complexity a + complexity b + complexity c cRandom a = runState $ do bb <- state random if bb && a >= 1 then ConstDir <$> state random else do [a', b', c'] <- state $ getPartition a 3 liftM3 IfDir (srand a') (srand b') (srand c') instance ComplexityRandom ExprBool where complexity (ConstBool _) = 1 complexity (CanSee x) = 1 + complexity x complexity (MaterialAt x) = 1 + complexity x complexity (RobotAt x) = 1 + complexity x complexity (EqualInt x y) = 1 + complexity x + complexity y complexity (GreaterInt x y) = 1 + complexity x + complexity y complexity (EqualDir x y) = 1 + complexity x + complexity y complexity (x :& y) = 1 + complexity x + complexity y complexity (x :| y) = 1 + complexity x + complexity y complexity (Not x) = 1 + complexity x cRandom cxty = runState $ do which <- state $ randomR (0, 8) case which of 0 -> ConstBool <$> state random 1 -> CanSee <$> cRandom -} getPartition :: (RandomGen g) => Int -> Int -> g -> ([Int], g) getPartition n k | trace ("getPartition " ++ show n ++ " " ++ show k) False = undefined | k == 0 = \g -> ([], g) | otherwise = value where value :: (RandomGen g) => g -> ([Int], g) value = case parts of [] -> \g -> ([], g) pts -> choice pts parts :: [[Int]] parts = map departition $ partitionsWithKParts k n departition (Partition x) = x choice :: (RandomGen g) => [a] -> g -> (a, g) choice [] = error "choice on empty list" choice xs = runState $ do index <- state $ randomR (0, length xs - 1) return $ xs !! index $(crDecls ''ExprBool) $(crDecls ''ExprDir) $(crDecls ''ExprInt) $(crDecls ''ExprPath) $(crDecls ''RP) $(crDecls ''ActionType)
kavigupta/Infsabot
Infsabot/Strategy/Random/Logic.hs
gpl-3.0
3,527
0
13
948
874
470
404
63
2
-- Copyright 2013 Gushcha Anton -- This file is part of PowerCom. -- -- PowerCom 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. -- -- PowerCom 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 PowerCom. If not, see <http://www.gnu.org/licenses/>. module Data.WeightedGraph ( Graph , emptyGraph , graphEdges , graphFromEdges , graphAddEdge , graphMerge ) where import qualified Data.Map as Map import UU.PPrint data Graph vertexMark edgeMark = Graph (Map.Map vertexMark (Map.Map vertexMark edgeMark)) instance (Pretty vertexMark, Pretty edgeMark) => Pretty (Graph vertexMark edgeMark) where pretty graph = foldl showVertex (string "Graph:\n") $ graphEdges graph where showVertex ss (from, to, weight) = ss <+> pretty from <+> string " -> " <+> pretty to <+> string " : " <+> pretty weight <+> string "\n" instance (Eq vertexMark, Eq edgeMark) => Eq (Graph vertexMark edgeMark) where (==) (Graph mapA) (Graph mapB) = mapA == mapB emptyGraph :: Graph vertexMark edgeMark emptyGraph = Graph Map.empty graphEdges :: Graph vertexMark edgeMark -> [(vertexMark, vertexMark, edgeMark)] graphEdges (Graph vertMap) = Map.foldrWithKey iterateVertecies [] vertMap where iterateVertecies :: vertexMark -> Map.Map vertexMark edgeMark -> [(vertexMark, vertexMark, edgeMark)] -> [(vertexMark, vertexMark, edgeMark)] iterateVertecies from vertexMap = ((map (\(to, weight) -> (from, to, weight)) $ Map.assocs vertexMap) ++) graphFromEdges :: (Ord vertexMark, Num edgeMark) => [(vertexMark, vertexMark, edgeMark)] -> Graph vertexMark edgeMark graphFromEdges = foldl graphAddEdge emptyGraph graphAddEdge :: (Ord vertexMark, Num edgeMark) => Graph vertexMark edgeMark -> (vertexMark, vertexMark, edgeMark) -> Graph vertexMark edgeMark graphAddEdge (Graph vertMap) (from, to, weight) = Graph $ if Map.member from vertMap then Map.insert from newFromMap vertMap else Map.insert from (Map.singleton to weight) vertMap where newFromMap = if Map.member to fromMap then Map.adjust (+ weight) to fromMap else Map.insert to weight fromMap fromMap = vertMap Map.! from graphMerge :: (Ord vertexMark, Num edgeMark) => Graph vertexMark edgeMark -> Graph vertexMark edgeMark -> Graph vertexMark edgeMark graphMerge graphA graphB = foldl graphAddEdge graphA $ graphEdges graphB
NCrashed/Kaissa
source/Data/WeightedGraph.hs
gpl-3.0
2,882
0
14
581
727
393
334
33
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.MapsEngine.Layers.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Create a layer asset. -- -- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.layers.create@. module Network.Google.Resource.MapsEngine.Layers.Create ( -- * REST Resource LayersCreateResource -- * Creating a Request , layersCreate , LayersCreate -- * Request Lenses , lcProcess , lcPayload ) where import Network.Google.MapsEngine.Types import Network.Google.Prelude -- | A resource alias for @mapsengine.layers.create@ method which the -- 'LayersCreate' request conforms to. type LayersCreateResource = "mapsengine" :> "v1" :> "layers" :> QueryParam "process" Bool :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Layer :> Post '[JSON] Layer -- | Create a layer asset. -- -- /See:/ 'layersCreate' smart constructor. data LayersCreate = LayersCreate' { _lcProcess :: !(Maybe Bool) , _lcPayload :: !Layer } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LayersCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lcProcess' -- -- * 'lcPayload' layersCreate :: Layer -- ^ 'lcPayload' -> LayersCreate layersCreate pLcPayload_ = LayersCreate' { _lcProcess = Nothing , _lcPayload = pLcPayload_ } -- | Whether to queue the created layer for processing. lcProcess :: Lens' LayersCreate (Maybe Bool) lcProcess = lens _lcProcess (\ s a -> s{_lcProcess = a}) -- | Multipart request metadata. lcPayload :: Lens' LayersCreate Layer lcPayload = lens _lcPayload (\ s a -> s{_lcPayload = a}) instance GoogleRequest LayersCreate where type Rs LayersCreate = Layer type Scopes LayersCreate = '["https://www.googleapis.com/auth/mapsengine"] requestClient LayersCreate'{..} = go _lcProcess (Just AltJSON) _lcPayload mapsEngineService where go = buildClient (Proxy :: Proxy LayersCreateResource) mempty
rueshyna/gogol
gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/Layers/Create.hs
mpl-2.0
2,895
0
13
676
387
232
155
59
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.AndroidManagement.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.AndroidManagement.Types.Product where import Network.Google.AndroidManagement.Types.Sum import Network.Google.Prelude -- | The Status type defines a logical error model that is suitable for -- different programming environments, including REST APIs and RPC APIs. It -- is used by gRPC (https:\/\/github.com\/grpc). Each Status message -- contains three pieces of data: error code, error message, and error -- details.You can find out more about this error model and how to work -- with it in the API Design Guide -- (https:\/\/cloud.google.com\/apis\/design\/errors). -- -- /See:/ 'status' smart constructor. data Status = Status' { _sDetails :: !(Maybe [StatusDetailsItem]) , _sCode :: !(Maybe (Textual Int32)) , _sMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sDetails' -- -- * 'sCode' -- -- * 'sMessage' status :: Status status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing} -- | A list of messages that carry the error details. There is a common set -- of message types for APIs to use. sDetails :: Lens' Status [StatusDetailsItem] sDetails = lens _sDetails (\ s a -> s{_sDetails = a}) . _Default . _Coerce -- | The status code, which should be an enum value of google.rpc.Code. sCode :: Lens' Status (Maybe Int32) sCode = lens _sCode (\ s a -> s{_sCode = a}) . mapping _Coerce -- | A developer-facing error message, which should be in English. Any -- user-facing error message should be localized and sent in the -- google.rpc.Status.details field, or localized by the client. sMessage :: Lens' Status (Maybe Text) sMessage = lens _sMessage (\ s a -> s{_sMessage = a}) instance FromJSON Status where parseJSON = withObject "Status" (\ o -> Status' <$> (o .:? "details" .!= mempty) <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON Status where toJSON Status'{..} = object (catMaybes [("details" .=) <$> _sDetails, ("code" .=) <$> _sCode, ("message" .=) <$> _sMessage]) -- | Response to a request to list policies for a given enterprise. -- -- /See:/ 'listPoliciesResponse' smart constructor. data ListPoliciesResponse = ListPoliciesResponse' { _lprNextPageToken :: !(Maybe Text) , _lprPolicies :: !(Maybe [Policy]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListPoliciesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lprNextPageToken' -- -- * 'lprPolicies' listPoliciesResponse :: ListPoliciesResponse listPoliciesResponse = ListPoliciesResponse' {_lprNextPageToken = Nothing, _lprPolicies = Nothing} -- | If there are more results, a token to retrieve next page of results. lprNextPageToken :: Lens' ListPoliciesResponse (Maybe Text) lprNextPageToken = lens _lprNextPageToken (\ s a -> s{_lprNextPageToken = a}) -- | The list of policies. lprPolicies :: Lens' ListPoliciesResponse [Policy] lprPolicies = lens _lprPolicies (\ s a -> s{_lprPolicies = a}) . _Default . _Coerce instance FromJSON ListPoliciesResponse where parseJSON = withObject "ListPoliciesResponse" (\ o -> ListPoliciesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "policies" .!= mempty)) instance ToJSON ListPoliciesResponse where toJSON ListPoliciesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lprNextPageToken, ("policies" .=) <$> _lprPolicies]) -- | Information about device memory and storage. -- -- /See:/ 'memoryInfo' smart constructor. data MemoryInfo = MemoryInfo' { _miTotalInternalStorage :: !(Maybe (Textual Int64)) , _miTotalRam :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MemoryInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'miTotalInternalStorage' -- -- * 'miTotalRam' memoryInfo :: MemoryInfo memoryInfo = MemoryInfo' {_miTotalInternalStorage = Nothing, _miTotalRam = Nothing} -- | Total internal storage on device in bytes. miTotalInternalStorage :: Lens' MemoryInfo (Maybe Int64) miTotalInternalStorage = lens _miTotalInternalStorage (\ s a -> s{_miTotalInternalStorage = a}) . mapping _Coerce -- | Total RAM on device in bytes. miTotalRam :: Lens' MemoryInfo (Maybe Int64) miTotalRam = lens _miTotalRam (\ s a -> s{_miTotalRam = a}) . mapping _Coerce instance FromJSON MemoryInfo where parseJSON = withObject "MemoryInfo" (\ o -> MemoryInfo' <$> (o .:? "totalInternalStorage") <*> (o .:? "totalRam")) instance ToJSON MemoryInfo where toJSON MemoryInfo'{..} = object (catMaybes [("totalInternalStorage" .=) <$> _miTotalInternalStorage, ("totalRam" .=) <$> _miTotalRam]) -- | A list of package names. -- -- /See:/ 'packageNameList' smart constructor. newtype PackageNameList = PackageNameList' { _pnlPackageNames :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PackageNameList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pnlPackageNames' packageNameList :: PackageNameList packageNameList = PackageNameList' {_pnlPackageNames = Nothing} -- | A list of package names. pnlPackageNames :: Lens' PackageNameList [Text] pnlPackageNames = lens _pnlPackageNames (\ s a -> s{_pnlPackageNames = a}) . _Default . _Coerce instance FromJSON PackageNameList where parseJSON = withObject "PackageNameList" (\ o -> PackageNameList' <$> (o .:? "packageNames" .!= mempty)) instance ToJSON PackageNameList where toJSON PackageNameList'{..} = object (catMaybes [("packageNames" .=) <$> _pnlPackageNames]) -- | A command. -- -- /See:/ 'command' smart constructor. data Command = Command' { _cResetPasswordFlags :: !(Maybe [CommandResetPasswordFlagsItem]) , _cNewPassword :: !(Maybe Text) , _cUserName :: !(Maybe Text) , _cErrorCode :: !(Maybe CommandErrorCode) , _cType :: !(Maybe CommandType) , _cDuration :: !(Maybe GDuration) , _cCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Command' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cResetPasswordFlags' -- -- * 'cNewPassword' -- -- * 'cUserName' -- -- * 'cErrorCode' -- -- * 'cType' -- -- * 'cDuration' -- -- * 'cCreateTime' command :: Command command = Command' { _cResetPasswordFlags = Nothing , _cNewPassword = Nothing , _cUserName = Nothing , _cErrorCode = Nothing , _cType = Nothing , _cDuration = Nothing , _cCreateTime = Nothing } -- | For commands of type RESET_PASSWORD, optionally specifies flags. cResetPasswordFlags :: Lens' Command [CommandResetPasswordFlagsItem] cResetPasswordFlags = lens _cResetPasswordFlags (\ s a -> s{_cResetPasswordFlags = a}) . _Default . _Coerce -- | For commands of type RESET_PASSWORD, optionally specifies the new -- password. cNewPassword :: Lens' Command (Maybe Text) cNewPassword = lens _cNewPassword (\ s a -> s{_cNewPassword = a}) -- | The resource name of the user that owns the device in the form -- enterprises\/{enterpriseId}\/users\/{userId}. This is automatically -- generated by the server based on the device the command is sent to. cUserName :: Lens' Command (Maybe Text) cUserName = lens _cUserName (\ s a -> s{_cUserName = a}) -- | If the command failed, an error code explaining the failure. This is not -- set when the command is cancelled by the caller. cErrorCode :: Lens' Command (Maybe CommandErrorCode) cErrorCode = lens _cErrorCode (\ s a -> s{_cErrorCode = a}) -- | The type of the command. cType :: Lens' Command (Maybe CommandType) cType = lens _cType (\ s a -> s{_cType = a}) -- | The duration for which the command is valid. The command will expire if -- not executed by the device during this time. The default duration if -- unspecified is ten minutes. There is no maximum duration. cDuration :: Lens' Command (Maybe Scientific) cDuration = lens _cDuration (\ s a -> s{_cDuration = a}) . mapping _GDuration -- | The timestamp at which the command was created. The timestamp is -- automatically generated by the server. cCreateTime :: Lens' Command (Maybe UTCTime) cCreateTime = lens _cCreateTime (\ s a -> s{_cCreateTime = a}) . mapping _DateTime instance FromJSON Command where parseJSON = withObject "Command" (\ o -> Command' <$> (o .:? "resetPasswordFlags" .!= mempty) <*> (o .:? "newPassword") <*> (o .:? "userName") <*> (o .:? "errorCode") <*> (o .:? "type") <*> (o .:? "duration") <*> (o .:? "createTime")) instance ToJSON Command where toJSON Command'{..} = object (catMaybes [("resetPasswordFlags" .=) <$> _cResetPasswordFlags, ("newPassword" .=) <$> _cNewPassword, ("userName" .=) <$> _cUserName, ("errorCode" .=) <$> _cErrorCode, ("type" .=) <$> _cType, ("duration" .=) <$> _cDuration, ("createTime" .=) <$> _cCreateTime]) -- | The response message for Operations.ListOperations. -- -- /See:/ 'listOperationsResponse' smart constructor. data ListOperationsResponse = ListOperationsResponse' { _lorNextPageToken :: !(Maybe Text) , _lorOperations :: !(Maybe [Operation]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lorNextPageToken' -- -- * 'lorOperations' listOperationsResponse :: ListOperationsResponse listOperationsResponse = ListOperationsResponse' {_lorNextPageToken = Nothing, _lorOperations = Nothing} -- | The standard List next-page token. lorNextPageToken :: Lens' ListOperationsResponse (Maybe Text) lorNextPageToken = lens _lorNextPageToken (\ s a -> s{_lorNextPageToken = a}) -- | A list of operations that matches the specified filter in the request. lorOperations :: Lens' ListOperationsResponse [Operation] lorOperations = lens _lorOperations (\ s a -> s{_lorOperations = a}) . _Default . _Coerce instance FromJSON ListOperationsResponse where parseJSON = withObject "ListOperationsResponse" (\ o -> ListOperationsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "operations" .!= mempty)) instance ToJSON ListOperationsResponse where toJSON ListOperationsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lorNextPageToken, ("operations" .=) <$> _lorOperations]) -- | Device display information. -- -- /See:/ 'display' smart constructor. data Display = Display' { _dHeight :: !(Maybe (Textual Int32)) , _dState :: !(Maybe DisplayState) , _dWidth :: !(Maybe (Textual Int32)) , _dName :: !(Maybe Text) , _dRefreshRate :: !(Maybe (Textual Int32)) , _dDisplayId :: !(Maybe (Textual Int32)) , _dDensity :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Display' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dHeight' -- -- * 'dState' -- -- * 'dWidth' -- -- * 'dName' -- -- * 'dRefreshRate' -- -- * 'dDisplayId' -- -- * 'dDensity' display :: Display display = Display' { _dHeight = Nothing , _dState = Nothing , _dWidth = Nothing , _dName = Nothing , _dRefreshRate = Nothing , _dDisplayId = Nothing , _dDensity = Nothing } -- | Display height in pixels. dHeight :: Lens' Display (Maybe Int32) dHeight = lens _dHeight (\ s a -> s{_dHeight = a}) . mapping _Coerce -- | State of the display. dState :: Lens' Display (Maybe DisplayState) dState = lens _dState (\ s a -> s{_dState = a}) -- | Display width in pixels. dWidth :: Lens' Display (Maybe Int32) dWidth = lens _dWidth (\ s a -> s{_dWidth = a}) . mapping _Coerce -- | Name of the display. dName :: Lens' Display (Maybe Text) dName = lens _dName (\ s a -> s{_dName = a}) -- | Refresh rate of the display in frames per second. dRefreshRate :: Lens' Display (Maybe Int32) dRefreshRate = lens _dRefreshRate (\ s a -> s{_dRefreshRate = a}) . mapping _Coerce -- | Unique display id. dDisplayId :: Lens' Display (Maybe Int32) dDisplayId = lens _dDisplayId (\ s a -> s{_dDisplayId = a}) . mapping _Coerce -- | Display density expressed as dots-per-inch. dDensity :: Lens' Display (Maybe Int32) dDensity = lens _dDensity (\ s a -> s{_dDensity = a}) . mapping _Coerce instance FromJSON Display where parseJSON = withObject "Display" (\ o -> Display' <$> (o .:? "height") <*> (o .:? "state") <*> (o .:? "width") <*> (o .:? "name") <*> (o .:? "refreshRate") <*> (o .:? "displayId") <*> (o .:? "density")) instance ToJSON Display where toJSON Display'{..} = object (catMaybes [("height" .=) <$> _dHeight, ("state" .=) <$> _dState, ("width" .=) <$> _dWidth, ("name" .=) <$> _dName, ("refreshRate" .=) <$> _dRefreshRate, ("displayId" .=) <$> _dDisplayId, ("density" .=) <$> _dDensity]) -- | Configuration for an always-on VPN connection. -- -- /See:/ 'alwaysOnVPNPackage' smart constructor. data AlwaysOnVPNPackage = AlwaysOnVPNPackage' { _aovpLockdownEnabled :: !(Maybe Bool) , _aovpPackageName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AlwaysOnVPNPackage' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aovpLockdownEnabled' -- -- * 'aovpPackageName' alwaysOnVPNPackage :: AlwaysOnVPNPackage alwaysOnVPNPackage = AlwaysOnVPNPackage' {_aovpLockdownEnabled = Nothing, _aovpPackageName = Nothing} -- | Disallows networking when the VPN is not connected. aovpLockdownEnabled :: Lens' AlwaysOnVPNPackage (Maybe Bool) aovpLockdownEnabled = lens _aovpLockdownEnabled (\ s a -> s{_aovpLockdownEnabled = a}) -- | The package name of the VPN app. aovpPackageName :: Lens' AlwaysOnVPNPackage (Maybe Text) aovpPackageName = lens _aovpPackageName (\ s a -> s{_aovpPackageName = a}) instance FromJSON AlwaysOnVPNPackage where parseJSON = withObject "AlwaysOnVPNPackage" (\ o -> AlwaysOnVPNPackage' <$> (o .:? "lockdownEnabled") <*> (o .:? "packageName")) instance ToJSON AlwaysOnVPNPackage where toJSON AlwaysOnVPNPackage'{..} = object (catMaybes [("lockdownEnabled" .=) <$> _aovpLockdownEnabled, ("packageName" .=) <$> _aovpPackageName]) -- | Network configuration for the device. See configure networks for more -- information. -- -- /See:/ 'policyOpenNetworkConfiguration' smart constructor. newtype PolicyOpenNetworkConfiguration = PolicyOpenNetworkConfiguration' { _poncAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PolicyOpenNetworkConfiguration' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'poncAddtional' policyOpenNetworkConfiguration :: HashMap Text JSONValue -- ^ 'poncAddtional' -> PolicyOpenNetworkConfiguration policyOpenNetworkConfiguration pPoncAddtional_ = PolicyOpenNetworkConfiguration' {_poncAddtional = _Coerce # pPoncAddtional_} -- | Properties of the object. poncAddtional :: Lens' PolicyOpenNetworkConfiguration (HashMap Text JSONValue) poncAddtional = lens _poncAddtional (\ s a -> s{_poncAddtional = a}) . _Coerce instance FromJSON PolicyOpenNetworkConfiguration where parseJSON = withObject "PolicyOpenNetworkConfiguration" (\ o -> PolicyOpenNetworkConfiguration' <$> (parseJSONObject o)) instance ToJSON PolicyOpenNetworkConfiguration where toJSON = toJSON . _poncAddtional -- | An action to launch an app. -- -- /See:/ 'launchAppAction' smart constructor. newtype LaunchAppAction = LaunchAppAction' { _laaPackageName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LaunchAppAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'laaPackageName' launchAppAction :: LaunchAppAction launchAppAction = LaunchAppAction' {_laaPackageName = Nothing} -- | Package name of app to be launched laaPackageName :: Lens' LaunchAppAction (Maybe Text) laaPackageName = lens _laaPackageName (\ s a -> s{_laaPackageName = a}) instance FromJSON LaunchAppAction where parseJSON = withObject "LaunchAppAction" (\ o -> LaunchAppAction' <$> (o .:? "packageName")) instance ToJSON LaunchAppAction where toJSON LaunchAppAction'{..} = object (catMaybes [("packageName" .=) <$> _laaPackageName]) -- | A rule that defines the actions to take if a device or work profile is -- not compliant with the policy specified in settingName. -- -- /See:/ 'policyEnforcementRule' smart constructor. data PolicyEnforcementRule = PolicyEnforcementRule' { _perWipeAction :: !(Maybe WipeAction) , _perSettingName :: !(Maybe Text) , _perBlockAction :: !(Maybe BlockAction) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PolicyEnforcementRule' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'perWipeAction' -- -- * 'perSettingName' -- -- * 'perBlockAction' policyEnforcementRule :: PolicyEnforcementRule policyEnforcementRule = PolicyEnforcementRule' { _perWipeAction = Nothing , _perSettingName = Nothing , _perBlockAction = Nothing } -- | An action to reset a fully managed device or delete a work profile. -- Note: blockAction must also be specified. perWipeAction :: Lens' PolicyEnforcementRule (Maybe WipeAction) perWipeAction = lens _perWipeAction (\ s a -> s{_perWipeAction = a}) -- | The top-level policy to enforce. For example, applications or -- passwordPolicies. perSettingName :: Lens' PolicyEnforcementRule (Maybe Text) perSettingName = lens _perSettingName (\ s a -> s{_perSettingName = a}) -- | An action to block access to apps and data on a fully managed device or -- in a work profile. This action also triggers a user-facing notification -- with information (where possible) on how to correct the compliance -- issue. Note: wipeAction must also be specified. perBlockAction :: Lens' PolicyEnforcementRule (Maybe BlockAction) perBlockAction = lens _perBlockAction (\ s a -> s{_perBlockAction = a}) instance FromJSON PolicyEnforcementRule where parseJSON = withObject "PolicyEnforcementRule" (\ o -> PolicyEnforcementRule' <$> (o .:? "wipeAction") <*> (o .:? "settingName") <*> (o .:? "blockAction")) instance ToJSON PolicyEnforcementRule where toJSON PolicyEnforcementRule'{..} = object (catMaybes [("wipeAction" .=) <$> _perWipeAction, ("settingName" .=) <$> _perSettingName, ("blockAction" .=) <$> _perBlockAction]) -- | Hardware status. Temperatures may be compared to the temperature -- thresholds available in hardwareInfo to determine hardware health. -- -- /See:/ 'hardwareStatus' smart constructor. data HardwareStatus = HardwareStatus' { _hsCPUTemperatures :: !(Maybe [Textual Double]) , _hsBatteryTemperatures :: !(Maybe [Textual Double]) , _hsGpuTemperatures :: !(Maybe [Textual Double]) , _hsFanSpeeds :: !(Maybe [Textual Double]) , _hsSkinTemperatures :: !(Maybe [Textual Double]) , _hsCPUUsages :: !(Maybe [Textual Double]) , _hsCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HardwareStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hsCPUTemperatures' -- -- * 'hsBatteryTemperatures' -- -- * 'hsGpuTemperatures' -- -- * 'hsFanSpeeds' -- -- * 'hsSkinTemperatures' -- -- * 'hsCPUUsages' -- -- * 'hsCreateTime' hardwareStatus :: HardwareStatus hardwareStatus = HardwareStatus' { _hsCPUTemperatures = Nothing , _hsBatteryTemperatures = Nothing , _hsGpuTemperatures = Nothing , _hsFanSpeeds = Nothing , _hsSkinTemperatures = Nothing , _hsCPUUsages = Nothing , _hsCreateTime = Nothing } -- | Current CPU temperatures in Celsius for each CPU on the device. hsCPUTemperatures :: Lens' HardwareStatus [Double] hsCPUTemperatures = lens _hsCPUTemperatures (\ s a -> s{_hsCPUTemperatures = a}) . _Default . _Coerce -- | Current battery temperatures in Celsius for each battery on the device. hsBatteryTemperatures :: Lens' HardwareStatus [Double] hsBatteryTemperatures = lens _hsBatteryTemperatures (\ s a -> s{_hsBatteryTemperatures = a}) . _Default . _Coerce -- | Current GPU temperatures in Celsius for each GPU on the device. hsGpuTemperatures :: Lens' HardwareStatus [Double] hsGpuTemperatures = lens _hsGpuTemperatures (\ s a -> s{_hsGpuTemperatures = a}) . _Default . _Coerce -- | Fan speeds in RPM for each fan on the device. Empty array means that -- there are no fans or fan speed is not supported on the system. hsFanSpeeds :: Lens' HardwareStatus [Double] hsFanSpeeds = lens _hsFanSpeeds (\ s a -> s{_hsFanSpeeds = a}) . _Default . _Coerce -- | Current device skin temperatures in Celsius. hsSkinTemperatures :: Lens' HardwareStatus [Double] hsSkinTemperatures = lens _hsSkinTemperatures (\ s a -> s{_hsSkinTemperatures = a}) . _Default . _Coerce -- | CPU usages in percentage for each core available on the device. Usage is -- 0 for each unplugged core. Empty array implies that CPU usage is not -- supported in the system. hsCPUUsages :: Lens' HardwareStatus [Double] hsCPUUsages = lens _hsCPUUsages (\ s a -> s{_hsCPUUsages = a}) . _Default . _Coerce -- | The time the measurements were taken. hsCreateTime :: Lens' HardwareStatus (Maybe UTCTime) hsCreateTime = lens _hsCreateTime (\ s a -> s{_hsCreateTime = a}) . mapping _DateTime instance FromJSON HardwareStatus where parseJSON = withObject "HardwareStatus" (\ o -> HardwareStatus' <$> (o .:? "cpuTemperatures" .!= mempty) <*> (o .:? "batteryTemperatures" .!= mempty) <*> (o .:? "gpuTemperatures" .!= mempty) <*> (o .:? "fanSpeeds" .!= mempty) <*> (o .:? "skinTemperatures" .!= mempty) <*> (o .:? "cpuUsages" .!= mempty) <*> (o .:? "createTime")) instance ToJSON HardwareStatus where toJSON HardwareStatus'{..} = object (catMaybes [("cpuTemperatures" .=) <$> _hsCPUTemperatures, ("batteryTemperatures" .=) <$> _hsBatteryTemperatures, ("gpuTemperatures" .=) <$> _hsGpuTemperatures, ("fanSpeeds" .=) <$> _hsFanSpeeds, ("skinTemperatures" .=) <$> _hsSkinTemperatures, ("cpuUsages" .=) <$> _hsCPUUsages, ("createTime" .=) <$> _hsCreateTime]) -- | Information about an app. -- -- /See:/ 'application' smart constructor. data Application = Application' { _aAppTracks :: !(Maybe [AppTrackInfo]) , _aManagedProperties :: !(Maybe [ManagedProperty]) , _aName :: !(Maybe Text) , _aPermissions :: !(Maybe [ApplicationPermission]) , _aTitle :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Application' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aAppTracks' -- -- * 'aManagedProperties' -- -- * 'aName' -- -- * 'aPermissions' -- -- * 'aTitle' application :: Application application = Application' { _aAppTracks = Nothing , _aManagedProperties = Nothing , _aName = Nothing , _aPermissions = Nothing , _aTitle = Nothing } -- | Application tracks visible to the enterprise. aAppTracks :: Lens' Application [AppTrackInfo] aAppTracks = lens _aAppTracks (\ s a -> s{_aAppTracks = a}) . _Default . _Coerce -- | The set of managed properties available to be pre-configured for the -- app. aManagedProperties :: Lens' Application [ManagedProperty] aManagedProperties = lens _aManagedProperties (\ s a -> s{_aManagedProperties = a}) . _Default . _Coerce -- | The name of the app in the form -- enterprises\/{enterpriseId}\/applications\/{package_name}. aName :: Lens' Application (Maybe Text) aName = lens _aName (\ s a -> s{_aName = a}) -- | The permissions required by the app. aPermissions :: Lens' Application [ApplicationPermission] aPermissions = lens _aPermissions (\ s a -> s{_aPermissions = a}) . _Default . _Coerce -- | The title of the app. Localized. aTitle :: Lens' Application (Maybe Text) aTitle = lens _aTitle (\ s a -> s{_aTitle = a}) instance FromJSON Application where parseJSON = withObject "Application" (\ o -> Application' <$> (o .:? "appTracks" .!= mempty) <*> (o .:? "managedProperties" .!= mempty) <*> (o .:? "name") <*> (o .:? "permissions" .!= mempty) <*> (o .:? "title")) instance ToJSON Application where toJSON Application'{..} = object (catMaybes [("appTracks" .=) <$> _aAppTracks, ("managedProperties" .=) <$> _aManagedProperties, ("name" .=) <$> _aName, ("permissions" .=) <$> _aPermissions, ("title" .=) <$> _aTitle]) -- | Policies for apps in the personal profile of a company-owned device with -- a work profile. -- -- /See:/ 'personalApplicationPolicy' smart constructor. data PersonalApplicationPolicy = PersonalApplicationPolicy' { _papPackageName :: !(Maybe Text) , _papInstallType :: !(Maybe PersonalApplicationPolicyInstallType) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PersonalApplicationPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'papPackageName' -- -- * 'papInstallType' personalApplicationPolicy :: PersonalApplicationPolicy personalApplicationPolicy = PersonalApplicationPolicy' {_papPackageName = Nothing, _papInstallType = Nothing} -- | The package name of the application. papPackageName :: Lens' PersonalApplicationPolicy (Maybe Text) papPackageName = lens _papPackageName (\ s a -> s{_papPackageName = a}) -- | The type of installation to perform. papInstallType :: Lens' PersonalApplicationPolicy (Maybe PersonalApplicationPolicyInstallType) papInstallType = lens _papInstallType (\ s a -> s{_papInstallType = a}) instance FromJSON PersonalApplicationPolicy where parseJSON = withObject "PersonalApplicationPolicy" (\ o -> PersonalApplicationPolicy' <$> (o .:? "packageName") <*> (o .:? "installType")) instance ToJSON PersonalApplicationPolicy where toJSON PersonalApplicationPolicy'{..} = object (catMaybes [("packageName" .=) <$> _papPackageName, ("installType" .=) <$> _papInstallType]) -- | Managed property. -- -- /See:/ 'managedProperty' smart constructor. data ManagedProperty = ManagedProperty' { _mpEntries :: !(Maybe [ManagedPropertyEntry]) , _mpNestedProperties :: !(Maybe [ManagedProperty]) , _mpKey :: !(Maybe Text) , _mpDefaultValue :: !(Maybe JSONValue) , _mpTitle :: !(Maybe Text) , _mpType :: !(Maybe ManagedPropertyType) , _mpDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ManagedProperty' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mpEntries' -- -- * 'mpNestedProperties' -- -- * 'mpKey' -- -- * 'mpDefaultValue' -- -- * 'mpTitle' -- -- * 'mpType' -- -- * 'mpDescription' managedProperty :: ManagedProperty managedProperty = ManagedProperty' { _mpEntries = Nothing , _mpNestedProperties = Nothing , _mpKey = Nothing , _mpDefaultValue = Nothing , _mpTitle = Nothing , _mpType = Nothing , _mpDescription = Nothing } -- | For CHOICE or MULTISELECT properties, the list of possible entries. mpEntries :: Lens' ManagedProperty [ManagedPropertyEntry] mpEntries = lens _mpEntries (\ s a -> s{_mpEntries = a}) . _Default . _Coerce -- | For BUNDLE_ARRAY properties, the list of nested properties. A -- BUNDLE_ARRAY property is at most two levels deep. mpNestedProperties :: Lens' ManagedProperty [ManagedProperty] mpNestedProperties = lens _mpNestedProperties (\ s a -> s{_mpNestedProperties = a}) . _Default . _Coerce -- | The unique key that the app uses to identify the property, e.g. -- \"com.google.android.gm.fieldname\". mpKey :: Lens' ManagedProperty (Maybe Text) mpKey = lens _mpKey (\ s a -> s{_mpKey = a}) -- | The default value of the property. BUNDLE_ARRAY properties don\'t have a -- default value. mpDefaultValue :: Lens' ManagedProperty (Maybe JSONValue) mpDefaultValue = lens _mpDefaultValue (\ s a -> s{_mpDefaultValue = a}) -- | The name of the property. Localized. mpTitle :: Lens' ManagedProperty (Maybe Text) mpTitle = lens _mpTitle (\ s a -> s{_mpTitle = a}) -- | The type of the property. mpType :: Lens' ManagedProperty (Maybe ManagedPropertyType) mpType = lens _mpType (\ s a -> s{_mpType = a}) -- | A longer description of the property, providing more detail of what it -- affects. Localized. mpDescription :: Lens' ManagedProperty (Maybe Text) mpDescription = lens _mpDescription (\ s a -> s{_mpDescription = a}) instance FromJSON ManagedProperty where parseJSON = withObject "ManagedProperty" (\ o -> ManagedProperty' <$> (o .:? "entries" .!= mempty) <*> (o .:? "nestedProperties" .!= mempty) <*> (o .:? "key") <*> (o .:? "defaultValue") <*> (o .:? "title") <*> (o .:? "type") <*> (o .:? "description")) instance ToJSON ManagedProperty where toJSON ManagedProperty'{..} = object (catMaybes [("entries" .=) <$> _mpEntries, ("nestedProperties" .=) <$> _mpNestedProperties, ("key" .=) <$> _mpKey, ("defaultValue" .=) <$> _mpDefaultValue, ("title" .=) <$> _mpTitle, ("type" .=) <$> _mpType, ("description" .=) <$> _mpDescription]) -- | Configuration info for an HTTP proxy. For a direct proxy, set the host, -- port, and excluded_hosts fields. For a PAC script proxy, set the pac_uri -- field. -- -- /See:/ 'proxyInfo' smart constructor. data ProxyInfo = ProxyInfo' { _piPacURI :: !(Maybe Text) , _piHost :: !(Maybe Text) , _piExcludedHosts :: !(Maybe [Text]) , _piPort :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProxyInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'piPacURI' -- -- * 'piHost' -- -- * 'piExcludedHosts' -- -- * 'piPort' proxyInfo :: ProxyInfo proxyInfo = ProxyInfo' { _piPacURI = Nothing , _piHost = Nothing , _piExcludedHosts = Nothing , _piPort = Nothing } -- | The URI of the PAC script used to configure the proxy. piPacURI :: Lens' ProxyInfo (Maybe Text) piPacURI = lens _piPacURI (\ s a -> s{_piPacURI = a}) -- | The host of the direct proxy. piHost :: Lens' ProxyInfo (Maybe Text) piHost = lens _piHost (\ s a -> s{_piHost = a}) -- | For a direct proxy, the hosts for which the proxy is bypassed. The host -- names may contain wildcards such as *.example.com. piExcludedHosts :: Lens' ProxyInfo [Text] piExcludedHosts = lens _piExcludedHosts (\ s a -> s{_piExcludedHosts = a}) . _Default . _Coerce -- | The port of the direct proxy. piPort :: Lens' ProxyInfo (Maybe Int32) piPort = lens _piPort (\ s a -> s{_piPort = a}) . mapping _Coerce instance FromJSON ProxyInfo where parseJSON = withObject "ProxyInfo" (\ o -> ProxyInfo' <$> (o .:? "pacUri") <*> (o .:? "host") <*> (o .:? "excludedHosts" .!= mempty) <*> (o .:? "port")) instance ToJSON ProxyInfo where toJSON ProxyInfo'{..} = object (catMaybes [("pacUri" .=) <$> _piPacURI, ("host" .=) <$> _piHost, ("excludedHosts" .=) <$> _piExcludedHosts, ("port" .=) <$> _piPort]) -- | A default activity for handling intents that match a particular intent -- filter. Note: To set up a kiosk, use InstallType to KIOSK rather than -- use persistent preferred activities. -- -- /See:/ 'persistentPreferredActivity' smart constructor. data PersistentPreferredActivity = PersistentPreferredActivity' { _ppaActions :: !(Maybe [Text]) , _ppaCategories :: !(Maybe [Text]) , _ppaReceiverActivity :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PersistentPreferredActivity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ppaActions' -- -- * 'ppaCategories' -- -- * 'ppaReceiverActivity' persistentPreferredActivity :: PersistentPreferredActivity persistentPreferredActivity = PersistentPreferredActivity' { _ppaActions = Nothing , _ppaCategories = Nothing , _ppaReceiverActivity = Nothing } -- | The intent actions to match in the filter. If any actions are included -- in the filter, then an intent\'s action must be one of those values for -- it to match. If no actions are included, the intent action is ignored. ppaActions :: Lens' PersistentPreferredActivity [Text] ppaActions = lens _ppaActions (\ s a -> s{_ppaActions = a}) . _Default . _Coerce -- | The intent categories to match in the filter. An intent includes the -- categories that it requires, all of which must be included in the filter -- in order to match. In other words, adding a category to the filter has -- no impact on matching unless that category is specified in the intent. ppaCategories :: Lens' PersistentPreferredActivity [Text] ppaCategories = lens _ppaCategories (\ s a -> s{_ppaCategories = a}) . _Default . _Coerce -- | The activity that should be the default intent handler. This should be -- an Android component name, e.g. -- com.android.enterprise.app\/.MainActivity. Alternatively, the value may -- be the package name of an app, which causes Android Device Policy to -- choose an appropriate activity from the app to handle the intent. ppaReceiverActivity :: Lens' PersistentPreferredActivity (Maybe Text) ppaReceiverActivity = lens _ppaReceiverActivity (\ s a -> s{_ppaReceiverActivity = a}) instance FromJSON PersistentPreferredActivity where parseJSON = withObject "PersistentPreferredActivity" (\ o -> PersistentPreferredActivity' <$> (o .:? "actions" .!= mempty) <*> (o .:? "categories" .!= mempty) <*> (o .:? "receiverActivity")) instance ToJSON PersistentPreferredActivity where toJSON PersistentPreferredActivity'{..} = object (catMaybes [("actions" .=) <$> _ppaActions, ("categories" .=) <$> _ppaCategories, ("receiverActivity" .=) <$> _ppaReceiverActivity]) -- | This resource represents a long-running operation that is the result of -- a network API call. -- -- /See:/ 'operation' smart constructor. data Operation = Operation' { _oDone :: !(Maybe Bool) , _oError :: !(Maybe Status) , _oResponse :: !(Maybe OperationResponse) , _oName :: !(Maybe Text) , _oMetadata :: !(Maybe OperationMetadata) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Operation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oDone' -- -- * 'oError' -- -- * 'oResponse' -- -- * 'oName' -- -- * 'oMetadata' operation :: Operation operation = Operation' { _oDone = Nothing , _oError = Nothing , _oResponse = Nothing , _oName = Nothing , _oMetadata = Nothing } -- | If the value is false, it means the operation is still in progress. If -- true, the operation is completed, and either error or response is -- available. oDone :: Lens' Operation (Maybe Bool) oDone = lens _oDone (\ s a -> s{_oDone = a}) -- | The error result of the operation in case of failure or cancellation. oError :: Lens' Operation (Maybe Status) oError = lens _oError (\ s a -> s{_oError = a}) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as Delete, the response is -- google.protobuf.Empty. If the original method is standard -- Get\/Create\/Update, the response should be the resource. For other -- methods, the response should have the type XxxResponse, where Xxx is the -- original method name. For example, if the original method name is -- TakeSnapshot(), the inferred response type is TakeSnapshotResponse. oResponse :: Lens' Operation (Maybe OperationResponse) oResponse = lens _oResponse (\ s a -> s{_oResponse = a}) -- | The server-assigned name, which is only unique within the same service -- that originally returns it. If you use the default HTTP mapping, the -- name should be a resource name ending with operations\/{unique_id}. oName :: Lens' Operation (Maybe Text) oName = lens _oName (\ s a -> s{_oName = a}) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. oMetadata :: Lens' Operation (Maybe OperationMetadata) oMetadata = lens _oMetadata (\ s a -> s{_oMetadata = a}) instance FromJSON Operation where parseJSON = withObject "Operation" (\ o -> Operation' <$> (o .:? "done") <*> (o .:? "error") <*> (o .:? "response") <*> (o .:? "name") <*> (o .:? "metadata")) instance ToJSON Operation where toJSON Operation'{..} = object (catMaybes [("done" .=) <$> _oDone, ("error" .=) <$> _oError, ("response" .=) <$> _oResponse, ("name" .=) <$> _oName, ("metadata" .=) <$> _oMetadata]) -- | A generic empty message that you can re-use to avoid defining duplicated -- empty messages in your APIs. A typical example is to use it as the -- request or the response type of an API method. For instance: service Foo -- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The -- JSON representation for Empty is empty JSON object {}. -- -- /See:/ 'empty' smart constructor. data Empty = Empty' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Empty' with the minimum fields required to make a request. -- empty :: Empty empty = Empty' instance FromJSON Empty where parseJSON = withObject "Empty" (\ o -> pure Empty') instance ToJSON Empty where toJSON = const emptyObject -- | Data hosted at an external location. The data is to be downloaded by -- Android Device Policy and verified against the hash. -- -- /See:/ 'externalData' smart constructor. data ExternalData = ExternalData' { _edURL :: !(Maybe Text) , _edSha256Hash :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ExternalData' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'edURL' -- -- * 'edSha256Hash' externalData :: ExternalData externalData = ExternalData' {_edURL = Nothing, _edSha256Hash = Nothing} -- | The absolute URL to the data, which must use either the http or https -- scheme. Android Device Policy doesn\'t provide any credentials in the -- GET request, so the URL must be publicly accessible. Including a long, -- random component in the URL may be used to prevent attackers from -- discovering the URL. edURL :: Lens' ExternalData (Maybe Text) edURL = lens _edURL (\ s a -> s{_edURL = a}) -- | The base-64 encoded SHA-256 hash of the content hosted at url. If the -- content doesn\'t match this hash, Android Device Policy won\'t use the -- data. edSha256Hash :: Lens' ExternalData (Maybe Text) edSha256Hash = lens _edSha256Hash (\ s a -> s{_edSha256Hash = a}) instance FromJSON ExternalData where parseJSON = withObject "ExternalData" (\ o -> ExternalData' <$> (o .:? "url") <*> (o .:? "sha256Hash")) instance ToJSON ExternalData where toJSON ExternalData'{..} = object (catMaybes [("url" .=) <$> _edURL, ("sha256Hash" .=) <$> _edSha256Hash]) -- | A compliance rule condition which is satisfied if the Android Framework -- API level on the device doesn\'t meet a minimum requirement. There can -- only be one rule with this type of condition per policy. -- -- /See:/ 'apiLevelCondition' smart constructor. newtype APILevelCondition = APILevelCondition' { _alcMinAPILevel :: Maybe (Textual Int32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'APILevelCondition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alcMinAPILevel' apiLevelCondition :: APILevelCondition apiLevelCondition = APILevelCondition' {_alcMinAPILevel = Nothing} -- | The minimum desired Android Framework API level. If the device doesn\'t -- meet the minimum requirement, this condition is satisfied. Must be -- greater than zero. alcMinAPILevel :: Lens' APILevelCondition (Maybe Int32) alcMinAPILevel = lens _alcMinAPILevel (\ s a -> s{_alcMinAPILevel = a}) . mapping _Coerce instance FromJSON APILevelCondition where parseJSON = withObject "APILevelCondition" (\ o -> APILevelCondition' <$> (o .:? "minApiLevel")) instance ToJSON APILevelCondition where toJSON APILevelCondition'{..} = object (catMaybes [("minApiLevel" .=) <$> _alcMinAPILevel]) -- | Response on issuing a command. This is currently empty as a placeholder. -- -- /See:/ 'issueCommandResponse' smart constructor. data IssueCommandResponse = IssueCommandResponse' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'IssueCommandResponse' with the minimum fields required to make a request. -- issueCommandResponse :: IssueCommandResponse issueCommandResponse = IssueCommandResponse' instance FromJSON IssueCommandResponse where parseJSON = withObject "IssueCommandResponse" (\ o -> pure IssueCommandResponse') instance ToJSON IssueCommandResponse where toJSON = const emptyObject -- | Information about security related device settings on device. -- -- /See:/ 'deviceSettings' smart constructor. data DeviceSettings = DeviceSettings' { _dsIsEncrypted :: !(Maybe Bool) , _dsAdbEnabled :: !(Maybe Bool) , _dsIsDeviceSecure :: !(Maybe Bool) , _dsVerifyAppsEnabled :: !(Maybe Bool) , _dsDevelopmentSettingsEnabled :: !(Maybe Bool) , _dsEncryptionStatus :: !(Maybe DeviceSettingsEncryptionStatus) , _dsUnknownSourcesEnabled :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DeviceSettings' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dsIsEncrypted' -- -- * 'dsAdbEnabled' -- -- * 'dsIsDeviceSecure' -- -- * 'dsVerifyAppsEnabled' -- -- * 'dsDevelopmentSettingsEnabled' -- -- * 'dsEncryptionStatus' -- -- * 'dsUnknownSourcesEnabled' deviceSettings :: DeviceSettings deviceSettings = DeviceSettings' { _dsIsEncrypted = Nothing , _dsAdbEnabled = Nothing , _dsIsDeviceSecure = Nothing , _dsVerifyAppsEnabled = Nothing , _dsDevelopmentSettingsEnabled = Nothing , _dsEncryptionStatus = Nothing , _dsUnknownSourcesEnabled = Nothing } -- | Whether the storage encryption is enabled. dsIsEncrypted :: Lens' DeviceSettings (Maybe Bool) dsIsEncrypted = lens _dsIsEncrypted (\ s a -> s{_dsIsEncrypted = a}) -- | Whether ADB -- (https:\/\/developer.android.com\/studio\/command-line\/adb.html) is -- enabled on the device. dsAdbEnabled :: Lens' DeviceSettings (Maybe Bool) dsAdbEnabled = lens _dsAdbEnabled (\ s a -> s{_dsAdbEnabled = a}) -- | Whether the device is secured with PIN\/password. dsIsDeviceSecure :: Lens' DeviceSettings (Maybe Bool) dsIsDeviceSecure = lens _dsIsDeviceSecure (\ s a -> s{_dsIsDeviceSecure = a}) -- | Whether Google Play Protect verification -- (https:\/\/support.google.com\/accounts\/answer\/2812853) is enforced on -- the device. dsVerifyAppsEnabled :: Lens' DeviceSettings (Maybe Bool) dsVerifyAppsEnabled = lens _dsVerifyAppsEnabled (\ s a -> s{_dsVerifyAppsEnabled = a}) -- | Whether developer mode is enabled on the device. dsDevelopmentSettingsEnabled :: Lens' DeviceSettings (Maybe Bool) dsDevelopmentSettingsEnabled = lens _dsDevelopmentSettingsEnabled (\ s a -> s{_dsDevelopmentSettingsEnabled = a}) -- | Encryption status from DevicePolicyManager. dsEncryptionStatus :: Lens' DeviceSettings (Maybe DeviceSettingsEncryptionStatus) dsEncryptionStatus = lens _dsEncryptionStatus (\ s a -> s{_dsEncryptionStatus = a}) -- | Whether installing apps from unknown sources is enabled. dsUnknownSourcesEnabled :: Lens' DeviceSettings (Maybe Bool) dsUnknownSourcesEnabled = lens _dsUnknownSourcesEnabled (\ s a -> s{_dsUnknownSourcesEnabled = a}) instance FromJSON DeviceSettings where parseJSON = withObject "DeviceSettings" (\ o -> DeviceSettings' <$> (o .:? "isEncrypted") <*> (o .:? "adbEnabled") <*> (o .:? "isDeviceSecure") <*> (o .:? "verifyAppsEnabled") <*> (o .:? "developmentSettingsEnabled") <*> (o .:? "encryptionStatus") <*> (o .:? "unknownSourcesEnabled")) instance ToJSON DeviceSettings where toJSON DeviceSettings'{..} = object (catMaybes [("isEncrypted" .=) <$> _dsIsEncrypted, ("adbEnabled" .=) <$> _dsAdbEnabled, ("isDeviceSecure" .=) <$> _dsIsDeviceSecure, ("verifyAppsEnabled" .=) <$> _dsVerifyAppsEnabled, ("developmentSettingsEnabled" .=) <$> _dsDevelopmentSettingsEnabled, ("encryptionStatus" .=) <$> _dsEncryptionStatus, ("unknownSourcesEnabled" .=) <$> _dsUnknownSourcesEnabled]) -- | An action to reset a fully managed device or delete a work profile. -- Note: blockAction must also be specified. -- -- /See:/ 'wipeAction' smart constructor. data WipeAction = WipeAction' { _waWipeAfterDays :: !(Maybe (Textual Int32)) , _waPreserveFrp :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WipeAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'waWipeAfterDays' -- -- * 'waPreserveFrp' wipeAction :: WipeAction wipeAction = WipeAction' {_waWipeAfterDays = Nothing, _waPreserveFrp = Nothing} -- | Number of days the policy is non-compliant before the device or work -- profile is wiped. wipeAfterDays must be greater than blockAfterDays. waWipeAfterDays :: Lens' WipeAction (Maybe Int32) waWipeAfterDays = lens _waWipeAfterDays (\ s a -> s{_waWipeAfterDays = a}) . mapping _Coerce -- | Whether the factory-reset protection data is preserved on the device. -- This setting doesn’t apply to work profiles. waPreserveFrp :: Lens' WipeAction (Maybe Bool) waPreserveFrp = lens _waPreserveFrp (\ s a -> s{_waPreserveFrp = a}) instance FromJSON WipeAction where parseJSON = withObject "WipeAction" (\ o -> WipeAction' <$> (o .:? "wipeAfterDays") <*> (o .:? "preserveFrp")) instance ToJSON WipeAction where toJSON WipeAction'{..} = object (catMaybes [("wipeAfterDays" .=) <$> _waWipeAfterDays, ("preserveFrp" .=) <$> _waPreserveFrp]) -- | Optional, a map containing configuration variables defined for the -- configuration. -- -- /See:/ 'managedConfigurationTemplateConfigurationVariables' smart constructor. newtype ManagedConfigurationTemplateConfigurationVariables = ManagedConfigurationTemplateConfigurationVariables' { _mctcvAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ManagedConfigurationTemplateConfigurationVariables' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mctcvAddtional' managedConfigurationTemplateConfigurationVariables :: HashMap Text Text -- ^ 'mctcvAddtional' -> ManagedConfigurationTemplateConfigurationVariables managedConfigurationTemplateConfigurationVariables pMctcvAddtional_ = ManagedConfigurationTemplateConfigurationVariables' {_mctcvAddtional = _Coerce # pMctcvAddtional_} mctcvAddtional :: Lens' ManagedConfigurationTemplateConfigurationVariables (HashMap Text Text) mctcvAddtional = lens _mctcvAddtional (\ s a -> s{_mctcvAddtional = a}) . _Coerce instance FromJSON ManagedConfigurationTemplateConfigurationVariables where parseJSON = withObject "ManagedConfigurationTemplateConfigurationVariables" (\ o -> ManagedConfigurationTemplateConfigurationVariables' <$> (parseJSONObject o)) instance ToJSON ManagedConfigurationTemplateConfigurationVariables where toJSON = toJSON . _mctcvAddtional -- | Information about device hardware. The fields related to temperature -- thresholds are only available if hardwareStatusEnabled is true in the -- device\'s policy. -- -- /See:/ 'hardwareInfo' smart constructor. data HardwareInfo = HardwareInfo' { _hiCPUThrottlingTemperatures :: !(Maybe [Textual Double]) , _hiManufacturer :: !(Maybe Text) , _hiBrand :: !(Maybe Text) , _hiCPUShutdownTemperatures :: !(Maybe [Textual Double]) , _hiBatteryThrottlingTemperatures :: !(Maybe [Textual Double]) , _hiModel :: !(Maybe Text) , _hiBatteryShutdownTemperatures :: !(Maybe [Textual Double]) , _hiSkinThrottlingTemperatures :: !(Maybe [Textual Double]) , _hiGpuShutdownTemperatures :: !(Maybe [Textual Double]) , _hiGpuThrottlingTemperatures :: !(Maybe [Textual Double]) , _hiSkinShutdownTemperatures :: !(Maybe [Textual Double]) , _hiSerialNumber :: !(Maybe Text) , _hiDeviceBasebandVersion :: !(Maybe Text) , _hiHardware :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HardwareInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hiCPUThrottlingTemperatures' -- -- * 'hiManufacturer' -- -- * 'hiBrand' -- -- * 'hiCPUShutdownTemperatures' -- -- * 'hiBatteryThrottlingTemperatures' -- -- * 'hiModel' -- -- * 'hiBatteryShutdownTemperatures' -- -- * 'hiSkinThrottlingTemperatures' -- -- * 'hiGpuShutdownTemperatures' -- -- * 'hiGpuThrottlingTemperatures' -- -- * 'hiSkinShutdownTemperatures' -- -- * 'hiSerialNumber' -- -- * 'hiDeviceBasebandVersion' -- -- * 'hiHardware' hardwareInfo :: HardwareInfo hardwareInfo = HardwareInfo' { _hiCPUThrottlingTemperatures = Nothing , _hiManufacturer = Nothing , _hiBrand = Nothing , _hiCPUShutdownTemperatures = Nothing , _hiBatteryThrottlingTemperatures = Nothing , _hiModel = Nothing , _hiBatteryShutdownTemperatures = Nothing , _hiSkinThrottlingTemperatures = Nothing , _hiGpuShutdownTemperatures = Nothing , _hiGpuThrottlingTemperatures = Nothing , _hiSkinShutdownTemperatures = Nothing , _hiSerialNumber = Nothing , _hiDeviceBasebandVersion = Nothing , _hiHardware = Nothing } -- | CPU throttling temperature thresholds in Celsius for each CPU on the -- device. hiCPUThrottlingTemperatures :: Lens' HardwareInfo [Double] hiCPUThrottlingTemperatures = lens _hiCPUThrottlingTemperatures (\ s a -> s{_hiCPUThrottlingTemperatures = a}) . _Default . _Coerce -- | Manufacturer. For example, Motorola. hiManufacturer :: Lens' HardwareInfo (Maybe Text) hiManufacturer = lens _hiManufacturer (\ s a -> s{_hiManufacturer = a}) -- | Brand of the device. For example, Google. hiBrand :: Lens' HardwareInfo (Maybe Text) hiBrand = lens _hiBrand (\ s a -> s{_hiBrand = a}) -- | CPU shutdown temperature thresholds in Celsius for each CPU on the -- device. hiCPUShutdownTemperatures :: Lens' HardwareInfo [Double] hiCPUShutdownTemperatures = lens _hiCPUShutdownTemperatures (\ s a -> s{_hiCPUShutdownTemperatures = a}) . _Default . _Coerce -- | Battery throttling temperature thresholds in Celsius for each battery on -- the device. hiBatteryThrottlingTemperatures :: Lens' HardwareInfo [Double] hiBatteryThrottlingTemperatures = lens _hiBatteryThrottlingTemperatures (\ s a -> s{_hiBatteryThrottlingTemperatures = a}) . _Default . _Coerce -- | The model of the device. For example, Asus Nexus 7. hiModel :: Lens' HardwareInfo (Maybe Text) hiModel = lens _hiModel (\ s a -> s{_hiModel = a}) -- | Battery shutdown temperature thresholds in Celsius for each battery on -- the device. hiBatteryShutdownTemperatures :: Lens' HardwareInfo [Double] hiBatteryShutdownTemperatures = lens _hiBatteryShutdownTemperatures (\ s a -> s{_hiBatteryShutdownTemperatures = a}) . _Default . _Coerce -- | Device skin throttling temperature thresholds in Celsius. hiSkinThrottlingTemperatures :: Lens' HardwareInfo [Double] hiSkinThrottlingTemperatures = lens _hiSkinThrottlingTemperatures (\ s a -> s{_hiSkinThrottlingTemperatures = a}) . _Default . _Coerce -- | GPU shutdown temperature thresholds in Celsius for each GPU on the -- device. hiGpuShutdownTemperatures :: Lens' HardwareInfo [Double] hiGpuShutdownTemperatures = lens _hiGpuShutdownTemperatures (\ s a -> s{_hiGpuShutdownTemperatures = a}) . _Default . _Coerce -- | GPU throttling temperature thresholds in Celsius for each GPU on the -- device. hiGpuThrottlingTemperatures :: Lens' HardwareInfo [Double] hiGpuThrottlingTemperatures = lens _hiGpuThrottlingTemperatures (\ s a -> s{_hiGpuThrottlingTemperatures = a}) . _Default . _Coerce -- | Device skin shutdown temperature thresholds in Celsius. hiSkinShutdownTemperatures :: Lens' HardwareInfo [Double] hiSkinShutdownTemperatures = lens _hiSkinShutdownTemperatures (\ s a -> s{_hiSkinShutdownTemperatures = a}) . _Default . _Coerce -- | The device serial number. hiSerialNumber :: Lens' HardwareInfo (Maybe Text) hiSerialNumber = lens _hiSerialNumber (\ s a -> s{_hiSerialNumber = a}) -- | Baseband version. For example, MDM9625_104662.22.05.34p. hiDeviceBasebandVersion :: Lens' HardwareInfo (Maybe Text) hiDeviceBasebandVersion = lens _hiDeviceBasebandVersion (\ s a -> s{_hiDeviceBasebandVersion = a}) -- | Name of the hardware. For example, Angler. hiHardware :: Lens' HardwareInfo (Maybe Text) hiHardware = lens _hiHardware (\ s a -> s{_hiHardware = a}) instance FromJSON HardwareInfo where parseJSON = withObject "HardwareInfo" (\ o -> HardwareInfo' <$> (o .:? "cpuThrottlingTemperatures" .!= mempty) <*> (o .:? "manufacturer") <*> (o .:? "brand") <*> (o .:? "cpuShutdownTemperatures" .!= mempty) <*> (o .:? "batteryThrottlingTemperatures" .!= mempty) <*> (o .:? "model") <*> (o .:? "batteryShutdownTemperatures" .!= mempty) <*> (o .:? "skinThrottlingTemperatures" .!= mempty) <*> (o .:? "gpuShutdownTemperatures" .!= mempty) <*> (o .:? "gpuThrottlingTemperatures" .!= mempty) <*> (o .:? "skinShutdownTemperatures" .!= mempty) <*> (o .:? "serialNumber") <*> (o .:? "deviceBasebandVersion") <*> (o .:? "hardware")) instance ToJSON HardwareInfo where toJSON HardwareInfo'{..} = object (catMaybes [("cpuThrottlingTemperatures" .=) <$> _hiCPUThrottlingTemperatures, ("manufacturer" .=) <$> _hiManufacturer, ("brand" .=) <$> _hiBrand, ("cpuShutdownTemperatures" .=) <$> _hiCPUShutdownTemperatures, ("batteryThrottlingTemperatures" .=) <$> _hiBatteryThrottlingTemperatures, ("model" .=) <$> _hiModel, ("batteryShutdownTemperatures" .=) <$> _hiBatteryShutdownTemperatures, ("skinThrottlingTemperatures" .=) <$> _hiSkinThrottlingTemperatures, ("gpuShutdownTemperatures" .=) <$> _hiGpuShutdownTemperatures, ("gpuThrottlingTemperatures" .=) <$> _hiGpuThrottlingTemperatures, ("skinShutdownTemperatures" .=) <$> _hiSkinShutdownTemperatures, ("serialNumber" .=) <$> _hiSerialNumber, ("deviceBasebandVersion" .=) <$> _hiDeviceBasebandVersion, ("hardware" .=) <$> _hiHardware]) -- | A device owned by an enterprise. Unless otherwise noted, all fields are -- read-only and can\'t be modified by enterprises.devices.patch. -- -- /See:/ 'device' smart constructor. data Device = Device' { _devMemoryInfo :: !(Maybe MemoryInfo) , _devPolicyCompliant :: !(Maybe Bool) , _devApplicationReports :: !(Maybe [ApplicationReport]) , _devPolicyName :: !(Maybe Text) , _devState :: !(Maybe DeviceState) , _devAppliedPolicyName :: !(Maybe Text) , _devLastStatusReportTime :: !(Maybe DateTime') , _devDeviceSettings :: !(Maybe DeviceSettings) , _devEnrollmentTokenName :: !(Maybe Text) , _devManagementMode :: !(Maybe DeviceManagementMode) , _devHardwareInfo :: !(Maybe HardwareInfo) , _devPowerManagementEvents :: !(Maybe [PowerManagementEvent]) , _devCommonCriteriaModeInfo :: !(Maybe CommonCriteriaModeInfo) , _devUserName :: !(Maybe Text) , _devMemoryEvents :: !(Maybe [MemoryEvent]) , _devAPILevel :: !(Maybe (Textual Int32)) , _devUser :: !(Maybe User) , _devDisabledReason :: !(Maybe UserFacingMessage) , _devSystemProperties :: !(Maybe DeviceSystemProperties) , _devLastPolicyComplianceReportTime :: !(Maybe DateTime') , _devAppliedPasswordPolicies :: !(Maybe [PasswordRequirements]) , _devSecurityPosture :: !(Maybe SecurityPosture) , _devEnrollmentTokenData :: !(Maybe Text) , _devName :: !(Maybe Text) , _devAppliedPolicyVersion :: !(Maybe (Textual Int64)) , _devHardwareStatusSamples :: !(Maybe [HardwareStatus]) , _devAppliedState :: !(Maybe DeviceAppliedState) , _devPreviousDeviceNames :: !(Maybe [Text]) , _devLastPolicySyncTime :: !(Maybe DateTime') , _devNetworkInfo :: !(Maybe NetworkInfo) , _devNonComplianceDetails :: !(Maybe [NonComplianceDetail]) , _devOwnership :: !(Maybe DeviceOwnership) , _devSoftwareInfo :: !(Maybe SoftwareInfo) , _devEnrollmentTime :: !(Maybe DateTime') , _devDisplays :: !(Maybe [Display]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Device' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'devMemoryInfo' -- -- * 'devPolicyCompliant' -- -- * 'devApplicationReports' -- -- * 'devPolicyName' -- -- * 'devState' -- -- * 'devAppliedPolicyName' -- -- * 'devLastStatusReportTime' -- -- * 'devDeviceSettings' -- -- * 'devEnrollmentTokenName' -- -- * 'devManagementMode' -- -- * 'devHardwareInfo' -- -- * 'devPowerManagementEvents' -- -- * 'devCommonCriteriaModeInfo' -- -- * 'devUserName' -- -- * 'devMemoryEvents' -- -- * 'devAPILevel' -- -- * 'devUser' -- -- * 'devDisabledReason' -- -- * 'devSystemProperties' -- -- * 'devLastPolicyComplianceReportTime' -- -- * 'devAppliedPasswordPolicies' -- -- * 'devSecurityPosture' -- -- * 'devEnrollmentTokenData' -- -- * 'devName' -- -- * 'devAppliedPolicyVersion' -- -- * 'devHardwareStatusSamples' -- -- * 'devAppliedState' -- -- * 'devPreviousDeviceNames' -- -- * 'devLastPolicySyncTime' -- -- * 'devNetworkInfo' -- -- * 'devNonComplianceDetails' -- -- * 'devOwnership' -- -- * 'devSoftwareInfo' -- -- * 'devEnrollmentTime' -- -- * 'devDisplays' device :: Device device = Device' { _devMemoryInfo = Nothing , _devPolicyCompliant = Nothing , _devApplicationReports = Nothing , _devPolicyName = Nothing , _devState = Nothing , _devAppliedPolicyName = Nothing , _devLastStatusReportTime = Nothing , _devDeviceSettings = Nothing , _devEnrollmentTokenName = Nothing , _devManagementMode = Nothing , _devHardwareInfo = Nothing , _devPowerManagementEvents = Nothing , _devCommonCriteriaModeInfo = Nothing , _devUserName = Nothing , _devMemoryEvents = Nothing , _devAPILevel = Nothing , _devUser = Nothing , _devDisabledReason = Nothing , _devSystemProperties = Nothing , _devLastPolicyComplianceReportTime = Nothing , _devAppliedPasswordPolicies = Nothing , _devSecurityPosture = Nothing , _devEnrollmentTokenData = Nothing , _devName = Nothing , _devAppliedPolicyVersion = Nothing , _devHardwareStatusSamples = Nothing , _devAppliedState = Nothing , _devPreviousDeviceNames = Nothing , _devLastPolicySyncTime = Nothing , _devNetworkInfo = Nothing , _devNonComplianceDetails = Nothing , _devOwnership = Nothing , _devSoftwareInfo = Nothing , _devEnrollmentTime = Nothing , _devDisplays = Nothing } -- | Memory information. This information is only available if -- memoryInfoEnabled is true in the device\'s policy. devMemoryInfo :: Lens' Device (Maybe MemoryInfo) devMemoryInfo = lens _devMemoryInfo (\ s a -> s{_devMemoryInfo = a}) -- | Whether the device is compliant with its policy. devPolicyCompliant :: Lens' Device (Maybe Bool) devPolicyCompliant = lens _devPolicyCompliant (\ s a -> s{_devPolicyCompliant = a}) -- | Reports for apps installed on the device. This information is only -- available when application_reports_enabled is true in the device\'s -- policy. devApplicationReports :: Lens' Device [ApplicationReport] devApplicationReports = lens _devApplicationReports (\ s a -> s{_devApplicationReports = a}) . _Default . _Coerce -- | The name of the policy applied to the device, in the form -- enterprises\/{enterpriseId}\/policies\/{policyId}. If not specified, the -- policy_name for the device\'s user is applied. This field can be -- modified by a patch request. You can specify only the policyId when -- calling enterprises.devices.patch, as long as the policyId doesn’t -- contain any slashes. The rest of the policy name is inferred. devPolicyName :: Lens' Device (Maybe Text) devPolicyName = lens _devPolicyName (\ s a -> s{_devPolicyName = a}) -- | The state to be applied to the device. This field can be modified by a -- patch request. Note that when calling enterprises.devices.patch, ACTIVE -- and DISABLED are the only allowable values. To enter the device into a -- DELETED state, call enterprises.devices.delete. devState :: Lens' Device (Maybe DeviceState) devState = lens _devState (\ s a -> s{_devState = a}) -- | The name of the policy currently applied to the device. devAppliedPolicyName :: Lens' Device (Maybe Text) devAppliedPolicyName = lens _devAppliedPolicyName (\ s a -> s{_devAppliedPolicyName = a}) -- | The last time the device sent a status report. devLastStatusReportTime :: Lens' Device (Maybe UTCTime) devLastStatusReportTime = lens _devLastStatusReportTime (\ s a -> s{_devLastStatusReportTime = a}) . mapping _DateTime -- | Device settings information. This information is only available if -- deviceSettingsEnabled is true in the device\'s policy. devDeviceSettings :: Lens' Device (Maybe DeviceSettings) devDeviceSettings = lens _devDeviceSettings (\ s a -> s{_devDeviceSettings = a}) -- | If the device was enrolled with an enrollment token, this field contains -- the name of the token. devEnrollmentTokenName :: Lens' Device (Maybe Text) devEnrollmentTokenName = lens _devEnrollmentTokenName (\ s a -> s{_devEnrollmentTokenName = a}) -- | The type of management mode Android Device Policy takes on the device. -- This influences which policy settings are supported. devManagementMode :: Lens' Device (Maybe DeviceManagementMode) devManagementMode = lens _devManagementMode (\ s a -> s{_devManagementMode = a}) -- | Detailed information about the device hardware. devHardwareInfo :: Lens' Device (Maybe HardwareInfo) devHardwareInfo = lens _devHardwareInfo (\ s a -> s{_devHardwareInfo = a}) -- | Power management events on the device in chronological order. This -- information is only available if powerManagementEventsEnabled is true in -- the device\'s policy. devPowerManagementEvents :: Lens' Device [PowerManagementEvent] devPowerManagementEvents = lens _devPowerManagementEvents (\ s a -> s{_devPowerManagementEvents = a}) . _Default . _Coerce -- | Information about Common Criteria Mode—security standards defined in the -- Common Criteria for Information Technology Security Evaluation -- (https:\/\/www.commoncriteriaportal.org\/) (CC).This information is only -- available if statusReportingSettings.commonCriteriaModeEnabled is true -- in the device\'s policy. devCommonCriteriaModeInfo :: Lens' Device (Maybe CommonCriteriaModeInfo) devCommonCriteriaModeInfo = lens _devCommonCriteriaModeInfo (\ s a -> s{_devCommonCriteriaModeInfo = a}) -- | The resource name of the user that owns this device in the form -- enterprises\/{enterpriseId}\/users\/{userId}. devUserName :: Lens' Device (Maybe Text) devUserName = lens _devUserName (\ s a -> s{_devUserName = a}) -- | Events related to memory and storage measurements in chronological -- order. This information is only available if memoryInfoEnabled is true -- in the device\'s policy. devMemoryEvents :: Lens' Device [MemoryEvent] devMemoryEvents = lens _devMemoryEvents (\ s a -> s{_devMemoryEvents = a}) . _Default . _Coerce -- | The API level of the Android platform version running on the device. devAPILevel :: Lens' Device (Maybe Int32) devAPILevel = lens _devAPILevel (\ s a -> s{_devAPILevel = a}) . mapping _Coerce -- | The user who owns the device. devUser :: Lens' Device (Maybe User) devUser = lens _devUser (\ s a -> s{_devUser = a}) -- | If the device state is DISABLED, an optional message that is displayed -- on the device indicating the reason the device is disabled. This field -- can be modified by a patch request. devDisabledReason :: Lens' Device (Maybe UserFacingMessage) devDisabledReason = lens _devDisabledReason (\ s a -> s{_devDisabledReason = a}) -- | Map of selected system properties name and value related to the device. -- This information is only available if systemPropertiesEnabled is true in -- the device\'s policy. devSystemProperties :: Lens' Device (Maybe DeviceSystemProperties) devSystemProperties = lens _devSystemProperties (\ s a -> s{_devSystemProperties = a}) -- | Deprecated. devLastPolicyComplianceReportTime :: Lens' Device (Maybe UTCTime) devLastPolicyComplianceReportTime = lens _devLastPolicyComplianceReportTime (\ s a -> s{_devLastPolicyComplianceReportTime = a}) . mapping _DateTime -- | The password requirements currently applied to the device. The applied -- requirements may be slightly different from those specified in -- passwordPolicies in some cases. fieldPath is set based on -- passwordPolicies. devAppliedPasswordPolicies :: Lens' Device [PasswordRequirements] devAppliedPasswordPolicies = lens _devAppliedPasswordPolicies (\ s a -> s{_devAppliedPasswordPolicies = a}) . _Default . _Coerce -- | Device\'s security posture value that reflects how secure the device is. devSecurityPosture :: Lens' Device (Maybe SecurityPosture) devSecurityPosture = lens _devSecurityPosture (\ s a -> s{_devSecurityPosture = a}) -- | If the device was enrolled with an enrollment token with additional data -- provided, this field contains that data. devEnrollmentTokenData :: Lens' Device (Maybe Text) devEnrollmentTokenData = lens _devEnrollmentTokenData (\ s a -> s{_devEnrollmentTokenData = a}) -- | The name of the device in the form -- enterprises\/{enterpriseId}\/devices\/{deviceId}. devName :: Lens' Device (Maybe Text) devName = lens _devName (\ s a -> s{_devName = a}) -- | The version of the policy currently applied to the device. devAppliedPolicyVersion :: Lens' Device (Maybe Int64) devAppliedPolicyVersion = lens _devAppliedPolicyVersion (\ s a -> s{_devAppliedPolicyVersion = a}) . mapping _Coerce -- | Hardware status samples in chronological order. This information is only -- available if hardwareStatusEnabled is true in the device\'s policy. devHardwareStatusSamples :: Lens' Device [HardwareStatus] devHardwareStatusSamples = lens _devHardwareStatusSamples (\ s a -> s{_devHardwareStatusSamples = a}) . _Default . _Coerce -- | The state currently applied to the device. devAppliedState :: Lens' Device (Maybe DeviceAppliedState) devAppliedState = lens _devAppliedState (\ s a -> s{_devAppliedState = a}) -- | If the same physical device has been enrolled multiple times, this field -- contains its previous device names. The serial number is used as the -- unique identifier to determine if the same physical device has enrolled -- previously. The names are in chronological order. devPreviousDeviceNames :: Lens' Device [Text] devPreviousDeviceNames = lens _devPreviousDeviceNames (\ s a -> s{_devPreviousDeviceNames = a}) . _Default . _Coerce -- | The last time the device fetched its policy. devLastPolicySyncTime :: Lens' Device (Maybe UTCTime) devLastPolicySyncTime = lens _devLastPolicySyncTime (\ s a -> s{_devLastPolicySyncTime = a}) . mapping _DateTime -- | Device network information. This information is only available if -- networkInfoEnabled is true in the device\'s policy. devNetworkInfo :: Lens' Device (Maybe NetworkInfo) devNetworkInfo = lens _devNetworkInfo (\ s a -> s{_devNetworkInfo = a}) -- | Details about policy settings that the device is not compliant with. devNonComplianceDetails :: Lens' Device [NonComplianceDetail] devNonComplianceDetails = lens _devNonComplianceDetails (\ s a -> s{_devNonComplianceDetails = a}) . _Default . _Coerce -- | Ownership of the managed device. devOwnership :: Lens' Device (Maybe DeviceOwnership) devOwnership = lens _devOwnership (\ s a -> s{_devOwnership = a}) -- | Detailed information about the device software. This information is only -- available if softwareInfoEnabled is true in the device\'s policy. devSoftwareInfo :: Lens' Device (Maybe SoftwareInfo) devSoftwareInfo = lens _devSoftwareInfo (\ s a -> s{_devSoftwareInfo = a}) -- | The time of device enrollment. devEnrollmentTime :: Lens' Device (Maybe UTCTime) devEnrollmentTime = lens _devEnrollmentTime (\ s a -> s{_devEnrollmentTime = a}) . mapping _DateTime -- | Detailed information about displays on the device. This information is -- only available if displayInfoEnabled is true in the device\'s policy. devDisplays :: Lens' Device [Display] devDisplays = lens _devDisplays (\ s a -> s{_devDisplays = a}) . _Default . _Coerce instance FromJSON Device where parseJSON = withObject "Device" (\ o -> Device' <$> (o .:? "memoryInfo") <*> (o .:? "policyCompliant") <*> (o .:? "applicationReports" .!= mempty) <*> (o .:? "policyName") <*> (o .:? "state") <*> (o .:? "appliedPolicyName") <*> (o .:? "lastStatusReportTime") <*> (o .:? "deviceSettings") <*> (o .:? "enrollmentTokenName") <*> (o .:? "managementMode") <*> (o .:? "hardwareInfo") <*> (o .:? "powerManagementEvents" .!= mempty) <*> (o .:? "commonCriteriaModeInfo") <*> (o .:? "userName") <*> (o .:? "memoryEvents" .!= mempty) <*> (o .:? "apiLevel") <*> (o .:? "user") <*> (o .:? "disabledReason") <*> (o .:? "systemProperties") <*> (o .:? "lastPolicyComplianceReportTime") <*> (o .:? "appliedPasswordPolicies" .!= mempty) <*> (o .:? "securityPosture") <*> (o .:? "enrollmentTokenData") <*> (o .:? "name") <*> (o .:? "appliedPolicyVersion") <*> (o .:? "hardwareStatusSamples" .!= mempty) <*> (o .:? "appliedState") <*> (o .:? "previousDeviceNames" .!= mempty) <*> (o .:? "lastPolicySyncTime") <*> (o .:? "networkInfo") <*> (o .:? "nonComplianceDetails" .!= mempty) <*> (o .:? "ownership") <*> (o .:? "softwareInfo") <*> (o .:? "enrollmentTime") <*> (o .:? "displays" .!= mempty)) instance ToJSON Device where toJSON Device'{..} = object (catMaybes [("memoryInfo" .=) <$> _devMemoryInfo, ("policyCompliant" .=) <$> _devPolicyCompliant, ("applicationReports" .=) <$> _devApplicationReports, ("policyName" .=) <$> _devPolicyName, ("state" .=) <$> _devState, ("appliedPolicyName" .=) <$> _devAppliedPolicyName, ("lastStatusReportTime" .=) <$> _devLastStatusReportTime, ("deviceSettings" .=) <$> _devDeviceSettings, ("enrollmentTokenName" .=) <$> _devEnrollmentTokenName, ("managementMode" .=) <$> _devManagementMode, ("hardwareInfo" .=) <$> _devHardwareInfo, ("powerManagementEvents" .=) <$> _devPowerManagementEvents, ("commonCriteriaModeInfo" .=) <$> _devCommonCriteriaModeInfo, ("userName" .=) <$> _devUserName, ("memoryEvents" .=) <$> _devMemoryEvents, ("apiLevel" .=) <$> _devAPILevel, ("user" .=) <$> _devUser, ("disabledReason" .=) <$> _devDisabledReason, ("systemProperties" .=) <$> _devSystemProperties, ("lastPolicyComplianceReportTime" .=) <$> _devLastPolicyComplianceReportTime, ("appliedPasswordPolicies" .=) <$> _devAppliedPasswordPolicies, ("securityPosture" .=) <$> _devSecurityPosture, ("enrollmentTokenData" .=) <$> _devEnrollmentTokenData, ("name" .=) <$> _devName, ("appliedPolicyVersion" .=) <$> _devAppliedPolicyVersion, ("hardwareStatusSamples" .=) <$> _devHardwareStatusSamples, ("appliedState" .=) <$> _devAppliedState, ("previousDeviceNames" .=) <$> _devPreviousDeviceNames, ("lastPolicySyncTime" .=) <$> _devLastPolicySyncTime, ("networkInfo" .=) <$> _devNetworkInfo, ("nonComplianceDetails" .=) <$> _devNonComplianceDetails, ("ownership" .=) <$> _devOwnership, ("softwareInfo" .=) <$> _devSoftwareInfo, ("enrollmentTime" .=) <$> _devEnrollmentTime, ("displays" .=) <$> _devDisplays]) -- | This feature is not generally available. -- -- /See:/ 'contentProviderEndpoint' smart constructor. data ContentProviderEndpoint = ContentProviderEndpoint' { _cpePackageName :: !(Maybe Text) , _cpeSigningCertsSha256 :: !(Maybe [Text]) , _cpeURI :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ContentProviderEndpoint' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpePackageName' -- -- * 'cpeSigningCertsSha256' -- -- * 'cpeURI' contentProviderEndpoint :: ContentProviderEndpoint contentProviderEndpoint = ContentProviderEndpoint' { _cpePackageName = Nothing , _cpeSigningCertsSha256 = Nothing , _cpeURI = Nothing } -- | This feature is not generally available. cpePackageName :: Lens' ContentProviderEndpoint (Maybe Text) cpePackageName = lens _cpePackageName (\ s a -> s{_cpePackageName = a}) -- | Required. This feature is not generally available. cpeSigningCertsSha256 :: Lens' ContentProviderEndpoint [Text] cpeSigningCertsSha256 = lens _cpeSigningCertsSha256 (\ s a -> s{_cpeSigningCertsSha256 = a}) . _Default . _Coerce -- | This feature is not generally available. cpeURI :: Lens' ContentProviderEndpoint (Maybe Text) cpeURI = lens _cpeURI (\ s a -> s{_cpeURI = a}) instance FromJSON ContentProviderEndpoint where parseJSON = withObject "ContentProviderEndpoint" (\ o -> ContentProviderEndpoint' <$> (o .:? "packageName") <*> (o .:? "signingCertsSha256" .!= mempty) <*> (o .:? "uri")) instance ToJSON ContentProviderEndpoint where toJSON ContentProviderEndpoint'{..} = object (catMaybes [("packageName" .=) <$> _cpePackageName, ("signingCertsSha256" .=) <$> _cpeSigningCertsSha256, ("uri" .=) <$> _cpeURI]) -- | Policies controlling personal usage on a company-owned device with a -- work profile. -- -- /See:/ 'personalUsagePolicies' smart constructor. data PersonalUsagePolicies = PersonalUsagePolicies' { _pupMaxDaysWithWorkOff :: !(Maybe (Textual Int32)) , _pupPersonalPlayStoreMode :: !(Maybe PersonalUsagePoliciesPersonalPlayStoreMode) , _pupScreenCaptureDisabled :: !(Maybe Bool) , _pupPersonalApplications :: !(Maybe [PersonalApplicationPolicy]) , _pupAccountTypesWithManagementDisabled :: !(Maybe [Text]) , _pupCameraDisabled :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PersonalUsagePolicies' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pupMaxDaysWithWorkOff' -- -- * 'pupPersonalPlayStoreMode' -- -- * 'pupScreenCaptureDisabled' -- -- * 'pupPersonalApplications' -- -- * 'pupAccountTypesWithManagementDisabled' -- -- * 'pupCameraDisabled' personalUsagePolicies :: PersonalUsagePolicies personalUsagePolicies = PersonalUsagePolicies' { _pupMaxDaysWithWorkOff = Nothing , _pupPersonalPlayStoreMode = Nothing , _pupScreenCaptureDisabled = Nothing , _pupPersonalApplications = Nothing , _pupAccountTypesWithManagementDisabled = Nothing , _pupCameraDisabled = Nothing } -- | Controls how long the work profile can stay off. The duration must be at -- least 3 days. pupMaxDaysWithWorkOff :: Lens' PersonalUsagePolicies (Maybe Int32) pupMaxDaysWithWorkOff = lens _pupMaxDaysWithWorkOff (\ s a -> s{_pupMaxDaysWithWorkOff = a}) . mapping _Coerce -- | Used together with personalApplications to control how apps in the -- personal profile are allowed or blocked. pupPersonalPlayStoreMode :: Lens' PersonalUsagePolicies (Maybe PersonalUsagePoliciesPersonalPlayStoreMode) pupPersonalPlayStoreMode = lens _pupPersonalPlayStoreMode (\ s a -> s{_pupPersonalPlayStoreMode = a}) -- | Whether screen capture is disabled. pupScreenCaptureDisabled :: Lens' PersonalUsagePolicies (Maybe Bool) pupScreenCaptureDisabled = lens _pupScreenCaptureDisabled (\ s a -> s{_pupScreenCaptureDisabled = a}) -- | Policy applied to applications in the personal profile. pupPersonalApplications :: Lens' PersonalUsagePolicies [PersonalApplicationPolicy] pupPersonalApplications = lens _pupPersonalApplications (\ s a -> s{_pupPersonalApplications = a}) . _Default . _Coerce -- | Account types that can\'t be managed by the user. pupAccountTypesWithManagementDisabled :: Lens' PersonalUsagePolicies [Text] pupAccountTypesWithManagementDisabled = lens _pupAccountTypesWithManagementDisabled (\ s a -> s{_pupAccountTypesWithManagementDisabled = a}) . _Default . _Coerce -- | Whether camera is disabled. pupCameraDisabled :: Lens' PersonalUsagePolicies (Maybe Bool) pupCameraDisabled = lens _pupCameraDisabled (\ s a -> s{_pupCameraDisabled = a}) instance FromJSON PersonalUsagePolicies where parseJSON = withObject "PersonalUsagePolicies" (\ o -> PersonalUsagePolicies' <$> (o .:? "maxDaysWithWorkOff") <*> (o .:? "personalPlayStoreMode") <*> (o .:? "screenCaptureDisabled") <*> (o .:? "personalApplications" .!= mempty) <*> (o .:? "accountTypesWithManagementDisabled" .!= mempty) <*> (o .:? "cameraDisabled")) instance ToJSON PersonalUsagePolicies where toJSON PersonalUsagePolicies'{..} = object (catMaybes [("maxDaysWithWorkOff" .=) <$> _pupMaxDaysWithWorkOff, ("personalPlayStoreMode" .=) <$> _pupPersonalPlayStoreMode, ("screenCaptureDisabled" .=) <$> _pupScreenCaptureDisabled, ("personalApplications" .=) <$> _pupPersonalApplications, ("accountTypesWithManagementDisabled" .=) <$> _pupAccountTypesWithManagementDisabled, ("cameraDisabled" .=) <$> _pupCameraDisabled]) -- | Additional details regarding the security posture of the device. -- -- /See:/ 'postureDetail' smart constructor. data PostureDetail = PostureDetail' { _pdAdvice :: !(Maybe [UserFacingMessage]) , _pdSecurityRisk :: !(Maybe PostureDetailSecurityRisk) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PostureDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdAdvice' -- -- * 'pdSecurityRisk' postureDetail :: PostureDetail postureDetail = PostureDetail' {_pdAdvice = Nothing, _pdSecurityRisk = Nothing} -- | Corresponding admin-facing advice to mitigate this security risk and -- improve the security posture of the device. pdAdvice :: Lens' PostureDetail [UserFacingMessage] pdAdvice = lens _pdAdvice (\ s a -> s{_pdAdvice = a}) . _Default . _Coerce -- | A specific security risk that negatively affects the security posture of -- the device. pdSecurityRisk :: Lens' PostureDetail (Maybe PostureDetailSecurityRisk) pdSecurityRisk = lens _pdSecurityRisk (\ s a -> s{_pdSecurityRisk = a}) instance FromJSON PostureDetail where parseJSON = withObject "PostureDetail" (\ o -> PostureDetail' <$> (o .:? "advice" .!= mempty) <*> (o .:? "securityRisk")) instance ToJSON PostureDetail where toJSON PostureDetail'{..} = object (catMaybes [("advice" .=) <$> _pdAdvice, ("securityRisk" .=) <$> _pdSecurityRisk]) -- | Information about Common Criteria Mode—security standards defined in the -- Common Criteria for Information Technology Security Evaluation -- (https:\/\/www.commoncriteriaportal.org\/) (CC).This information is only -- available if statusReportingSettings.commonCriteriaModeEnabled is true -- in the device\'s policy. -- -- /See:/ 'commonCriteriaModeInfo' smart constructor. newtype CommonCriteriaModeInfo = CommonCriteriaModeInfo' { _ccmiCommonCriteriaModeStatus :: Maybe CommonCriteriaModeInfoCommonCriteriaModeStatus } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CommonCriteriaModeInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccmiCommonCriteriaModeStatus' commonCriteriaModeInfo :: CommonCriteriaModeInfo commonCriteriaModeInfo = CommonCriteriaModeInfo' {_ccmiCommonCriteriaModeStatus = Nothing} -- | Whether Common Criteria Mode is enabled. ccmiCommonCriteriaModeStatus :: Lens' CommonCriteriaModeInfo (Maybe CommonCriteriaModeInfoCommonCriteriaModeStatus) ccmiCommonCriteriaModeStatus = lens _ccmiCommonCriteriaModeStatus (\ s a -> s{_ccmiCommonCriteriaModeStatus = a}) instance FromJSON CommonCriteriaModeInfo where parseJSON = withObject "CommonCriteriaModeInfo" (\ o -> CommonCriteriaModeInfo' <$> (o .:? "commonCriteriaModeStatus")) instance ToJSON CommonCriteriaModeInfo where toJSON CommonCriteriaModeInfo'{..} = object (catMaybes [("commonCriteriaModeStatus" .=) <$> _ccmiCommonCriteriaModeStatus]) -- -- /See:/ 'statusDetailsItem' smart constructor. newtype StatusDetailsItem = StatusDetailsItem' { _sdiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdiAddtional' statusDetailsItem :: HashMap Text JSONValue -- ^ 'sdiAddtional' -> StatusDetailsItem statusDetailsItem pSdiAddtional_ = StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_} -- | Properties of the object. Contains field \'type with type URL. sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue) sdiAddtional = lens _sdiAddtional (\ s a -> s{_sdiAddtional = a}) . _Coerce instance FromJSON StatusDetailsItem where parseJSON = withObject "StatusDetailsItem" (\ o -> StatusDetailsItem' <$> (parseJSONObject o)) instance ToJSON StatusDetailsItem where toJSON = toJSON . _sdiAddtional -- | This feature is not generally available. -- -- /See:/ 'oncCertificateProvider' smart constructor. data OncCertificateProvider = OncCertificateProvider' { _ocpContentProviderEndpoint :: !(Maybe ContentProviderEndpoint) , _ocpCertificateReferences :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OncCertificateProvider' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocpContentProviderEndpoint' -- -- * 'ocpCertificateReferences' oncCertificateProvider :: OncCertificateProvider oncCertificateProvider = OncCertificateProvider' {_ocpContentProviderEndpoint = Nothing, _ocpCertificateReferences = Nothing} -- | This feature is not generally available. ocpContentProviderEndpoint :: Lens' OncCertificateProvider (Maybe ContentProviderEndpoint) ocpContentProviderEndpoint = lens _ocpContentProviderEndpoint (\ s a -> s{_ocpContentProviderEndpoint = a}) -- | This feature is not generally available. ocpCertificateReferences :: Lens' OncCertificateProvider [Text] ocpCertificateReferences = lens _ocpCertificateReferences (\ s a -> s{_ocpCertificateReferences = a}) . _Default . _Coerce instance FromJSON OncCertificateProvider where parseJSON = withObject "OncCertificateProvider" (\ o -> OncCertificateProvider' <$> (o .:? "contentProviderEndpoint") <*> (o .:? "certificateReferences" .!= mempty)) instance ToJSON OncCertificateProvider where toJSON OncCertificateProvider'{..} = object (catMaybes [("contentProviderEndpoint" .=) <$> _ocpContentProviderEndpoint, ("certificateReferences" .=) <$> _ocpCertificateReferences]) -- | An entry of a managed property. -- -- /See:/ 'managedPropertyEntry' smart constructor. data ManagedPropertyEntry = ManagedPropertyEntry' { _mpeValue :: !(Maybe Text) , _mpeName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ManagedPropertyEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mpeValue' -- -- * 'mpeName' managedPropertyEntry :: ManagedPropertyEntry managedPropertyEntry = ManagedPropertyEntry' {_mpeValue = Nothing, _mpeName = Nothing} -- | The machine-readable value of the entry, which should be used in the -- configuration. Not localized. mpeValue :: Lens' ManagedPropertyEntry (Maybe Text) mpeValue = lens _mpeValue (\ s a -> s{_mpeValue = a}) -- | The human-readable name of the value. Localized. mpeName :: Lens' ManagedPropertyEntry (Maybe Text) mpeName = lens _mpeName (\ s a -> s{_mpeName = a}) instance FromJSON ManagedPropertyEntry where parseJSON = withObject "ManagedPropertyEntry" (\ o -> ManagedPropertyEntry' <$> (o .:? "value") <*> (o .:? "name")) instance ToJSON ManagedPropertyEntry where toJSON ManagedPropertyEntry'{..} = object (catMaybes [("value" .=) <$> _mpeValue, ("name" .=) <$> _mpeName]) -- | A system freeze period. When a device’s clock is within the freeze -- period, all incoming system updates (including security patches) are -- blocked and won’t be installed. When a device is outside the freeze -- period, normal update behavior applies. Leap years are ignored in freeze -- period calculations, in particular: * If Feb. 29th is set as the start -- or end date of a freeze period, the freeze period will start or end on -- Feb. 28th instead. * When a device’s system clock reads Feb. 29th, it’s -- treated as Feb. 28th. * When calculating the number of days in a freeze -- period or the time between two freeze periods, Feb. 29th is ignored and -- not counted as a day. -- -- /See:/ 'freezePeriod' smart constructor. data FreezePeriod = FreezePeriod' { _fpEndDate :: !(Maybe Date) , _fpStartDate :: !(Maybe Date) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FreezePeriod' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fpEndDate' -- -- * 'fpStartDate' freezePeriod :: FreezePeriod freezePeriod = FreezePeriod' {_fpEndDate = Nothing, _fpStartDate = Nothing} -- | The end date (inclusive) of the freeze period. Must be no later than 90 -- days from the start date. If the end date is earlier than the start -- date, the freeze period is considered wrapping year-end. Note: year must -- not be set. For example, {\"month\": 1,\"date\": 30}. fpEndDate :: Lens' FreezePeriod (Maybe Date) fpEndDate = lens _fpEndDate (\ s a -> s{_fpEndDate = a}) -- | The start date (inclusive) of the freeze period. Note: year must not be -- set. For example, {\"month\": 1,\"date\": 30}. fpStartDate :: Lens' FreezePeriod (Maybe Date) fpStartDate = lens _fpStartDate (\ s a -> s{_fpStartDate = a}) instance FromJSON FreezePeriod where parseJSON = withObject "FreezePeriod" (\ o -> FreezePeriod' <$> (o .:? "endDate") <*> (o .:? "startDate")) instance ToJSON FreezePeriod where toJSON FreezePeriod'{..} = object (catMaybes [("endDate" .=) <$> _fpEndDate, ("startDate" .=) <$> _fpStartDate]) -- | Telephony information associated with a given SIM card on the device. -- Only supported on fully managed devices starting from Android API level -- 23. -- -- /See:/ 'telephonyInfo' smart constructor. data TelephonyInfo = TelephonyInfo' { _tiPhoneNumber :: !(Maybe Text) , _tiCarrierName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TelephonyInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiPhoneNumber' -- -- * 'tiCarrierName' telephonyInfo :: TelephonyInfo telephonyInfo = TelephonyInfo' {_tiPhoneNumber = Nothing, _tiCarrierName = Nothing} -- | The phone number associated with this SIM card. tiPhoneNumber :: Lens' TelephonyInfo (Maybe Text) tiPhoneNumber = lens _tiPhoneNumber (\ s a -> s{_tiPhoneNumber = a}) -- | The carrier name associated with this SIM card. tiCarrierName :: Lens' TelephonyInfo (Maybe Text) tiCarrierName = lens _tiCarrierName (\ s a -> s{_tiCarrierName = a}) instance FromJSON TelephonyInfo where parseJSON = withObject "TelephonyInfo" (\ o -> TelephonyInfo' <$> (o .:? "phoneNumber") <*> (o .:? "carrierName")) instance ToJSON TelephonyInfo where toJSON TelephonyInfo'{..} = object (catMaybes [("phoneNumber" .=) <$> _tiPhoneNumber, ("carrierName" .=) <$> _tiCarrierName]) -- | Controls apps\' access to private keys. The rule determines which -- private key, if any, Android Device Policy grants to the specified app. -- Access is granted either when the app calls -- KeyChain.choosePrivateKeyAlias -- (https:\/\/developer.android.com\/reference\/android\/security\/KeyChain#choosePrivateKeyAlias%28android.app.Activity,%20android.security.KeyChainAliasCallback,%20java.lang.String[],%20java.security.Principal[],%20java.lang.String,%20int,%20java.lang.String%29) -- (or any overloads) to request a private key alias for a given URL, or -- for rules that are not URL-specific (that is, if urlPattern is not set, -- or set to the empty string or .*) on Android 11 and above, directly so -- that the app can call KeyChain.getPrivateKey -- (https:\/\/developer.android.com\/reference\/android\/security\/KeyChain#getPrivateKey%28android.content.Context,%20java.lang.String%29), -- without first having to call KeyChain.choosePrivateKeyAlias.When an app -- calls KeyChain.choosePrivateKeyAlias if more than one -- choosePrivateKeyRules matches, the last matching rule defines which key -- alias to return. -- -- /See:/ 'choosePrivateKeyRule' smart constructor. data ChoosePrivateKeyRule = ChoosePrivateKeyRule' { _cpkrPrivateKeyAlias :: !(Maybe Text) , _cpkrURLPattern :: !(Maybe Text) , _cpkrPackageNames :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ChoosePrivateKeyRule' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpkrPrivateKeyAlias' -- -- * 'cpkrURLPattern' -- -- * 'cpkrPackageNames' choosePrivateKeyRule :: ChoosePrivateKeyRule choosePrivateKeyRule = ChoosePrivateKeyRule' { _cpkrPrivateKeyAlias = Nothing , _cpkrURLPattern = Nothing , _cpkrPackageNames = Nothing } -- | The alias of the private key to be used. cpkrPrivateKeyAlias :: Lens' ChoosePrivateKeyRule (Maybe Text) cpkrPrivateKeyAlias = lens _cpkrPrivateKeyAlias (\ s a -> s{_cpkrPrivateKeyAlias = a}) -- | The URL pattern to match against the URL of the request. If not set or -- empty, it matches all URLs. This uses the regular expression syntax of -- java.util.regex.Pattern. cpkrURLPattern :: Lens' ChoosePrivateKeyRule (Maybe Text) cpkrURLPattern = lens _cpkrURLPattern (\ s a -> s{_cpkrURLPattern = a}) -- | The package names to which this rule applies. The hash of the signing -- certificate for each app is verified against the hash provided by Play. -- If no package names are specified, then the alias is provided to all -- apps that call KeyChain.choosePrivateKeyAlias -- (https:\/\/developer.android.com\/reference\/android\/security\/KeyChain#choosePrivateKeyAlias%28android.app.Activity,%20android.security.KeyChainAliasCallback,%20java.lang.String[],%20java.security.Principal[],%20java.lang.String,%20int,%20java.lang.String%29) -- or any overloads (but not without calling -- KeyChain.choosePrivateKeyAlias, even on Android 11 and above). Any app -- with the same Android UID as a package specified here will have access -- when they call KeyChain.choosePrivateKeyAlias. cpkrPackageNames :: Lens' ChoosePrivateKeyRule [Text] cpkrPackageNames = lens _cpkrPackageNames (\ s a -> s{_cpkrPackageNames = a}) . _Default . _Coerce instance FromJSON ChoosePrivateKeyRule where parseJSON = withObject "ChoosePrivateKeyRule" (\ o -> ChoosePrivateKeyRule' <$> (o .:? "privateKeyAlias") <*> (o .:? "urlPattern") <*> (o .:? "packageNames" .!= mempty)) instance ToJSON ChoosePrivateKeyRule where toJSON ChoosePrivateKeyRule'{..} = object (catMaybes [("privateKeyAlias" .=) <$> _cpkrPrivateKeyAlias, ("urlPattern" .=) <$> _cpkrURLPattern, ("packageNames" .=) <$> _cpkrPackageNames]) -- | A map containing pairs, where locale is a well-formed BCP 47 language -- (https:\/\/www.w3.org\/International\/articles\/language-tags\/) code, -- such as en-US, es-ES, or fr. -- -- /See:/ 'userFacingMessageLocalizedMessages' smart constructor. newtype UserFacingMessageLocalizedMessages = UserFacingMessageLocalizedMessages' { _ufmlmAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UserFacingMessageLocalizedMessages' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ufmlmAddtional' userFacingMessageLocalizedMessages :: HashMap Text Text -- ^ 'ufmlmAddtional' -> UserFacingMessageLocalizedMessages userFacingMessageLocalizedMessages pUfmlmAddtional_ = UserFacingMessageLocalizedMessages' {_ufmlmAddtional = _Coerce # pUfmlmAddtional_} ufmlmAddtional :: Lens' UserFacingMessageLocalizedMessages (HashMap Text Text) ufmlmAddtional = lens _ufmlmAddtional (\ s a -> s{_ufmlmAddtional = a}) . _Coerce instance FromJSON UserFacingMessageLocalizedMessages where parseJSON = withObject "UserFacingMessageLocalizedMessages" (\ o -> UserFacingMessageLocalizedMessages' <$> (parseJSONObject o)) instance ToJSON UserFacingMessageLocalizedMessages where toJSON = toJSON . _ufmlmAddtional -- | A user belonging to an enterprise. -- -- /See:/ 'user' smart constructor. newtype User = User' { _uAccountIdentifier :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'User' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uAccountIdentifier' user :: User user = User' {_uAccountIdentifier = Nothing} -- | A unique identifier you create for this user, such as user342 or -- asset#44418. This field must be set when the user is created and can\'t -- be updated. This field must not contain personally identifiable -- information (PII). This identifier must be 1024 characters or less; -- otherwise, the update policy request will fail. uAccountIdentifier :: Lens' User (Maybe Text) uAccountIdentifier = lens _uAccountIdentifier (\ s a -> s{_uAccountIdentifier = a}) instance FromJSON User where parseJSON = withObject "User" (\ o -> User' <$> (o .:? "accountIdentifier")) instance ToJSON User where toJSON User'{..} = object (catMaybes [("accountIdentifier" .=) <$> _uAccountIdentifier]) -- | Represents a whole or partial calendar date, such as a birthday. The -- time of day and time zone are either specified elsewhere or are -- insignificant. The date is relative to the Gregorian Calendar. This can -- represent one of the following: A full date, with non-zero year, month, -- and day values A month and day value, with a zero year, such as an -- anniversary A year on its own, with zero month and day values A year and -- month value, with a zero day, such as a credit card expiration -- dateRelated types are google.type.TimeOfDay and -- google.protobuf.Timestamp. -- -- /See:/ 'date' smart constructor. data Date = Date' { _dDay :: !(Maybe (Textual Int32)) , _dYear :: !(Maybe (Textual Int32)) , _dMonth :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Date' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dDay' -- -- * 'dYear' -- -- * 'dMonth' date :: Date date = Date' {_dDay = Nothing, _dYear = Nothing, _dMonth = Nothing} -- | Day of a month. Must be from 1 to 31 and valid for the year and month, -- or 0 to specify a year by itself or a year and month where the day -- isn\'t significant. dDay :: Lens' Date (Maybe Int32) dDay = lens _dDay (\ s a -> s{_dDay = a}) . mapping _Coerce -- | Year of the date. Must be from 1 to 9999, or 0 to specify a date without -- a year. dYear :: Lens' Date (Maybe Int32) dYear = lens _dYear (\ s a -> s{_dYear = a}) . mapping _Coerce -- | Month of a year. Must be from 1 to 12, or 0 to specify a year without a -- month and day. dMonth :: Lens' Date (Maybe Int32) dMonth = lens _dMonth (\ s a -> s{_dMonth = a}) . mapping _Coerce instance FromJSON Date where parseJSON = withObject "Date" (\ o -> Date' <$> (o .:? "day") <*> (o .:? "year") <*> (o .:? "month")) instance ToJSON Date where toJSON Date'{..} = object (catMaybes [("day" .=) <$> _dDay, ("year" .=) <$> _dYear, ("month" .=) <$> _dMonth]) -- | The security posture of the device, as determined by the current device -- state and the policies applied. -- -- /See:/ 'securityPosture' smart constructor. data SecurityPosture = SecurityPosture' { _spPostureDetails :: !(Maybe [PostureDetail]) , _spDevicePosture :: !(Maybe SecurityPostureDevicePosture) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SecurityPosture' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'spPostureDetails' -- -- * 'spDevicePosture' securityPosture :: SecurityPosture securityPosture = SecurityPosture' {_spPostureDetails = Nothing, _spDevicePosture = Nothing} -- | Additional details regarding the security posture of the device. spPostureDetails :: Lens' SecurityPosture [PostureDetail] spPostureDetails = lens _spPostureDetails (\ s a -> s{_spPostureDetails = a}) . _Default . _Coerce -- | Device\'s security posture value. spDevicePosture :: Lens' SecurityPosture (Maybe SecurityPostureDevicePosture) spDevicePosture = lens _spDevicePosture (\ s a -> s{_spDevicePosture = a}) instance FromJSON SecurityPosture where parseJSON = withObject "SecurityPosture" (\ o -> SecurityPosture' <$> (o .:? "postureDetails" .!= mempty) <*> (o .:? "devicePosture")) instance ToJSON SecurityPosture where toJSON SecurityPosture'{..} = object (catMaybes [("postureDetails" .=) <$> _spPostureDetails, ("devicePosture" .=) <$> _spDevicePosture]) -- | Configuration for managing system updates -- -- /See:/ 'systemUpdate' smart constructor. data SystemUpdate = SystemUpdate' { _suFreezePeriods :: !(Maybe [FreezePeriod]) , _suEndMinutes :: !(Maybe (Textual Int32)) , _suStartMinutes :: !(Maybe (Textual Int32)) , _suType :: !(Maybe SystemUpdateType) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SystemUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'suFreezePeriods' -- -- * 'suEndMinutes' -- -- * 'suStartMinutes' -- -- * 'suType' systemUpdate :: SystemUpdate systemUpdate = SystemUpdate' { _suFreezePeriods = Nothing , _suEndMinutes = Nothing , _suStartMinutes = Nothing , _suType = Nothing } -- | An annually repeating time period in which over-the-air (OTA) system -- updates are postponed to freeze the OS version running on a device. To -- prevent freezing the device indefinitely, each freeze period must be -- separated by at least 60 days. suFreezePeriods :: Lens' SystemUpdate [FreezePeriod] suFreezePeriods = lens _suFreezePeriods (\ s a -> s{_suFreezePeriods = a}) . _Default . _Coerce -- | If the type is WINDOWED, the end of the maintenance window, measured as -- the number of minutes after midnight in device\'s local time. This value -- must be between 0 and 1439, inclusive. If this value is less than -- start_minutes, then the maintenance window spans midnight. If the -- maintenance window specified is smaller than 30 minutes, the actual -- window is extended to 30 minutes beyond the start time. suEndMinutes :: Lens' SystemUpdate (Maybe Int32) suEndMinutes = lens _suEndMinutes (\ s a -> s{_suEndMinutes = a}) . mapping _Coerce -- | If the type is WINDOWED, the start of the maintenance window, measured -- as the number of minutes after midnight in the device\'s local time. -- This value must be between 0 and 1439, inclusive. suStartMinutes :: Lens' SystemUpdate (Maybe Int32) suStartMinutes = lens _suStartMinutes (\ s a -> s{_suStartMinutes = a}) . mapping _Coerce -- | The type of system update to configure. suType :: Lens' SystemUpdate (Maybe SystemUpdateType) suType = lens _suType (\ s a -> s{_suType = a}) instance FromJSON SystemUpdate where parseJSON = withObject "SystemUpdate" (\ o -> SystemUpdate' <$> (o .:? "freezePeriods" .!= mempty) <*> (o .:? "endMinutes") <*> (o .:? "startMinutes") <*> (o .:? "type")) instance ToJSON SystemUpdate where toJSON SystemUpdate'{..} = object (catMaybes [("freezePeriods" .=) <$> _suFreezePeriods, ("endMinutes" .=) <$> _suEndMinutes, ("startMinutes" .=) <$> _suStartMinutes, ("type" .=) <$> _suType]) -- | Map of selected system properties name and value related to the device. -- This information is only available if systemPropertiesEnabled is true in -- the device\'s policy. -- -- /See:/ 'deviceSystemProperties' smart constructor. newtype DeviceSystemProperties = DeviceSystemProperties' { _dspAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DeviceSystemProperties' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dspAddtional' deviceSystemProperties :: HashMap Text Text -- ^ 'dspAddtional' -> DeviceSystemProperties deviceSystemProperties pDspAddtional_ = DeviceSystemProperties' {_dspAddtional = _Coerce # pDspAddtional_} dspAddtional :: Lens' DeviceSystemProperties (HashMap Text Text) dspAddtional = lens _dspAddtional (\ s a -> s{_dspAddtional = a}) . _Coerce instance FromJSON DeviceSystemProperties where parseJSON = withObject "DeviceSystemProperties" (\ o -> DeviceSystemProperties' <$> (parseJSONObject o)) instance ToJSON DeviceSystemProperties where toJSON = toJSON . _dspAddtional -- | Information reported about an installed app. -- -- /See:/ 'applicationReport' smart constructor. data ApplicationReport = ApplicationReport' { _arVersionCode :: !(Maybe (Textual Int32)) , _arSigningKeyCertFingerprints :: !(Maybe [Text]) , _arState :: !(Maybe ApplicationReportState) , _arVersionName :: !(Maybe Text) , _arPackageName :: !(Maybe Text) , _arPackageSha256Hash :: !(Maybe Text) , _arKeyedAppStates :: !(Maybe [KeyedAppState]) , _arApplicationSource :: !(Maybe ApplicationReportApplicationSource) , _arEvents :: !(Maybe [ApplicationEvent]) , _arDisplayName :: !(Maybe Text) , _arInstallerPackageName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationReport' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'arVersionCode' -- -- * 'arSigningKeyCertFingerprints' -- -- * 'arState' -- -- * 'arVersionName' -- -- * 'arPackageName' -- -- * 'arPackageSha256Hash' -- -- * 'arKeyedAppStates' -- -- * 'arApplicationSource' -- -- * 'arEvents' -- -- * 'arDisplayName' -- -- * 'arInstallerPackageName' applicationReport :: ApplicationReport applicationReport = ApplicationReport' { _arVersionCode = Nothing , _arSigningKeyCertFingerprints = Nothing , _arState = Nothing , _arVersionName = Nothing , _arPackageName = Nothing , _arPackageSha256Hash = Nothing , _arKeyedAppStates = Nothing , _arApplicationSource = Nothing , _arEvents = Nothing , _arDisplayName = Nothing , _arInstallerPackageName = Nothing } -- | The app version code, which can be used to determine whether one version -- is more recent than another. arVersionCode :: Lens' ApplicationReport (Maybe Int32) arVersionCode = lens _arVersionCode (\ s a -> s{_arVersionCode = a}) . mapping _Coerce -- | The SHA-1 hash of each android.content.pm.Signature -- (https:\/\/developer.android.com\/reference\/android\/content\/pm\/Signature.html) -- associated with the app package. Each byte of each hash value is -- represented as a two-digit hexadecimal number. arSigningKeyCertFingerprints :: Lens' ApplicationReport [Text] arSigningKeyCertFingerprints = lens _arSigningKeyCertFingerprints (\ s a -> s{_arSigningKeyCertFingerprints = a}) . _Default . _Coerce -- | Application state. arState :: Lens' ApplicationReport (Maybe ApplicationReportState) arState = lens _arState (\ s a -> s{_arState = a}) -- | The app version as displayed to the user. arVersionName :: Lens' ApplicationReport (Maybe Text) arVersionName = lens _arVersionName (\ s a -> s{_arVersionName = a}) -- | Package name of the app. arPackageName :: Lens' ApplicationReport (Maybe Text) arPackageName = lens _arPackageName (\ s a -> s{_arPackageName = a}) -- | The SHA-256 hash of the app\'s APK file, which can be used to verify the -- app hasn\'t been modified. Each byte of the hash value is represented as -- a two-digit hexadecimal number. arPackageSha256Hash :: Lens' ApplicationReport (Maybe Text) arPackageSha256Hash = lens _arPackageSha256Hash (\ s a -> s{_arPackageSha256Hash = a}) -- | List of keyed app states reported by the app. arKeyedAppStates :: Lens' ApplicationReport [KeyedAppState] arKeyedAppStates = lens _arKeyedAppStates (\ s a -> s{_arKeyedAppStates = a}) . _Default . _Coerce -- | The source of the package. arApplicationSource :: Lens' ApplicationReport (Maybe ApplicationReportApplicationSource) arApplicationSource = lens _arApplicationSource (\ s a -> s{_arApplicationSource = a}) -- | List of app events. The most recent 20 events are stored in the list. arEvents :: Lens' ApplicationReport [ApplicationEvent] arEvents = lens _arEvents (\ s a -> s{_arEvents = a}) . _Default . _Coerce -- | The display name of the app. arDisplayName :: Lens' ApplicationReport (Maybe Text) arDisplayName = lens _arDisplayName (\ s a -> s{_arDisplayName = a}) -- | The package name of the app that installed this app. arInstallerPackageName :: Lens' ApplicationReport (Maybe Text) arInstallerPackageName = lens _arInstallerPackageName (\ s a -> s{_arInstallerPackageName = a}) instance FromJSON ApplicationReport where parseJSON = withObject "ApplicationReport" (\ o -> ApplicationReport' <$> (o .:? "versionCode") <*> (o .:? "signingKeyCertFingerprints" .!= mempty) <*> (o .:? "state") <*> (o .:? "versionName") <*> (o .:? "packageName") <*> (o .:? "packageSha256Hash") <*> (o .:? "keyedAppStates" .!= mempty) <*> (o .:? "applicationSource") <*> (o .:? "events" .!= mempty) <*> (o .:? "displayName") <*> (o .:? "installerPackageName")) instance ToJSON ApplicationReport where toJSON ApplicationReport'{..} = object (catMaybes [("versionCode" .=) <$> _arVersionCode, ("signingKeyCertFingerprints" .=) <$> _arSigningKeyCertFingerprints, ("state" .=) <$> _arState, ("versionName" .=) <$> _arVersionName, ("packageName" .=) <$> _arPackageName, ("packageSha256Hash" .=) <$> _arPackageSha256Hash, ("keyedAppStates" .=) <$> _arKeyedAppStates, ("applicationSource" .=) <$> _arApplicationSource, ("events" .=) <$> _arEvents, ("displayName" .=) <$> _arDisplayName, ("installerPackageName" .=) <$> _arInstallerPackageName]) -- | Security policies set to the most secure values by default. To maintain -- the security posture of a device, we don\'t recommend overriding any of -- the default values. -- -- /See:/ 'advancedSecurityOverrides' smart constructor. data AdvancedSecurityOverrides = AdvancedSecurityOverrides' { _asoUntrustedAppsPolicy :: !(Maybe AdvancedSecurityOverridesUntrustedAppsPolicy) , _asoCommonCriteriaMode :: !(Maybe AdvancedSecurityOverridesCommonCriteriaMode) , _asoDeveloperSettings :: !(Maybe AdvancedSecurityOverridesDeveloperSettings) , _asoGooglePlayProtectVerifyApps :: !(Maybe AdvancedSecurityOverridesGooglePlayProtectVerifyApps) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AdvancedSecurityOverrides' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asoUntrustedAppsPolicy' -- -- * 'asoCommonCriteriaMode' -- -- * 'asoDeveloperSettings' -- -- * 'asoGooglePlayProtectVerifyApps' advancedSecurityOverrides :: AdvancedSecurityOverrides advancedSecurityOverrides = AdvancedSecurityOverrides' { _asoUntrustedAppsPolicy = Nothing , _asoCommonCriteriaMode = Nothing , _asoDeveloperSettings = Nothing , _asoGooglePlayProtectVerifyApps = Nothing } -- | The policy for untrusted apps (apps from unknown sources) enforced on -- the device. Replaces install_unknown_sources_allowed (deprecated). asoUntrustedAppsPolicy :: Lens' AdvancedSecurityOverrides (Maybe AdvancedSecurityOverridesUntrustedAppsPolicy) asoUntrustedAppsPolicy = lens _asoUntrustedAppsPolicy (\ s a -> s{_asoUntrustedAppsPolicy = a}) -- | Controls Common Criteria Mode—security standards defined in the Common -- Criteria for Information Technology Security Evaluation -- (https:\/\/www.commoncriteriaportal.org\/) (CC). Enabling Common -- Criteria Mode increases certain security components on a device, -- including AES-GCM encryption of Bluetooth Long Term Keys, and Wi-Fi -- configuration stores.Warning: Common Criteria Mode enforces a strict -- security model typically only required for IT products used in national -- security systems and other highly sensitive organizations. Standard -- device use may be affected. Only enabled if required. asoCommonCriteriaMode :: Lens' AdvancedSecurityOverrides (Maybe AdvancedSecurityOverridesCommonCriteriaMode) asoCommonCriteriaMode = lens _asoCommonCriteriaMode (\ s a -> s{_asoCommonCriteriaMode = a}) -- | Controls access to developer settings: developer options and safe boot. -- Replaces safeBootDisabled (deprecated) and debuggingFeaturesAllowed -- (deprecated). asoDeveloperSettings :: Lens' AdvancedSecurityOverrides (Maybe AdvancedSecurityOverridesDeveloperSettings) asoDeveloperSettings = lens _asoDeveloperSettings (\ s a -> s{_asoDeveloperSettings = a}) -- | Whether Google Play Protect verification -- (https:\/\/support.google.com\/accounts\/answer\/2812853) is enforced. -- Replaces ensureVerifyAppsEnabled (deprecated). asoGooglePlayProtectVerifyApps :: Lens' AdvancedSecurityOverrides (Maybe AdvancedSecurityOverridesGooglePlayProtectVerifyApps) asoGooglePlayProtectVerifyApps = lens _asoGooglePlayProtectVerifyApps (\ s a -> s{_asoGooglePlayProtectVerifyApps = a}) instance FromJSON AdvancedSecurityOverrides where parseJSON = withObject "AdvancedSecurityOverrides" (\ o -> AdvancedSecurityOverrides' <$> (o .:? "untrustedAppsPolicy") <*> (o .:? "commonCriteriaMode") <*> (o .:? "developerSettings") <*> (o .:? "googlePlayProtectVerifyApps")) instance ToJSON AdvancedSecurityOverrides where toJSON AdvancedSecurityOverrides'{..} = object (catMaybes [("untrustedAppsPolicy" .=) <$> _asoUntrustedAppsPolicy, ("commonCriteriaMode" .=) <$> _asoCommonCriteriaMode, ("developerSettings" .=) <$> _asoDeveloperSettings, ("googlePlayProtectVerifyApps" .=) <$> _asoGooglePlayProtectVerifyApps]) -- | An enrollment token. -- -- /See:/ 'enrollmentToken' smart constructor. data EnrollmentToken = EnrollmentToken' { _etPolicyName :: !(Maybe Text) , _etValue :: !(Maybe Text) , _etQrCode :: !(Maybe Text) , _etAdditionalData :: !(Maybe Text) , _etUser :: !(Maybe User) , _etAllowPersonalUsage :: !(Maybe EnrollmentTokenAllowPersonalUsage) , _etName :: !(Maybe Text) , _etOneTimeOnly :: !(Maybe Bool) , _etExpirationTimestamp :: !(Maybe DateTime') , _etDuration :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EnrollmentToken' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'etPolicyName' -- -- * 'etValue' -- -- * 'etQrCode' -- -- * 'etAdditionalData' -- -- * 'etUser' -- -- * 'etAllowPersonalUsage' -- -- * 'etName' -- -- * 'etOneTimeOnly' -- -- * 'etExpirationTimestamp' -- -- * 'etDuration' enrollmentToken :: EnrollmentToken enrollmentToken = EnrollmentToken' { _etPolicyName = Nothing , _etValue = Nothing , _etQrCode = Nothing , _etAdditionalData = Nothing , _etUser = Nothing , _etAllowPersonalUsage = Nothing , _etName = Nothing , _etOneTimeOnly = Nothing , _etExpirationTimestamp = Nothing , _etDuration = Nothing } -- | The name of the policy initially applied to the enrolled device, in the -- form enterprises\/{enterpriseId}\/policies\/{policyId}. If not -- specified, the policy_name for the device’s user is applied. If -- user_name is also not specified, -- enterprises\/{enterpriseId}\/policies\/default is applied by default. -- When updating this field, you can specify only the policyId as long as -- the policyId doesn’t contain any slashes. The rest of the policy name -- will be inferred. etPolicyName :: Lens' EnrollmentToken (Maybe Text) etPolicyName = lens _etPolicyName (\ s a -> s{_etPolicyName = a}) -- | The token value that\'s passed to the device and authorizes the device -- to enroll. This is a read-only field generated by the server. etValue :: Lens' EnrollmentToken (Maybe Text) etValue = lens _etValue (\ s a -> s{_etValue = a}) -- | A JSON string whose UTF-8 representation can be used to generate a QR -- code to enroll a device with this enrollment token. To enroll a device -- using NFC, the NFC record must contain a serialized java.util.Properties -- representation of the properties in the JSON. etQrCode :: Lens' EnrollmentToken (Maybe Text) etQrCode = lens _etQrCode (\ s a -> s{_etQrCode = a}) -- | Optional, arbitrary data associated with the enrollment token. This -- could contain, for example, the ID of an org unit the device is assigned -- to after enrollment. After a device enrolls with the token, this data -- will be exposed in the enrollment_token_data field of the Device -- resource. The data must be 1024 characters or less; otherwise, the -- creation request will fail. etAdditionalData :: Lens' EnrollmentToken (Maybe Text) etAdditionalData = lens _etAdditionalData (\ s a -> s{_etAdditionalData = a}) -- | The user associated with this enrollment token. If it\'s specified when -- the enrollment token is created and the user does not exist, the user -- will be created. This field must not contain personally identifiable -- information. Only the account_identifier field needs to be set. etUser :: Lens' EnrollmentToken (Maybe User) etUser = lens _etUser (\ s a -> s{_etUser = a}) -- | Controls whether personal usage is allowed on a device provisioned with -- this enrollment token.For company-owned devices: Enabling personal usage -- allows the user to set up a work profile on the device. Disabling -- personal usage requires the user provision the device as a fully managed -- device.For personally-owned devices: Enabling personal usage allows the -- user to set up a work profile on the device. Disabling personal usage -- will prevent the device from provisioning. Personal usage cannot be -- disabled on personally-owned device. etAllowPersonalUsage :: Lens' EnrollmentToken (Maybe EnrollmentTokenAllowPersonalUsage) etAllowPersonalUsage = lens _etAllowPersonalUsage (\ s a -> s{_etAllowPersonalUsage = a}) -- | The name of the enrollment token, which is generated by the server -- during creation, in the form -- enterprises\/{enterpriseId}\/enrollmentTokens\/{enrollmentTokenId}. etName :: Lens' EnrollmentToken (Maybe Text) etName = lens _etName (\ s a -> s{_etName = a}) -- | Whether the enrollment token is for one time use only. If the flag is -- set to true, only one device can use it for registration. etOneTimeOnly :: Lens' EnrollmentToken (Maybe Bool) etOneTimeOnly = lens _etOneTimeOnly (\ s a -> s{_etOneTimeOnly = a}) -- | The expiration time of the token. This is a read-only field generated by -- the server. etExpirationTimestamp :: Lens' EnrollmentToken (Maybe UTCTime) etExpirationTimestamp = lens _etExpirationTimestamp (\ s a -> s{_etExpirationTimestamp = a}) . mapping _DateTime -- | The length of time the enrollment token is valid, ranging from 1 minute -- to 90 days. If not specified, the default duration is 1 hour. etDuration :: Lens' EnrollmentToken (Maybe Scientific) etDuration = lens _etDuration (\ s a -> s{_etDuration = a}) . mapping _GDuration instance FromJSON EnrollmentToken where parseJSON = withObject "EnrollmentToken" (\ o -> EnrollmentToken' <$> (o .:? "policyName") <*> (o .:? "value") <*> (o .:? "qrCode") <*> (o .:? "additionalData") <*> (o .:? "user") <*> (o .:? "allowPersonalUsage") <*> (o .:? "name") <*> (o .:? "oneTimeOnly") <*> (o .:? "expirationTimestamp") <*> (o .:? "duration")) instance ToJSON EnrollmentToken where toJSON EnrollmentToken'{..} = object (catMaybes [("policyName" .=) <$> _etPolicyName, ("value" .=) <$> _etValue, ("qrCode" .=) <$> _etQrCode, ("additionalData" .=) <$> _etAdditionalData, ("user" .=) <$> _etUser, ("allowPersonalUsage" .=) <$> _etAllowPersonalUsage, ("name" .=) <$> _etName, ("oneTimeOnly" .=) <$> _etOneTimeOnly, ("expirationTimestamp" .=) <$> _etExpirationTimestamp, ("duration" .=) <$> _etDuration]) -- | Response to a request to list enterprises. -- -- /See:/ 'listEnterprisesResponse' smart constructor. data ListEnterprisesResponse = ListEnterprisesResponse' { _lerNextPageToken :: !(Maybe Text) , _lerEnterprises :: !(Maybe [Enterprise]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListEnterprisesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lerNextPageToken' -- -- * 'lerEnterprises' listEnterprisesResponse :: ListEnterprisesResponse listEnterprisesResponse = ListEnterprisesResponse' {_lerNextPageToken = Nothing, _lerEnterprises = Nothing} -- | If there are more results, a token to retrieve next page of results. lerNextPageToken :: Lens' ListEnterprisesResponse (Maybe Text) lerNextPageToken = lens _lerNextPageToken (\ s a -> s{_lerNextPageToken = a}) -- | The list of enterprises. lerEnterprises :: Lens' ListEnterprisesResponse [Enterprise] lerEnterprises = lens _lerEnterprises (\ s a -> s{_lerEnterprises = a}) . _Default . _Coerce instance FromJSON ListEnterprisesResponse where parseJSON = withObject "ListEnterprisesResponse" (\ o -> ListEnterprisesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "enterprises" .!= mempty)) instance ToJSON ListEnterprisesResponse where toJSON ListEnterprisesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lerNextPageToken, ("enterprises" .=) <$> _lerEnterprises]) -- | Managed configuration applied to the app. The format for the -- configuration is dictated by the ManagedProperty values supported by the -- app. Each field name in the managed configuration must match the key -- field of the ManagedProperty. The field value must be compatible with -- the type of the ManagedProperty: *type* *JSON value* BOOL true or false -- STRING string INTEGER number CHOICE string MULTISELECT array of strings -- HIDDEN string BUNDLE_ARRAY array of objects -- -- /See:/ 'applicationPolicyManagedConfiguration' smart constructor. newtype ApplicationPolicyManagedConfiguration = ApplicationPolicyManagedConfiguration' { _apmcAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationPolicyManagedConfiguration' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apmcAddtional' applicationPolicyManagedConfiguration :: HashMap Text JSONValue -- ^ 'apmcAddtional' -> ApplicationPolicyManagedConfiguration applicationPolicyManagedConfiguration pApmcAddtional_ = ApplicationPolicyManagedConfiguration' {_apmcAddtional = _Coerce # pApmcAddtional_} -- | Properties of the object. apmcAddtional :: Lens' ApplicationPolicyManagedConfiguration (HashMap Text JSONValue) apmcAddtional = lens _apmcAddtional (\ s a -> s{_apmcAddtional = a}) . _Coerce instance FromJSON ApplicationPolicyManagedConfiguration where parseJSON = withObject "ApplicationPolicyManagedConfiguration" (\ o -> ApplicationPolicyManagedConfiguration' <$> (parseJSONObject o)) instance ToJSON ApplicationPolicyManagedConfiguration where toJSON = toJSON . _apmcAddtional -- | An action to block access to apps and data on a fully managed device or -- in a work profile. This action also triggers a device or work profile to -- displays a user-facing notification with information (where possible) on -- how to correct the compliance issue. Note: wipeAction must also be -- specified. -- -- /See:/ 'blockAction' smart constructor. data BlockAction = BlockAction' { _baBlockScope :: !(Maybe BlockActionBlockScope) , _baBlockAfterDays :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BlockAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'baBlockScope' -- -- * 'baBlockAfterDays' blockAction :: BlockAction blockAction = BlockAction' {_baBlockScope = Nothing, _baBlockAfterDays = Nothing} -- | Specifies the scope of this BlockAction. Only applicable to devices that -- are company-owned. baBlockScope :: Lens' BlockAction (Maybe BlockActionBlockScope) baBlockScope = lens _baBlockScope (\ s a -> s{_baBlockScope = a}) -- | Number of days the policy is non-compliant before the device or work -- profile is blocked. To block access immediately, set to 0. -- blockAfterDays must be less than wipeAfterDays. baBlockAfterDays :: Lens' BlockAction (Maybe Int32) baBlockAfterDays = lens _baBlockAfterDays (\ s a -> s{_baBlockAfterDays = a}) . mapping _Coerce instance FromJSON BlockAction where parseJSON = withObject "BlockAction" (\ o -> BlockAction' <$> (o .:? "blockScope") <*> (o .:? "blockAfterDays")) instance ToJSON BlockAction where toJSON BlockAction'{..} = object (catMaybes [("blockScope" .=) <$> _baBlockScope, ("blockAfterDays" .=) <$> _baBlockAfterDays]) -- | Settings controlling the behavior of status reports. -- -- /See:/ 'statusReportingSettings' smart constructor. data StatusReportingSettings = StatusReportingSettings' { _srsSoftwareInfoEnabled :: !(Maybe Bool) , _srsHardwareStatusEnabled :: !(Maybe Bool) , _srsPowerManagementEventsEnabled :: !(Maybe Bool) , _srsDisplayInfoEnabled :: !(Maybe Bool) , _srsApplicationReportsEnabled :: !(Maybe Bool) , _srsMemoryInfoEnabled :: !(Maybe Bool) , _srsNetworkInfoEnabled :: !(Maybe Bool) , _srsDeviceSettingsEnabled :: !(Maybe Bool) , _srsCommonCriteriaModeEnabled :: !(Maybe Bool) , _srsSystemPropertiesEnabled :: !(Maybe Bool) , _srsApplicationReportingSettings :: !(Maybe ApplicationReportingSettings) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusReportingSettings' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srsSoftwareInfoEnabled' -- -- * 'srsHardwareStatusEnabled' -- -- * 'srsPowerManagementEventsEnabled' -- -- * 'srsDisplayInfoEnabled' -- -- * 'srsApplicationReportsEnabled' -- -- * 'srsMemoryInfoEnabled' -- -- * 'srsNetworkInfoEnabled' -- -- * 'srsDeviceSettingsEnabled' -- -- * 'srsCommonCriteriaModeEnabled' -- -- * 'srsSystemPropertiesEnabled' -- -- * 'srsApplicationReportingSettings' statusReportingSettings :: StatusReportingSettings statusReportingSettings = StatusReportingSettings' { _srsSoftwareInfoEnabled = Nothing , _srsHardwareStatusEnabled = Nothing , _srsPowerManagementEventsEnabled = Nothing , _srsDisplayInfoEnabled = Nothing , _srsApplicationReportsEnabled = Nothing , _srsMemoryInfoEnabled = Nothing , _srsNetworkInfoEnabled = Nothing , _srsDeviceSettingsEnabled = Nothing , _srsCommonCriteriaModeEnabled = Nothing , _srsSystemPropertiesEnabled = Nothing , _srsApplicationReportingSettings = Nothing } -- | Whether software info reporting is enabled. srsSoftwareInfoEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsSoftwareInfoEnabled = lens _srsSoftwareInfoEnabled (\ s a -> s{_srsSoftwareInfoEnabled = a}) -- | Whether hardware status reporting is enabled. Report data is not -- available for personally owned devices with work profiles. srsHardwareStatusEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsHardwareStatusEnabled = lens _srsHardwareStatusEnabled (\ s a -> s{_srsHardwareStatusEnabled = a}) -- | Whether power management event reporting is enabled. Report data is not -- available for personally owned devices with work profiles. srsPowerManagementEventsEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsPowerManagementEventsEnabled = lens _srsPowerManagementEventsEnabled (\ s a -> s{_srsPowerManagementEventsEnabled = a}) -- | Whether displays reporting is enabled. Report data is not available for -- personally owned devices with work profiles. srsDisplayInfoEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsDisplayInfoEnabled = lens _srsDisplayInfoEnabled (\ s a -> s{_srsDisplayInfoEnabled = a}) -- | Whether app reports are enabled. srsApplicationReportsEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsApplicationReportsEnabled = lens _srsApplicationReportsEnabled (\ s a -> s{_srsApplicationReportsEnabled = a}) -- | Whether memory reporting is enabled. srsMemoryInfoEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsMemoryInfoEnabled = lens _srsMemoryInfoEnabled (\ s a -> s{_srsMemoryInfoEnabled = a}) -- | Whether network info reporting is enabled. srsNetworkInfoEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsNetworkInfoEnabled = lens _srsNetworkInfoEnabled (\ s a -> s{_srsNetworkInfoEnabled = a}) -- | Whether device settings reporting is enabled. srsDeviceSettingsEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsDeviceSettingsEnabled = lens _srsDeviceSettingsEnabled (\ s a -> s{_srsDeviceSettingsEnabled = a}) -- | Whether Common Criteria Mode reporting is enabled. srsCommonCriteriaModeEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsCommonCriteriaModeEnabled = lens _srsCommonCriteriaModeEnabled (\ s a -> s{_srsCommonCriteriaModeEnabled = a}) -- | Whether system properties reporting is enabled. srsSystemPropertiesEnabled :: Lens' StatusReportingSettings (Maybe Bool) srsSystemPropertiesEnabled = lens _srsSystemPropertiesEnabled (\ s a -> s{_srsSystemPropertiesEnabled = a}) -- | Application reporting settings. Only applicable if -- application_reports_enabled is true. srsApplicationReportingSettings :: Lens' StatusReportingSettings (Maybe ApplicationReportingSettings) srsApplicationReportingSettings = lens _srsApplicationReportingSettings (\ s a -> s{_srsApplicationReportingSettings = a}) instance FromJSON StatusReportingSettings where parseJSON = withObject "StatusReportingSettings" (\ o -> StatusReportingSettings' <$> (o .:? "softwareInfoEnabled") <*> (o .:? "hardwareStatusEnabled") <*> (o .:? "powerManagementEventsEnabled") <*> (o .:? "displayInfoEnabled") <*> (o .:? "applicationReportsEnabled") <*> (o .:? "memoryInfoEnabled") <*> (o .:? "networkInfoEnabled") <*> (o .:? "deviceSettingsEnabled") <*> (o .:? "commonCriteriaModeEnabled") <*> (o .:? "systemPropertiesEnabled") <*> (o .:? "applicationReportingSettings")) instance ToJSON StatusReportingSettings where toJSON StatusReportingSettings'{..} = object (catMaybes [("softwareInfoEnabled" .=) <$> _srsSoftwareInfoEnabled, ("hardwareStatusEnabled" .=) <$> _srsHardwareStatusEnabled, ("powerManagementEventsEnabled" .=) <$> _srsPowerManagementEventsEnabled, ("displayInfoEnabled" .=) <$> _srsDisplayInfoEnabled, ("applicationReportsEnabled" .=) <$> _srsApplicationReportsEnabled, ("memoryInfoEnabled" .=) <$> _srsMemoryInfoEnabled, ("networkInfoEnabled" .=) <$> _srsNetworkInfoEnabled, ("deviceSettingsEnabled" .=) <$> _srsDeviceSettingsEnabled, ("commonCriteriaModeEnabled" .=) <$> _srsCommonCriteriaModeEnabled, ("systemPropertiesEnabled" .=) <$> _srsSystemPropertiesEnabled, ("applicationReportingSettings" .=) <$> _srsApplicationReportingSettings]) -- | Information about a potential pending system update. -- -- /See:/ 'systemUpdateInfo' smart constructor. data SystemUpdateInfo = SystemUpdateInfo' { _suiUpdateStatus :: !(Maybe SystemUpdateInfoUpdateStatus) , _suiUpdateReceivedTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SystemUpdateInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'suiUpdateStatus' -- -- * 'suiUpdateReceivedTime' systemUpdateInfo :: SystemUpdateInfo systemUpdateInfo = SystemUpdateInfo' {_suiUpdateStatus = Nothing, _suiUpdateReceivedTime = Nothing} -- | The status of an update: whether an update exists and what type it is. suiUpdateStatus :: Lens' SystemUpdateInfo (Maybe SystemUpdateInfoUpdateStatus) suiUpdateStatus = lens _suiUpdateStatus (\ s a -> s{_suiUpdateStatus = a}) -- | The time when the update was first available. A zero value indicates -- that this field is not set. This field is set only if an update is -- available (that is, updateStatus is neither UPDATE_STATUS_UNKNOWN nor -- UP_TO_DATE). suiUpdateReceivedTime :: Lens' SystemUpdateInfo (Maybe UTCTime) suiUpdateReceivedTime = lens _suiUpdateReceivedTime (\ s a -> s{_suiUpdateReceivedTime = a}) . mapping _DateTime instance FromJSON SystemUpdateInfo where parseJSON = withObject "SystemUpdateInfo" (\ o -> SystemUpdateInfo' <$> (o .:? "updateStatus") <*> (o .:? "updateReceivedTime")) instance ToJSON SystemUpdateInfo where toJSON SystemUpdateInfo'{..} = object (catMaybes [("updateStatus" .=) <$> _suiUpdateStatus, ("updateReceivedTime" .=) <$> _suiUpdateReceivedTime]) -- | An icon for a web app. Supported formats are: png, jpg and webp. -- -- /See:/ 'webAppIcon' smart constructor. newtype WebAppIcon = WebAppIcon' { _waiImageData :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WebAppIcon' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'waiImageData' webAppIcon :: WebAppIcon webAppIcon = WebAppIcon' {_waiImageData = Nothing} -- | The actual bytes of the image in a base64url encoded string (c.f. -- RFC4648, section 5 \"Base 64 Encoding with URL and Filename Safe -- Alphabet\"). - The image type can be png or jpg. - The image should -- ideally be square. - The image should ideally have a size of 512x512. waiImageData :: Lens' WebAppIcon (Maybe Text) waiImageData = lens _waiImageData (\ s a -> s{_waiImageData = a}) instance FromJSON WebAppIcon where parseJSON = withObject "WebAppIcon" (\ o -> WebAppIcon' <$> (o .:? "imageData")) instance ToJSON WebAppIcon where toJSON WebAppIcon'{..} = object (catMaybes [("imageData" .=) <$> _waiImageData]) -- | Policy for an individual app. -- -- /See:/ 'applicationPolicy' smart constructor. data ApplicationPolicy = ApplicationPolicy' { _apAccessibleTrackIds :: !(Maybe [Text]) , _apDelegatedScopes :: !(Maybe [ApplicationPolicyDelegatedScopesItem]) , _apPackageName :: !(Maybe Text) , _apManagedConfiguration :: !(Maybe ApplicationPolicyManagedConfiguration) , _apDefaultPermissionPolicy :: !(Maybe ApplicationPolicyDefaultPermissionPolicy) , _apDisabled :: !(Maybe Bool) , _apLockTaskAllowed :: !(Maybe Bool) , _apPermissionGrants :: !(Maybe [PermissionGrant]) , _apConnectedWorkAndPersonalApp :: !(Maybe ApplicationPolicyConnectedWorkAndPersonalApp) , _apManagedConfigurationTemplate :: !(Maybe ManagedConfigurationTemplate) , _apAutoUpdateMode :: !(Maybe ApplicationPolicyAutoUpdateMode) , _apMinimumVersionCode :: !(Maybe (Textual Int32)) , _apInstallType :: !(Maybe ApplicationPolicyInstallType) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apAccessibleTrackIds' -- -- * 'apDelegatedScopes' -- -- * 'apPackageName' -- -- * 'apManagedConfiguration' -- -- * 'apDefaultPermissionPolicy' -- -- * 'apDisabled' -- -- * 'apLockTaskAllowed' -- -- * 'apPermissionGrants' -- -- * 'apConnectedWorkAndPersonalApp' -- -- * 'apManagedConfigurationTemplate' -- -- * 'apAutoUpdateMode' -- -- * 'apMinimumVersionCode' -- -- * 'apInstallType' applicationPolicy :: ApplicationPolicy applicationPolicy = ApplicationPolicy' { _apAccessibleTrackIds = Nothing , _apDelegatedScopes = Nothing , _apPackageName = Nothing , _apManagedConfiguration = Nothing , _apDefaultPermissionPolicy = Nothing , _apDisabled = Nothing , _apLockTaskAllowed = Nothing , _apPermissionGrants = Nothing , _apConnectedWorkAndPersonalApp = Nothing , _apManagedConfigurationTemplate = Nothing , _apAutoUpdateMode = Nothing , _apMinimumVersionCode = Nothing , _apInstallType = Nothing } -- | List of the app’s track IDs that a device belonging to the enterprise -- can access. If the list contains multiple track IDs, devices receive the -- latest version among all accessible tracks. If the list contains no -- track IDs, devices only have access to the app’s production track. More -- details about each track are available in AppTrackInfo. apAccessibleTrackIds :: Lens' ApplicationPolicy [Text] apAccessibleTrackIds = lens _apAccessibleTrackIds (\ s a -> s{_apAccessibleTrackIds = a}) . _Default . _Coerce -- | The scopes delegated to the app from Android Device Policy. apDelegatedScopes :: Lens' ApplicationPolicy [ApplicationPolicyDelegatedScopesItem] apDelegatedScopes = lens _apDelegatedScopes (\ s a -> s{_apDelegatedScopes = a}) . _Default . _Coerce -- | The package name of the app. For example, com.google.android.youtube for -- the YouTube app. apPackageName :: Lens' ApplicationPolicy (Maybe Text) apPackageName = lens _apPackageName (\ s a -> s{_apPackageName = a}) -- | Managed configuration applied to the app. The format for the -- configuration is dictated by the ManagedProperty values supported by the -- app. Each field name in the managed configuration must match the key -- field of the ManagedProperty. The field value must be compatible with -- the type of the ManagedProperty: *type* *JSON value* BOOL true or false -- STRING string INTEGER number CHOICE string MULTISELECT array of strings -- HIDDEN string BUNDLE_ARRAY array of objects apManagedConfiguration :: Lens' ApplicationPolicy (Maybe ApplicationPolicyManagedConfiguration) apManagedConfiguration = lens _apManagedConfiguration (\ s a -> s{_apManagedConfiguration = a}) -- | The default policy for all permissions requested by the app. If -- specified, this overrides the policy-level default_permission_policy -- which applies to all apps. It does not override the permission_grants -- which applies to all apps. apDefaultPermissionPolicy :: Lens' ApplicationPolicy (Maybe ApplicationPolicyDefaultPermissionPolicy) apDefaultPermissionPolicy = lens _apDefaultPermissionPolicy (\ s a -> s{_apDefaultPermissionPolicy = a}) -- | Whether the app is disabled. When disabled, the app data is still -- preserved. apDisabled :: Lens' ApplicationPolicy (Maybe Bool) apDisabled = lens _apDisabled (\ s a -> s{_apDisabled = a}) -- | Whether the app is allowed to lock itself in full-screen mode. -- DEPRECATED. Use InstallType KIOSK or kioskCustomLauncherEnabled to to -- configure a dedicated device. apLockTaskAllowed :: Lens' ApplicationPolicy (Maybe Bool) apLockTaskAllowed = lens _apLockTaskAllowed (\ s a -> s{_apLockTaskAllowed = a}) -- | Explicit permission grants or denials for the app. These values override -- the default_permission_policy and permission_grants which apply to all -- apps. apPermissionGrants :: Lens' ApplicationPolicy [PermissionGrant] apPermissionGrants = lens _apPermissionGrants (\ s a -> s{_apPermissionGrants = a}) . _Default . _Coerce -- | Controls whether the app can communicate with itself across a device’s -- work and personal profiles, subject to user consent. apConnectedWorkAndPersonalApp :: Lens' ApplicationPolicy (Maybe ApplicationPolicyConnectedWorkAndPersonalApp) apConnectedWorkAndPersonalApp = lens _apConnectedWorkAndPersonalApp (\ s a -> s{_apConnectedWorkAndPersonalApp = a}) -- | The managed configurations template for the app, saved from the managed -- configurations iframe. This field is ignored if managed_configuration is -- set. apManagedConfigurationTemplate :: Lens' ApplicationPolicy (Maybe ManagedConfigurationTemplate) apManagedConfigurationTemplate = lens _apManagedConfigurationTemplate (\ s a -> s{_apManagedConfigurationTemplate = a}) -- | Controls the auto-update mode for the app. apAutoUpdateMode :: Lens' ApplicationPolicy (Maybe ApplicationPolicyAutoUpdateMode) apAutoUpdateMode = lens _apAutoUpdateMode (\ s a -> s{_apAutoUpdateMode = a}) -- | The minimum version of the app that runs on the device. If set, the -- device attempts to update the app to at least this version code. If the -- app is not up-to-date, the device will contain a NonComplianceDetail -- with non_compliance_reason set to APP_NOT_UPDATED. The app must already -- be published to Google Play with a version code greater than or equal to -- this value. At most 20 apps may specify a minimum version code per -- policy. apMinimumVersionCode :: Lens' ApplicationPolicy (Maybe Int32) apMinimumVersionCode = lens _apMinimumVersionCode (\ s a -> s{_apMinimumVersionCode = a}) . mapping _Coerce -- | The type of installation to perform. apInstallType :: Lens' ApplicationPolicy (Maybe ApplicationPolicyInstallType) apInstallType = lens _apInstallType (\ s a -> s{_apInstallType = a}) instance FromJSON ApplicationPolicy where parseJSON = withObject "ApplicationPolicy" (\ o -> ApplicationPolicy' <$> (o .:? "accessibleTrackIds" .!= mempty) <*> (o .:? "delegatedScopes" .!= mempty) <*> (o .:? "packageName") <*> (o .:? "managedConfiguration") <*> (o .:? "defaultPermissionPolicy") <*> (o .:? "disabled") <*> (o .:? "lockTaskAllowed") <*> (o .:? "permissionGrants" .!= mempty) <*> (o .:? "connectedWorkAndPersonalApp") <*> (o .:? "managedConfigurationTemplate") <*> (o .:? "autoUpdateMode") <*> (o .:? "minimumVersionCode") <*> (o .:? "installType")) instance ToJSON ApplicationPolicy where toJSON ApplicationPolicy'{..} = object (catMaybes [("accessibleTrackIds" .=) <$> _apAccessibleTrackIds, ("delegatedScopes" .=) <$> _apDelegatedScopes, ("packageName" .=) <$> _apPackageName, ("managedConfiguration" .=) <$> _apManagedConfiguration, ("defaultPermissionPolicy" .=) <$> _apDefaultPermissionPolicy, ("disabled" .=) <$> _apDisabled, ("lockTaskAllowed" .=) <$> _apLockTaskAllowed, ("permissionGrants" .=) <$> _apPermissionGrants, ("connectedWorkAndPersonalApp" .=) <$> _apConnectedWorkAndPersonalApp, ("managedConfigurationTemplate" .=) <$> _apManagedConfigurationTemplate, ("autoUpdateMode" .=) <$> _apAutoUpdateMode, ("minimumVersionCode" .=) <$> _apMinimumVersionCode, ("installType" .=) <$> _apInstallType]) -- | Response to a request to list devices for a given enterprise. -- -- /See:/ 'listDevicesResponse' smart constructor. data ListDevicesResponse = ListDevicesResponse' { _ldrNextPageToken :: !(Maybe Text) , _ldrDevices :: !(Maybe [Device]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListDevicesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ldrNextPageToken' -- -- * 'ldrDevices' listDevicesResponse :: ListDevicesResponse listDevicesResponse = ListDevicesResponse' {_ldrNextPageToken = Nothing, _ldrDevices = Nothing} -- | If there are more results, a token to retrieve next page of results. ldrNextPageToken :: Lens' ListDevicesResponse (Maybe Text) ldrNextPageToken = lens _ldrNextPageToken (\ s a -> s{_ldrNextPageToken = a}) -- | The list of devices. ldrDevices :: Lens' ListDevicesResponse [Device] ldrDevices = lens _ldrDevices (\ s a -> s{_ldrDevices = a}) . _Default . _Coerce instance FromJSON ListDevicesResponse where parseJSON = withObject "ListDevicesResponse" (\ o -> ListDevicesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "devices" .!= mempty)) instance ToJSON ListDevicesResponse where toJSON ListDevicesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _ldrNextPageToken, ("devices" .=) <$> _ldrDevices]) -- | The managed configurations template for the app, saved from the managed -- configurations iframe. -- -- /See:/ 'managedConfigurationTemplate' smart constructor. data ManagedConfigurationTemplate = ManagedConfigurationTemplate' { _mctTemplateId :: !(Maybe Text) , _mctConfigurationVariables :: !(Maybe ManagedConfigurationTemplateConfigurationVariables) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ManagedConfigurationTemplate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mctTemplateId' -- -- * 'mctConfigurationVariables' managedConfigurationTemplate :: ManagedConfigurationTemplate managedConfigurationTemplate = ManagedConfigurationTemplate' {_mctTemplateId = Nothing, _mctConfigurationVariables = Nothing} -- | The ID of the managed configurations template. mctTemplateId :: Lens' ManagedConfigurationTemplate (Maybe Text) mctTemplateId = lens _mctTemplateId (\ s a -> s{_mctTemplateId = a}) -- | Optional, a map containing configuration variables defined for the -- configuration. mctConfigurationVariables :: Lens' ManagedConfigurationTemplate (Maybe ManagedConfigurationTemplateConfigurationVariables) mctConfigurationVariables = lens _mctConfigurationVariables (\ s a -> s{_mctConfigurationVariables = a}) instance FromJSON ManagedConfigurationTemplate where parseJSON = withObject "ManagedConfigurationTemplate" (\ o -> ManagedConfigurationTemplate' <$> (o .:? "templateId") <*> (o .:? "configurationVariables")) instance ToJSON ManagedConfigurationTemplate where toJSON ManagedConfigurationTemplate'{..} = object (catMaybes [("templateId" .=) <$> _mctTemplateId, ("configurationVariables" .=) <$> _mctConfigurationVariables]) -- | The configuration applied to an enterprise. -- -- /See:/ 'enterprise' smart constructor. data Enterprise = Enterprise' { _eAppAutoApprovalEnabled :: !(Maybe Bool) , _eEnabledNotificationTypes :: !(Maybe [EnterpriseEnabledNotificationTypesItem]) , _eSigninDetails :: !(Maybe [SigninDetail]) , _eName :: !(Maybe Text) , _ePubsubTopic :: !(Maybe Text) , _eEnterpriseDisplayName :: !(Maybe Text) , _eLogo :: !(Maybe ExternalData) , _eTermsAndConditions :: !(Maybe [TermsAndConditions]) , _eContactInfo :: !(Maybe ContactInfo) , _ePrimaryColor :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Enterprise' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eAppAutoApprovalEnabled' -- -- * 'eEnabledNotificationTypes' -- -- * 'eSigninDetails' -- -- * 'eName' -- -- * 'ePubsubTopic' -- -- * 'eEnterpriseDisplayName' -- -- * 'eLogo' -- -- * 'eTermsAndConditions' -- -- * 'eContactInfo' -- -- * 'ePrimaryColor' enterprise :: Enterprise enterprise = Enterprise' { _eAppAutoApprovalEnabled = Nothing , _eEnabledNotificationTypes = Nothing , _eSigninDetails = Nothing , _eName = Nothing , _ePubsubTopic = Nothing , _eEnterpriseDisplayName = Nothing , _eLogo = Nothing , _eTermsAndConditions = Nothing , _eContactInfo = Nothing , _ePrimaryColor = Nothing } -- | Deprecated and unused. eAppAutoApprovalEnabled :: Lens' Enterprise (Maybe Bool) eAppAutoApprovalEnabled = lens _eAppAutoApprovalEnabled (\ s a -> s{_eAppAutoApprovalEnabled = a}) -- | The types of Google Pub\/Sub notifications enabled for the enterprise. eEnabledNotificationTypes :: Lens' Enterprise [EnterpriseEnabledNotificationTypesItem] eEnabledNotificationTypes = lens _eEnabledNotificationTypes (\ s a -> s{_eEnabledNotificationTypes = a}) . _Default . _Coerce -- | Sign-in details of the enterprise. eSigninDetails :: Lens' Enterprise [SigninDetail] eSigninDetails = lens _eSigninDetails (\ s a -> s{_eSigninDetails = a}) . _Default . _Coerce -- | The name of the enterprise which is generated by the server during -- creation, in the form enterprises\/{enterpriseId}. eName :: Lens' Enterprise (Maybe Text) eName = lens _eName (\ s a -> s{_eName = a}) -- | The topic that Cloud Pub\/Sub notifications are published to, in the -- form projects\/{project}\/topics\/{topic}. This field is only required -- if Pub\/Sub notifications are enabled. ePubsubTopic :: Lens' Enterprise (Maybe Text) ePubsubTopic = lens _ePubsubTopic (\ s a -> s{_ePubsubTopic = a}) -- | The name of the enterprise displayed to users. eEnterpriseDisplayName :: Lens' Enterprise (Maybe Text) eEnterpriseDisplayName = lens _eEnterpriseDisplayName (\ s a -> s{_eEnterpriseDisplayName = a}) -- | An image displayed as a logo during device provisioning. Supported types -- are: image\/bmp, image\/gif, image\/x-ico, image\/jpeg, image\/png, -- image\/webp, image\/vnd.wap.wbmp, image\/x-adobe-dng. eLogo :: Lens' Enterprise (Maybe ExternalData) eLogo = lens _eLogo (\ s a -> s{_eLogo = a}) -- | Terms and conditions that must be accepted when provisioning a device -- for this enterprise. A page of terms is generated for each value in this -- list. eTermsAndConditions :: Lens' Enterprise [TermsAndConditions] eTermsAndConditions = lens _eTermsAndConditions (\ s a -> s{_eTermsAndConditions = a}) . _Default . _Coerce -- | The enterprise contact info of an EMM-managed enterprise. eContactInfo :: Lens' Enterprise (Maybe ContactInfo) eContactInfo = lens _eContactInfo (\ s a -> s{_eContactInfo = a}) -- | A color in RGB format that indicates the predominant color to display in -- the device management app UI. The color components are stored as -- follows: (red \<\< 16) | (green \<\< 8) | blue, where the value of each -- component is between 0 and 255, inclusive. ePrimaryColor :: Lens' Enterprise (Maybe Int32) ePrimaryColor = lens _ePrimaryColor (\ s a -> s{_ePrimaryColor = a}) . mapping _Coerce instance FromJSON Enterprise where parseJSON = withObject "Enterprise" (\ o -> Enterprise' <$> (o .:? "appAutoApprovalEnabled") <*> (o .:? "enabledNotificationTypes" .!= mempty) <*> (o .:? "signinDetails" .!= mempty) <*> (o .:? "name") <*> (o .:? "pubsubTopic") <*> (o .:? "enterpriseDisplayName") <*> (o .:? "logo") <*> (o .:? "termsAndConditions" .!= mempty) <*> (o .:? "contactInfo") <*> (o .:? "primaryColor")) instance ToJSON Enterprise where toJSON Enterprise'{..} = object (catMaybes [("appAutoApprovalEnabled" .=) <$> _eAppAutoApprovalEnabled, ("enabledNotificationTypes" .=) <$> _eEnabledNotificationTypes, ("signinDetails" .=) <$> _eSigninDetails, ("name" .=) <$> _eName, ("pubsubTopic" .=) <$> _ePubsubTopic, ("enterpriseDisplayName" .=) <$> _eEnterpriseDisplayName, ("logo" .=) <$> _eLogo, ("termsAndConditions" .=) <$> _eTermsAndConditions, ("contactInfo" .=) <$> _eContactInfo, ("primaryColor" .=) <$> _ePrimaryColor]) -- | An event related to memory and storage measurements. -- -- /See:/ 'memoryEvent' smart constructor. data MemoryEvent = MemoryEvent' { _meByteCount :: !(Maybe (Textual Int64)) , _meEventType :: !(Maybe MemoryEventEventType) , _meCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MemoryEvent' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'meByteCount' -- -- * 'meEventType' -- -- * 'meCreateTime' memoryEvent :: MemoryEvent memoryEvent = MemoryEvent' {_meByteCount = Nothing, _meEventType = Nothing, _meCreateTime = Nothing} -- | The number of free bytes in the medium, or for -- EXTERNAL_STORAGE_DETECTED, the total capacity in bytes of the storage -- medium. meByteCount :: Lens' MemoryEvent (Maybe Int64) meByteCount = lens _meByteCount (\ s a -> s{_meByteCount = a}) . mapping _Coerce -- | Event type. meEventType :: Lens' MemoryEvent (Maybe MemoryEventEventType) meEventType = lens _meEventType (\ s a -> s{_meEventType = a}) -- | The creation time of the event. meCreateTime :: Lens' MemoryEvent (Maybe UTCTime) meCreateTime = lens _meCreateTime (\ s a -> s{_meCreateTime = a}) . mapping _DateTime instance FromJSON MemoryEvent where parseJSON = withObject "MemoryEvent" (\ o -> MemoryEvent' <$> (o .:? "byteCount") <*> (o .:? "eventType") <*> (o .:? "createTime")) instance ToJSON MemoryEvent where toJSON MemoryEvent'{..} = object (catMaybes [("byteCount" .=) <$> _meByteCount, ("eventType" .=) <$> _meEventType, ("createTime" .=) <$> _meCreateTime]) -- | Configuration for an Android permission and its grant state. -- -- /See:/ 'permissionGrant' smart constructor. data PermissionGrant = PermissionGrant' { _pgPolicy :: !(Maybe PermissionGrantPolicy) , _pgPermission :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PermissionGrant' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgPolicy' -- -- * 'pgPermission' permissionGrant :: PermissionGrant permissionGrant = PermissionGrant' {_pgPolicy = Nothing, _pgPermission = Nothing} -- | The policy for granting the permission. pgPolicy :: Lens' PermissionGrant (Maybe PermissionGrantPolicy) pgPolicy = lens _pgPolicy (\ s a -> s{_pgPolicy = a}) -- | The Android permission or group, e.g. android.permission.READ_CALENDAR -- or android.permission_group.CALENDAR. pgPermission :: Lens' PermissionGrant (Maybe Text) pgPermission = lens _pgPermission (\ s a -> s{_pgPermission = a}) instance FromJSON PermissionGrant where parseJSON = withObject "PermissionGrant" (\ o -> PermissionGrant' <$> (o .:? "policy") <*> (o .:? "permission")) instance ToJSON PermissionGrant where toJSON PermissionGrant'{..} = object (catMaybes [("policy" .=) <$> _pgPolicy, ("permission" .=) <$> _pgPermission]) -- | A resource containing sign in details for an enterprise. -- -- /See:/ 'signinDetail' smart constructor. data SigninDetail = SigninDetail' { _sdSigninURL :: !(Maybe Text) , _sdQrCode :: !(Maybe Text) , _sdAllowPersonalUsage :: !(Maybe SigninDetailAllowPersonalUsage) , _sdSigninEnrollmentToken :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SigninDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdSigninURL' -- -- * 'sdQrCode' -- -- * 'sdAllowPersonalUsage' -- -- * 'sdSigninEnrollmentToken' signinDetail :: SigninDetail signinDetail = SigninDetail' { _sdSigninURL = Nothing , _sdQrCode = Nothing , _sdAllowPersonalUsage = Nothing , _sdSigninEnrollmentToken = Nothing } -- | Sign-in URL for authentication when device is provisioned with a sign-in -- enrollment token. The sign-in endpoint should finish authentication flow -- with a URL in the form of -- https:\/\/enterprise.google.com\/android\/enroll?et= for a successful -- login, or https:\/\/enterprise.google.com\/android\/enroll\/invalid for -- a failed login. sdSigninURL :: Lens' SigninDetail (Maybe Text) sdSigninURL = lens _sdSigninURL (\ s a -> s{_sdSigninURL = a}) -- | A JSON string whose UTF-8 representation can be used to generate a QR -- code to enroll a device with this enrollment token. To enroll a device -- using NFC, the NFC record must contain a serialized java.util.Properties -- representation of the properties in the JSON. This is a read-only field -- generated by the server. sdQrCode :: Lens' SigninDetail (Maybe Text) sdQrCode = lens _sdQrCode (\ s a -> s{_sdQrCode = a}) -- | Controls whether personal usage is allowed on a device provisioned with -- this enrollment token.For company-owned devices: Enabling personal usage -- allows the user to set up a work profile on the device. Disabling -- personal usage requires the user provision the device as a fully managed -- device.For personally-owned devices: Enabling personal usage allows the -- user to set up a work profile on the device. Disabling personal usage -- will prevent the device from provisioning. Personal usage cannot be -- disabled on personally-owned device. sdAllowPersonalUsage :: Lens' SigninDetail (Maybe SigninDetailAllowPersonalUsage) sdAllowPersonalUsage = lens _sdAllowPersonalUsage (\ s a -> s{_sdAllowPersonalUsage = a}) -- | An enterprise wide enrollment token used to trigger custom sign-in flow. -- This is a read-only field generated by the server. sdSigninEnrollmentToken :: Lens' SigninDetail (Maybe Text) sdSigninEnrollmentToken = lens _sdSigninEnrollmentToken (\ s a -> s{_sdSigninEnrollmentToken = a}) instance FromJSON SigninDetail where parseJSON = withObject "SigninDetail" (\ o -> SigninDetail' <$> (o .:? "signinUrl") <*> (o .:? "qrCode") <*> (o .:? "allowPersonalUsage") <*> (o .:? "signinEnrollmentToken")) instance ToJSON SigninDetail where toJSON SigninDetail'{..} = object (catMaybes [("signinUrl" .=) <$> _sdSigninURL, ("qrCode" .=) <$> _sdQrCode, ("allowPersonalUsage" .=) <$> _sdAllowPersonalUsage, ("signinEnrollmentToken" .=) <$> _sdSigninEnrollmentToken]) -- | An enterprise signup URL. -- -- /See:/ 'signupURL' smart constructor. data SignupURL = SignupURL' { _suURL :: !(Maybe Text) , _suName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SignupURL' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'suURL' -- -- * 'suName' signupURL :: SignupURL signupURL = SignupURL' {_suURL = Nothing, _suName = Nothing} -- | A URL where an enterprise admin can register their enterprise. The page -- can\'t be rendered in an iframe. suURL :: Lens' SignupURL (Maybe Text) suURL = lens _suURL (\ s a -> s{_suURL = a}) -- | The name of the resource. Use this value in the signupUrl field when -- calling enterprises.create to complete the enterprise signup flow. suName :: Lens' SignupURL (Maybe Text) suName = lens _suName (\ s a -> s{_suName = a}) instance FromJSON SignupURL where parseJSON = withObject "SignupURL" (\ o -> SignupURL' <$> (o .:? "url") <*> (o .:? "name")) instance ToJSON SignupURL where toJSON SignupURL'{..} = object (catMaybes [("url" .=) <$> _suURL, ("name" .=) <$> _suName]) -- | Id to name association of a app track. -- -- /See:/ 'appTrackInfo' smart constructor. data AppTrackInfo = AppTrackInfo' { _atiTrackAlias :: !(Maybe Text) , _atiTrackId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AppTrackInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'atiTrackAlias' -- -- * 'atiTrackId' appTrackInfo :: AppTrackInfo appTrackInfo = AppTrackInfo' {_atiTrackAlias = Nothing, _atiTrackId = Nothing} -- | The track name associated with the trackId, set in the Play Console. The -- name is modifiable from Play Console. atiTrackAlias :: Lens' AppTrackInfo (Maybe Text) atiTrackAlias = lens _atiTrackAlias (\ s a -> s{_atiTrackAlias = a}) -- | The unmodifiable unique track identifier, taken from the releaseTrackId -- in the URL of the Play Console page that displays the app’s track -- information. atiTrackId :: Lens' AppTrackInfo (Maybe Text) atiTrackId = lens _atiTrackId (\ s a -> s{_atiTrackId = a}) instance FromJSON AppTrackInfo where parseJSON = withObject "AppTrackInfo" (\ o -> AppTrackInfo' <$> (o .:? "trackAlias") <*> (o .:? "trackId")) instance ToJSON AppTrackInfo where toJSON AppTrackInfo'{..} = object (catMaybes [("trackAlias" .=) <$> _atiTrackAlias, ("trackId" .=) <$> _atiTrackId]) -- | Device network info. -- -- /See:/ 'networkInfo' smart constructor. data NetworkInfo = NetworkInfo' { _niTelephonyInfos :: !(Maybe [TelephonyInfo]) , _niNetworkOperatorName :: !(Maybe Text) , _niMeid :: !(Maybe Text) , _niImei :: !(Maybe Text) , _niWifiMACAddress :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NetworkInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'niTelephonyInfos' -- -- * 'niNetworkOperatorName' -- -- * 'niMeid' -- -- * 'niImei' -- -- * 'niWifiMACAddress' networkInfo :: NetworkInfo networkInfo = NetworkInfo' { _niTelephonyInfos = Nothing , _niNetworkOperatorName = Nothing , _niMeid = Nothing , _niImei = Nothing , _niWifiMACAddress = Nothing } -- | Provides telephony information associated with each SIM card on the -- device. Only supported on fully managed devices starting from Android -- API level 23. niTelephonyInfos :: Lens' NetworkInfo [TelephonyInfo] niTelephonyInfos = lens _niTelephonyInfos (\ s a -> s{_niTelephonyInfos = a}) . _Default . _Coerce -- | Alphabetic name of current registered operator. For example, Vodafone. niNetworkOperatorName :: Lens' NetworkInfo (Maybe Text) niNetworkOperatorName = lens _niNetworkOperatorName (\ s a -> s{_niNetworkOperatorName = a}) -- | MEID number of the CDMA device. For example, A00000292788E1. niMeid :: Lens' NetworkInfo (Maybe Text) niMeid = lens _niMeid (\ s a -> s{_niMeid = a}) -- | IMEI number of the GSM device. For example, A1000031212. niImei :: Lens' NetworkInfo (Maybe Text) niImei = lens _niImei (\ s a -> s{_niImei = a}) -- | Wi-Fi MAC address of the device. For example, 7c:11:11:11:11:11. niWifiMACAddress :: Lens' NetworkInfo (Maybe Text) niWifiMACAddress = lens _niWifiMACAddress (\ s a -> s{_niWifiMACAddress = a}) instance FromJSON NetworkInfo where parseJSON = withObject "NetworkInfo" (\ o -> NetworkInfo' <$> (o .:? "telephonyInfos" .!= mempty) <*> (o .:? "networkOperatorName") <*> (o .:? "meid") <*> (o .:? "imei") <*> (o .:? "wifiMacAddress")) instance ToJSON NetworkInfo where toJSON NetworkInfo'{..} = object (catMaybes [("telephonyInfos" .=) <$> _niTelephonyInfos, ("networkOperatorName" .=) <$> _niNetworkOperatorName, ("meid" .=) <$> _niMeid, ("imei" .=) <$> _niImei, ("wifiMacAddress" .=) <$> _niWifiMACAddress]) -- | A power management event. -- -- /See:/ 'powerManagementEvent' smart constructor. data PowerManagementEvent = PowerManagementEvent' { _pmeBatteryLevel :: !(Maybe (Textual Double)) , _pmeEventType :: !(Maybe PowerManagementEventEventType) , _pmeCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PowerManagementEvent' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pmeBatteryLevel' -- -- * 'pmeEventType' -- -- * 'pmeCreateTime' powerManagementEvent :: PowerManagementEvent powerManagementEvent = PowerManagementEvent' { _pmeBatteryLevel = Nothing , _pmeEventType = Nothing , _pmeCreateTime = Nothing } -- | For BATTERY_LEVEL_COLLECTED events, the battery level as a percentage. pmeBatteryLevel :: Lens' PowerManagementEvent (Maybe Double) pmeBatteryLevel = lens _pmeBatteryLevel (\ s a -> s{_pmeBatteryLevel = a}) . mapping _Coerce -- | Event type. pmeEventType :: Lens' PowerManagementEvent (Maybe PowerManagementEventEventType) pmeEventType = lens _pmeEventType (\ s a -> s{_pmeEventType = a}) -- | The creation time of the event. pmeCreateTime :: Lens' PowerManagementEvent (Maybe UTCTime) pmeCreateTime = lens _pmeCreateTime (\ s a -> s{_pmeCreateTime = a}) . mapping _DateTime instance FromJSON PowerManagementEvent where parseJSON = withObject "PowerManagementEvent" (\ o -> PowerManagementEvent' <$> (o .:? "batteryLevel") <*> (o .:? "eventType") <*> (o .:? "createTime")) instance ToJSON PowerManagementEvent where toJSON PowerManagementEvent'{..} = object (catMaybes [("batteryLevel" .=) <$> _pmeBatteryLevel, ("eventType" .=) <$> _pmeEventType, ("createTime" .=) <$> _pmeCreateTime]) -- | A policy resource represents a group of settings that govern the -- behavior of a managed device and the apps installed on it. -- -- /See:/ 'policy' smart constructor. data Policy = Policy' { _pBluetoothConfigDisabled :: !(Maybe Bool) , _pUnmuteMicrophoneDisabled :: !(Maybe Bool) , _pMountPhysicalMediaDisabled :: !(Maybe Bool) , _pFrpAdminEmails :: !(Maybe [Text]) , _pAppAutoUpdatePolicy :: !(Maybe PolicyAppAutoUpdatePolicy) , _pEncryptionPolicy :: !(Maybe PolicyEncryptionPolicy) , _pAndroidDevicePolicyTracks :: !(Maybe [PolicyAndroidDevicePolicyTracksItem]) , _pSafeBootDisabled :: !(Maybe Bool) , _pAlwaysOnVPNPackage :: !(Maybe AlwaysOnVPNPackage) , _pChoosePrivateKeyRules :: !(Maybe [ChoosePrivateKeyRule]) , _pCredentialsConfigDisabled :: !(Maybe Bool) , _pRecommendedGlobalProxy :: !(Maybe ProxyInfo) , _pPermittedAccessibilityServices :: !(Maybe PackageNameList) , _pKeyguardDisabled :: !(Maybe Bool) , _pOncCertificateProviders :: !(Maybe [OncCertificateProvider]) , _pSkipFirstUseHintsEnabled :: !(Maybe Bool) , _pAdjustVolumeDisabled :: !(Maybe Bool) , _pDefaultPermissionPolicy :: !(Maybe PolicyDefaultPermissionPolicy) , _pUninstallAppsDisabled :: !(Maybe Bool) , _pSetUserIconDisabled :: !(Maybe Bool) , _pPermittedInputMethods :: !(Maybe PackageNameList) , _pMinimumAPILevel :: !(Maybe (Textual Int32)) , _pScreenCaptureDisabled :: !(Maybe Bool) , _pAddUserDisabled :: !(Maybe Bool) , _pShareLocationDisabled :: !(Maybe Bool) , _pAutoTimeRequired :: !(Maybe Bool) , _pInstallAppsDisabled :: !(Maybe Bool) , _pCreateWindowsDisabled :: !(Maybe Bool) , _pNetworkResetDisabled :: !(Maybe Bool) , _pPersonalUsagePolicies :: !(Maybe PersonalUsagePolicies) , _pBluetoothContactSharingDisabled :: !(Maybe Bool) , _pPermissionGrants :: !(Maybe [PermissionGrant]) , _pShortSupportMessage :: !(Maybe UserFacingMessage) , _pStayOnPluggedModes :: !(Maybe [PolicyStayOnPluggedModesItem]) , _pDataRoamingDisabled :: !(Maybe Bool) , _pDebuggingFeaturesAllowed :: !(Maybe Bool) , _pKioskCustomLauncherEnabled :: !(Maybe Bool) , _pWifiConfigsLockdownEnabled :: !(Maybe Bool) , _pUsbMassStorageEnabled :: !(Maybe Bool) , _pNetworkEscapeHatchEnabled :: !(Maybe Bool) , _pSystemUpdate :: !(Maybe SystemUpdate) , _pInstallUnknownSourcesAllowed :: !(Maybe Bool) , _pName :: !(Maybe Text) , _pPrivateKeySelectionEnabled :: !(Maybe Bool) , _pAdvancedSecurityOverrides :: !(Maybe AdvancedSecurityOverrides) , _pOutgoingCallsDisabled :: !(Maybe Bool) , _pStatusReportingSettings :: !(Maybe StatusReportingSettings) , _pRemoveUserDisabled :: !(Maybe Bool) , _pMobileNetworksConfigDisabled :: !(Maybe Bool) , _pVersion :: !(Maybe (Textual Int64)) , _pEnsureVerifyAppsEnabled :: !(Maybe Bool) , _pSetWallpaperDisabled :: !(Maybe Bool) , _pVPNConfigDisabled :: !(Maybe Bool) , _pSetupActions :: !(Maybe [SetupAction]) , _pOpenNetworkConfiguration :: !(Maybe PolicyOpenNetworkConfiguration) , _pModifyAccountsDisabled :: !(Maybe Bool) , _pBlockApplicationsEnabled :: !(Maybe Bool) , _pKeyguardDisabledFeatures :: !(Maybe [PolicyKeyguardDisabledFeaturesItem]) , _pFunDisabled :: !(Maybe Bool) , _pSmsDisabled :: !(Maybe Bool) , _pMaximumTimeToLock :: !(Maybe (Textual Int64)) , _pOutgoingBeamDisabled :: !(Maybe Bool) , _pStatusBarDisabled :: !(Maybe Bool) , _pCellBroadcastsConfigDisabled :: !(Maybe Bool) , _pDeviceOwnerLockScreenInfo :: !(Maybe UserFacingMessage) , _pPlayStoreMode :: !(Maybe PolicyPlayStoreMode) , _pKioskCustomization :: !(Maybe KioskCustomization) , _pComplianceRules :: !(Maybe [ComplianceRule]) , _pTetheringConfigDisabled :: !(Maybe Bool) , _pAccountTypesWithManagementDisabled :: !(Maybe [Text]) , _pWifiConfigDisabled :: !(Maybe Bool) , _pPersistentPreferredActivities :: !(Maybe [PersistentPreferredActivity]) , _pPasswordRequirements :: !(Maybe PasswordRequirements) , _pAutoDateAndTimeZone :: !(Maybe PolicyAutoDateAndTimeZone) , _pLongSupportMessage :: !(Maybe UserFacingMessage) , _pLocationMode :: !(Maybe PolicyLocationMode) , _pBluetoothDisabled :: !(Maybe Bool) , _pPolicyEnforcementRules :: !(Maybe [PolicyEnforcementRule]) , _pUsbFileTransferDisabled :: !(Maybe Bool) , _pCameraDisabled :: !(Maybe Bool) , _pApplications :: !(Maybe [ApplicationPolicy]) , _pPasswordPolicies :: !(Maybe [PasswordRequirements]) , _pFactoryResetDisabled :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Policy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pBluetoothConfigDisabled' -- -- * 'pUnmuteMicrophoneDisabled' -- -- * 'pMountPhysicalMediaDisabled' -- -- * 'pFrpAdminEmails' -- -- * 'pAppAutoUpdatePolicy' -- -- * 'pEncryptionPolicy' -- -- * 'pAndroidDevicePolicyTracks' -- -- * 'pSafeBootDisabled' -- -- * 'pAlwaysOnVPNPackage' -- -- * 'pChoosePrivateKeyRules' -- -- * 'pCredentialsConfigDisabled' -- -- * 'pRecommendedGlobalProxy' -- -- * 'pPermittedAccessibilityServices' -- -- * 'pKeyguardDisabled' -- -- * 'pOncCertificateProviders' -- -- * 'pSkipFirstUseHintsEnabled' -- -- * 'pAdjustVolumeDisabled' -- -- * 'pDefaultPermissionPolicy' -- -- * 'pUninstallAppsDisabled' -- -- * 'pSetUserIconDisabled' -- -- * 'pPermittedInputMethods' -- -- * 'pMinimumAPILevel' -- -- * 'pScreenCaptureDisabled' -- -- * 'pAddUserDisabled' -- -- * 'pShareLocationDisabled' -- -- * 'pAutoTimeRequired' -- -- * 'pInstallAppsDisabled' -- -- * 'pCreateWindowsDisabled' -- -- * 'pNetworkResetDisabled' -- -- * 'pPersonalUsagePolicies' -- -- * 'pBluetoothContactSharingDisabled' -- -- * 'pPermissionGrants' -- -- * 'pShortSupportMessage' -- -- * 'pStayOnPluggedModes' -- -- * 'pDataRoamingDisabled' -- -- * 'pDebuggingFeaturesAllowed' -- -- * 'pKioskCustomLauncherEnabled' -- -- * 'pWifiConfigsLockdownEnabled' -- -- * 'pUsbMassStorageEnabled' -- -- * 'pNetworkEscapeHatchEnabled' -- -- * 'pSystemUpdate' -- -- * 'pInstallUnknownSourcesAllowed' -- -- * 'pName' -- -- * 'pPrivateKeySelectionEnabled' -- -- * 'pAdvancedSecurityOverrides' -- -- * 'pOutgoingCallsDisabled' -- -- * 'pStatusReportingSettings' -- -- * 'pRemoveUserDisabled' -- -- * 'pMobileNetworksConfigDisabled' -- -- * 'pVersion' -- -- * 'pEnsureVerifyAppsEnabled' -- -- * 'pSetWallpaperDisabled' -- -- * 'pVPNConfigDisabled' -- -- * 'pSetupActions' -- -- * 'pOpenNetworkConfiguration' -- -- * 'pModifyAccountsDisabled' -- -- * 'pBlockApplicationsEnabled' -- -- * 'pKeyguardDisabledFeatures' -- -- * 'pFunDisabled' -- -- * 'pSmsDisabled' -- -- * 'pMaximumTimeToLock' -- -- * 'pOutgoingBeamDisabled' -- -- * 'pStatusBarDisabled' -- -- * 'pCellBroadcastsConfigDisabled' -- -- * 'pDeviceOwnerLockScreenInfo' -- -- * 'pPlayStoreMode' -- -- * 'pKioskCustomization' -- -- * 'pComplianceRules' -- -- * 'pTetheringConfigDisabled' -- -- * 'pAccountTypesWithManagementDisabled' -- -- * 'pWifiConfigDisabled' -- -- * 'pPersistentPreferredActivities' -- -- * 'pPasswordRequirements' -- -- * 'pAutoDateAndTimeZone' -- -- * 'pLongSupportMessage' -- -- * 'pLocationMode' -- -- * 'pBluetoothDisabled' -- -- * 'pPolicyEnforcementRules' -- -- * 'pUsbFileTransferDisabled' -- -- * 'pCameraDisabled' -- -- * 'pApplications' -- -- * 'pPasswordPolicies' -- -- * 'pFactoryResetDisabled' policy :: Policy policy = Policy' { _pBluetoothConfigDisabled = Nothing , _pUnmuteMicrophoneDisabled = Nothing , _pMountPhysicalMediaDisabled = Nothing , _pFrpAdminEmails = Nothing , _pAppAutoUpdatePolicy = Nothing , _pEncryptionPolicy = Nothing , _pAndroidDevicePolicyTracks = Nothing , _pSafeBootDisabled = Nothing , _pAlwaysOnVPNPackage = Nothing , _pChoosePrivateKeyRules = Nothing , _pCredentialsConfigDisabled = Nothing , _pRecommendedGlobalProxy = Nothing , _pPermittedAccessibilityServices = Nothing , _pKeyguardDisabled = Nothing , _pOncCertificateProviders = Nothing , _pSkipFirstUseHintsEnabled = Nothing , _pAdjustVolumeDisabled = Nothing , _pDefaultPermissionPolicy = Nothing , _pUninstallAppsDisabled = Nothing , _pSetUserIconDisabled = Nothing , _pPermittedInputMethods = Nothing , _pMinimumAPILevel = Nothing , _pScreenCaptureDisabled = Nothing , _pAddUserDisabled = Nothing , _pShareLocationDisabled = Nothing , _pAutoTimeRequired = Nothing , _pInstallAppsDisabled = Nothing , _pCreateWindowsDisabled = Nothing , _pNetworkResetDisabled = Nothing , _pPersonalUsagePolicies = Nothing , _pBluetoothContactSharingDisabled = Nothing , _pPermissionGrants = Nothing , _pShortSupportMessage = Nothing , _pStayOnPluggedModes = Nothing , _pDataRoamingDisabled = Nothing , _pDebuggingFeaturesAllowed = Nothing , _pKioskCustomLauncherEnabled = Nothing , _pWifiConfigsLockdownEnabled = Nothing , _pUsbMassStorageEnabled = Nothing , _pNetworkEscapeHatchEnabled = Nothing , _pSystemUpdate = Nothing , _pInstallUnknownSourcesAllowed = Nothing , _pName = Nothing , _pPrivateKeySelectionEnabled = Nothing , _pAdvancedSecurityOverrides = Nothing , _pOutgoingCallsDisabled = Nothing , _pStatusReportingSettings = Nothing , _pRemoveUserDisabled = Nothing , _pMobileNetworksConfigDisabled = Nothing , _pVersion = Nothing , _pEnsureVerifyAppsEnabled = Nothing , _pSetWallpaperDisabled = Nothing , _pVPNConfigDisabled = Nothing , _pSetupActions = Nothing , _pOpenNetworkConfiguration = Nothing , _pModifyAccountsDisabled = Nothing , _pBlockApplicationsEnabled = Nothing , _pKeyguardDisabledFeatures = Nothing , _pFunDisabled = Nothing , _pSmsDisabled = Nothing , _pMaximumTimeToLock = Nothing , _pOutgoingBeamDisabled = Nothing , _pStatusBarDisabled = Nothing , _pCellBroadcastsConfigDisabled = Nothing , _pDeviceOwnerLockScreenInfo = Nothing , _pPlayStoreMode = Nothing , _pKioskCustomization = Nothing , _pComplianceRules = Nothing , _pTetheringConfigDisabled = Nothing , _pAccountTypesWithManagementDisabled = Nothing , _pWifiConfigDisabled = Nothing , _pPersistentPreferredActivities = Nothing , _pPasswordRequirements = Nothing , _pAutoDateAndTimeZone = Nothing , _pLongSupportMessage = Nothing , _pLocationMode = Nothing , _pBluetoothDisabled = Nothing , _pPolicyEnforcementRules = Nothing , _pUsbFileTransferDisabled = Nothing , _pCameraDisabled = Nothing , _pApplications = Nothing , _pPasswordPolicies = Nothing , _pFactoryResetDisabled = Nothing } -- | Whether configuring bluetooth is disabled. pBluetoothConfigDisabled :: Lens' Policy (Maybe Bool) pBluetoothConfigDisabled = lens _pBluetoothConfigDisabled (\ s a -> s{_pBluetoothConfigDisabled = a}) -- | Whether the microphone is muted and adjusting microphone volume is -- disabled. pUnmuteMicrophoneDisabled :: Lens' Policy (Maybe Bool) pUnmuteMicrophoneDisabled = lens _pUnmuteMicrophoneDisabled (\ s a -> s{_pUnmuteMicrophoneDisabled = a}) -- | Whether the user mounting physical external media is disabled. pMountPhysicalMediaDisabled :: Lens' Policy (Maybe Bool) pMountPhysicalMediaDisabled = lens _pMountPhysicalMediaDisabled (\ s a -> s{_pMountPhysicalMediaDisabled = a}) -- | Email addresses of device administrators for factory reset protection. -- When the device is factory reset, it will require one of these admins to -- log in with the Google account email and password to unlock the device. -- If no admins are specified, the device won\'t provide factory reset -- protection. pFrpAdminEmails :: Lens' Policy [Text] pFrpAdminEmails = lens _pFrpAdminEmails (\ s a -> s{_pFrpAdminEmails = a}) . _Default . _Coerce -- | Deprecated. Use autoUpdateMode instead.When autoUpdateMode is set to -- AUTO_UPDATE_POSTPONED or AUTO_UPDATE_HIGH_PRIORITY, this field has no -- effect.The app auto update policy, which controls when automatic app -- updates can be applied. pAppAutoUpdatePolicy :: Lens' Policy (Maybe PolicyAppAutoUpdatePolicy) pAppAutoUpdatePolicy = lens _pAppAutoUpdatePolicy (\ s a -> s{_pAppAutoUpdatePolicy = a}) -- | Whether encryption is enabled pEncryptionPolicy :: Lens' Policy (Maybe PolicyEncryptionPolicy) pEncryptionPolicy = lens _pEncryptionPolicy (\ s a -> s{_pEncryptionPolicy = a}) -- | The app tracks for Android Device Policy the device can access. The -- device receives the latest version among all accessible tracks. If no -- tracks are specified, then the device only uses the production track. pAndroidDevicePolicyTracks :: Lens' Policy [PolicyAndroidDevicePolicyTracksItem] pAndroidDevicePolicyTracks = lens _pAndroidDevicePolicyTracks (\ s a -> s{_pAndroidDevicePolicyTracks = a}) . _Default . _Coerce -- | Whether rebooting the device into safe boot is disabled. pSafeBootDisabled :: Lens' Policy (Maybe Bool) pSafeBootDisabled = lens _pSafeBootDisabled (\ s a -> s{_pSafeBootDisabled = a}) -- | Configuration for an always-on VPN connection. Use with -- vpn_config_disabled to prevent modification of this setting. pAlwaysOnVPNPackage :: Lens' Policy (Maybe AlwaysOnVPNPackage) pAlwaysOnVPNPackage = lens _pAlwaysOnVPNPackage (\ s a -> s{_pAlwaysOnVPNPackage = a}) -- | Rules for determining apps\' access to private keys. See -- ChoosePrivateKeyRule for details. pChoosePrivateKeyRules :: Lens' Policy [ChoosePrivateKeyRule] pChoosePrivateKeyRules = lens _pChoosePrivateKeyRules (\ s a -> s{_pChoosePrivateKeyRules = a}) . _Default . _Coerce -- | Whether configuring user credentials is disabled. pCredentialsConfigDisabled :: Lens' Policy (Maybe Bool) pCredentialsConfigDisabled = lens _pCredentialsConfigDisabled (\ s a -> s{_pCredentialsConfigDisabled = a}) -- | The network-independent global HTTP proxy. Typically proxies should be -- configured per-network in open_network_configuration. However for -- unusual configurations like general internal filtering a global HTTP -- proxy may be useful. If the proxy is not accessible, network access may -- break. The global proxy is only a recommendation and some apps may -- ignore it. pRecommendedGlobalProxy :: Lens' Policy (Maybe ProxyInfo) pRecommendedGlobalProxy = lens _pRecommendedGlobalProxy (\ s a -> s{_pRecommendedGlobalProxy = a}) -- | Specifies permitted accessibility services. If the field is not set, any -- accessibility service can be used. If the field is set, only the -- accessibility services in this list and the system\'s built-in -- accessibility service can be used. In particular, if the field is set to -- empty, only the system\'s built-in accessibility servicess can be used. pPermittedAccessibilityServices :: Lens' Policy (Maybe PackageNameList) pPermittedAccessibilityServices = lens _pPermittedAccessibilityServices (\ s a -> s{_pPermittedAccessibilityServices = a}) -- | Whether the keyguard is disabled. pKeyguardDisabled :: Lens' Policy (Maybe Bool) pKeyguardDisabled = lens _pKeyguardDisabled (\ s a -> s{_pKeyguardDisabled = a}) -- | This feature is not generally available. pOncCertificateProviders :: Lens' Policy [OncCertificateProvider] pOncCertificateProviders = lens _pOncCertificateProviders (\ s a -> s{_pOncCertificateProviders = a}) . _Default . _Coerce -- | Flag to skip hints on the first use. Enterprise admin can enable the -- system recommendation for apps to skip their user tutorial and other -- introductory hints on first start-up. pSkipFirstUseHintsEnabled :: Lens' Policy (Maybe Bool) pSkipFirstUseHintsEnabled = lens _pSkipFirstUseHintsEnabled (\ s a -> s{_pSkipFirstUseHintsEnabled = a}) -- | Whether adjusting the master volume is disabled. Also mutes the device. pAdjustVolumeDisabled :: Lens' Policy (Maybe Bool) pAdjustVolumeDisabled = lens _pAdjustVolumeDisabled (\ s a -> s{_pAdjustVolumeDisabled = a}) -- | The default permission policy for runtime permission requests. pDefaultPermissionPolicy :: Lens' Policy (Maybe PolicyDefaultPermissionPolicy) pDefaultPermissionPolicy = lens _pDefaultPermissionPolicy (\ s a -> s{_pDefaultPermissionPolicy = a}) -- | Whether user uninstallation of applications is disabled. pUninstallAppsDisabled :: Lens' Policy (Maybe Bool) pUninstallAppsDisabled = lens _pUninstallAppsDisabled (\ s a -> s{_pUninstallAppsDisabled = a}) -- | Whether changing the user icon is disabled. pSetUserIconDisabled :: Lens' Policy (Maybe Bool) pSetUserIconDisabled = lens _pSetUserIconDisabled (\ s a -> s{_pSetUserIconDisabled = a}) -- | If present, only the input methods provided by packages in this list are -- permitted. If this field is present, but the list is empty, then only -- system input methods are permitted. pPermittedInputMethods :: Lens' Policy (Maybe PackageNameList) pPermittedInputMethods = lens _pPermittedInputMethods (\ s a -> s{_pPermittedInputMethods = a}) -- | The minimum allowed Android API level. pMinimumAPILevel :: Lens' Policy (Maybe Int32) pMinimumAPILevel = lens _pMinimumAPILevel (\ s a -> s{_pMinimumAPILevel = a}) . mapping _Coerce -- | Whether screen capture is disabled. pScreenCaptureDisabled :: Lens' Policy (Maybe Bool) pScreenCaptureDisabled = lens _pScreenCaptureDisabled (\ s a -> s{_pScreenCaptureDisabled = a}) -- | Whether adding new users and profiles is disabled. pAddUserDisabled :: Lens' Policy (Maybe Bool) pAddUserDisabled = lens _pAddUserDisabled (\ s a -> s{_pAddUserDisabled = a}) -- | Whether location sharing is disabled. pShareLocationDisabled :: Lens' Policy (Maybe Bool) pShareLocationDisabled = lens _pShareLocationDisabled (\ s a -> s{_pShareLocationDisabled = a}) -- | Whether auto time is required, which prevents the user from manually -- setting the date and time. If autoDateAndTimeZone is set, this field is -- ignored. pAutoTimeRequired :: Lens' Policy (Maybe Bool) pAutoTimeRequired = lens _pAutoTimeRequired (\ s a -> s{_pAutoTimeRequired = a}) -- | Whether user installation of apps is disabled. pInstallAppsDisabled :: Lens' Policy (Maybe Bool) pInstallAppsDisabled = lens _pInstallAppsDisabled (\ s a -> s{_pInstallAppsDisabled = a}) -- | Whether creating windows besides app windows is disabled. pCreateWindowsDisabled :: Lens' Policy (Maybe Bool) pCreateWindowsDisabled = lens _pCreateWindowsDisabled (\ s a -> s{_pCreateWindowsDisabled = a}) -- | Whether resetting network settings is disabled. pNetworkResetDisabled :: Lens' Policy (Maybe Bool) pNetworkResetDisabled = lens _pNetworkResetDisabled (\ s a -> s{_pNetworkResetDisabled = a}) -- | Policies managing personal usage on a company-owned device. pPersonalUsagePolicies :: Lens' Policy (Maybe PersonalUsagePolicies) pPersonalUsagePolicies = lens _pPersonalUsagePolicies (\ s a -> s{_pPersonalUsagePolicies = a}) -- | Whether bluetooth contact sharing is disabled. pBluetoothContactSharingDisabled :: Lens' Policy (Maybe Bool) pBluetoothContactSharingDisabled = lens _pBluetoothContactSharingDisabled (\ s a -> s{_pBluetoothContactSharingDisabled = a}) -- | Explicit permission or group grants or denials for all apps. These -- values override the default_permission_policy. pPermissionGrants :: Lens' Policy [PermissionGrant] pPermissionGrants = lens _pPermissionGrants (\ s a -> s{_pPermissionGrants = a}) . _Default . _Coerce -- | A message displayed to the user in the settings screen wherever -- functionality has been disabled by the admin. If the message is longer -- than 200 characters it may be truncated. pShortSupportMessage :: Lens' Policy (Maybe UserFacingMessage) pShortSupportMessage = lens _pShortSupportMessage (\ s a -> s{_pShortSupportMessage = a}) -- | The battery plugged in modes for which the device stays on. When using -- this setting, it is recommended to clear maximum_time_to_lock so that -- the device doesn\'t lock itself while it stays on. pStayOnPluggedModes :: Lens' Policy [PolicyStayOnPluggedModesItem] pStayOnPluggedModes = lens _pStayOnPluggedModes (\ s a -> s{_pStayOnPluggedModes = a}) . _Default . _Coerce -- | Whether roaming data services are disabled. pDataRoamingDisabled :: Lens' Policy (Maybe Bool) pDataRoamingDisabled = lens _pDataRoamingDisabled (\ s a -> s{_pDataRoamingDisabled = a}) -- | Whether the user is allowed to enable debugging features. pDebuggingFeaturesAllowed :: Lens' Policy (Maybe Bool) pDebuggingFeaturesAllowed = lens _pDebuggingFeaturesAllowed (\ s a -> s{_pDebuggingFeaturesAllowed = a}) -- | Whether the kiosk custom launcher is enabled. This replaces the home -- screen with a launcher that locks down the device to the apps installed -- via the applications setting. Apps appear on a single page in -- alphabetical order. Use kioskCustomization to further configure the -- kiosk device behavior. pKioskCustomLauncherEnabled :: Lens' Policy (Maybe Bool) pKioskCustomLauncherEnabled = lens _pKioskCustomLauncherEnabled (\ s a -> s{_pKioskCustomLauncherEnabled = a}) -- | DEPRECATED - Use wifi_config_disabled. pWifiConfigsLockdownEnabled :: Lens' Policy (Maybe Bool) pWifiConfigsLockdownEnabled = lens _pWifiConfigsLockdownEnabled (\ s a -> s{_pWifiConfigsLockdownEnabled = a}) -- | Whether USB storage is enabled. Deprecated. pUsbMassStorageEnabled :: Lens' Policy (Maybe Bool) pUsbMassStorageEnabled = lens _pUsbMassStorageEnabled (\ s a -> s{_pUsbMassStorageEnabled = a}) -- | Whether the network escape hatch is enabled. If a network connection -- can\'t be made at boot time, the escape hatch prompts the user to -- temporarily connect to a network in order to refresh the device policy. -- After applying policy, the temporary network will be forgotten and the -- device will continue booting. This prevents being unable to connect to a -- network if there is no suitable network in the last policy and the -- device boots into an app in lock task mode, or the user is otherwise -- unable to reach device settings.Note: Setting wifiConfigDisabled to true -- will override this setting under specific circumstances. Please see -- wifiConfigDisabled for further details. pNetworkEscapeHatchEnabled :: Lens' Policy (Maybe Bool) pNetworkEscapeHatchEnabled = lens _pNetworkEscapeHatchEnabled (\ s a -> s{_pNetworkEscapeHatchEnabled = a}) -- | The system update policy, which controls how OS updates are applied. If -- the update type is WINDOWED, the update window will automatically apply -- to Play app updates as well. pSystemUpdate :: Lens' Policy (Maybe SystemUpdate) pSystemUpdate = lens _pSystemUpdate (\ s a -> s{_pSystemUpdate = a}) -- | This field has no effect. pInstallUnknownSourcesAllowed :: Lens' Policy (Maybe Bool) pInstallUnknownSourcesAllowed = lens _pInstallUnknownSourcesAllowed (\ s a -> s{_pInstallUnknownSourcesAllowed = a}) -- | The name of the policy in the form -- enterprises\/{enterpriseId}\/policies\/{policyId}. pName :: Lens' Policy (Maybe Text) pName = lens _pName (\ s a -> s{_pName = a}) -- | Allows showing UI on a device for a user to choose a private key alias -- if there are no matching rules in ChoosePrivateKeyRules. For devices -- below Android P, setting this may leave enterprise keys vulnerable. pPrivateKeySelectionEnabled :: Lens' Policy (Maybe Bool) pPrivateKeySelectionEnabled = lens _pPrivateKeySelectionEnabled (\ s a -> s{_pPrivateKeySelectionEnabled = a}) -- | Security policies set to the most secure values by default. To maintain -- the security posture of a device, we don\'t recommend overriding any of -- the default values. pAdvancedSecurityOverrides :: Lens' Policy (Maybe AdvancedSecurityOverrides) pAdvancedSecurityOverrides = lens _pAdvancedSecurityOverrides (\ s a -> s{_pAdvancedSecurityOverrides = a}) -- | Whether outgoing calls are disabled. pOutgoingCallsDisabled :: Lens' Policy (Maybe Bool) pOutgoingCallsDisabled = lens _pOutgoingCallsDisabled (\ s a -> s{_pOutgoingCallsDisabled = a}) -- | Status reporting settings pStatusReportingSettings :: Lens' Policy (Maybe StatusReportingSettings) pStatusReportingSettings = lens _pStatusReportingSettings (\ s a -> s{_pStatusReportingSettings = a}) -- | Whether removing other users is disabled. pRemoveUserDisabled :: Lens' Policy (Maybe Bool) pRemoveUserDisabled = lens _pRemoveUserDisabled (\ s a -> s{_pRemoveUserDisabled = a}) -- | Whether configuring mobile networks is disabled. pMobileNetworksConfigDisabled :: Lens' Policy (Maybe Bool) pMobileNetworksConfigDisabled = lens _pMobileNetworksConfigDisabled (\ s a -> s{_pMobileNetworksConfigDisabled = a}) -- | The version of the policy. This is a read-only field. The version is -- incremented each time the policy is updated. pVersion :: Lens' Policy (Maybe Int64) pVersion = lens _pVersion (\ s a -> s{_pVersion = a}) . mapping _Coerce -- | Whether app verification is force-enabled. pEnsureVerifyAppsEnabled :: Lens' Policy (Maybe Bool) pEnsureVerifyAppsEnabled = lens _pEnsureVerifyAppsEnabled (\ s a -> s{_pEnsureVerifyAppsEnabled = a}) -- | Whether changing the wallpaper is disabled. pSetWallpaperDisabled :: Lens' Policy (Maybe Bool) pSetWallpaperDisabled = lens _pSetWallpaperDisabled (\ s a -> s{_pSetWallpaperDisabled = a}) -- | Whether configuring VPN is disabled. pVPNConfigDisabled :: Lens' Policy (Maybe Bool) pVPNConfigDisabled = lens _pVPNConfigDisabled (\ s a -> s{_pVPNConfigDisabled = a}) -- | Actions to take during the setup process. pSetupActions :: Lens' Policy [SetupAction] pSetupActions = lens _pSetupActions (\ s a -> s{_pSetupActions = a}) . _Default . _Coerce -- | Network configuration for the device. See configure networks for more -- information. pOpenNetworkConfiguration :: Lens' Policy (Maybe PolicyOpenNetworkConfiguration) pOpenNetworkConfiguration = lens _pOpenNetworkConfiguration (\ s a -> s{_pOpenNetworkConfiguration = a}) -- | Whether adding or removing accounts is disabled. pModifyAccountsDisabled :: Lens' Policy (Maybe Bool) pModifyAccountsDisabled = lens _pModifyAccountsDisabled (\ s a -> s{_pModifyAccountsDisabled = a}) -- | Whether applications other than the ones configured in applications are -- blocked from being installed. When set, applications that were installed -- under a previous policy but no longer appear in the policy are -- automatically uninstalled. pBlockApplicationsEnabled :: Lens' Policy (Maybe Bool) pBlockApplicationsEnabled = lens _pBlockApplicationsEnabled (\ s a -> s{_pBlockApplicationsEnabled = a}) -- | Disabled keyguard customizations, such as widgets. pKeyguardDisabledFeatures :: Lens' Policy [PolicyKeyguardDisabledFeaturesItem] pKeyguardDisabledFeatures = lens _pKeyguardDisabledFeatures (\ s a -> s{_pKeyguardDisabledFeatures = a}) . _Default . _Coerce -- | Whether the user is allowed to have fun. Controls whether the Easter egg -- game in Settings is disabled. pFunDisabled :: Lens' Policy (Maybe Bool) pFunDisabled = lens _pFunDisabled (\ s a -> s{_pFunDisabled = a}) -- | Whether sending and receiving SMS messages is disabled. pSmsDisabled :: Lens' Policy (Maybe Bool) pSmsDisabled = lens _pSmsDisabled (\ s a -> s{_pSmsDisabled = a}) -- | Maximum time in milliseconds for user activity until the device locks. A -- value of 0 means there is no restriction. pMaximumTimeToLock :: Lens' Policy (Maybe Int64) pMaximumTimeToLock = lens _pMaximumTimeToLock (\ s a -> s{_pMaximumTimeToLock = a}) . mapping _Coerce -- | Whether using NFC to beam data from apps is disabled. pOutgoingBeamDisabled :: Lens' Policy (Maybe Bool) pOutgoingBeamDisabled = lens _pOutgoingBeamDisabled (\ s a -> s{_pOutgoingBeamDisabled = a}) -- | Whether the status bar is disabled. This disables notifications, quick -- settings, and other screen overlays that allow escape from full-screen -- mode. DEPRECATED. To disable the status bar on a kiosk device, use -- InstallType KIOSK or kioskCustomLauncherEnabled. pStatusBarDisabled :: Lens' Policy (Maybe Bool) pStatusBarDisabled = lens _pStatusBarDisabled (\ s a -> s{_pStatusBarDisabled = a}) -- | Whether configuring cell broadcast is disabled. pCellBroadcastsConfigDisabled :: Lens' Policy (Maybe Bool) pCellBroadcastsConfigDisabled = lens _pCellBroadcastsConfigDisabled (\ s a -> s{_pCellBroadcastsConfigDisabled = a}) -- | The device owner information to be shown on the lock screen. pDeviceOwnerLockScreenInfo :: Lens' Policy (Maybe UserFacingMessage) pDeviceOwnerLockScreenInfo = lens _pDeviceOwnerLockScreenInfo (\ s a -> s{_pDeviceOwnerLockScreenInfo = a}) -- | This mode controls which apps are available to the user in the Play -- Store and the behavior on the device when apps are removed from the -- policy. pPlayStoreMode :: Lens' Policy (Maybe PolicyPlayStoreMode) pPlayStoreMode = lens _pPlayStoreMode (\ s a -> s{_pPlayStoreMode = a}) -- | Settings controlling the behavior of a device in kiosk mode. To enable -- kiosk mode, set kioskCustomLauncherEnabled to true or specify an app in -- the policy with installType KIOSK. pKioskCustomization :: Lens' Policy (Maybe KioskCustomization) pKioskCustomization = lens _pKioskCustomization (\ s a -> s{_pKioskCustomization = a}) -- | Rules declaring which mitigating actions to take when a device is not -- compliant with its policy. When the conditions for multiple rules are -- satisfied, all of the mitigating actions for the rules are taken. There -- is a maximum limit of 100 rules. Use policy enforcement rules instead. pComplianceRules :: Lens' Policy [ComplianceRule] pComplianceRules = lens _pComplianceRules (\ s a -> s{_pComplianceRules = a}) . _Default . _Coerce -- | Whether configuring tethering and portable hotspots is disabled. pTetheringConfigDisabled :: Lens' Policy (Maybe Bool) pTetheringConfigDisabled = lens _pTetheringConfigDisabled (\ s a -> s{_pTetheringConfigDisabled = a}) -- | Account types that can\'t be managed by the user. pAccountTypesWithManagementDisabled :: Lens' Policy [Text] pAccountTypesWithManagementDisabled = lens _pAccountTypesWithManagementDisabled (\ s a -> s{_pAccountTypesWithManagementDisabled = a}) . _Default . _Coerce -- | Whether configuring Wi-Fi access points is disabled.Note: If a network -- connection can\'t be made at boot time and configuring Wi-Fi is disabled -- then network escape hatch will be shown in order to refresh the device -- policy (see networkEscapeHatchEnabled). pWifiConfigDisabled :: Lens' Policy (Maybe Bool) pWifiConfigDisabled = lens _pWifiConfigDisabled (\ s a -> s{_pWifiConfigDisabled = a}) -- | Default intent handler activities. pPersistentPreferredActivities :: Lens' Policy [PersistentPreferredActivity] pPersistentPreferredActivities = lens _pPersistentPreferredActivities (\ s a -> s{_pPersistentPreferredActivities = a}) . _Default . _Coerce -- | Password requirements. The field -- password_requirements.require_password_unlock must not be set. -- DEPRECATED - Use password_policies.Note:Complexity-based values of -- PasswordQuality, that is, COMPLEXITY_LOW, COMPLEXITY_MEDIUM, and -- COMPLEXITY_HIGH, cannot be used here. pPasswordRequirements :: Lens' Policy (Maybe PasswordRequirements) pPasswordRequirements = lens _pPasswordRequirements (\ s a -> s{_pPasswordRequirements = a}) -- | Whether auto date, time, and time zone are enabled on a company-owned -- device. If this is set, then autoTimeRequired is ignored. pAutoDateAndTimeZone :: Lens' Policy (Maybe PolicyAutoDateAndTimeZone) pAutoDateAndTimeZone = lens _pAutoDateAndTimeZone (\ s a -> s{_pAutoDateAndTimeZone = a}) -- | A message displayed to the user in the device administators settings -- screen. pLongSupportMessage :: Lens' Policy (Maybe UserFacingMessage) pLongSupportMessage = lens _pLongSupportMessage (\ s a -> s{_pLongSupportMessage = a}) -- | The degree of location detection enabled. pLocationMode :: Lens' Policy (Maybe PolicyLocationMode) pLocationMode = lens _pLocationMode (\ s a -> s{_pLocationMode = a}) -- | Whether bluetooth is disabled. Prefer this setting over -- bluetooth_config_disabled because bluetooth_config_disabled can be -- bypassed by the user. pBluetoothDisabled :: Lens' Policy (Maybe Bool) pBluetoothDisabled = lens _pBluetoothDisabled (\ s a -> s{_pBluetoothDisabled = a}) -- | Rules that define the behavior when a particular policy can not be -- applied on device pPolicyEnforcementRules :: Lens' Policy [PolicyEnforcementRule] pPolicyEnforcementRules = lens _pPolicyEnforcementRules (\ s a -> s{_pPolicyEnforcementRules = a}) . _Default . _Coerce -- | Whether transferring files over USB is disabled. pUsbFileTransferDisabled :: Lens' Policy (Maybe Bool) pUsbFileTransferDisabled = lens _pUsbFileTransferDisabled (\ s a -> s{_pUsbFileTransferDisabled = a}) -- | Whether all cameras on the device are disabled. pCameraDisabled :: Lens' Policy (Maybe Bool) pCameraDisabled = lens _pCameraDisabled (\ s a -> s{_pCameraDisabled = a}) -- | Policy applied to apps. pApplications :: Lens' Policy [ApplicationPolicy] pApplications = lens _pApplications (\ s a -> s{_pApplications = a}) . _Default . _Coerce -- | Password requirement policies. Different policies can be set for work -- profile or fully managed devices by setting the password_scope field in -- the policy. pPasswordPolicies :: Lens' Policy [PasswordRequirements] pPasswordPolicies = lens _pPasswordPolicies (\ s a -> s{_pPasswordPolicies = a}) . _Default . _Coerce -- | Whether factory resetting from settings is disabled. pFactoryResetDisabled :: Lens' Policy (Maybe Bool) pFactoryResetDisabled = lens _pFactoryResetDisabled (\ s a -> s{_pFactoryResetDisabled = a}) instance FromJSON Policy where parseJSON = withObject "Policy" (\ o -> Policy' <$> (o .:? "bluetoothConfigDisabled") <*> (o .:? "unmuteMicrophoneDisabled") <*> (o .:? "mountPhysicalMediaDisabled") <*> (o .:? "frpAdminEmails" .!= mempty) <*> (o .:? "appAutoUpdatePolicy") <*> (o .:? "encryptionPolicy") <*> (o .:? "androidDevicePolicyTracks" .!= mempty) <*> (o .:? "safeBootDisabled") <*> (o .:? "alwaysOnVpnPackage") <*> (o .:? "choosePrivateKeyRules" .!= mempty) <*> (o .:? "credentialsConfigDisabled") <*> (o .:? "recommendedGlobalProxy") <*> (o .:? "permittedAccessibilityServices") <*> (o .:? "keyguardDisabled") <*> (o .:? "oncCertificateProviders" .!= mempty) <*> (o .:? "skipFirstUseHintsEnabled") <*> (o .:? "adjustVolumeDisabled") <*> (o .:? "defaultPermissionPolicy") <*> (o .:? "uninstallAppsDisabled") <*> (o .:? "setUserIconDisabled") <*> (o .:? "permittedInputMethods") <*> (o .:? "minimumApiLevel") <*> (o .:? "screenCaptureDisabled") <*> (o .:? "addUserDisabled") <*> (o .:? "shareLocationDisabled") <*> (o .:? "autoTimeRequired") <*> (o .:? "installAppsDisabled") <*> (o .:? "createWindowsDisabled") <*> (o .:? "networkResetDisabled") <*> (o .:? "personalUsagePolicies") <*> (o .:? "bluetoothContactSharingDisabled") <*> (o .:? "permissionGrants" .!= mempty) <*> (o .:? "shortSupportMessage") <*> (o .:? "stayOnPluggedModes" .!= mempty) <*> (o .:? "dataRoamingDisabled") <*> (o .:? "debuggingFeaturesAllowed") <*> (o .:? "kioskCustomLauncherEnabled") <*> (o .:? "wifiConfigsLockdownEnabled") <*> (o .:? "usbMassStorageEnabled") <*> (o .:? "networkEscapeHatchEnabled") <*> (o .:? "systemUpdate") <*> (o .:? "installUnknownSourcesAllowed") <*> (o .:? "name") <*> (o .:? "privateKeySelectionEnabled") <*> (o .:? "advancedSecurityOverrides") <*> (o .:? "outgoingCallsDisabled") <*> (o .:? "statusReportingSettings") <*> (o .:? "removeUserDisabled") <*> (o .:? "mobileNetworksConfigDisabled") <*> (o .:? "version") <*> (o .:? "ensureVerifyAppsEnabled") <*> (o .:? "setWallpaperDisabled") <*> (o .:? "vpnConfigDisabled") <*> (o .:? "setupActions" .!= mempty) <*> (o .:? "openNetworkConfiguration") <*> (o .:? "modifyAccountsDisabled") <*> (o .:? "blockApplicationsEnabled") <*> (o .:? "keyguardDisabledFeatures" .!= mempty) <*> (o .:? "funDisabled") <*> (o .:? "smsDisabled") <*> (o .:? "maximumTimeToLock") <*> (o .:? "outgoingBeamDisabled") <*> (o .:? "statusBarDisabled") <*> (o .:? "cellBroadcastsConfigDisabled") <*> (o .:? "deviceOwnerLockScreenInfo") <*> (o .:? "playStoreMode") <*> (o .:? "kioskCustomization") <*> (o .:? "complianceRules" .!= mempty) <*> (o .:? "tetheringConfigDisabled") <*> (o .:? "accountTypesWithManagementDisabled" .!= mempty) <*> (o .:? "wifiConfigDisabled") <*> (o .:? "persistentPreferredActivities" .!= mempty) <*> (o .:? "passwordRequirements") <*> (o .:? "autoDateAndTimeZone") <*> (o .:? "longSupportMessage") <*> (o .:? "locationMode") <*> (o .:? "bluetoothDisabled") <*> (o .:? "policyEnforcementRules" .!= mempty) <*> (o .:? "usbFileTransferDisabled") <*> (o .:? "cameraDisabled") <*> (o .:? "applications" .!= mempty) <*> (o .:? "passwordPolicies" .!= mempty) <*> (o .:? "factoryResetDisabled")) instance ToJSON Policy where toJSON Policy'{..} = object (catMaybes [("bluetoothConfigDisabled" .=) <$> _pBluetoothConfigDisabled, ("unmuteMicrophoneDisabled" .=) <$> _pUnmuteMicrophoneDisabled, ("mountPhysicalMediaDisabled" .=) <$> _pMountPhysicalMediaDisabled, ("frpAdminEmails" .=) <$> _pFrpAdminEmails, ("appAutoUpdatePolicy" .=) <$> _pAppAutoUpdatePolicy, ("encryptionPolicy" .=) <$> _pEncryptionPolicy, ("androidDevicePolicyTracks" .=) <$> _pAndroidDevicePolicyTracks, ("safeBootDisabled" .=) <$> _pSafeBootDisabled, ("alwaysOnVpnPackage" .=) <$> _pAlwaysOnVPNPackage, ("choosePrivateKeyRules" .=) <$> _pChoosePrivateKeyRules, ("credentialsConfigDisabled" .=) <$> _pCredentialsConfigDisabled, ("recommendedGlobalProxy" .=) <$> _pRecommendedGlobalProxy, ("permittedAccessibilityServices" .=) <$> _pPermittedAccessibilityServices, ("keyguardDisabled" .=) <$> _pKeyguardDisabled, ("oncCertificateProviders" .=) <$> _pOncCertificateProviders, ("skipFirstUseHintsEnabled" .=) <$> _pSkipFirstUseHintsEnabled, ("adjustVolumeDisabled" .=) <$> _pAdjustVolumeDisabled, ("defaultPermissionPolicy" .=) <$> _pDefaultPermissionPolicy, ("uninstallAppsDisabled" .=) <$> _pUninstallAppsDisabled, ("setUserIconDisabled" .=) <$> _pSetUserIconDisabled, ("permittedInputMethods" .=) <$> _pPermittedInputMethods, ("minimumApiLevel" .=) <$> _pMinimumAPILevel, ("screenCaptureDisabled" .=) <$> _pScreenCaptureDisabled, ("addUserDisabled" .=) <$> _pAddUserDisabled, ("shareLocationDisabled" .=) <$> _pShareLocationDisabled, ("autoTimeRequired" .=) <$> _pAutoTimeRequired, ("installAppsDisabled" .=) <$> _pInstallAppsDisabled, ("createWindowsDisabled" .=) <$> _pCreateWindowsDisabled, ("networkResetDisabled" .=) <$> _pNetworkResetDisabled, ("personalUsagePolicies" .=) <$> _pPersonalUsagePolicies, ("bluetoothContactSharingDisabled" .=) <$> _pBluetoothContactSharingDisabled, ("permissionGrants" .=) <$> _pPermissionGrants, ("shortSupportMessage" .=) <$> _pShortSupportMessage, ("stayOnPluggedModes" .=) <$> _pStayOnPluggedModes, ("dataRoamingDisabled" .=) <$> _pDataRoamingDisabled, ("debuggingFeaturesAllowed" .=) <$> _pDebuggingFeaturesAllowed, ("kioskCustomLauncherEnabled" .=) <$> _pKioskCustomLauncherEnabled, ("wifiConfigsLockdownEnabled" .=) <$> _pWifiConfigsLockdownEnabled, ("usbMassStorageEnabled" .=) <$> _pUsbMassStorageEnabled, ("networkEscapeHatchEnabled" .=) <$> _pNetworkEscapeHatchEnabled, ("systemUpdate" .=) <$> _pSystemUpdate, ("installUnknownSourcesAllowed" .=) <$> _pInstallUnknownSourcesAllowed, ("name" .=) <$> _pName, ("privateKeySelectionEnabled" .=) <$> _pPrivateKeySelectionEnabled, ("advancedSecurityOverrides" .=) <$> _pAdvancedSecurityOverrides, ("outgoingCallsDisabled" .=) <$> _pOutgoingCallsDisabled, ("statusReportingSettings" .=) <$> _pStatusReportingSettings, ("removeUserDisabled" .=) <$> _pRemoveUserDisabled, ("mobileNetworksConfigDisabled" .=) <$> _pMobileNetworksConfigDisabled, ("version" .=) <$> _pVersion, ("ensureVerifyAppsEnabled" .=) <$> _pEnsureVerifyAppsEnabled, ("setWallpaperDisabled" .=) <$> _pSetWallpaperDisabled, ("vpnConfigDisabled" .=) <$> _pVPNConfigDisabled, ("setupActions" .=) <$> _pSetupActions, ("openNetworkConfiguration" .=) <$> _pOpenNetworkConfiguration, ("modifyAccountsDisabled" .=) <$> _pModifyAccountsDisabled, ("blockApplicationsEnabled" .=) <$> _pBlockApplicationsEnabled, ("keyguardDisabledFeatures" .=) <$> _pKeyguardDisabledFeatures, ("funDisabled" .=) <$> _pFunDisabled, ("smsDisabled" .=) <$> _pSmsDisabled, ("maximumTimeToLock" .=) <$> _pMaximumTimeToLock, ("outgoingBeamDisabled" .=) <$> _pOutgoingBeamDisabled, ("statusBarDisabled" .=) <$> _pStatusBarDisabled, ("cellBroadcastsConfigDisabled" .=) <$> _pCellBroadcastsConfigDisabled, ("deviceOwnerLockScreenInfo" .=) <$> _pDeviceOwnerLockScreenInfo, ("playStoreMode" .=) <$> _pPlayStoreMode, ("kioskCustomization" .=) <$> _pKioskCustomization, ("complianceRules" .=) <$> _pComplianceRules, ("tetheringConfigDisabled" .=) <$> _pTetheringConfigDisabled, ("accountTypesWithManagementDisabled" .=) <$> _pAccountTypesWithManagementDisabled, ("wifiConfigDisabled" .=) <$> _pWifiConfigDisabled, ("persistentPreferredActivities" .=) <$> _pPersistentPreferredActivities, ("passwordRequirements" .=) <$> _pPasswordRequirements, ("autoDateAndTimeZone" .=) <$> _pAutoDateAndTimeZone, ("longSupportMessage" .=) <$> _pLongSupportMessage, ("locationMode" .=) <$> _pLocationMode, ("bluetoothDisabled" .=) <$> _pBluetoothDisabled, ("policyEnforcementRules" .=) <$> _pPolicyEnforcementRules, ("usbFileTransferDisabled" .=) <$> _pUsbFileTransferDisabled, ("cameraDisabled" .=) <$> _pCameraDisabled, ("applications" .=) <$> _pApplications, ("passwordPolicies" .=) <$> _pPasswordPolicies, ("factoryResetDisabled" .=) <$> _pFactoryResetDisabled]) -- | A compliance rule condition which is satisfied if there exists any -- matching NonComplianceDetail for the device. A NonComplianceDetail -- matches a NonComplianceDetailCondition if all the fields which are set -- within the NonComplianceDetailCondition match the corresponding -- NonComplianceDetail fields. -- -- /See:/ 'nonComplianceDetailCondition' smart constructor. data NonComplianceDetailCondition = NonComplianceDetailCondition' { _ncdcPackageName :: !(Maybe Text) , _ncdcNonComplianceReason :: !(Maybe NonComplianceDetailConditionNonComplianceReason) , _ncdcSettingName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NonComplianceDetailCondition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ncdcPackageName' -- -- * 'ncdcNonComplianceReason' -- -- * 'ncdcSettingName' nonComplianceDetailCondition :: NonComplianceDetailCondition nonComplianceDetailCondition = NonComplianceDetailCondition' { _ncdcPackageName = Nothing , _ncdcNonComplianceReason = Nothing , _ncdcSettingName = Nothing } -- | The package name of the app that\'s out of compliance. If not set, then -- this condition matches any package name. ncdcPackageName :: Lens' NonComplianceDetailCondition (Maybe Text) ncdcPackageName = lens _ncdcPackageName (\ s a -> s{_ncdcPackageName = a}) -- | The reason the device is not in compliance with the setting. If not set, -- then this condition matches any reason. ncdcNonComplianceReason :: Lens' NonComplianceDetailCondition (Maybe NonComplianceDetailConditionNonComplianceReason) ncdcNonComplianceReason = lens _ncdcNonComplianceReason (\ s a -> s{_ncdcNonComplianceReason = a}) -- | The name of the policy setting. This is the JSON field name of a -- top-level Policy field. If not set, then this condition matches any -- setting name. ncdcSettingName :: Lens' NonComplianceDetailCondition (Maybe Text) ncdcSettingName = lens _ncdcSettingName (\ s a -> s{_ncdcSettingName = a}) instance FromJSON NonComplianceDetailCondition where parseJSON = withObject "NonComplianceDetailCondition" (\ o -> NonComplianceDetailCondition' <$> (o .:? "packageName") <*> (o .:? "nonComplianceReason") <*> (o .:? "settingName")) instance ToJSON NonComplianceDetailCondition where toJSON NonComplianceDetailCondition'{..} = object (catMaybes [("packageName" .=) <$> _ncdcPackageName, ("nonComplianceReason" .=) <$> _ncdcNonComplianceReason, ("settingName" .=) <$> _ncdcSettingName]) -- | Keyed app state reported by the app. -- -- /See:/ 'keyedAppState' smart constructor. data KeyedAppState = KeyedAppState' { _kasData :: !(Maybe Text) , _kasSeverity :: !(Maybe KeyedAppStateSeverity) , _kasKey :: !(Maybe Text) , _kasMessage :: !(Maybe Text) , _kasLastUpdateTime :: !(Maybe DateTime') , _kasCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'KeyedAppState' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'kasData' -- -- * 'kasSeverity' -- -- * 'kasKey' -- -- * 'kasMessage' -- -- * 'kasLastUpdateTime' -- -- * 'kasCreateTime' keyedAppState :: KeyedAppState keyedAppState = KeyedAppState' { _kasData = Nothing , _kasSeverity = Nothing , _kasKey = Nothing , _kasMessage = Nothing , _kasLastUpdateTime = Nothing , _kasCreateTime = Nothing } -- | Optionally, a machine-readable value to be read by the EMM. For example, -- setting values that the admin can choose to query against in the EMM -- console (e.g. “notify me if the battery_warning data \< 10”). kasData :: Lens' KeyedAppState (Maybe Text) kasData = lens _kasData (\ s a -> s{_kasData = a}) -- | The severity of the app state. kasSeverity :: Lens' KeyedAppState (Maybe KeyedAppStateSeverity) kasSeverity = lens _kasSeverity (\ s a -> s{_kasSeverity = a}) -- | The key for the app state. Acts as a point of reference for what the app -- is providing state for. For example, when providing managed -- configuration feedback, this key could be the managed configuration key. kasKey :: Lens' KeyedAppState (Maybe Text) kasKey = lens _kasKey (\ s a -> s{_kasKey = a}) -- | Optionally, a free-form message string to explain the app state. If the -- state was triggered by a particular value (e.g. a managed configuration -- value), it should be included in the message. kasMessage :: Lens' KeyedAppState (Maybe Text) kasMessage = lens _kasMessage (\ s a -> s{_kasMessage = a}) -- | The time the app state was most recently updated. kasLastUpdateTime :: Lens' KeyedAppState (Maybe UTCTime) kasLastUpdateTime = lens _kasLastUpdateTime (\ s a -> s{_kasLastUpdateTime = a}) . mapping _DateTime -- | The creation time of the app state on the device. kasCreateTime :: Lens' KeyedAppState (Maybe UTCTime) kasCreateTime = lens _kasCreateTime (\ s a -> s{_kasCreateTime = a}) . mapping _DateTime instance FromJSON KeyedAppState where parseJSON = withObject "KeyedAppState" (\ o -> KeyedAppState' <$> (o .:? "data") <*> (o .:? "severity") <*> (o .:? "key") <*> (o .:? "message") <*> (o .:? "lastUpdateTime") <*> (o .:? "createTime")) instance ToJSON KeyedAppState where toJSON KeyedAppState'{..} = object (catMaybes [("data" .=) <$> _kasData, ("severity" .=) <$> _kasSeverity, ("key" .=) <$> _kasKey, ("message" .=) <$> _kasMessage, ("lastUpdateTime" .=) <$> _kasLastUpdateTime, ("createTime" .=) <$> _kasCreateTime]) -- | Settings controlling the behavior of a device in kiosk mode. To enable -- kiosk mode, set kioskCustomLauncherEnabled to true or specify an app in -- the policy with installType KIOSK. -- -- /See:/ 'kioskCustomization' smart constructor. data KioskCustomization = KioskCustomization' { _kcSystemNavigation :: !(Maybe KioskCustomizationSystemNavigation) , _kcDeviceSettings :: !(Maybe KioskCustomizationDeviceSettings) , _kcPowerButtonActions :: !(Maybe KioskCustomizationPowerButtonActions) , _kcSystemErrorWarnings :: !(Maybe KioskCustomizationSystemErrorWarnings) , _kcStatusBar :: !(Maybe KioskCustomizationStatusBar) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'KioskCustomization' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'kcSystemNavigation' -- -- * 'kcDeviceSettings' -- -- * 'kcPowerButtonActions' -- -- * 'kcSystemErrorWarnings' -- -- * 'kcStatusBar' kioskCustomization :: KioskCustomization kioskCustomization = KioskCustomization' { _kcSystemNavigation = Nothing , _kcDeviceSettings = Nothing , _kcPowerButtonActions = Nothing , _kcSystemErrorWarnings = Nothing , _kcStatusBar = Nothing } -- | Specifies which navigation features are enabled (e.g. Home, Overview -- buttons) in kiosk mode. kcSystemNavigation :: Lens' KioskCustomization (Maybe KioskCustomizationSystemNavigation) kcSystemNavigation = lens _kcSystemNavigation (\ s a -> s{_kcSystemNavigation = a}) -- | Specifies whether the Settings app is allowed in kiosk mode. kcDeviceSettings :: Lens' KioskCustomization (Maybe KioskCustomizationDeviceSettings) kcDeviceSettings = lens _kcDeviceSettings (\ s a -> s{_kcDeviceSettings = a}) -- | Sets the behavior of a device in kiosk mode when a user presses and -- holds (long-presses) the Power button. kcPowerButtonActions :: Lens' KioskCustomization (Maybe KioskCustomizationPowerButtonActions) kcPowerButtonActions = lens _kcPowerButtonActions (\ s a -> s{_kcPowerButtonActions = a}) -- | Specifies whether system error dialogs for crashed or unresponsive apps -- are blocked in kiosk mode. When blocked, the system will force-stop the -- app as if the user chooses the \"close app\" option on the UI. kcSystemErrorWarnings :: Lens' KioskCustomization (Maybe KioskCustomizationSystemErrorWarnings) kcSystemErrorWarnings = lens _kcSystemErrorWarnings (\ s a -> s{_kcSystemErrorWarnings = a}) -- | Specifies whether system info and notifications are disabled in kiosk -- mode. kcStatusBar :: Lens' KioskCustomization (Maybe KioskCustomizationStatusBar) kcStatusBar = lens _kcStatusBar (\ s a -> s{_kcStatusBar = a}) instance FromJSON KioskCustomization where parseJSON = withObject "KioskCustomization" (\ o -> KioskCustomization' <$> (o .:? "systemNavigation") <*> (o .:? "deviceSettings") <*> (o .:? "powerButtonActions") <*> (o .:? "systemErrorWarnings") <*> (o .:? "statusBar")) instance ToJSON KioskCustomization where toJSON KioskCustomization'{..} = object (catMaybes [("systemNavigation" .=) <$> _kcSystemNavigation, ("deviceSettings" .=) <$> _kcDeviceSettings, ("powerButtonActions" .=) <$> _kcPowerButtonActions, ("systemErrorWarnings" .=) <$> _kcSystemErrorWarnings, ("statusBar" .=) <$> _kcStatusBar]) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. -- -- /See:/ 'operationMetadata' smart constructor. newtype OperationMetadata = OperationMetadata' { _omAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omAddtional' operationMetadata :: HashMap Text JSONValue -- ^ 'omAddtional' -> OperationMetadata operationMetadata pOmAddtional_ = OperationMetadata' {_omAddtional = _Coerce # pOmAddtional_} -- | Properties of the object. Contains field \'type with type URL. omAddtional :: Lens' OperationMetadata (HashMap Text JSONValue) omAddtional = lens _omAddtional (\ s a -> s{_omAddtional = a}) . _Coerce instance FromJSON OperationMetadata where parseJSON = withObject "OperationMetadata" (\ o -> OperationMetadata' <$> (parseJSONObject o)) instance ToJSON OperationMetadata where toJSON = toJSON . _omAddtional -- | A web token used to access the managed Google Play iframe. -- -- /See:/ 'webToken' smart constructor. data WebToken = WebToken' { _wtParentFrameURL :: !(Maybe Text) , _wtValue :: !(Maybe Text) , _wtName :: !(Maybe Text) , _wtEnabledFeatures :: !(Maybe [WebTokenEnabledFeaturesItem]) , _wtPermissions :: !(Maybe [WebTokenPermissionsItem]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WebToken' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wtParentFrameURL' -- -- * 'wtValue' -- -- * 'wtName' -- -- * 'wtEnabledFeatures' -- -- * 'wtPermissions' webToken :: WebToken webToken = WebToken' { _wtParentFrameURL = Nothing , _wtValue = Nothing , _wtName = Nothing , _wtEnabledFeatures = Nothing , _wtPermissions = Nothing } -- | The URL of the parent frame hosting the iframe with the embedded UI. To -- prevent XSS, the iframe may not be hosted at other URLs. The URL must -- use the https scheme. wtParentFrameURL :: Lens' WebToken (Maybe Text) wtParentFrameURL = lens _wtParentFrameURL (\ s a -> s{_wtParentFrameURL = a}) -- | The token value which is used in the hosting page to generate the iframe -- with the embedded UI. This is a read-only field generated by the server. wtValue :: Lens' WebToken (Maybe Text) wtValue = lens _wtValue (\ s a -> s{_wtValue = a}) -- | The name of the web token, which is generated by the server during -- creation in the form -- enterprises\/{enterpriseId}\/webTokens\/{webTokenId}. wtName :: Lens' WebToken (Maybe Text) wtName = lens _wtName (\ s a -> s{_wtName = a}) -- | The features to enable. Use this if you want to control exactly which -- feature(s) will be activated; leave empty to allow all -- features.Restrictions \/ things to note: - If no features are listed -- here, all features are enabled — this is the default behavior where you -- give access to all features to your admins. - This must not contain any -- FEATURE_UNSPECIFIED values. - Repeated values are ignored wtEnabledFeatures :: Lens' WebToken [WebTokenEnabledFeaturesItem] wtEnabledFeatures = lens _wtEnabledFeatures (\ s a -> s{_wtEnabledFeatures = a}) . _Default . _Coerce -- | Permissions available to an admin in the embedded UI. An admin must have -- all of these permissions in order to view the UI. This field is -- deprecated. wtPermissions :: Lens' WebToken [WebTokenPermissionsItem] wtPermissions = lens _wtPermissions (\ s a -> s{_wtPermissions = a}) . _Default . _Coerce instance FromJSON WebToken where parseJSON = withObject "WebToken" (\ o -> WebToken' <$> (o .:? "parentFrameUrl") <*> (o .:? "value") <*> (o .:? "name") <*> (o .:? "enabledFeatures" .!= mempty) <*> (o .:? "permissions" .!= mempty)) instance ToJSON WebToken where toJSON WebToken'{..} = object (catMaybes [("parentFrameUrl" .=) <$> _wtParentFrameURL, ("value" .=) <$> _wtValue, ("name" .=) <$> _wtName, ("enabledFeatures" .=) <$> _wtEnabledFeatures, ("permissions" .=) <$> _wtPermissions]) -- | A rule declaring which mitigating actions to take when a device is not -- compliant with its policy. For every rule, there is always an implicit -- mitigating action to set policy_compliant to false for the Device -- resource, and display a message on the device indicating that the device -- is not compliant with its policy. Other mitigating actions may -- optionally be taken as well, depending on the field values in the rule. -- -- /See:/ 'complianceRule' smart constructor. data ComplianceRule = ComplianceRule' { _crAPILevelCondition :: !(Maybe APILevelCondition) , _crDisableApps :: !(Maybe Bool) , _crPackageNamesToDisable :: !(Maybe [Text]) , _crNonComplianceDetailCondition :: !(Maybe NonComplianceDetailCondition) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ComplianceRule' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'crAPILevelCondition' -- -- * 'crDisableApps' -- -- * 'crPackageNamesToDisable' -- -- * 'crNonComplianceDetailCondition' complianceRule :: ComplianceRule complianceRule = ComplianceRule' { _crAPILevelCondition = Nothing , _crDisableApps = Nothing , _crPackageNamesToDisable = Nothing , _crNonComplianceDetailCondition = Nothing } -- | A condition which is satisfied if the Android Framework API level on the -- device doesn\'t meet a minimum requirement. crAPILevelCondition :: Lens' ComplianceRule (Maybe APILevelCondition) crAPILevelCondition = lens _crAPILevelCondition (\ s a -> s{_crAPILevelCondition = a}) -- | If set to true, the rule includes a mitigating action to disable apps so -- that the device is effectively disabled, but app data is preserved. If -- the device is running an app in locked task mode, the app will be closed -- and a UI showing the reason for non-compliance will be displayed. crDisableApps :: Lens' ComplianceRule (Maybe Bool) crDisableApps = lens _crDisableApps (\ s a -> s{_crDisableApps = a}) -- | If set, the rule includes a mitigating action to disable apps specified -- in the list, but app data is preserved. crPackageNamesToDisable :: Lens' ComplianceRule [Text] crPackageNamesToDisable = lens _crPackageNamesToDisable (\ s a -> s{_crPackageNamesToDisable = a}) . _Default . _Coerce -- | A condition which is satisfied if there exists any matching -- NonComplianceDetail for the device. crNonComplianceDetailCondition :: Lens' ComplianceRule (Maybe NonComplianceDetailCondition) crNonComplianceDetailCondition = lens _crNonComplianceDetailCondition (\ s a -> s{_crNonComplianceDetailCondition = a}) instance FromJSON ComplianceRule where parseJSON = withObject "ComplianceRule" (\ o -> ComplianceRule' <$> (o .:? "apiLevelCondition") <*> (o .:? "disableApps") <*> (o .:? "packageNamesToDisable" .!= mempty) <*> (o .:? "nonComplianceDetailCondition")) instance ToJSON ComplianceRule where toJSON ComplianceRule'{..} = object (catMaybes [("apiLevelCondition" .=) <$> _crAPILevelCondition, ("disableApps" .=) <$> _crDisableApps, ("packageNamesToDisable" .=) <$> _crPackageNamesToDisable, ("nonComplianceDetailCondition" .=) <$> _crNonComplianceDetailCondition]) -- | Response to a request to list web apps for a given enterprise. -- -- /See:/ 'listWebAppsResponse' smart constructor. data ListWebAppsResponse = ListWebAppsResponse' { _lwarNextPageToken :: !(Maybe Text) , _lwarWebApps :: !(Maybe [WebApp]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListWebAppsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lwarNextPageToken' -- -- * 'lwarWebApps' listWebAppsResponse :: ListWebAppsResponse listWebAppsResponse = ListWebAppsResponse' {_lwarNextPageToken = Nothing, _lwarWebApps = Nothing} -- | If there are more results, a token to retrieve next page of results. lwarNextPageToken :: Lens' ListWebAppsResponse (Maybe Text) lwarNextPageToken = lens _lwarNextPageToken (\ s a -> s{_lwarNextPageToken = a}) -- | The list of web apps. lwarWebApps :: Lens' ListWebAppsResponse [WebApp] lwarWebApps = lens _lwarWebApps (\ s a -> s{_lwarWebApps = a}) . _Default . _Coerce instance FromJSON ListWebAppsResponse where parseJSON = withObject "ListWebAppsResponse" (\ o -> ListWebAppsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "webApps" .!= mempty)) instance ToJSON ListWebAppsResponse where toJSON ListWebAppsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lwarNextPageToken, ("webApps" .=) <$> _lwarWebApps]) -- | Requirements for the password used to unlock a device. -- -- /See:/ 'passwordRequirements' smart constructor. data PasswordRequirements = PasswordRequirements' { _prPasswordMinimumSymbols :: !(Maybe (Textual Int32)) , _prMaximumFailedPasswordsForWipe :: !(Maybe (Textual Int32)) , _prPasswordExpirationTimeout :: !(Maybe GDuration) , _prPasswordMinimumNonLetter :: !(Maybe (Textual Int32)) , _prPasswordHistoryLength :: !(Maybe (Textual Int32)) , _prPasswordMinimumLetters :: !(Maybe (Textual Int32)) , _prPasswordMinimumUpperCase :: !(Maybe (Textual Int32)) , _prRequirePasswordUnlock :: !(Maybe PasswordRequirementsRequirePasswordUnlock) , _prPasswordMinimumNumeric :: !(Maybe (Textual Int32)) , _prPasswordQuality :: !(Maybe PasswordRequirementsPasswordQuality) , _prPasswordMinimumLength :: !(Maybe (Textual Int32)) , _prPasswordScope :: !(Maybe PasswordRequirementsPasswordScope) , _prPasswordMinimumLowerCase :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PasswordRequirements' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'prPasswordMinimumSymbols' -- -- * 'prMaximumFailedPasswordsForWipe' -- -- * 'prPasswordExpirationTimeout' -- -- * 'prPasswordMinimumNonLetter' -- -- * 'prPasswordHistoryLength' -- -- * 'prPasswordMinimumLetters' -- -- * 'prPasswordMinimumUpperCase' -- -- * 'prRequirePasswordUnlock' -- -- * 'prPasswordMinimumNumeric' -- -- * 'prPasswordQuality' -- -- * 'prPasswordMinimumLength' -- -- * 'prPasswordScope' -- -- * 'prPasswordMinimumLowerCase' passwordRequirements :: PasswordRequirements passwordRequirements = PasswordRequirements' { _prPasswordMinimumSymbols = Nothing , _prMaximumFailedPasswordsForWipe = Nothing , _prPasswordExpirationTimeout = Nothing , _prPasswordMinimumNonLetter = Nothing , _prPasswordHistoryLength = Nothing , _prPasswordMinimumLetters = Nothing , _prPasswordMinimumUpperCase = Nothing , _prRequirePasswordUnlock = Nothing , _prPasswordMinimumNumeric = Nothing , _prPasswordQuality = Nothing , _prPasswordMinimumLength = Nothing , _prPasswordScope = Nothing , _prPasswordMinimumLowerCase = Nothing } -- | Minimum number of symbols required in the password. Only enforced when -- password_quality is COMPLEX. prPasswordMinimumSymbols :: Lens' PasswordRequirements (Maybe Int32) prPasswordMinimumSymbols = lens _prPasswordMinimumSymbols (\ s a -> s{_prPasswordMinimumSymbols = a}) . mapping _Coerce -- | Number of incorrect device-unlock passwords that can be entered before a -- device is wiped. A value of 0 means there is no restriction. prMaximumFailedPasswordsForWipe :: Lens' PasswordRequirements (Maybe Int32) prMaximumFailedPasswordsForWipe = lens _prMaximumFailedPasswordsForWipe (\ s a -> s{_prMaximumFailedPasswordsForWipe = a}) . mapping _Coerce -- | Password expiration timeout. prPasswordExpirationTimeout :: Lens' PasswordRequirements (Maybe Scientific) prPasswordExpirationTimeout = lens _prPasswordExpirationTimeout (\ s a -> s{_prPasswordExpirationTimeout = a}) . mapping _GDuration -- | Minimum number of non-letter characters (numerical digits or symbols) -- required in the password. Only enforced when password_quality is -- COMPLEX. prPasswordMinimumNonLetter :: Lens' PasswordRequirements (Maybe Int32) prPasswordMinimumNonLetter = lens _prPasswordMinimumNonLetter (\ s a -> s{_prPasswordMinimumNonLetter = a}) . mapping _Coerce -- | The length of the password history. After setting this field, the user -- won\'t be able to enter a new password that is the same as any password -- in the history. A value of 0 means there is no restriction. prPasswordHistoryLength :: Lens' PasswordRequirements (Maybe Int32) prPasswordHistoryLength = lens _prPasswordHistoryLength (\ s a -> s{_prPasswordHistoryLength = a}) . mapping _Coerce -- | Minimum number of letters required in the password. Only enforced when -- password_quality is COMPLEX. prPasswordMinimumLetters :: Lens' PasswordRequirements (Maybe Int32) prPasswordMinimumLetters = lens _prPasswordMinimumLetters (\ s a -> s{_prPasswordMinimumLetters = a}) . mapping _Coerce -- | Minimum number of upper case letters required in the password. Only -- enforced when password_quality is COMPLEX. prPasswordMinimumUpperCase :: Lens' PasswordRequirements (Maybe Int32) prPasswordMinimumUpperCase = lens _prPasswordMinimumUpperCase (\ s a -> s{_prPasswordMinimumUpperCase = a}) . mapping _Coerce -- | The length of time after a device or work profile is unlocked using a -- strong form of authentication (password, PIN, pattern) that it can be -- unlocked using any other authentication method (e.g. fingerprint, trust -- agents, face). After the specified time period elapses, only strong -- forms of authentication can be used to unlock the device or work -- profile. prRequirePasswordUnlock :: Lens' PasswordRequirements (Maybe PasswordRequirementsRequirePasswordUnlock) prRequirePasswordUnlock = lens _prRequirePasswordUnlock (\ s a -> s{_prRequirePasswordUnlock = a}) -- | Minimum number of numerical digits required in the password. Only -- enforced when password_quality is COMPLEX. prPasswordMinimumNumeric :: Lens' PasswordRequirements (Maybe Int32) prPasswordMinimumNumeric = lens _prPasswordMinimumNumeric (\ s a -> s{_prPasswordMinimumNumeric = a}) . mapping _Coerce -- | The required password quality. prPasswordQuality :: Lens' PasswordRequirements (Maybe PasswordRequirementsPasswordQuality) prPasswordQuality = lens _prPasswordQuality (\ s a -> s{_prPasswordQuality = a}) -- | The minimum allowed password length. A value of 0 means there is no -- restriction. Only enforced when password_quality is NUMERIC, -- NUMERIC_COMPLEX, ALPHABETIC, ALPHANUMERIC, or COMPLEX. prPasswordMinimumLength :: Lens' PasswordRequirements (Maybe Int32) prPasswordMinimumLength = lens _prPasswordMinimumLength (\ s a -> s{_prPasswordMinimumLength = a}) . mapping _Coerce -- | The scope that the password requirement applies to. prPasswordScope :: Lens' PasswordRequirements (Maybe PasswordRequirementsPasswordScope) prPasswordScope = lens _prPasswordScope (\ s a -> s{_prPasswordScope = a}) -- | Minimum number of lower case letters required in the password. Only -- enforced when password_quality is COMPLEX. prPasswordMinimumLowerCase :: Lens' PasswordRequirements (Maybe Int32) prPasswordMinimumLowerCase = lens _prPasswordMinimumLowerCase (\ s a -> s{_prPasswordMinimumLowerCase = a}) . mapping _Coerce instance FromJSON PasswordRequirements where parseJSON = withObject "PasswordRequirements" (\ o -> PasswordRequirements' <$> (o .:? "passwordMinimumSymbols") <*> (o .:? "maximumFailedPasswordsForWipe") <*> (o .:? "passwordExpirationTimeout") <*> (o .:? "passwordMinimumNonLetter") <*> (o .:? "passwordHistoryLength") <*> (o .:? "passwordMinimumLetters") <*> (o .:? "passwordMinimumUpperCase") <*> (o .:? "requirePasswordUnlock") <*> (o .:? "passwordMinimumNumeric") <*> (o .:? "passwordQuality") <*> (o .:? "passwordMinimumLength") <*> (o .:? "passwordScope") <*> (o .:? "passwordMinimumLowerCase")) instance ToJSON PasswordRequirements where toJSON PasswordRequirements'{..} = object (catMaybes [("passwordMinimumSymbols" .=) <$> _prPasswordMinimumSymbols, ("maximumFailedPasswordsForWipe" .=) <$> _prMaximumFailedPasswordsForWipe, ("passwordExpirationTimeout" .=) <$> _prPasswordExpirationTimeout, ("passwordMinimumNonLetter" .=) <$> _prPasswordMinimumNonLetter, ("passwordHistoryLength" .=) <$> _prPasswordHistoryLength, ("passwordMinimumLetters" .=) <$> _prPasswordMinimumLetters, ("passwordMinimumUpperCase" .=) <$> _prPasswordMinimumUpperCase, ("requirePasswordUnlock" .=) <$> _prRequirePasswordUnlock, ("passwordMinimumNumeric" .=) <$> _prPasswordMinimumNumeric, ("passwordQuality" .=) <$> _prPasswordQuality, ("passwordMinimumLength" .=) <$> _prPasswordMinimumLength, ("passwordScope" .=) <$> _prPasswordScope, ("passwordMinimumLowerCase" .=) <$> _prPasswordMinimumLowerCase]) -- | Provides detail about non-compliance with a policy setting. -- -- /See:/ 'nonComplianceDetail' smart constructor. data NonComplianceDetail = NonComplianceDetail' { _ncdFieldPath :: !(Maybe Text) , _ncdPackageName :: !(Maybe Text) , _ncdInstallationFailureReason :: !(Maybe NonComplianceDetailInstallationFailureReason) , _ncdNonComplianceReason :: !(Maybe NonComplianceDetailNonComplianceReason) , _ncdSettingName :: !(Maybe Text) , _ncdCurrentValue :: !(Maybe JSONValue) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NonComplianceDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ncdFieldPath' -- -- * 'ncdPackageName' -- -- * 'ncdInstallationFailureReason' -- -- * 'ncdNonComplianceReason' -- -- * 'ncdSettingName' -- -- * 'ncdCurrentValue' nonComplianceDetail :: NonComplianceDetail nonComplianceDetail = NonComplianceDetail' { _ncdFieldPath = Nothing , _ncdPackageName = Nothing , _ncdInstallationFailureReason = Nothing , _ncdNonComplianceReason = Nothing , _ncdSettingName = Nothing , _ncdCurrentValue = Nothing } -- | For settings with nested fields, if a particular nested field is out of -- compliance, this specifies the full path to the offending field. The -- path is formatted in the same way the policy JSON field would be -- referenced in JavaScript, that is: 1) For object-typed fields, the field -- name is followed by a dot then by a subfield name. 2) For array-typed -- fields, the field name is followed by the array index enclosed in -- brackets. For example, to indicate a problem with the url field in the -- externalData field in the 3rd application, the path would be -- applications[2].externalData.url ncdFieldPath :: Lens' NonComplianceDetail (Maybe Text) ncdFieldPath = lens _ncdFieldPath (\ s a -> s{_ncdFieldPath = a}) -- | The package name indicating which app is out of compliance, if -- applicable. ncdPackageName :: Lens' NonComplianceDetail (Maybe Text) ncdPackageName = lens _ncdPackageName (\ s a -> s{_ncdPackageName = a}) -- | If package_name is set and the non-compliance reason is -- APP_NOT_INSTALLED or APP_NOT_UPDATED, the detailed reason the app can\'t -- be installed or updated. ncdInstallationFailureReason :: Lens' NonComplianceDetail (Maybe NonComplianceDetailInstallationFailureReason) ncdInstallationFailureReason = lens _ncdInstallationFailureReason (\ s a -> s{_ncdInstallationFailureReason = a}) -- | The reason the device is not in compliance with the setting. ncdNonComplianceReason :: Lens' NonComplianceDetail (Maybe NonComplianceDetailNonComplianceReason) ncdNonComplianceReason = lens _ncdNonComplianceReason (\ s a -> s{_ncdNonComplianceReason = a}) -- | The name of the policy setting. This is the JSON field name of a -- top-level Policy field. ncdSettingName :: Lens' NonComplianceDetail (Maybe Text) ncdSettingName = lens _ncdSettingName (\ s a -> s{_ncdSettingName = a}) -- | If the policy setting could not be applied, the current value of the -- setting on the device. ncdCurrentValue :: Lens' NonComplianceDetail (Maybe JSONValue) ncdCurrentValue = lens _ncdCurrentValue (\ s a -> s{_ncdCurrentValue = a}) instance FromJSON NonComplianceDetail where parseJSON = withObject "NonComplianceDetail" (\ o -> NonComplianceDetail' <$> (o .:? "fieldPath") <*> (o .:? "packageName") <*> (o .:? "installationFailureReason") <*> (o .:? "nonComplianceReason") <*> (o .:? "settingName") <*> (o .:? "currentValue")) instance ToJSON NonComplianceDetail where toJSON NonComplianceDetail'{..} = object (catMaybes [("fieldPath" .=) <$> _ncdFieldPath, ("packageName" .=) <$> _ncdPackageName, ("installationFailureReason" .=) <$> _ncdInstallationFailureReason, ("nonComplianceReason" .=) <$> _ncdNonComplianceReason, ("settingName" .=) <$> _ncdSettingName, ("currentValue" .=) <$> _ncdCurrentValue]) -- | An app-related event. -- -- /See:/ 'applicationEvent' smart constructor. data ApplicationEvent = ApplicationEvent' { _aeEventType :: !(Maybe ApplicationEventEventType) , _aeCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationEvent' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aeEventType' -- -- * 'aeCreateTime' applicationEvent :: ApplicationEvent applicationEvent = ApplicationEvent' {_aeEventType = Nothing, _aeCreateTime = Nothing} -- | App event type. aeEventType :: Lens' ApplicationEvent (Maybe ApplicationEventEventType) aeEventType = lens _aeEventType (\ s a -> s{_aeEventType = a}) -- | The creation time of the event. aeCreateTime :: Lens' ApplicationEvent (Maybe UTCTime) aeCreateTime = lens _aeCreateTime (\ s a -> s{_aeCreateTime = a}) . mapping _DateTime instance FromJSON ApplicationEvent where parseJSON = withObject "ApplicationEvent" (\ o -> ApplicationEvent' <$> (o .:? "eventType") <*> (o .:? "createTime")) instance ToJSON ApplicationEvent where toJSON ApplicationEvent'{..} = object (catMaybes [("eventType" .=) <$> _aeEventType, ("createTime" .=) <$> _aeCreateTime]) -- | A terms and conditions page to be accepted during provisioning. -- -- /See:/ 'termsAndConditions' smart constructor. data TermsAndConditions = TermsAndConditions' { _tacContent :: !(Maybe UserFacingMessage) , _tacHeader :: !(Maybe UserFacingMessage) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TermsAndConditions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tacContent' -- -- * 'tacHeader' termsAndConditions :: TermsAndConditions termsAndConditions = TermsAndConditions' {_tacContent = Nothing, _tacHeader = Nothing} -- | A well-formatted HTML string. It will be parsed on the client with -- android.text.Html#fromHtml. tacContent :: Lens' TermsAndConditions (Maybe UserFacingMessage) tacContent = lens _tacContent (\ s a -> s{_tacContent = a}) -- | A short header which appears above the HTML content. tacHeader :: Lens' TermsAndConditions (Maybe UserFacingMessage) tacHeader = lens _tacHeader (\ s a -> s{_tacHeader = a}) instance FromJSON TermsAndConditions where parseJSON = withObject "TermsAndConditions" (\ o -> TermsAndConditions' <$> (o .:? "content") <*> (o .:? "header")) instance ToJSON TermsAndConditions where toJSON TermsAndConditions'{..} = object (catMaybes [("content" .=) <$> _tacContent, ("header" .=) <$> _tacHeader]) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as Delete, the response is -- google.protobuf.Empty. If the original method is standard -- Get\/Create\/Update, the response should be the resource. For other -- methods, the response should have the type XxxResponse, where Xxx is the -- original method name. For example, if the original method name is -- TakeSnapshot(), the inferred response type is TakeSnapshotResponse. -- -- /See:/ 'operationResponse' smart constructor. newtype OperationResponse = OperationResponse' { _orAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orAddtional' operationResponse :: HashMap Text JSONValue -- ^ 'orAddtional' -> OperationResponse operationResponse pOrAddtional_ = OperationResponse' {_orAddtional = _Coerce # pOrAddtional_} -- | Properties of the object. Contains field \'type with type URL. orAddtional :: Lens' OperationResponse (HashMap Text JSONValue) orAddtional = lens _orAddtional (\ s a -> s{_orAddtional = a}) . _Coerce instance FromJSON OperationResponse where parseJSON = withObject "OperationResponse" (\ o -> OperationResponse' <$> (parseJSONObject o)) instance ToJSON OperationResponse where toJSON = toJSON . _orAddtional -- | Provides a user-facing message with locale info. The maximum message -- length is 4096 characters. -- -- /See:/ 'userFacingMessage' smart constructor. data UserFacingMessage = UserFacingMessage' { _ufmLocalizedMessages :: !(Maybe UserFacingMessageLocalizedMessages) , _ufmDefaultMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UserFacingMessage' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ufmLocalizedMessages' -- -- * 'ufmDefaultMessage' userFacingMessage :: UserFacingMessage userFacingMessage = UserFacingMessage' {_ufmLocalizedMessages = Nothing, _ufmDefaultMessage = Nothing} -- | A map containing pairs, where locale is a well-formed BCP 47 language -- (https:\/\/www.w3.org\/International\/articles\/language-tags\/) code, -- such as en-US, es-ES, or fr. ufmLocalizedMessages :: Lens' UserFacingMessage (Maybe UserFacingMessageLocalizedMessages) ufmLocalizedMessages = lens _ufmLocalizedMessages (\ s a -> s{_ufmLocalizedMessages = a}) -- | The default message displayed if no localized message is specified or -- the user\'s locale doesn\'t match with any of the localized messages. A -- default message must be provided if any localized messages are provided. ufmDefaultMessage :: Lens' UserFacingMessage (Maybe Text) ufmDefaultMessage = lens _ufmDefaultMessage (\ s a -> s{_ufmDefaultMessage = a}) instance FromJSON UserFacingMessage where parseJSON = withObject "UserFacingMessage" (\ o -> UserFacingMessage' <$> (o .:? "localizedMessages") <*> (o .:? "defaultMessage")) instance ToJSON UserFacingMessage where toJSON UserFacingMessage'{..} = object (catMaybes [("localizedMessages" .=) <$> _ufmLocalizedMessages, ("defaultMessage" .=) <$> _ufmDefaultMessage]) -- | Contact details for LaForge enterprises. -- -- /See:/ 'contactInfo' smart constructor. data ContactInfo = ContactInfo' { _ciContactEmail :: !(Maybe Text) , _ciDataProtectionOfficerName :: !(Maybe Text) , _ciEuRepresentativeName :: !(Maybe Text) , _ciEuRepresentativeEmail :: !(Maybe Text) , _ciEuRepresentativePhone :: !(Maybe Text) , _ciDataProtectionOfficerEmail :: !(Maybe Text) , _ciDataProtectionOfficerPhone :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ContactInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ciContactEmail' -- -- * 'ciDataProtectionOfficerName' -- -- * 'ciEuRepresentativeName' -- -- * 'ciEuRepresentativeEmail' -- -- * 'ciEuRepresentativePhone' -- -- * 'ciDataProtectionOfficerEmail' -- -- * 'ciDataProtectionOfficerPhone' contactInfo :: ContactInfo contactInfo = ContactInfo' { _ciContactEmail = Nothing , _ciDataProtectionOfficerName = Nothing , _ciEuRepresentativeName = Nothing , _ciEuRepresentativeEmail = Nothing , _ciEuRepresentativePhone = Nothing , _ciDataProtectionOfficerEmail = Nothing , _ciDataProtectionOfficerPhone = Nothing } -- | Email address for a point of contact, which will be used to send -- important announcements related to managed Google Play. ciContactEmail :: Lens' ContactInfo (Maybe Text) ciContactEmail = lens _ciContactEmail (\ s a -> s{_ciContactEmail = a}) -- | The name of the data protection officer. ciDataProtectionOfficerName :: Lens' ContactInfo (Maybe Text) ciDataProtectionOfficerName = lens _ciDataProtectionOfficerName (\ s a -> s{_ciDataProtectionOfficerName = a}) -- | The name of the EU representative. ciEuRepresentativeName :: Lens' ContactInfo (Maybe Text) ciEuRepresentativeName = lens _ciEuRepresentativeName (\ s a -> s{_ciEuRepresentativeName = a}) -- | The email of the EU representative. The email is validated but not -- verified. ciEuRepresentativeEmail :: Lens' ContactInfo (Maybe Text) ciEuRepresentativeEmail = lens _ciEuRepresentativeEmail (\ s a -> s{_ciEuRepresentativeEmail = a}) -- | The phone number of the EU representative. The phone number is validated -- but not verified. ciEuRepresentativePhone :: Lens' ContactInfo (Maybe Text) ciEuRepresentativePhone = lens _ciEuRepresentativePhone (\ s a -> s{_ciEuRepresentativePhone = a}) -- | The email of the data protection officer. The email is validated but not -- verified. ciDataProtectionOfficerEmail :: Lens' ContactInfo (Maybe Text) ciDataProtectionOfficerEmail = lens _ciDataProtectionOfficerEmail (\ s a -> s{_ciDataProtectionOfficerEmail = a}) -- | The phone number of the data protection officer The phone number is -- validated but not verified. ciDataProtectionOfficerPhone :: Lens' ContactInfo (Maybe Text) ciDataProtectionOfficerPhone = lens _ciDataProtectionOfficerPhone (\ s a -> s{_ciDataProtectionOfficerPhone = a}) instance FromJSON ContactInfo where parseJSON = withObject "ContactInfo" (\ o -> ContactInfo' <$> (o .:? "contactEmail") <*> (o .:? "dataProtectionOfficerName") <*> (o .:? "euRepresentativeName") <*> (o .:? "euRepresentativeEmail") <*> (o .:? "euRepresentativePhone") <*> (o .:? "dataProtectionOfficerEmail") <*> (o .:? "dataProtectionOfficerPhone")) instance ToJSON ContactInfo where toJSON ContactInfo'{..} = object (catMaybes [("contactEmail" .=) <$> _ciContactEmail, ("dataProtectionOfficerName" .=) <$> _ciDataProtectionOfficerName, ("euRepresentativeName" .=) <$> _ciEuRepresentativeName, ("euRepresentativeEmail" .=) <$> _ciEuRepresentativeEmail, ("euRepresentativePhone" .=) <$> _ciEuRepresentativePhone, ("dataProtectionOfficerEmail" .=) <$> _ciDataProtectionOfficerEmail, ("dataProtectionOfficerPhone" .=) <$> _ciDataProtectionOfficerPhone]) -- | Information about device software. -- -- /See:/ 'softwareInfo' smart constructor. data SoftwareInfo = SoftwareInfo' { _siSecurityPatchLevel :: !(Maybe Text) , _siAndroidDevicePolicyVersionName :: !(Maybe Text) , _siDeviceKernelVersion :: !(Maybe Text) , _siAndroidDevicePolicyVersionCode :: !(Maybe (Textual Int32)) , _siDeviceBuildSignature :: !(Maybe Text) , _siSystemUpdateInfo :: !(Maybe SystemUpdateInfo) , _siBootLoaderVersion :: !(Maybe Text) , _siAndroidBuildTime :: !(Maybe DateTime') , _siPrimaryLanguageCode :: !(Maybe Text) , _siAndroidBuildNumber :: !(Maybe Text) , _siAndroidVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SoftwareInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siSecurityPatchLevel' -- -- * 'siAndroidDevicePolicyVersionName' -- -- * 'siDeviceKernelVersion' -- -- * 'siAndroidDevicePolicyVersionCode' -- -- * 'siDeviceBuildSignature' -- -- * 'siSystemUpdateInfo' -- -- * 'siBootLoaderVersion' -- -- * 'siAndroidBuildTime' -- -- * 'siPrimaryLanguageCode' -- -- * 'siAndroidBuildNumber' -- -- * 'siAndroidVersion' softwareInfo :: SoftwareInfo softwareInfo = SoftwareInfo' { _siSecurityPatchLevel = Nothing , _siAndroidDevicePolicyVersionName = Nothing , _siDeviceKernelVersion = Nothing , _siAndroidDevicePolicyVersionCode = Nothing , _siDeviceBuildSignature = Nothing , _siSystemUpdateInfo = Nothing , _siBootLoaderVersion = Nothing , _siAndroidBuildTime = Nothing , _siPrimaryLanguageCode = Nothing , _siAndroidBuildNumber = Nothing , _siAndroidVersion = Nothing } -- | Security patch level, e.g. 2016-05-01. siSecurityPatchLevel :: Lens' SoftwareInfo (Maybe Text) siSecurityPatchLevel = lens _siSecurityPatchLevel (\ s a -> s{_siSecurityPatchLevel = a}) -- | The Android Device Policy app version as displayed to the user. siAndroidDevicePolicyVersionName :: Lens' SoftwareInfo (Maybe Text) siAndroidDevicePolicyVersionName = lens _siAndroidDevicePolicyVersionName (\ s a -> s{_siAndroidDevicePolicyVersionName = a}) -- | Kernel version, for example, 2.6.32.9-g103d848. siDeviceKernelVersion :: Lens' SoftwareInfo (Maybe Text) siDeviceKernelVersion = lens _siDeviceKernelVersion (\ s a -> s{_siDeviceKernelVersion = a}) -- | The Android Device Policy app version code. siAndroidDevicePolicyVersionCode :: Lens' SoftwareInfo (Maybe Int32) siAndroidDevicePolicyVersionCode = lens _siAndroidDevicePolicyVersionCode (\ s a -> s{_siAndroidDevicePolicyVersionCode = a}) . mapping _Coerce -- | SHA-256 hash of android.content.pm.Signature -- (https:\/\/developer.android.com\/reference\/android\/content\/pm\/Signature.html) -- associated with the system package, which can be used to verify that the -- system build hasn\'t been modified. siDeviceBuildSignature :: Lens' SoftwareInfo (Maybe Text) siDeviceBuildSignature = lens _siDeviceBuildSignature (\ s a -> s{_siDeviceBuildSignature = a}) -- | Information about a potential pending system update. siSystemUpdateInfo :: Lens' SoftwareInfo (Maybe SystemUpdateInfo) siSystemUpdateInfo = lens _siSystemUpdateInfo (\ s a -> s{_siSystemUpdateInfo = a}) -- | The system bootloader version number, e.g. 0.6.7. siBootLoaderVersion :: Lens' SoftwareInfo (Maybe Text) siBootLoaderVersion = lens _siBootLoaderVersion (\ s a -> s{_siBootLoaderVersion = a}) -- | Build time. siAndroidBuildTime :: Lens' SoftwareInfo (Maybe UTCTime) siAndroidBuildTime = lens _siAndroidBuildTime (\ s a -> s{_siAndroidBuildTime = a}) . mapping _DateTime -- | An IETF BCP 47 language code for the primary locale on the device. siPrimaryLanguageCode :: Lens' SoftwareInfo (Maybe Text) siPrimaryLanguageCode = lens _siPrimaryLanguageCode (\ s a -> s{_siPrimaryLanguageCode = a}) -- | Android build ID string meant for displaying to the user. For example, -- shamu-userdebug 6.0.1 MOB30I 2756745 dev-keys. siAndroidBuildNumber :: Lens' SoftwareInfo (Maybe Text) siAndroidBuildNumber = lens _siAndroidBuildNumber (\ s a -> s{_siAndroidBuildNumber = a}) -- | The user-visible Android version string. For example, 6.0.1. siAndroidVersion :: Lens' SoftwareInfo (Maybe Text) siAndroidVersion = lens _siAndroidVersion (\ s a -> s{_siAndroidVersion = a}) instance FromJSON SoftwareInfo where parseJSON = withObject "SoftwareInfo" (\ o -> SoftwareInfo' <$> (o .:? "securityPatchLevel") <*> (o .:? "androidDevicePolicyVersionName") <*> (o .:? "deviceKernelVersion") <*> (o .:? "androidDevicePolicyVersionCode") <*> (o .:? "deviceBuildSignature") <*> (o .:? "systemUpdateInfo") <*> (o .:? "bootloaderVersion") <*> (o .:? "androidBuildTime") <*> (o .:? "primaryLanguageCode") <*> (o .:? "androidBuildNumber") <*> (o .:? "androidVersion")) instance ToJSON SoftwareInfo where toJSON SoftwareInfo'{..} = object (catMaybes [("securityPatchLevel" .=) <$> _siSecurityPatchLevel, ("androidDevicePolicyVersionName" .=) <$> _siAndroidDevicePolicyVersionName, ("deviceKernelVersion" .=) <$> _siDeviceKernelVersion, ("androidDevicePolicyVersionCode" .=) <$> _siAndroidDevicePolicyVersionCode, ("deviceBuildSignature" .=) <$> _siDeviceBuildSignature, ("systemUpdateInfo" .=) <$> _siSystemUpdateInfo, ("bootloaderVersion" .=) <$> _siBootLoaderVersion, ("androidBuildTime" .=) <$> _siAndroidBuildTime, ("primaryLanguageCode" .=) <$> _siPrimaryLanguageCode, ("androidBuildNumber" .=) <$> _siAndroidBuildNumber, ("androidVersion" .=) <$> _siAndroidVersion]) -- | Settings controlling the behavior of application reports. -- -- /See:/ 'applicationReportingSettings' smart constructor. newtype ApplicationReportingSettings = ApplicationReportingSettings' { _arsIncludeRemovedApps :: Maybe Bool } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationReportingSettings' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'arsIncludeRemovedApps' applicationReportingSettings :: ApplicationReportingSettings applicationReportingSettings = ApplicationReportingSettings' {_arsIncludeRemovedApps = Nothing} -- | Whether removed apps are included in application reports. arsIncludeRemovedApps :: Lens' ApplicationReportingSettings (Maybe Bool) arsIncludeRemovedApps = lens _arsIncludeRemovedApps (\ s a -> s{_arsIncludeRemovedApps = a}) instance FromJSON ApplicationReportingSettings where parseJSON = withObject "ApplicationReportingSettings" (\ o -> ApplicationReportingSettings' <$> (o .:? "includeRemovedApps")) instance ToJSON ApplicationReportingSettings where toJSON ApplicationReportingSettings'{..} = object (catMaybes [("includeRemovedApps" .=) <$> _arsIncludeRemovedApps]) -- | A permission required by the app. -- -- /See:/ 'applicationPermission' smart constructor. data ApplicationPermission = ApplicationPermission' { _apName :: !(Maybe Text) , _apDescription :: !(Maybe Text) , _apPermissionId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ApplicationPermission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apName' -- -- * 'apDescription' -- -- * 'apPermissionId' applicationPermission :: ApplicationPermission applicationPermission = ApplicationPermission' {_apName = Nothing, _apDescription = Nothing, _apPermissionId = Nothing} -- | The name of the permission. Localized. apName :: Lens' ApplicationPermission (Maybe Text) apName = lens _apName (\ s a -> s{_apName = a}) -- | A longer description of the permission, providing more detail on what it -- affects. Localized. apDescription :: Lens' ApplicationPermission (Maybe Text) apDescription = lens _apDescription (\ s a -> s{_apDescription = a}) -- | An opaque string uniquely identifying the permission. Not localized. apPermissionId :: Lens' ApplicationPermission (Maybe Text) apPermissionId = lens _apPermissionId (\ s a -> s{_apPermissionId = a}) instance FromJSON ApplicationPermission where parseJSON = withObject "ApplicationPermission" (\ o -> ApplicationPermission' <$> (o .:? "name") <*> (o .:? "description") <*> (o .:? "permissionId")) instance ToJSON ApplicationPermission where toJSON ApplicationPermission'{..} = object (catMaybes [("name" .=) <$> _apName, ("description" .=) <$> _apDescription, ("permissionId" .=) <$> _apPermissionId]) -- | An action executed during setup. -- -- /See:/ 'setupAction' smart constructor. data SetupAction = SetupAction' { _saLaunchApp :: !(Maybe LaunchAppAction) , _saTitle :: !(Maybe UserFacingMessage) , _saDescription :: !(Maybe UserFacingMessage) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SetupAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'saLaunchApp' -- -- * 'saTitle' -- -- * 'saDescription' setupAction :: SetupAction setupAction = SetupAction' {_saLaunchApp = Nothing, _saTitle = Nothing, _saDescription = Nothing} -- | An action to launch an app. saLaunchApp :: Lens' SetupAction (Maybe LaunchAppAction) saLaunchApp = lens _saLaunchApp (\ s a -> s{_saLaunchApp = a}) -- | Title of this action. saTitle :: Lens' SetupAction (Maybe UserFacingMessage) saTitle = lens _saTitle (\ s a -> s{_saTitle = a}) -- | Description of this action. saDescription :: Lens' SetupAction (Maybe UserFacingMessage) saDescription = lens _saDescription (\ s a -> s{_saDescription = a}) instance FromJSON SetupAction where parseJSON = withObject "SetupAction" (\ o -> SetupAction' <$> (o .:? "launchApp") <*> (o .:? "title") <*> (o .:? "description")) instance ToJSON SetupAction where toJSON SetupAction'{..} = object (catMaybes [("launchApp" .=) <$> _saLaunchApp, ("title" .=) <$> _saTitle, ("description" .=) <$> _saDescription]) -- | A web app. -- -- /See:/ 'webApp' smart constructor. data WebApp = WebApp' { _waVersionCode :: !(Maybe (Textual Int64)) , _waIcons :: !(Maybe [WebAppIcon]) , _waStartURL :: !(Maybe Text) , _waDisplayMode :: !(Maybe WebAppDisplayMode) , _waName :: !(Maybe Text) , _waTitle :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WebApp' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'waVersionCode' -- -- * 'waIcons' -- -- * 'waStartURL' -- -- * 'waDisplayMode' -- -- * 'waName' -- -- * 'waTitle' webApp :: WebApp webApp = WebApp' { _waVersionCode = Nothing , _waIcons = Nothing , _waStartURL = Nothing , _waDisplayMode = Nothing , _waName = Nothing , _waTitle = Nothing } -- | The current version of the app.Note that the version can automatically -- increase during the lifetime of the web app, while Google does internal -- housekeeping to keep the web app up-to-date. waVersionCode :: Lens' WebApp (Maybe Int64) waVersionCode = lens _waVersionCode (\ s a -> s{_waVersionCode = a}) . mapping _Coerce -- | A list of icons for the web app. Must have at least one element. waIcons :: Lens' WebApp [WebAppIcon] waIcons = lens _waIcons (\ s a -> s{_waIcons = a}) . _Default . _Coerce -- | The start URL, i.e. the URL that should load when the user opens the -- application. waStartURL :: Lens' WebApp (Maybe Text) waStartURL = lens _waStartURL (\ s a -> s{_waStartURL = a}) -- | The display mode of the web app. waDisplayMode :: Lens' WebApp (Maybe WebAppDisplayMode) waDisplayMode = lens _waDisplayMode (\ s a -> s{_waDisplayMode = a}) -- | The name of the web app, which is generated by the server during -- creation in the form -- enterprises\/{enterpriseId}\/webApps\/{packageName}. waName :: Lens' WebApp (Maybe Text) waName = lens _waName (\ s a -> s{_waName = a}) -- | The title of the web app as displayed to the user (e.g., amongst a list -- of other applications, or as a label for an icon). waTitle :: Lens' WebApp (Maybe Text) waTitle = lens _waTitle (\ s a -> s{_waTitle = a}) instance FromJSON WebApp where parseJSON = withObject "WebApp" (\ o -> WebApp' <$> (o .:? "versionCode") <*> (o .:? "icons" .!= mempty) <*> (o .:? "startUrl") <*> (o .:? "displayMode") <*> (o .:? "name") <*> (o .:? "title")) instance ToJSON WebApp where toJSON WebApp'{..} = object (catMaybes [("versionCode" .=) <$> _waVersionCode, ("icons" .=) <$> _waIcons, ("startUrl" .=) <$> _waStartURL, ("displayMode" .=) <$> _waDisplayMode, ("name" .=) <$> _waName, ("title" .=) <$> _waTitle])
brendanhay/gogol
gogol-androidmanagement/gen/Network/Google/AndroidManagement/Types/Product.hs
mpl-2.0
282,686
0
93
66,397
47,842
27,641
20,201
5,532
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.AdExchangeBuyer.PretargetingConfig.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Inserts a new pretargeting configuration. -- -- /See:/ <https://developers.google.com/ad-exchange/buyer-rest Ad Exchange Buyer API Reference> for @adexchangebuyer.pretargetingConfig.insert@. module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Insert ( -- * REST Resource PretargetingConfigInsertResource -- * Creating a Request , pretargetingConfigInsert , PretargetingConfigInsert -- * Request Lenses , pciPayload , pciAccountId ) where import Network.Google.AdExchangeBuyer.Types import Network.Google.Prelude -- | A resource alias for @adexchangebuyer.pretargetingConfig.insert@ method which the -- 'PretargetingConfigInsert' request conforms to. type PretargetingConfigInsertResource = "adexchangebuyer" :> "v1.4" :> "pretargetingconfigs" :> Capture "accountId" (Textual Int64) :> QueryParam "alt" AltJSON :> ReqBody '[JSON] PretargetingConfig :> Post '[JSON] PretargetingConfig -- | Inserts a new pretargeting configuration. -- -- /See:/ 'pretargetingConfigInsert' smart constructor. data PretargetingConfigInsert = PretargetingConfigInsert' { _pciPayload :: !PretargetingConfig , _pciAccountId :: !(Textual Int64) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PretargetingConfigInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pciPayload' -- -- * 'pciAccountId' pretargetingConfigInsert :: PretargetingConfig -- ^ 'pciPayload' -> Int64 -- ^ 'pciAccountId' -> PretargetingConfigInsert pretargetingConfigInsert pPciPayload_ pPciAccountId_ = PretargetingConfigInsert' { _pciPayload = pPciPayload_ , _pciAccountId = _Coerce # pPciAccountId_ } -- | Multipart request metadata. pciPayload :: Lens' PretargetingConfigInsert PretargetingConfig pciPayload = lens _pciPayload (\ s a -> s{_pciPayload = a}) -- | The account id to insert the pretargeting config for. pciAccountId :: Lens' PretargetingConfigInsert Int64 pciAccountId = lens _pciAccountId (\ s a -> s{_pciAccountId = a}) . _Coerce instance GoogleRequest PretargetingConfigInsert where type Rs PretargetingConfigInsert = PretargetingConfig type Scopes PretargetingConfigInsert = '["https://www.googleapis.com/auth/adexchange.buyer"] requestClient PretargetingConfigInsert'{..} = go _pciAccountId (Just AltJSON) _pciPayload adExchangeBuyerService where go = buildClient (Proxy :: Proxy PretargetingConfigInsertResource) mempty
rueshyna/gogol
gogol-adexchange-buyer/gen/Network/Google/Resource/AdExchangeBuyer/PretargetingConfig/Insert.hs
mpl-2.0
3,536
0
13
740
402
240
162
63
1
-- -- Copyright 2017-2018 Azad Bolour -- Licensed under GNU Affero General Public License v3.0 - -- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md -- module BoardGame.Server.Domain.HopelessBlanksSpec where import Test.Hspec import qualified Data.Set as Set import qualified Bolour.Language.Domain.WordDictionary as Dict import qualified BoardGame.Server.Domain.StripMatcher as StripMatcher import qualified BoardGame.Server.Domain.Board as Board import BoardGame.Server.Domain.Board (Board, Board(Board)) import BoardGame.Server.Domain.Tray (Tray, Tray(Tray)) import BoardGame.Common.Domain.PiecePoint (PiecePoint, PiecePoint(PiecePoint)) import BoardGame.Common.Domain.Piece (Piece, Piece(Piece)) import Bolour.Plane.Domain.Point (Point, Point(Point)) import qualified Bolour.Plane.Domain.Axis as Axis trayCapacity :: Int trayCapacity = 3 dimension :: Int dimension = 3 emptyBoard :: Board emptyBoard = Board.mkEmptyBoard dimension tray :: Tray tray = Tray trayCapacity [] -- no need for pieces in this test maxMaskedWords :: Int maxMaskedWords = 2 myWords = ["AND", "TAN"] maskedWords = Set.toList $ Dict.mkMaskedWords myWords maxMaskedWords dictionary = Dict.mkDictionary "en" myWords maskedWords maxMaskedWords gridPieces :: [PiecePoint] gridPieces = [ PiecePoint (Piece 'A' "0") (Point 2 0), PiecePoint (Piece 'N' "1") (Point 2 1), PiecePoint (Piece 'D' "2") (Point 2 2), PiecePoint (Piece 'T' "3") (Point 0 1), PiecePoint (Piece 'A' "4") (Point 1 1) ] board = Board.setPiecePoints emptyBoard gridPieces spec :: Spec spec = do describe "hopeless blanks" $ it "find hopeless blanks" $ do let hopeless = StripMatcher.hopelessBlankPoints board dictionary print hopeless -- Dict.isWord dictionary "TEST" `shouldBe` True describe "masked words" $ it "compute masked words" $ do Dict.isMaskedWord dictionary " A " `shouldBe` True Dict.isMaskedWord dictionary " D" `shouldBe` True describe "set hopeless blank points as dead recursive" $ it "set hopeless blank points as dead recursive" $ do let (finalBoard, deadPoints) = StripMatcher.findAndSetBoardBlackPoints dictionary board print deadPoints
azadbolour/boardgame
haskell-server/test/BoardGame/Server/Domain/HopelessBlanksSpec.hs
agpl-3.0
2,208
0
14
353
559
317
242
47
1
{-# LANGUAGE ScopedTypeVariables #-} -- | -- Module : BitTorrent -- Copyright : (c) Alexandru Scvortov 2009 -- License : LGPL (see LICENSE file) -- Maintainer : scvalex@gmail.com -- -- This module centralizes the functions. As a rule of thumb, this -- should be the only module that you need to import in order to use -- the BitTorrent library. -- -- This does NOT include any of the concurrent stuff, network stuff or -- managers. -- module BitTorrent ( Metainfo(..), InfoHash, readMetainfo, parseMetainfo , PeerId, makeMyPeerId, translatePeerId , getLTorrentDir, getDefaultDownloadDir , createFilePathIfMissing, (</>), calculateFileChecksum , Peer(..), Handshake(..), Message(..), newPeerIO, newPeerSTM , setPeerChocked, setPeerInterested, setPiecemap, readPiecemap , hPutHandshake, hGetHandshake, hGetMessage, hPutMessage , Entity(..) , Piecemap, makePiecemap , PieceStatus(..), PieceStatusArray , makeInitialRequest, TrackerRequest(..), TrackerResponse(..) , getPeers, doTrackerQuery, getCompleteIncomplete , readConfig, writeConfig, writeConfigIfMissing , readConfigDefault ) where import Prelude hiding ( catch ) import BitTorrent.Peer import BitTorrent.Tracker import Control.Concurrent import Control.Exception import Control.Monad.Trans import Data.Array.Unboxed import qualified Data.ByteString.Lazy.Char8 as L import Data.Metainfo import Data.PeerId import Data.Piecemap import Network.Entity import System.Configuration import System.Directory ( getUserDocumentsDirectory ) import System.Directory.Extra import System.IO import Text.Printf ( printf ) -- | Read and parse a metainfo file. readMetainfo :: FilePath -> IO Metainfo readMetainfo f = do bracket (openBinaryFile f ReadMode) (hClose) (\h -> do txt <- L.hGetContents h case parseMetainfo txt of Nothing -> fail $ printf "readMetainfo: could not parse ``%s''" f Just mi -> return mi) -- | Lift an action from IO to a MonadIO. io :: MonadIO m => IO a -> m a io = liftIO -- | Return the path to the user's default download directory. getDefaultDownloadDir :: MonadIO m => m FilePath getDefaultDownloadDir = do docs <- io $ getUserDocumentsDirectory return $ docs </> "downloads" -- | The current status of a piece. data PieceStatus = Complete -- ^ The piece has been downloaded and checked | DontHave -- ^ The piece has not been downloaded yet | Getting [ThreadId] -- ^ One or more peer handlers is -- downloading this piece deriving (Show, Eq) type PieceStatusArray = Array Int PieceStatus
scvalex/ltorrent
BitTorrent.hs
lgpl-3.0
2,714
0
16
598
496
302
194
53
2
module Themes (myTheme, myButtonedTheme, Theme (..)) where import XMonad.Layout.Decoration(Theme(..), Decoration, DefaultShrinker) import XMonad.Layout.ImageButtonDecoration import XMonad.Util.Image import qualified Colors as C myButtonedTheme = defaultThemeWithImageButtons { fontName = "xft:RobotoCondensed:size=11" , decoHeight = 20 , activeColor = C.backgroundColor , inactiveColor = C.backgroundColor , urgentColor = C.backgroundColor , activeBorderColor = C.backgroundColor , inactiveBorderColor = C.backgroundColor , urgentBorderColor = C.backgroundColor , activeTextColor = C.focusedColor , inactiveTextColor = C.normalColor , urgentTextColor = C.urgentColor , windowTitleIcons = [ (menuButton, CenterLeft 3) , (closeButton, CenterRight 3) , (maxiButton, CenterRight 18) , (miniButton, CenterRight 33) ] } myTheme = myButtonedTheme { windowTitleAddons = [] , windowTitleIcons = [] } -- The images in a 0-1 scale to make -- it easier to visualize convertToBool' :: [Int] -> [Bool] convertToBool' = map (\x -> x == 1) convertToBool :: [[Int]] -> [[Bool]] convertToBool = map convertToBool' menuButton' :: [[Int]] menuButton' = [[1,1,1,1,1,1,1,1,1,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1]] menuButton :: [[Bool]] menuButton = convertToBool menuButton' miniButton' :: [[Int]] miniButton' = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [1,1,1,1,1,1,1,1,1,1]] miniButton :: [[Bool]] miniButton = convertToBool miniButton' maxiButton' :: [[Int]] maxiButton' = [[1,1,1,1,1,1,1,1,1,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1]] maxiButton :: [[Bool]] maxiButton = convertToBool maxiButton' closeButton' :: [[Int]] closeButton' = [[1,0,0,0,0,0,0,0,0,1], [0,1,0,0,0,0,0,0,1,0], [0,0,1,0,0,0,0,1,0,0], [0,0,0,1,0,0,1,0,0,0], [0,0,0,0,1,1,0,0,0,0], [0,0,0,0,1,1,0,0,0,0], [0,0,0,1,0,0,1,0,0,0], [0,0,1,0,0,0,0,1,0,0], [0,1,0,0,0,0,0,0,1,0], [1,0,0,0,0,0,0,0,0,1]] closeButton :: [[Bool]] closeButton = convertToBool closeButton'
Balletie/.xmonad
lib/Themes.hs
unlicense
3,091
0
9
894
1,752
1,146
606
80
1
{-| This package provides basic types used for the Bitcoin networking protocol together with Data.Serialize instances for efficiently serializing and de-serializing them. More information on the bitcoin protocol is available here: <http://en.bitcoin.it/wiki/Protocol_specification> -} module Network.Haskoin.Network ( module X ) where import Network.Haskoin.Network.Bloom as X import Network.Haskoin.Network.Message as X import Network.Haskoin.Network.Types as X
xenog/haskoin
src/Network/Haskoin/Network.hs
unlicense
507
0
4
96
41
31
10
5
0
{-| -} module Trace ( Ray( Ray , rayPoint , rayVector , rayMinParam , rayMaxParam ) , rayAt , rayParamIsValid , Intersection( Intersection , isectP , isectN , isectUV , isectRay , isectRayParam , isectRayEpsilon ) , Traceable( Traceable , trace , traceHit ) , mkTraceable , quadricRayEpsilonFactor ) where import VecMath (Normal3, Point3, Transform (xform), UVCoord, Vector3, toPoint3, toVector3, (.*), (.*)) ---------------------------------------------------------------------------------------------------- -- RAY STUFF -- |Ray. data Ray = Ray { rayPoint :: !Point3 -- ^ starting point for the ray , rayVector :: !Vector3 -- ^ vector in the direction of the ray , rayMinParam :: !Float -- ^ minimum parametric value (units of ray vector length) , rayMaxParam :: !Float -- ^ maximum parametric value (units of ray vector length) } deriving (Show) instance Transform Ray where xform x (Ray p v tmin tmax) = Ray (xform x p) (xform x v) tmin tmax -- |Evaluates a ray at a given parametric coordinate. rayAt :: Ray -> Float -> Point3 rayAt (Ray p v _ _) t = let pvec = toVector3 p in toPoint3 $ pvec + (v .* t) -- |Checks if a given ray parameter (t) falls inside the allowed range. rayParamIsValid :: Ray -> Float -> Bool rayParamIsValid (Ray _ _ tmin tmax) t = (t >= tmin) && (t <= tmax) ---------------------------------------------------------------------------------------------------- -- INTERSECTION WITH A PRIMITIVE -- |Intersection between a ray and a primitive. data Intersection = Intersection { isectP :: Point3 , isectN :: Normal3 , isectUV :: UVCoord , isectRay :: Ray , isectRayParam :: Float , isectRayEpsilon :: Float } instance Transform Intersection where xform x (Intersection p n uv ray rp re) = Intersection (xform x p) (xform x n) uv (xform x ray) rp re ---------------------------------------------------------------------------------------------------- -- TRACEABLE THING -- | Traceable. -- -- Something is traceable if a ray can be fired against it and some intersection data found. -- Traceable things exist in their own coordinate system (because they know of no other!). Thus, -- rays and intersections are all implicitly in "object space" for a traceable. data Traceable = Traceable { -- | Traces a ray against an object. trace :: Ray -> Maybe Intersection -- | Checks if a ray strikes an object , traceHit :: Ray -> Bool } -- | Default implementation of a 'traceHit' function, using an existing 'trace' function. defaultTraceHit :: (Ray -> Maybe Intersection) -> Ray -> Bool defaultTraceHit t r = maybe False (const True) (t r) -- | Creates a traceable from only a ray-intersection function, providing a default implementation -- of traceHit. mkTraceable :: (Ray -> Maybe Intersection) -> Traceable mkTraceable f = Traceable { trace = f , traceHit = defaultTraceHit f } ---------------------------------------------------------------------------------------------------- -- TOP-LEVEL STUFF -- |Factor used to scale ray intersections for quadrics. quadricRayEpsilonFactor :: Float quadricRayEpsilonFactor = 5.0e-4
lancelet/approxier
src/lib/Trace.hs
apache-2.0
3,314
0
10
742
601
357
244
74
1
-- http://www.codewars.com/kata/52756e5ad454534f220001ef module LongestCommonSubsequence where import Data.List import Data.Ord lcs :: String -> String -> String lcs x y = maximumBy (comparing length) (subsequences x `intersect` subsequences y)
Bodigrim/katas
src/haskell/4-Longest-Common-Subsequence.hs
bsd-2-clause
246
0
8
29
64
35
29
5
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Module : Web.Pagure.Lens -- Copyright : (C) 2015 Ricky Elrod -- License : BSD2 (see LICENSE file) -- Maintainer : Ricky Elrod <relrod@redhat.com> -- Stability : experimental -- Portability : ghc (lens) -- -- Lenses for the various Pagure types. We generate them all here so that we -- can take advantage of typeclass method overloading hackery put in place by -- 'makeFields'. ---------------------------------------------------------------------------- module Web.Pagure.Lens where import Control.Lens import Web.Pagure.Types import Web.Pagure.Types.Issue import Web.Pagure.Types.Project import Web.Pagure.Types.User -- Types makeFields ''PagureConfig makeFields ''User -- Issues makeFields ''IssueResponse makeFields ''IssueArgs makeFields ''Issue makeFields ''IssueComment makeFields ''IssueFilters -- Project makeFields ''PullRequest makeFields ''PullRequestComment -- User makeFields ''UserResponse makeFields ''UserRepo
fedora-infra/pagure-haskell
src/Web/Pagure/Lens.hs
bsd-2-clause
1,161
0
6
133
148
81
67
21
0
{-# LANGUAGE TupleSections, OverloadedStrings, DoAndIfThenElse,TemplateHaskell #-} module Handler.Home where import Import import Yesod.Auth import Handler.Widget import Handler.Form import Handler.Utils(requireAuthId') import Data.FileEmbed import Data.Text.Encoding (decodeUtf8) import Data.List (find) import qualified Data.ByteString as BS import Network.Wai import Text.Blaze.Html (preEscapedToHtml) {- optionsAuthR :: Handler RepPlain optionsAuthR = do -- ToDo: Add other sites. setHeader "Access-Control-Allow-Origin" "http://pubs.acs.org" setHeader "Access-Control-Allow-Methods" "GET, OPTIONS" return $ RepPlain $ toContent ("" :: Text) -} getHomeR :: Handler Html getHomeR = do mu <- maybeAuthId mobile <- isMobile redirect $ case (mu,mobile) of (Just user,False) -> PaperListR (Just user,True) -> PaperListMobileR (Nothing,False) -> WelcomeR (Nothing,True) -> WelcomeMobileR getStartR :: Handler Html getStartR = do mobile <- isMobile redirect $ if mobile then PaperListMobileR else PaperListR isMobile :: Handler Bool isMobile = do req <- waiRequest let hs = requestHeaders req let mua = fromMaybe ("","") $ find (\(k,v) -> k == "User-Agent") hs return $ any (\s -> s `BS.isInfixOf` (snd mua)) ["Android","iPhone","iPad","iPod"] getWelcomeR :: Handler Html getWelcomeR = nowrapLayout $(widgetFile "welcome") getWelcomeMobileR :: Handler Html getWelcomeMobileR = nowrapLayout $(widgetFile "welcome_mobile") getSignUpR :: Handler Html getSignUpR = do email <- requireAuthId' -- (widget, enctype) <- generateFormPost signUpForm muser <- runDB $ getBy (UniqueUser email) allowed <- isThisUserAllowed email if allowed then case muser of Just _ -> do nowrapLayout $(widgetFile "duplicated_user") Nothing -> do (confirmRegisterFW, enctype) <- generateFormPost (confirmRegisterF email) nowrapLayout $(widgetFile "confirm_register") else nowrapLayout $(widgetFile "register_suspended") -- This is used for controlling the number of new registration users. -- This returns True by default. isThisUserAllowed :: Text -> Handler Bool isThisUserAllowed _ = return True getUnregisteredR :: Handler Html getUnregisteredR = nowrapLayout $(widgetFile "not_registered_user") postConfirmSignUpR :: Handler Html postConfirmSignUpR = do ((result, widget), enctype) <- runFormPost (confirmRegisterF "") case result of FormSuccess user@(User _email first last) -> do email <- maybeAuthId if email == Just _email then do runDB $ insert user redirect PaperListR else redirect WelcomeR _ -> redirect WelcomeR policyText :: Text policyText = decodeUtf8 $(embedFile "config/policy_embed.html")
hirokai/PaperServer
Handler/Home.hs
bsd-2-clause
2,772
0
16
515
718
369
349
67
4
{-- Copyright (c) 2014-2020, Clockwork Dev Studio All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Common where import LexerData import ParserData import SemanticsData import CompilerData import Options import qualified Data.Map as Map import qualified Data.Sequence as Seq import System.IO import System.Exit import Control.Monad.State import Control.Monad.Except import Control.Monad.Identity import Control.Applicative (Applicative(..)) instance Functor CodeTransformation where fmap = liftM instance Applicative CodeTransformation where pure = return (<*>) = ap data Config = Config { configInputFile :: Handle, configOutputFile :: Handle, configSourceFileName :: String, configAsmFileName :: String, configObjectFileName :: String, configOptions :: Options } deriving (Show) data CodeState = ArgumentState { argumentStateArguments :: [String] } | LexState { lexStateID :: LexStateID, lexStateIncludeFileDepth :: Int, lexStateIncludeFileNameStack :: [String], lexStateIncludeFileNames :: [String], lexStateCurrentToken :: Token, lexStatePendingTokens :: Seq.Seq Token, lexStateTokens :: Seq.Seq Token, lexStateLineNumber :: Int, lexStateLineOffset :: Int, lexStateCharacters :: String, lexStateCompoundTokens :: [CompoundToken], lexStateConfig :: Config } | ParseState { parseStateIncludeFileNameStack :: [String], parseStateIncludeFileNames :: [String], parseStateTree :: Statement, parseStateTokens :: [Token], parseStateInFunction :: Bool, parseStateConfig :: Config } | SemanticState { semanticStateIncludeFileNameStack :: [String], semanticStateLineNumberStack :: [Int], semanticStateIncludeFileNames :: [String], semanticStateCompositeTypeID :: Int, semanticStateProgram :: [Statement], semanticStateSymbols :: SymbolTable, semanticStateLocalSymbols :: SymbolTable, semanticStateTypes :: SymbolTable, semanticStateInts :: IntConstantTable, semanticStateFloats :: FloatConstantTable, semanticStateStrings :: StringTable, semanticStateNameSpace :: Symbol, semanticStateDebugInfo :: DebugInfo, semanticStateLoopDepth :: Int, semanticStateConfig :: Config } | CompileState { compileStateIncludeFileNameStack :: [String], compileStateIncludeFileNames :: [String], compileStateProgram :: [Statement], compileStateAsm :: Asm, compileStateSymbols :: SymbolTable, compileStateLocalSymbols :: SymbolTable, compileStateTypes :: SymbolTable, compileStateInts :: IntConstantTable, compileStateFloats :: FloatConstantTable, compileStateStrings :: StringTable, compileStateNameSpace :: Symbol, compileStateExitLabelIDs :: [Int], compileStateDebugInfo :: DebugInfo, compileStateRegisters :: CPUContext, compileStateLineNumberStack :: [Int], compileStateLabelID :: Int, compileStateConfig :: Config } | AsmState { asmStateCode :: [String], asmStateDebugInfo :: DebugInfo, asmStateConfig :: Config } | LinkState { linkStateDebugInfo :: DebugInfo, linkStateConfig :: Config } deriving (Show) newtype CodeTransformation action = CodeTransformation {runCodeTransformation :: ExceptT FatalError (StateT CodeState IO) action} deriving (Monad, MonadIO, MonadError FatalError, MonadState CodeState) codeTransformation :: CodeState -> CodeTransformation () -> IO (Either FatalError (), CodeState) codeTransformation codeState action = (runStateT (runExceptT (runCodeTransformation action))) codeState transformCode :: CodeTransformation () -> CodeState -> IO CodeState transformCode action state = do (success,codeState) <- codeTransformation state action case success of (Left fatalError) -> do liftIO $ putStrLn (formatFatalError fatalError) liftIO $ exitSuccess (Right ()) -> return codeState verboseCommentary :: String -> Bool -> CodeTransformation () verboseCommentary msg verbose = do if verbose then liftIO $ putStr msg else return () data FatalError = FatalError { fatalErrorFileName :: String, fatalErrorLineNumber :: Int, fatalErrorOffset :: Int, fatalErrorMessage :: String } deriving (Show, Eq) formatFatalError :: FatalError -> String formatFatalError (FatalError fileName line offset msg) = fileName ++ ":" ++ show line ++ ":" ++ show offset ++ ": " ++ msg
clockworkdevstudio/Idlewild-Lang
Common.hs
bsd-2-clause
6,107
0
15
1,425
986
588
398
122
2
-------------------------------------------------------------------------------- -- | Some internal utility functions module Firefly.Internal ( fromBool , toBool ) where -------------------------------------------------------------------------------- import Foreign.C.Types (CInt) -------------------------------------------------------------------------------- toBool :: CInt -> Bool toBool = (/= 0) {-# INLINE toBool #-} -------------------------------------------------------------------------------- fromBool :: Bool -> CInt fromBool True = 1 fromBool False = 0 {-# INLINE fromBool #-}
jaspervdj/firefly
src/Firefly/Internal.hs
bsd-3-clause
619
0
5
80
75
47
28
11
1
module Y2015.Day14 (answer1, answer2) where import Data.List (sort, group, maximumBy) import Data.Ord (comparing) answer1 :: IO () answer1 = print $ maximum $ map (distanceRun inputTime) reindeers answer2 :: IO () answer2 = let winners = concatMap winnersAtRound [1 .. inputTime] points = map length $ group $ sort winners in print $ maximum points data Reindeer = Reindeer { name :: String, dist :: Int, trun :: Int, trest :: Int } deriving (Show, Eq, Ord) inputTime = 2503 reindeers = [ Reindeer "Rudolph" 22 8 165 , Reindeer "Cupid" 8 17 114 , Reindeer "Prancer" 18 6 103 , Reindeer "Donner" 25 6 145 , Reindeer "Dasher" 11 12 125 , Reindeer "Comet" 21 6 121 , Reindeer "Blitzen" 18 3 50 , Reindeer "Vixen" 20 4 75 , Reindeer "Dancer" 7 20 119 ] distanceRun time (Reindeer _ d run rest) = let x = run * (time `quot` (run + rest)) y = min run (time `mod` (run + rest)) in d * (x + y) winnersAtRound :: Int -> [Reindeer] winnersAtRound t = let distances = map (distanceRun t) reindeers maxDist = maximum distances pairs = zip distances reindeers winners = filter (\(d, _) -> d == maxDist) pairs in map snd winners
geekingfrog/advent-of-code
src/Y2015/Day14.hs
bsd-3-clause
1,264
0
13
357
486
259
227
38
1
module Lexer where import Text.ParserCombinators.Parsec.Number import Text.Parsec hiding (tokens, token) import Data.Foldable (msum) import Data.Char type Lexer a = Parsec String () a data TokenPos = TokenPos {getToken :: Token, getposition :: SourcePos} data Token = Identifier String | CapIdentifier String | Number Double | ReservedS ReservedSymbol | ReservedW ReservedWord deriving Eq data ReservedSymbol = Plus | Multiply | Equal | BackSlash | Dot | Semicolon | LeftParenthesis | RightParenthesis deriving (Bounded, Enum, Eq) instance Show TokenPos where show = show . getToken instance Show Token where show (Identifier str) = show str -- show to enclose in "" to diferentiate with reservedWords show (CapIdentifier str) = show str show (Number n ) = show n show (ReservedS s) = "'" ++ (toChar s : "'") show (ReservedW w) = show w reservedSymbols :: [ReservedSymbol] reservedSymbols = [minBound .. maxBound] toChar :: ReservedSymbol -> Char toChar Plus = '+' toChar Multiply = '*' toChar Equal = '=' toChar BackSlash = '\\' toChar Dot = '.' toChar Semicolon = ';' toChar LeftParenthesis = '(' toChar RightParenthesis = ')' toString :: ReservedWord -> String toString w = case show w of (x : xs) -> toLower x : xs [] -> error "incorrect instance show ReservedWord" data ReservedWord = Let | In deriving (Show, Bounded, Enum, Eq) reservedWords :: [ReservedWord] reservedWords = [minBound .. maxBound] lexer :: String -> Either ParseError [TokenPos] lexer = parse tokens "" parsePos :: Lexer Token -> Lexer TokenPos parsePos p = TokenPos <$> p <*> getPosition tokens :: Lexer [TokenPos] tokens = spaces *> many (token <* spaces) token :: Lexer TokenPos token = parsePos $ choice [ msum (map symbol reservedSymbols) , msum (map keyWord reservedWords) , capIdentifier , identifier , double ] capIdentifier :: Lexer Token capIdentifier = do first <- upper rest <- many alphaNum return $ CapIdentifier $ first : rest identifier :: Lexer Token identifier = do first <- lower rest <- many alphaNum return $ Identifier $ first : rest symbol :: ReservedSymbol -> Lexer Token symbol s = char (toChar s) >> return ( ReservedS s) keyWord :: ReservedWord -> Lexer Token keyWord w = try $ string (toString w) >> notFollowedBy alphaNum >> return (ReservedW w) double :: Lexer Token double = do f <- sign <*> floating spaces return $ Number f
kwibus/myLang
src/Lexer.hs
bsd-3-clause
2,648
0
10
702
836
436
400
80
2
module Sort where import Data.List hiding (null) import Prelude hiding (null) -- selection sort ssort :: Ord a => [a] -> [a] ssort = unfoldr phi where phi [] = Nothing phi xs = let r@(y, ys) = (minimum xs, xs \\ [y]) in Just r -- select data Tree a = Null | Fork (Tree a, a, Tree a) deriving (Show, Eq) foldt (c, f) = u where u Null = c u (Fork (lt, n, rt)) = f (u lt, n, u rt) flatten = foldt (nil, join) nil = [] join (x, a, y) = x ++ [a] ++ y inordered = foldt (null, fork . check) null = Null fork = Fork check :: (Tree a, b, Tree a) -> (Tree a, b, Tree a) check (l, x, r) = undefined -- how to... intree Null = [] intree (Fork (lt, a, rt)) = [lt] ++ [rt]
cutsea110/aop
src/Sort.hs
bsd-3-clause
687
0
13
178
397
222
175
21
2
module Sexy.Functions (module X) where import Sexy.Functions.List as X import Sexy.Functions.Maybe as X import Sexy.Functions.Either as X import Sexy.Functions.Bool as X
DanBurton/sexy
src/Sexy/Functions.hs
bsd-3-clause
171
0
4
22
44
32
12
5
0
-- This demo shows how to authenticate users using OAuth and how to -- reuse the access tokens. -- It used the OAuth out of band (OOB) mode and can be used as a starting -- point to write an application that does not to have a web view. -- -- Make sure to set the environment variables XING_CONSUMER_KEY and -- XING_CONSUMER_SECRET before trying this demo. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import System.IO (hFlush, stdout) import Data.Maybe (fromJust, isJust) import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Trans.Resource (MonadResource) import Data.Monoid (mappend) import qualified Data.ByteString.Char8 as BS import qualified Data.Text.IO as T import Web.XING import System.Environment (getEnv) import qualified System.IO.Error import qualified Control.Exception as E readVerifier :: URL -> IO Verifier readVerifier url = do putStrLn "Please confirm the authorization at" putStrLn $ " " `mappend` (BS.unpack url) putStr "Please enter the PIN: " >> hFlush stdout BS.getLine showAccessToken :: (AccessToken, BS.ByteString) -> IO () showAccessToken (accessToken, uid) = do putStrLn $ "" putStrLn $ "Hello " `mappend` (BS.unpack uid) `mappend` "!" putStrLn $ "You should set the access token as environment variables:" putStrLn $ "" putStrLn $ " export XING_ACCESS_TOKEN_KEY=\"" `mappend` ((BS.unpack.token) accessToken) `mappend` "\"" putStrLn $ " export XING_ACCESS_TOKEN_SECRET=\"" `mappend` ((BS.unpack.tokenSecret) accessToken) `mappend` "\"" putStrLn $ "" handshake :: (MonadResource m, MonadBaseControl IO m) => OAuth -> Manager -> m (AccessToken, BS.ByteString) handshake oa manager = do (requestToken, url) <- getRequestToken oa manager verifier <- liftIO $ readVerifier url getAccessToken requestToken verifier oa manager readAccessToken :: IO (Maybe Credential) readAccessToken = do access_token_key <- getEnv "XING_ACCESS_TOKEN_KEY" access_token_secret <- getEnv "XING_ACCESS_TOKEN_SECRET" return $ Just $ newCredential (BS.pack access_token_key) (BS.pack access_token_secret) main :: IO () main = do consumer_key <- getEnv "XING_CONSUMER_KEY" consumer_secret <- getEnv "XING_CONSUMER_SECRET" let xingConsumer = consumer (BS.pack consumer_key) (BS.pack consumer_secret) maybeAccessToken <- E.catch (readAccessToken) (\(_ :: System.IO.Error.IOError) -> return Nothing) putStrLn "XING API demo" user <- withManager $ \manager -> do accessToken <- if isJust maybeAccessToken then return $ fromJust maybeAccessToken else auth xingConsumer manager getIdCard xingConsumer manager accessToken T.putStrLn (displayName user) auth :: (MonadResource m, MonadBaseControl IO m) => OAuth -> Manager -> m RequestToken auth oa manager = do res@(accessToken, _) <- handshake oa manager liftIO $ showAccessToken res return accessToken
JanAhrens/xing-api-haskell
demos/cli-demo.hs
bsd-3-clause
2,981
0
15
506
768
402
366
70
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} -- | Miscellaneous functions used throughout the compiler. module Fay.Compiler.Misc where import Fay.Compiler.Prelude import Fay.Compiler.PrimOp import Fay.Compiler.QName (unname) import Fay.Config import qualified Fay.Exts as F import Fay.Exts.NoAnnotation (unAnn) import qualified Fay.Exts.NoAnnotation as N import qualified Fay.Exts.Scoped as S import Fay.Types import Control.Monad.Error import Control.Monad.RWS import qualified Data.Map as M import Data.Version (parseVersion) import Distribution.HaskellSuite.Modules import Language.Haskell.Exts.Annotated hiding (name) import Language.Haskell.Names import System.IO import System.Process (readProcess) import Text.ParserCombinators.ReadP (readP_to_S) -- | Wrap an expression in a thunk. thunk :: JsExp -> JsExp -- thunk exp = JsNew (fayBuiltin "Thunk") [JsFun [] [] (Just exp)] thunk expr = case expr of -- JS constants don't need to be in thunks, they're already strict. JsLit{} -> expr -- Functions (e.g. lets) used for introducing a new lexical scope -- aren't necessary inside a thunk. This is a simple aesthetic -- optimization. JsApp fun@JsFun{} [] -> JsNew JsThunk [fun] -- Otherwise make a regular thunk. _ -> JsNew JsThunk [JsFun Nothing [] [] (Just expr)] -- | Wrap an expression in a thunk. stmtsThunk :: [JsStmt] -> JsExp stmtsThunk stmts = JsNew JsThunk [JsFun Nothing [] stmts Nothing] -- | Generate unique names. uniqueNames :: [JsName] uniqueNames = map JsParam [1::Integer ..] -- | Resolve a given maybe-qualified name to a fully qualifed name. tryResolveName :: Show l => QName (Scoped l) -> Maybe N.QName tryResolveName s@Special{} = Just $ unAnn s tryResolveName s@(UnQual _ (Ident _ n)) | "$gen" `isPrefixOf` n = Just $ unAnn s tryResolveName (unAnn -> Qual () (ModuleName () "$Prelude") n) = Just $ Qual () (ModuleName () "Prelude") n tryResolveName q@(Qual _ (ModuleName _ "Fay$") _) = Just $ unAnn q tryResolveName (Qual (Scoped ni _) _ _) = case ni of GlobalValue n -> replaceWithBuiltIns . origName2QName $ origName n _ -> Nothing -- TODO should LocalValue just return the name for qualified imports? tryResolveName q@(UnQual (Scoped ni _) (unAnn -> name)) = case ni of GlobalValue n -> replaceWithBuiltIns . origName2QName $ origName n LocalValue _ -> Just $ UnQual () name ScopeError _ -> resolvePrimOp q _ -> Nothing origName2QName :: OrigName -> N.QName origName2QName = gname2Qname . origGName where gname2Qname :: GName -> N.QName gname2Qname g = case g of GName "" s -> UnQual () $ mkName s GName m s -> Qual () (ModuleName () m) $ mkName s where mkName s@(x:_) | isAlpha x || x == '_' = Ident () s | otherwise = Symbol () s mkName "" = error "mkName \"\"" replaceWithBuiltIns :: N.QName -> Maybe N.QName replaceWithBuiltIns n = findPrimOp n <|> return n -- | Resolve a given maybe-qualified name to a fully qualifed name. -- Use this when a resolution failure is a bug. unsafeResolveName :: S.QName -> Compile N.QName unsafeResolveName q = maybe (throwError $ UnableResolveQualified (unAnn q)) return $ tryResolveName q -- | Resolve a newtype constructor. lookupNewtypeConst :: S.QName -> Compile (Maybe (Maybe N.QName,N.Type)) lookupNewtypeConst n = do let mName = tryResolveName n case mName of Nothing -> return Nothing Just name -> do newtypes <- gets stateNewtypes case find (\(cname,_,_) -> cname == name) newtypes of Nothing -> return Nothing Just (_,dname,ty) -> return $ Just (dname,ty) -- | Resolve a newtype destructor. lookupNewtypeDest :: S.QName -> Compile (Maybe (N.QName,N.Type)) lookupNewtypeDest n = do let mName = tryResolveName n newtypes <- gets stateNewtypes case find (\(_,dname,_) -> dname == mName) newtypes of Nothing -> return Nothing Just (cname,_,ty) -> return $ Just (cname,ty) -- | Qualify a name for the current module. qualify :: Name a -> Compile N.QName qualify (Ident _ name) = do modulename <- gets stateModuleName return (Qual () modulename (Ident () name)) qualify (Symbol _ name) = do modulename <- gets stateModuleName return (Qual () modulename (Symbol () name)) -- | Qualify a QName for the current module if unqualified. qualifyQName :: QName a -> Compile N.QName qualifyQName (UnQual _ name) = qualify name qualifyQName (unAnn -> n) = return n -- | Make a top-level binding. bindToplevel :: Bool -> Maybe SrcSpan -> Name a -> JsExp -> Compile JsStmt bindToplevel toplevel msrcloc (unAnn -> name) expr = if toplevel then do mod <- gets stateModuleName return $ JsSetQName msrcloc (Qual () mod name) expr else return $ JsVar (JsNameVar $ UnQual () name) expr -- | Force an expression in a thunk. force :: JsExp -> JsExp force expr | isConstant expr = expr | otherwise = JsApp (JsName JsForce) [expr] -- | Is a JS expression a literal (constant)? isConstant :: JsExp -> Bool isConstant JsLit{} = True isConstant _ = False -- | Deconstruct a parse result (a la maybe, foldr, either). parseResult :: ((F.SrcLoc,String) -> b) -> (a -> b) -> ParseResult a -> b parseResult die ok result = case result of ParseOk a -> ok a ParseFailed srcloc msg -> die (srcloc,msg) -- | Get a config option. config :: (Config -> a) -> Compile a config f = asks (f . readerConfig) -- | Optimize pattern matching conditions by merging conditions in common. -- TODO This is buggy and no longer used. Fails on tests/case3 optimizePatConditions :: [[JsStmt]] -> [[JsStmt]] optimizePatConditions = id {- concatMap merge . groupBy sameIf where sameIf [JsIf cond1 _ _] [JsIf cond2 _ _] = cond1 == cond2 sameIf _ _ = False merge xs@([JsIf cond _ _]:_) = [[JsIf cond (concat (optimizePatConditions (map getIfConsequent xs))) []]] merge noifs = noifs getIfConsequent [JsIf _ cons _] = cons getIfConsequent other = other -} -- | Throw a JS exception. throw :: String -> JsExp -> JsStmt throw msg expr = JsThrow (JsList [JsLit (JsStr msg),expr]) -- | Throw a JS exception (in an expression). throwExp :: String -> JsExp -> JsExp throwExp msg expr = JsThrowExp (JsList [JsLit (JsStr msg),expr]) -- | Is an alt a wildcard? isWildCardAlt :: S.Alt -> Bool isWildCardAlt (Alt _ pat _ _) = isWildCardPat pat -- | Is a pattern a wildcard? isWildCardPat :: S.Pat -> Bool isWildCardPat PWildCard{} = True isWildCardPat PVar{} = True isWildCardPat _ = False -- | Return formatter string if expression is a FFI call. ffiExp :: Exp a -> Maybe String ffiExp (App _ (Var _ (UnQual _ (Ident _ "ffi"))) (Lit _ (String _ formatstr _))) = Just formatstr ffiExp _ = Nothing -- | Generate a temporary, SCOPED name for testing conditions and -- such. withScopedTmpJsName :: (JsName -> Compile a) -> Compile a withScopedTmpJsName withName = do depth <- gets stateNameDepth modify $ \s -> s { stateNameDepth = depth + 1 } ret <- withName $ JsTmp depth modify $ \s -> s { stateNameDepth = depth } return ret -- | Generate a temporary, SCOPED name for testing conditions and -- such. We don't have name tracking yet, so instead we use this. withScopedTmpName :: (S.Name -> Compile a) -> Compile a withScopedTmpName withName = do depth <- gets stateNameDepth modify $ \s -> s { stateNameDepth = depth + 1 } ret <- withName $ Ident S.noI $ "$gen" ++ show depth modify $ \s -> s { stateNameDepth = depth } return ret -- | Print out a compiler warning. warn :: String -> Compile () warn "" = return () warn w = config id >>= io . (`ioWarn` w) ioWarn :: Config -> String -> IO () ioWarn _ "" = return () ioWarn cfg w = when (configWall cfg) $ hPutStrLn stderr $ "Warning: " ++ w -- | Pretty print a source location. printSrcLoc :: S.SrcLoc -> String printSrcLoc SrcLoc{..} = srcFilename ++ ":" ++ show srcLine ++ ":" ++ show srcColumn printSrcSpanInfo :: SrcSpanInfo -> String printSrcSpanInfo (SrcSpanInfo a b) = concat $ printSrcSpan a : map printSrcSpan b printSrcSpan :: SrcSpan -> String printSrcSpan SrcSpan{..} = srcSpanFilename ++ ": (" ++ show srcSpanStartLine ++ "," ++ show srcSpanStartColumn ++ ")-(" ++ show srcSpanEndLine ++ "," ++ show srcSpanEndColumn ++ ")" -- | Lookup the record for a given type name. typeToRecs :: QName a -> Compile [N.QName] typeToRecs (unAnn -> typ) = fromMaybe [] . lookup typ <$> gets stateRecordTypes recToFields :: S.QName -> Compile [N.Name] recToFields con = case tryResolveName con of Nothing -> return [] Just c -> fromMaybe [] . lookup c <$> gets stateRecords -- | Get the fields for a given type. typeToFields :: QName a -> Compile [N.Name] typeToFields (unAnn -> typ) = do allrecs <- gets stateRecords typerecs <- typeToRecs typ return . concatMap snd . filter ((`elem` typerecs) . fst) $ allrecs -- | Get the flag used for GHC, this differs between GHC-7.6.0 and -- GHC-everything-else so we need to specially test for that. It's -- lame, but that's random flag name changes for you. getGhcPackageDbFlag :: IO String getGhcPackageDbFlag = do s <- readProcess "ghc" ["--version"] "" return $ case (mapMaybe readVersion $ words s, readVersion "7.6.0") of (v:_, Just min') | v > min' -> "-package-db" _ -> "-package-conf" where readVersion = listToMaybe . filter (null . snd) . readP_to_S parseVersion -- | Run the top level compilation for all modules. runTopCompile :: CompileReader -> CompileState -> Compile a -> IO (Either CompileError (a,CompileState,CompileWriter)) runTopCompile reader' state' m = fst <$> runModuleT (runErrorT (runRWST (unCompile m) reader' state')) [] "fay" (\_fp -> return undefined) M.empty -- | Runs compilation for a single module. runCompileModule :: CompileReader -> CompileState -> Compile a -> CompileModule a runCompileModule reader' state' m = runErrorT (runRWST (unCompile m) reader' state') shouldBeDesugared :: (Functor f, Show (f ())) => f l -> Compile a shouldBeDesugared = throwError . ShouldBeDesugared . show . unAnn -- | Check if the given language pragmas are all present. hasLanguagePragmas :: [String] -> [ModulePragma l] -> Bool hasLanguagePragmas pragmas modulePragmas = (== length pragmas) . length . filter (`elem` pragmas) $ flattenPragmas modulePragmas where flattenPragmas :: [ModulePragma l] -> [String] flattenPragmas ps = concatMap pragmaName ps pragmaName (LanguagePragma _ q) = map unname q pragmaName _ = [] hasLanguagePragma :: String -> [ModulePragma l] -> Bool hasLanguagePragma pr = hasLanguagePragmas [pr] -- | if then else for when 'configOptimizeNewtypes'. ifOptimizeNewtypes :: Compile a -> Compile a -> Compile a ifOptimizeNewtypes then' else' = do optimize <- config configOptimizeNewtypes if optimize then then' else else'
fpco/fay
src/Fay/Compiler/Misc.hs
bsd-3-clause
11,328
0
17
2,561
3,313
1,690
1,623
196
5
module Paths_gpipe_test ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/lemarwin/code/gpipe-test/.stack-work/install/x86_64-linux/lts-4.0/7.10.3/bin" libdir = "/home/lemarwin/code/gpipe-test/.stack-work/install/x86_64-linux/lts-4.0/7.10.3/lib/x86_64-linux-ghc-7.10.3/gpipe-test-0.1.0.0-2GJvtNww2LhCvfszxtf0TF" datadir = "/home/lemarwin/code/gpipe-test/.stack-work/install/x86_64-linux/lts-4.0/7.10.3/share/x86_64-linux-ghc-7.10.3/gpipe-test-0.1.0.0" libexecdir = "/home/lemarwin/code/gpipe-test/.stack-work/install/x86_64-linux/lts-4.0/7.10.3/libexec" sysconfdir = "/home/lemarwin/code/gpipe-test/.stack-work/install/x86_64-linux/lts-4.0/7.10.3/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "gpipe_test_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "gpipe_test_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "gpipe_test_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "gpipe_test_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "gpipe_test_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
Teaspot-Studio/gpipe-test
.stack-work/dist/x86_64-linux/Cabal-1.22.5.0/build/autogen/Paths_gpipe_test.hs
bsd-3-clause
1,654
0
10
177
362
206
156
28
1
{-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Version -- Copyright : (c) The University of Glasgow 2004 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (local universal quantification in ReadP) -- -- A general library for representation and manipulation of versions. -- -- Versioning schemes are many and varied, so the version -- representation provided by this library is intended to be a -- compromise between complete generality, where almost no common -- functionality could reasonably be provided, and fixing a particular -- versioning scheme, which would probably be too restrictive. -- -- So the approach taken here is to provide a representation which -- subsumes many of the versioning schemes commonly in use, and we -- provide implementations of 'Eq', 'Ord' and conversion to\/from 'String' -- which will be appropriate for some applications, but not all. -- ----------------------------------------------------------------------------- module Data.Version ( -- * The @Version@ type Version(..), -- * A concrete representation of @Version@ showVersion, parseVersion, ) where import Data.Char ( isDigit, isAlphaNum ) import Data.Eq import Data.List import Data.Ord import Data.Typeable ( Typeable ) import GHC.Base ( ($), (&&), Monad(..), String, Int, liftM ) import GHC.Read import GHC.Show import Text.ParserCombinators.ReadP import Text.Read ( read ) {- | A 'Version' represents the version of a software entity. An instance of 'Eq' is provided, which implements exact equality modulo reordering of the tags in the 'versionTags' field. An instance of 'Ord' is also provided, which gives lexicographic ordering on the 'versionBranch' fields (i.e. 2.1 > 2.0, 1.2.3 > 1.2.2, etc.). This is expected to be sufficient for many uses, but note that you may need to use a more specific ordering for your versioning scheme. For example, some versioning schemes may include pre-releases which have tags @\"pre1\"@, @\"pre2\"@, and so on, and these would need to be taken into account when determining ordering. In some cases, date ordering may be more appropriate, so the application would have to look for @date@ tags in the 'versionTags' field and compare those. The bottom line is, don't always assume that 'compare' and other 'Ord' operations are the right thing for every 'Version'. Similarly, concrete representations of versions may differ. One possible concrete representation is provided (see 'showVersion' and 'parseVersion'), but depending on the application a different concrete representation may be more appropriate. -} data Version = Version { versionBranch :: [Int], -- ^ The numeric branch for this version. This reflects the -- fact that most software versions are tree-structured; there -- is a main trunk which is tagged with versions at various -- points (1,2,3...), and the first branch off the trunk after -- version 3 is 3.1, the second branch off the trunk after -- version 3 is 3.2, and so on. The tree can be branched -- arbitrarily, just by adding more digits. -- -- We represent the branch as a list of 'Int', so -- version 3.2.1 becomes [3,2,1]. Lexicographic ordering -- (i.e. the default instance of 'Ord' for @[Int]@) gives -- the natural ordering of branches. versionTags :: [String] -- really a bag -- ^ A version can be tagged with an arbitrary list of strings. -- The interpretation of the list of tags is entirely dependent -- on the entity that this version applies to. } deriving (Read,Show,Typeable) instance Eq Version where v1 == v2 = versionBranch v1 == versionBranch v2 && sort (versionTags v1) == sort (versionTags v2) -- tags may be in any order instance Ord Version where v1 `compare` v2 = versionBranch v1 `compare` versionBranch v2 -- ----------------------------------------------------------------------------- -- A concrete representation of 'Version' -- | Provides one possible concrete representation for 'Version'. For -- a version with 'versionBranch' @= [1,2,3]@ and 'versionTags' -- @= [\"tag1\",\"tag2\"]@, the output will be @1.2.3-tag1-tag2@. -- showVersion :: Version -> String showVersion (Version branch tags) = concat (intersperse "." (map show branch)) ++ concatMap ('-':) tags -- | A parser for versions in the format produced by 'showVersion'. -- parseVersion :: ReadP Version parseVersion = do branch <- sepBy1 (liftM read $ munch1 isDigit) (char '.') tags <- many (char '-' >> munch1 isAlphaNum) return Version{versionBranch=branch, versionTags=tags}
jstolarek/ghc
libraries/base/Data/Version.hs
bsd-3-clause
5,139
0
11
1,150
448
270
178
33
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE PatternGuards #-} module Narradar.Constraints.RPO where import Prelude hiding ((>)) import qualified Prelude import Control.DeepSeq import Control.Exception(assert) import Control.Monad import Data.Foldable (Foldable) import Data.List import Data.Typeable import Narradar.Framework.Ppr import Narradar.Types.Term import Narradar.Utils class HasPrecedence a where precedence :: a -> Int class HasStatus a where status :: a -> Status class HasFiltering a where filtering :: a -> Either Int [Int] data Status = Mul | Lex (Maybe [Int]) deriving (Eq, Ord, Show) mkStatus mul perm | mul = Mul | otherwise = assert (if all oneOrNone perm then True else pprTrace perm False) $ assert (all oneOrNone (transpose perm)) $ Lex (Just [ head ([i | (i,True) <- zip [1..] perm_i] ++ [-1]) | perm_i <- perm]) where oneOrNone [] = True oneOrNone (False:xx) = oneOrNone xx oneOrNone (True:xx) = not $ or xx instance Pretty Status where pPrint = text.show instance NFData Status where rnf Mul = (); rnf (Lex mi) = rnf mi data RPO m a = RPO {(>), (>~), (~~) :: a -> a -> m Bool} symbolRPO :: (id ~ TermId t, HasId t, Pretty id, HasPrecedence id, HasStatus id, Foldable t, Eq v, Eq(t(Term t v)) ,Monad m) => RPO m (Term t v) symbolRPO = RPO{..} where infixr 4 > infixr 4 >~ infixr 4 ~~ s >~ t = s > t <|> s ~~ t s ~~ t | s == t = return True | Just id_s <- rootSymbol s, tt_s <- directSubterms s , Just id_t <- rootSymbol t, tt_t <- directSubterms t = precedence id_s == precedence id_t &> exeq id_s id_t tt_s tt_t | otherwise = return False s > t | s == t = return False | Just id_t <- rootSymbol t, tt_t <- directSubterms t , Just id_s <- rootSymbol s, tt_s <- directSubterms s = anyM (>~ t) tt_s <|> (allM (s >) tt_t <&> (precedence id_s Prelude.> precedence id_t |> (precedence id_s == precedence id_t &> exgt id_s id_t tt_s tt_t))) | Just id_s <- rootSymbol s, tt_s <- directSubterms s = anyM (>~ t) tt_s | otherwise = return False exgt id_s id_t | Mul <- status id_s, Mul <- status id_t = mulD (>) (~~) | Lex ps <- status id_s, Lex pt <- status id_t = lexsD (>) (~~) (removeFiltered ps) (removeFiltered pt) | otherwise = \_ _ -> return False exeq id_s id_t | Mul <- status id_s, Mul <- status id_t = muleqD (~~) | Lex ps <- status id_s, Lex pt <- status id_t = lexseqD (~~) (removeFiltered ps) (removeFiltered pt) | otherwise = \_ _ -> return False removeFiltered = fmap ( filter (/= (-1))) lexD (>) (~~) [] _ = return False lexD (>) (~~) _ [] = return True lexD (>) (~~) (f:ff) (g:gg) = (f > g) <|> (f ~~ g <&> lexD (>) (~~) ff gg) lexeqD (~~) [] [] = return True lexeqD (~~) _ [] = return False lexeqD (~~) [] _ = return False lexeqD (~~) (f:ff) (g:gg) = (f ~~ g <&> lexeqD (~~) ff gg) lexsD (>) (~~) f_perm g_perm ff gg = lexD (>) (~~) (maybe ff (permute ff) f_perm) (maybe gg (permute gg) g_perm) lexseqD (~~) f_perm g_perm ff gg = lexeqD (~~) (maybe ff (permute ff) f_perm) (maybe gg (permute gg) g_perm) mulD (>) (~~) m1 m2 = muleqD (~~) m1 m2 <&> (exists m1' $ \x -> exists m2' $ \y -> x > y) where m1' = m1 \\ m2 m2' = m2 \\ m1 muleqD (~~) m1 m2 = forall m2' $ \y-> exists m1' $ \x -> x ~~ y where m1' = m1 \\ m2 m2' = m2 \\ m1 infixr 3 <&> infixr 3 &> infixr 3 <& infixr 2 <|> infixr 2 |> infixr 2 <| (<|>) = liftM2 (||) (<&>) = liftM2 (&&) x |> y = (x ||) <$> y x &> y = (x &&) <$> y x <| y = (|| y) <$> x x <& y = (&& y) <$> x forall = flip allM exists = flip anyM (<$>) = liftM sel = selectSafe "Narradar.Constraints.RPO" symbolRPOAF :: (id ~ TermId t, HasId t, Pretty id, HasPrecedence id, HasStatus id, HasFiltering id, Foldable t, Eq v, Eq(t(Term t v)) ,Monad m) => RPO m (Term t v) symbolRPOAF = RPO{..} where infixr 4 > infixr 4 >~ infixr 4 ~~ s >~ t = s > t <|> s ~~ t s ~~ t | s == t = return True | Just id_s <- rootSymbol s, tt_s <- directSubterms s , Left i <- filtering id_s = tt_s !! pred i ~~ t | Just id_t <- rootSymbol t, tt_t <- directSubterms t , Left j <- filtering id_t = tt_t !! pred j ~~ s | Just id_s <- rootSymbol s, tt_s <- directSubterms s , Just id_t <- rootSymbol t, tt_t <- directSubterms t , Right _ <- filtering id_s , Right _ <- filtering id_t = precedence id_s == precedence id_t &> exeq id_s id_t tt_s tt_t | otherwise = return False s > t | Just id_t <- rootSymbol t, tt_t <- directSubterms t , Just id_s <- rootSymbol s, tt_s <- directSubterms s , Right ii <- filtering id_s , Left j <- filtering id_t = s > tt_t !! pred j | Just id_t <- rootSymbol t, tt_t <- directSubterms t , Just id_s <- rootSymbol s, tt_s <- directSubterms s , Right ii <- filtering id_s , Right jj <- filtering id_t = anyM (>~ t) (sel 3 ii tt_s) <|> (allM (s >) (sel 4 jj tt_t) <&> (precedence id_s Prelude.> precedence id_t |> (precedence id_s == precedence id_t &> exgt id_s id_t tt_s tt_t))) | Just id_s <- rootSymbol s, tt_s <- directSubterms s , Right ii <- filtering id_s = anyM (>~ t) (sel 5 ii tt_s) | Just id_s <- rootSymbol s, tt_s <- directSubterms s , Left i <- filtering id_s = tt_s !! pred i > t | otherwise = return False exgt id_s id_t tt_s tt_t | Mul <- status id_s, Mul <- status id_t = mulD (>) (~~) (sel 11 ii tt_s) (sel 12 jj tt_t) | Lex ps <- status id_s, Lex pt <- status id_t = lexsD (>) (~~) id_s id_t tt_s tt_t | otherwise = return False where Right ii = filtering id_s Right jj = filtering id_t exeq id_s id_t tt_s tt_t | Mul <- status id_s, Mul <- status id_t = muleqD (~~) (sel 1 ii tt_s) (sel 2 jj tt_t) | Lex ps <- status id_s, Lex pt <- status id_t = lexseqD (~~) id_s id_t tt_s tt_t | otherwise = return False where Right ii = filtering id_s Right jj = filtering id_t lexD (>) (~~) [] _ = return False lexD (>) (~~) _ [] = return True lexD (>) (~~) (f:ff) (g:gg) = (f > g) <|> (f ~~ g <&> lexD (>) (~~) ff gg) lexeqD (~~) [] [] = return True lexeqD (~~) _ [] = return False lexeqD (~~) [] _ = return False lexeqD (~~) (f:ff) (g:gg) = (f ~~ g <&> lexeqD (~~) ff gg) lexsD (>) (~~) id_f id_g ff gg = lexD (>) (~~) (selectLexArgs id_f ff) (selectLexArgs id_g gg) lexseqD (~~) id_f id_g ff gg = lexeqD (~~) (selectLexArgs id_f ff) (selectLexArgs id_g gg) selectLexArgs id tt | Lex (Just p) <- status id = permute tt p | Right ii <- filtering id = sel 13 ii tt mulD (>) (~~) m1 m2 = muleqD (\s t -> s > t <|> s ~~ t) m1' m2' <&> (exists m1' $ \x -> exists m2' $ \y -> x > y) where m1' = m1 \\ m2 m2' = m2 \\ m1 muleqD (~~) m1 m2 = forall m2' $ \y-> exists m1' $ \x -> x ~~ y where m1' = m1 \\ m2 m2' = m2 \\ m1 infixr 3 <&> infixr 3 &> infixr 3 <& infixr 2 <|> infixr 2 |> infixr 2 <| (<|>) = liftM2 (||) (<&>) = liftM2 (&&) x |> y = (x ||) <$> y x &> y = (x &&) <$> y x <| y = (|| y) <$> x x <& y = (&& y) <$> x forall = flip allM exists = flip anyM (<$>) = liftM sel n ii = selectSafe ("Narradar.Constraints.RPO.symbolRPOAF - " ++ show n) (map pred ii) sel6 = sel 6 sel7 = sel 7 sel8 = sel 8 sel9 = sel 9 allM f xx = and `liftM` mapM f xx anyM f xx = or `liftM` mapM f xx permute ff ii = map fst $ dropWhile ( (<0) . snd) $ sortBy (compare `on` snd) (zip ff ii) {- verifyRPOAF typ the_rules the_pairs decPairs = let theAf = AF.fromList' $ map getFiltering (toList $ getAllSymbols signature) theFilteredPairs = rules $ AF.apply theAf the_pairs theDecPairs = CE.assert (P.all (P.< npairs) decPairs) $ select decPairs (rules the_pairs) theWeakPairs = select ([0..npairs - 1] \\ decPairs) (rules the_pairs) theUsableRules = Set.fromList [ l:->r | l:->r <- rules the_rules , let Just id = rootSymbol l , usable id ] expectedUsableRules = Set.fromList [ rule | let urAf = Set.fromList $ rules(iUsableRules3 typ the_rules the_pairs (rhs <$> theFilteredPairs)) , rule <- rules the_rules , AF.apply theAf rule `Set.member` urAf] falseDecreasingPairs = [ s:->t | s:->t <- theDecPairs, not(s > t)) return (s:->t) falseWeaklyDecreasingPairs <- runListT $ do s:->t <- li theWeakPairs guard =<< lift (evalDecode $ not( s >~ t)) return (s:->t) falseWeaklyDecreasingRules <- runListT $ do s:->t <- li (toList theUsableRules) guard =<< lift (evalDecode $ not( s >~ t)) return (s:->t) let missingUsableRules = [] -- toList (Set.difference expected_usableRules the_usableRules) excessUsableRules = [] -- toList (Set.difference the_usableRules expected_usableRules) return VerifyRPOAF{thePairs = rules the_pairs, ..} where signature = getSignature (the_rules `mappend` the_pairs) getFiltering s = do isListAF <- evalDecode $ listAF s filterings <- mapM decode (filtering_vv s) let positions = [ i | (i,True) <- zip [1..(getArity signature s)] filterings] return $ if isListAF then (s, Right positions) else case positions of [p] -> (s, Left p) _ -> error ("Invalid collapsing filtering " ++ show positions ++ " for symbol " ++ show (pPrint s)) npairs = length (rules the_pairs) -}
pepeiborra/narradar
src/Narradar/Constraints/RPO.hs
bsd-3-clause
10,478
6
19
3,467
3,795
1,925
1,870
206
6
main :: IO () main = do putStrLn . show $ sum . map (\n -> n^n) $ [1..1000]
bgwines/project-euler
src/solved/problem48.hs
bsd-3-clause
77
0
12
20
55
28
27
3
1
{-# LANGUAGE RecordWildCards #-} module Report( reportText, reportHTML ) where import Data.List.Extra import Data.Tree import Data.Char import Data.Hashable import qualified Data.Set as Set import Numeric.Extra import Util import Type presort :: [Tree Val] -> [Tree Val] presort = sortOn (negate . timeInh . rootLabel) . fmapForest (sortOn (negate . timeTot . rootLabel)) reportHTML :: [Tree Val] -> [String] reportHTML vals = let vals2 = presort vals indent i x = x{name = replicate (i*2) ' ' ++ name x} links = Set.fromList $ map (name . rootLabel) vals2 anchor x = "<a id='" ++ show (hash x) ++ "'></a>" in (["<pre>"] ++) $ (++ ["</pre>"]) $ intercalate [""] $ (" TOT INH IND" : map (showHTML links . rootLabel) (take 25 vals2)) : [ anchor (name $ rootLabel x) : map (showHTML $ Set.delete (name $ rootLabel x) links) (flatten $ fmapTreeDepth indent x) | x <- vals2] showHTML :: Set.Set String -> Val -> String showHTML xs Val{..} = intercalate " " [showDouble timeTot, showDouble timeInh, showDouble timeInd ,spc ++ (if nam `Set.member` xs then link else nam) ++ " (" ++ show entries ++ ")"] where link = "<a href='#" ++ show (hash nam) ++ "'>" ++ nam ++ "</a>" (spc,nam) = span isSpace name reportText :: [Tree Val] -> [String] reportText vals = let vals2 = presort vals indent i x = x{name = replicate (i*2) ' ' ++ name x} in intercalate ["",""] $ (" TOT INH IND" : map (showText . rootLabel) (take 25 vals2)) : [map showText $ flatten $ fmapTreeDepth indent x | x <- vals2] showText :: Val -> String showText Val{..} = intercalate " " [showDouble timeTot, showDouble timeInh, showDouble timeInd, name ++ " (" ++ show entries ++ ")"] showDouble :: Double -> String showDouble x = case showDP 1 x of "0.0" -> " -" "100.0" -> "99.9" -- avoid making the column bigger for a corner case ['0','.',x] -> [' ',' ','.',x] x -> replicate (4 - length x) ' ' ++ x
ndmitchell/profiterole
src/Report.hs
bsd-3-clause
2,048
0
16
524
827
433
394
49
4
{-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables, GADTs, TypeFamilies, MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ >= 709 {-# LANGUAGE Safe #-} #elif __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif #if __GLASGOW_HASKELL__ >= 703 {-# OPTIONS_GHC -fprof-auto #-} #endif #if __GLASGOW_HASKELL__ < 701 {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} #endif module Compiler.Hoopl.Dataflow ( DataflowLattice(..), JoinFun, OldFact(..), NewFact(..), Fact, mkFactBase , ChangeFlag(..), changeIf , FwdPass(..) , FwdTransfer(..), mkFTransfer, mkFTransfer3 , FwdRewrite(..), mkFRewrite, mkFRewrite3, noFwdRewrite , wrapFR, wrapFR2 , BwdPass(..) , BwdTransfer(..), mkBTransfer, mkBTransfer3 , wrapBR, wrapBR2 , BwdRewrite(..), mkBRewrite, mkBRewrite3, noBwdRewrite , analyzeAndRewriteFwd, analyzeAndRewriteBwd -- * Respecting Fuel -- $fuel ) where import Compiler.Hoopl.Block import Compiler.Hoopl.Collections import Compiler.Hoopl.Checkpoint import Compiler.Hoopl.Fuel import Compiler.Hoopl.Graph hiding (Graph) -- hiding so we can redefine -- and include definition in paper import Compiler.Hoopl.Label import Control.Monad import Data.Maybe ----------------------------------------------------------------------------- -- DataflowLattice ----------------------------------------------------------------------------- data DataflowLattice a = DataflowLattice { fact_name :: String -- Documentation , fact_bot :: a -- Lattice bottom element , fact_join :: JoinFun a -- Lattice join plus change flag -- (changes iff result > old fact) } -- ^ A transfer function might want to use the logging flag -- to control debugging, as in for example, it updates just one element -- in a big finite map. We don't want Hoopl to show the whole fact, -- and only the transfer function knows exactly what changed. type JoinFun a = Label -> OldFact a -> NewFact a -> (ChangeFlag, a) -- the label argument is for debugging purposes only newtype OldFact a = OldFact a newtype NewFact a = NewFact a data ChangeFlag = NoChange | SomeChange deriving (Eq, Ord) changeIf :: Bool -> ChangeFlag changeIf changed = if changed then SomeChange else NoChange -- | 'mkFactBase' creates a 'FactBase' from a list of ('Label', fact) -- pairs. If the same label appears more than once, the relevant facts -- are joined. mkFactBase :: forall f. DataflowLattice f -> [(Label, f)] -> FactBase f mkFactBase lattice = foldl add mapEmpty where add :: FactBase f -> (Label, f) -> FactBase f add map (lbl, f) = mapInsert lbl newFact map where newFact = case mapLookup lbl map of Nothing -> f Just f' -> snd $ join lbl (OldFact f') (NewFact f) join = fact_join lattice ----------------------------------------------------------------------------- -- Analyze and rewrite forward: the interface ----------------------------------------------------------------------------- data FwdPass m n f = FwdPass { fp_lattice :: DataflowLattice f , fp_transfer :: FwdTransfer n f , fp_rewrite :: FwdRewrite m n f } newtype FwdTransfer n f = FwdTransfer3 { getFTransfer3 :: ( n C O -> f -> f , n O O -> f -> f , n O C -> f -> FactBase f ) } newtype FwdRewrite m n f -- see Note [Respects Fuel] = FwdRewrite3 { getFRewrite3 :: ( n C O -> f -> m (Maybe (Graph n C O, FwdRewrite m n f)) , n O O -> f -> m (Maybe (Graph n O O, FwdRewrite m n f)) , n O C -> f -> m (Maybe (Graph n O C, FwdRewrite m n f)) ) } {-# INLINE wrapFR #-} wrapFR :: (forall e x. (n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f ))) -> (n' e x -> f' -> m' (Maybe (Graph n' e x, FwdRewrite m' n' f'))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> FwdRewrite m n f -> FwdRewrite m' n' f' -- see Note [Respects Fuel] wrapFR wrap (FwdRewrite3 (f, m, l)) = FwdRewrite3 (wrap f, wrap m, wrap l) {-# INLINE wrapFR2 #-} wrapFR2 :: (forall e x . (n1 e x -> f1 -> m1 (Maybe (Graph n1 e x, FwdRewrite m1 n1 f1))) -> (n2 e x -> f2 -> m2 (Maybe (Graph n2 e x, FwdRewrite m2 n2 f2))) -> (n3 e x -> f3 -> m3 (Maybe (Graph n3 e x, FwdRewrite m3 n3 f3))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> FwdRewrite m1 n1 f1 -> FwdRewrite m2 n2 f2 -> FwdRewrite m3 n3 f3 -- see Note [Respects Fuel] wrapFR2 wrap2 (FwdRewrite3 (f1, m1, l1)) (FwdRewrite3 (f2, m2, l2)) = FwdRewrite3 (wrap2 f1 f2, wrap2 m1 m2, wrap2 l1 l2) mkFTransfer3 :: (n C O -> f -> f) -> (n O O -> f -> f) -> (n O C -> f -> FactBase f) -> FwdTransfer n f mkFTransfer3 f m l = FwdTransfer3 (f, m, l) mkFTransfer :: (forall e x . n e x -> f -> Fact x f) -> FwdTransfer n f mkFTransfer f = FwdTransfer3 (f, f, f) -- | Functions passed to 'mkFRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite3' respects fuel. mkFRewrite3 :: forall m n f. FuelMonad m => (n C O -> f -> m (Maybe (Graph n C O))) -> (n O O -> f -> m (Maybe (Graph n O O))) -> (n O C -> f -> m (Maybe (Graph n O C))) -> FwdRewrite m n f mkFRewrite3 f m l = FwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> m (Maybe a)) -> t -> t1 -> m (Maybe (a, FwdRewrite m n f)) lift rw node fact = liftM (liftM asRew) (withFuel =<< rw node fact) asRew :: forall t. t -> (t, FwdRewrite m n f) asRew g = (g, noFwdRewrite) noFwdRewrite :: Monad m => FwdRewrite m n f noFwdRewrite = FwdRewrite3 (noRewrite, noRewrite, noRewrite) noRewrite :: Monad m => a -> b -> m (Maybe c) noRewrite _ _ = return Nothing -- | Functions passed to 'mkFRewrite' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite' respects fuel. mkFRewrite :: FuelMonad m => (forall e x . n e x -> f -> m (Maybe (Graph n e x))) -> FwdRewrite m n f mkFRewrite f = mkFRewrite3 f f f type family Fact x f :: * type instance Fact C f = FactBase f type instance Fact O f = f -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeAndRewriteFwd :: forall m n f e x entries. (CheckpointMonad m, NonLocal n, LabelsPtr entries) => FwdPass m n f -> MaybeC e entries -> Graph n e x -> Fact e f -> m (Graph n e x, FactBase f, MaybeO x f) analyzeAndRewriteFwd pass entries g f = do (rg, fout) <- arfGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedExitFact g' fout) distinguishedExitFact :: forall n e x f . Graph n e x -> Fact x f -> MaybeO x f distinguishedExitFact g f = maybe g where maybe :: Graph n e x -> MaybeO x f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany _ _ x) = case x of NothingO -> NothingO JustO _ -> JustO f ---------------------------------------------------------------- -- Forward Implementation ---------------------------------------------------------------- type Entries e = MaybeC e [Label] arfGraph :: forall m n f e x . (NonLocal n, CheckpointMonad m) => FwdPass m n f -> Entries e -> Graph n e x -> Fact e f -> m (DG f n e x, Fact x f) arfGraph pass@FwdPass { fp_lattice = lattice, fp_transfer = transfer, fp_rewrite = rewrite } entries = graph where {- nested type synonyms would be so lovely here type ARF thing = forall e x . thing e x -> f -> m (DG f n e x, Fact x f) type ARFX thing = forall e x . thing e x -> Fact e f -> m (DG f n e x, Fact x f) -} graph :: Graph n e x -> Fact e f -> m (DG f n e x, Fact x f) -- @ start block.tex -2 block :: forall e x . Block n e x -> f -> m (DG f n e x, Fact x f) -- @ end block.tex -- @ start node.tex -4 node :: forall e x . (ShapeLifter e x) => n e x -> f -> m (DG f n e x, Fact x f) -- @ end node.tex -- @ start bodyfun.tex body :: [Label] -> LabelMap (Block n C C) -> Fact C f -> m (DG f n C C, Fact C f) -- @ end bodyfun.tex -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' -- @ start cat.tex -2 cat :: forall e a x f1 f2 f3. (f1 -> m (DG f n e a, f2)) -> (f2 -> m (DG f n a x, f3)) -> (f1 -> m (DG f n e x, f3)) -- @ end cat.tex graph GNil = \f -> return (dgnil, f) graph (GUnit blk) = block blk graph (GMany e bdy x) = (e `ebcat` bdy) `cat` exit x where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact e f -> m (DG f n e C, Fact C f) exit :: MaybeO x (Block n C O) -> Fact C f -> m (DG f n C x, Fact x f) exit (JustO blk) = arfx block blk exit NothingO = \fb -> return (dgnilC, fb) ebcat entry bdy = c entries entry where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact e f -> m (DG f n e C, Fact C f) c NothingC (JustO entry) = block entry `cat` body (successors entry) bdy c (JustC entries) NothingO = body entries bdy c _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks -- @ start block.tex -2 block BNil = \f -> return (dgnil, f) block (BlockCO l b) = node l `cat` block b block (BlockCC l b n) = node l `cat` block b `cat` node n block (BlockOC b n) = block b `cat` node n block (BMiddle n) = node n block (BCat b1 b2) = block b1 `cat` block b2 -- @ end block.tex block (BSnoc h n) = block h `cat` node n block (BCons n t) = node n `cat` block t -- @ start node.tex -4 node n f = do { grw <- frewrite rewrite n f ; case grw of Nothing -> return ( singletonDG f n , ftransfer transfer n f ) Just (g, rw) -> let pass' = pass { fp_rewrite = rw } f' = fwdEntryFact n f in arfGraph pass' (fwdEntryLabel n) g f' } -- @ end node.tex -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} -- @ start cat.tex -2 cat ft1 ft2 f = do { (g1,f1) <- ft1 f ; (g2,f2) <- ft2 f1 ; return (g1 `dgSplice` g2, f2) } -- @ end cat.tex arfx :: forall thing x . NonLocal thing => (thing C x -> f -> m (DG f n C x, Fact x f)) -> (thing C x -> Fact C f -> m (DG f n C x, Fact x f)) arfx arf thing fb = arf thing $ fromJust $ lookupFact (entryLabel thing) $ joinInFacts lattice fb -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' -- @ start bodyfun.tex body entries blockmap init_fbase = fixpoint Fwd lattice do_block entries blockmap init_fbase where do_block :: forall x. Block n C x -> FactBase f -> m (DG f n C x, Fact x f) do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- @ end bodyfun.tex -- Join all the incoming facts with bottom. -- We know the results _shouldn't change_, but the transfer -- functions might, for example, generate some debugging traces. joinInFacts :: DataflowLattice f -> FactBase f -> FactBase f joinInFacts (lattice @ DataflowLattice {fact_bot = bot, fact_join = fj}) fb = mkFactBase lattice $ map botJoin $ mapToList fb where botJoin (l, f) = (l, snd $ fj l (OldFact bot) (NewFact f)) forwardBlockList :: (NonLocal n, LabelsPtr entry) => entry -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for forward analysis, -- along with the list of Labels it may depend on for facts. forwardBlockList entries blks = postorder_dfs_from blks entries ----------------------------------------------------------------------------- -- Backward analysis and rewriting: the interface ----------------------------------------------------------------------------- data BwdPass m n f = BwdPass { bp_lattice :: DataflowLattice f , bp_transfer :: BwdTransfer n f , bp_rewrite :: BwdRewrite m n f } newtype BwdTransfer n f = BwdTransfer3 { getBTransfer3 :: ( n C O -> f -> f , n O O -> f -> f , n O C -> FactBase f -> f ) } newtype BwdRewrite m n f = BwdRewrite3 { getBRewrite3 :: ( n C O -> f -> m (Maybe (Graph n C O, BwdRewrite m n f)) , n O O -> f -> m (Maybe (Graph n O O, BwdRewrite m n f)) , n O C -> FactBase f -> m (Maybe (Graph n O C, BwdRewrite m n f)) ) } {-# INLINE wrapBR #-} wrapBR :: (forall e x . Shape x -> (n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f ))) -> (n' e x -> Fact x f' -> m' (Maybe (Graph n' e x, BwdRewrite m' n' f'))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> BwdRewrite m n f -> BwdRewrite m' n' f' -- see Note [Respects Fuel] wrapBR wrap (BwdRewrite3 (f, m, l)) = BwdRewrite3 (wrap Open f, wrap Open m, wrap Closed l) {-# INLINE wrapBR2 #-} wrapBR2 :: (forall e x . Shape x -> (n1 e x -> Fact x f1 -> m1 (Maybe (Graph n1 e x, BwdRewrite m1 n1 f1))) -> (n2 e x -> Fact x f2 -> m2 (Maybe (Graph n2 e x, BwdRewrite m2 n2 f2))) -> (n3 e x -> Fact x f3 -> m3 (Maybe (Graph n3 e x, BwdRewrite m3 n3 f3)))) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> BwdRewrite m1 n1 f1 -> BwdRewrite m2 n2 f2 -> BwdRewrite m3 n3 f3 -- see Note [Respects Fuel] wrapBR2 wrap2 (BwdRewrite3 (f1, m1, l1)) (BwdRewrite3 (f2, m2, l2)) = BwdRewrite3 (wrap2 Open f1 f2, wrap2 Open m1 m2, wrap2 Closed l1 l2) mkBTransfer3 :: (n C O -> f -> f) -> (n O O -> f -> f) -> (n O C -> FactBase f -> f) -> BwdTransfer n f mkBTransfer3 f m l = BwdTransfer3 (f, m, l) mkBTransfer :: (forall e x . n e x -> Fact x f -> f) -> BwdTransfer n f mkBTransfer f = BwdTransfer3 (f, f, f) -- | Functions passed to 'mkBRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkBRewrite3' respects fuel. mkBRewrite3 :: forall m n f. FuelMonad m => (n C O -> f -> m (Maybe (Graph n C O))) -> (n O O -> f -> m (Maybe (Graph n O O))) -> (n O C -> FactBase f -> m (Maybe (Graph n O C))) -> BwdRewrite m n f mkBRewrite3 f m l = BwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> m (Maybe a)) -> t -> t1 -> m (Maybe (a, BwdRewrite m n f)) lift rw node fact = liftM (liftM asRew) (withFuel =<< rw node fact) asRew :: t -> (t, BwdRewrite m n f) asRew g = (g, noBwdRewrite) noBwdRewrite :: Monad m => BwdRewrite m n f noBwdRewrite = BwdRewrite3 (noRewrite, noRewrite, noRewrite) -- | Functions passed to 'mkBRewrite' should not be aware of the fuel supply. -- The result returned by 'mkBRewrite' respects fuel. mkBRewrite :: FuelMonad m => (forall e x . n e x -> Fact x f -> m (Maybe (Graph n e x))) -> BwdRewrite m n f mkBRewrite f = mkBRewrite3 f f f ----------------------------------------------------------------------------- -- Backward implementation ----------------------------------------------------------------------------- arbGraph :: forall m n f e x . (NonLocal n, CheckpointMonad m) => BwdPass m n f -> Entries e -> Graph n e x -> Fact x f -> m (DG f n e x, Fact e f) arbGraph pass@BwdPass { bp_lattice = lattice, bp_transfer = transfer, bp_rewrite = rewrite } entries = graph where {- nested type synonyms would be so lovely here type ARB thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, f) type ARBX thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, Fact e f) -} graph :: Graph n e x -> Fact x f -> m (DG f n e x, Fact e f) block :: forall e x . Block n e x -> Fact x f -> m (DG f n e x, f) node :: forall e x . (ShapeLifter e x) => n e x -> Fact x f -> m (DG f n e x, f) body :: [Label] -> Body n -> Fact C f -> m (DG f n C C, Fact C f) cat :: forall e a x info info' info''. (info' -> m (DG f n e a, info'')) -> (info -> m (DG f n a x, info')) -> (info -> m (DG f n e x, info'')) graph GNil = \f -> return (dgnil, f) graph (GUnit blk) = block blk graph (GMany e bdy x) = (e `ebcat` bdy) `cat` exit x where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact C f -> m (DG f n e C, Fact e f) exit :: MaybeO x (Block n C O) -> Fact x f -> m (DG f n C x, Fact C f) exit (JustO blk) = arbx block blk exit NothingO = \fb -> return (dgnilC, fb) ebcat entry bdy = c entries entry where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact C f -> m (DG f n e C, Fact e f) c NothingC (JustO entry) = block entry `cat` body (successors entry) bdy c (JustC entries) NothingO = body entries bdy c _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks block BNil = \f -> return (dgnil, f) block (BlockCO l b) = node l `cat` block b block (BlockCC l b n) = node l `cat` block b `cat` node n block (BlockOC b n) = block b `cat` node n block (BMiddle n) = node n block (BCat b1 b2) = block b1 `cat` block b2 block (BSnoc h n) = block h `cat` node n block (BCons n t) = node n `cat` block t node n f = do { bwdres <- brewrite rewrite n f ; case bwdres of Nothing -> return (singletonDG entry_f n, entry_f) where entry_f = btransfer transfer n f Just (g, rw) -> do { let pass' = pass { bp_rewrite = rw } ; (g, f) <- arbGraph pass' (fwdEntryLabel n) g f ; return (g, bwdEntryFact lattice n f)} } -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} cat ft1 ft2 f = do { (g2,f2) <- ft2 f ; (g1,f1) <- ft1 f2 ; return (g1 `dgSplice` g2, f1) } arbx :: forall thing x . NonLocal thing => (thing C x -> Fact x f -> m (DG f n C x, f)) -> (thing C x -> Fact x f -> m (DG f n C x, Fact C f)) arbx arb thing f = do { (rg, f) <- arb thing f ; let fb = joinInFacts lattice $ mapSingleton (entryLabel thing) f ; return (rg, fb) } -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' body entries blockmap init_fbase = fixpoint Bwd lattice do_block (map entryLabel (backwardBlockList entries blockmap)) blockmap init_fbase where do_block :: forall x. Block n C x -> Fact x f -> m (DG f n C x, LabelMap f) do_block b f = do (g, f) <- block b f return (g, mapSingleton (entryLabel b) f) backwardBlockList :: (LabelsPtr entries, NonLocal n) => entries -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for backward analysis, -- along with the list of Labels it may depend on for facts. backwardBlockList entries body = reverse $ forwardBlockList entries body {- The forward and backward cases are not dual. In the forward case, the entry points are known, and one simply traverses the body blocks from those points. In the backward case, something is known about the exit points, but this information is essentially useless, because we don't actually have a dual graph (that is, one with edges reversed) to compute with. (Even if we did have a dual graph, it would not avail us---a backward analysis must include reachable blocks that don't reach the exit, as in a procedure that loops forever and has side effects.) -} -- | if the graph being analyzed is open at the exit, I don't -- quite understand the implications of possible other exits analyzeAndRewriteBwd :: (CheckpointMonad m, NonLocal n, LabelsPtr entries) => BwdPass m n f -> MaybeC e entries -> Graph n e x -> Fact x f -> m (Graph n e x, FactBase f, MaybeO e f) analyzeAndRewriteBwd pass entries g f = do (rg, fout) <- arbGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedEntryFact g' fout) distinguishedEntryFact :: forall n e x f . Graph n e x -> Fact e f -> MaybeO e f distinguishedEntryFact g f = maybe g where maybe :: Graph n e x -> MaybeO e f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany e _ _) = case e of NothingO -> NothingO JustO _ -> JustO f ----------------------------------------------------------------------------- -- fixpoint: finding fixed points ----------------------------------------------------------------------------- -- See Note [TxFactBase invariants] updateFact :: DataflowLattice f -> LabelMap (DBlock f n C C) -> Label -> f -- out fact -> ([Label], FactBase f) -> ([Label], FactBase f) -- See Note [TxFactBase change flag] updateFact lat newblocks lbl new_fact (cha, fbase) | NoChange <- cha2, lbl `mapMember` newblocks = (cha, fbase) | otherwise = (lbl:cha, mapInsert lbl res_fact fbase) where (cha2, res_fact) -- Note [Unreachable blocks] = case lookupFact lbl fbase of Nothing -> (SomeChange, new_fact_debug) -- Note [Unreachable blocks] Just old_fact -> join old_fact where join old_fact = fact_join lat lbl (OldFact old_fact) (NewFact new_fact) (_, new_fact_debug) = join (fact_bot lat) {- -- this doesn't work because it can't be implemented class Monad m => FixpointMonad m where observeChangedFactBase :: m (Maybe (FactBase f)) -> Maybe (FactBase f) -} -- @ start fptype.tex data Direction = Fwd | Bwd fixpoint :: forall m n f. (CheckpointMonad m, NonLocal n) => Direction -> DataflowLattice f -> (Block n C C -> Fact C f -> m (DG f n C C, Fact C f)) -> [Label] -> LabelMap (Block n C C) -> (Fact C f -> m (DG f n C C, Fact C f)) -- @ end fptype.tex -- @ start fpimp.tex fixpoint direction lat do_block entries blockmap init_fbase = do -- trace ("fixpoint: " ++ show (case direction of Fwd -> True; Bwd -> False) ++ " " ++ show (mapKeys blockmap) ++ show entries ++ " " ++ show (mapKeys init_fbase)) $ return() (fbase, newblocks) <- loop init_fbase entries mapEmpty -- trace ("fixpoint DONE: " ++ show (mapKeys fbase) ++ show (mapKeys newblocks)) $ return() return (GMany NothingO newblocks NothingO, mapDeleteList (mapKeys blockmap) fbase) -- The successors of the Graph are the the Labels -- for which we have facts and which are *not* in -- the blocks of the graph where -- mapping from L -> Ls. If the fact for L changes, re-analyse Ls. dep_blocks :: LabelMap [Label] dep_blocks = mapFromListWith (++) [ (l, [entryLabel b]) | b <- mapElems blockmap , l <- case direction of Fwd -> [entryLabel b] Bwd -> successors b ] loop :: FactBase f -- current factbase (increases monotonically) -> [Label] -- blocks still to analyse (Todo: use a better rep) -> LabelMap (DBlock f n C C) -- transformed graph -> m (FactBase f, LabelMap (DBlock f n C C)) loop fbase [] newblocks = return (fbase, newblocks) loop fbase (lbl:todo) newblocks = do case mapLookup lbl blockmap of Nothing -> loop fbase todo newblocks Just blk -> do -- trace ("analysing: " ++ show lbl) $ return () (rg, out_facts) <- do_block blk fbase let (changed, fbase') = mapFoldWithKey (updateFact lat newblocks) ([],fbase) out_facts -- trace ("fbase': " ++ show (mapKeys fbase')) $ return () -- trace ("changed: " ++ show changed) $ return () let to_analyse = filter (`notElem` todo) $ concatMap (\l -> mapFindWithDefault [] l dep_blocks) changed -- trace ("to analyse: " ++ show to_analyse) $ return () let newblocks' = case rg of GMany _ blks _ -> mapUnion blks newblocks loop fbase' (todo ++ to_analyse) newblocks' {- Note [TxFactBase invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The TxFactBase is used only during a fixpoint iteration (or "sweep"), and accumulates facts (and the transformed code) during the fixpoint iteration. * tfb_fbase increases monotonically, across all sweeps * At the beginning of each sweep tfb_cha = NoChange tfb_lbls = {} * During each sweep we process each block in turn. Processing a block is done thus: 1. Read from tfb_fbase the facts for its entry label (forward) or successors labels (backward) 2. Transform those facts into new facts for its successors (forward) or entry label (backward) 3. Augment tfb_fbase with that info We call the labels read in step (1) the "in-labels" of the sweep * The field tfb_lbls is the set of in-labels of all blocks that have been processed so far this sweep, including the block that is currently being processed. tfb_lbls is initialised to {}. It is a subset of the Labels of the *original* (not transformed) blocks. * The tfb_cha field is set to SomeChange iff we decide we need to perform another iteration of the fixpoint loop. It is initialsed to NoChange. Specifically, we set tfb_cha to SomeChange in step (3) iff (a) The fact in tfb_fbase for a block L changes (b) L is in tfb_lbls Reason: until a label enters the in-labels its accumuated fact in tfb_fbase has not been read, hence cannot affect the outcome Note [Unreachable blocks] ~~~~~~~~~~~~~~~~~~~~~~~~~ A block that is not in the domain of tfb_fbase is "currently unreachable". A currently-unreachable block is not even analyzed. Reason: consider constant prop and this graph, with entry point L1: L1: x:=3; goto L4 L2: x:=4; goto L4 L4: if x>3 goto L2 else goto L5 Here L2 is actually unreachable, but if we process it with bottom input fact, we'll propagate (x=4) to L4, and nuke the otherwise-good rewriting of L4. * If a currently-unreachable block is not analyzed, then its rewritten graph will not be accumulated in tfb_rg. And that is good: unreachable blocks simply do not appear in the output. * Note that clients must be careful to provide a fact (even if bottom) for each entry point. Otherwise useful blocks may be garbage collected. * Note that updateFact must set the change-flag if a label goes from not-in-fbase to in-fbase, even if its fact is bottom. In effect the real fact lattice is UNR bottom the points above bottom * Even if the fact is going from UNR to bottom, we still call the client's fact_join function because it might give the client some useful debugging information. * All of this only applies for *forward* fixpoints. For the backward case we must treat every block as reachable; it might finish with a 'return', and therefore have no successors, for example. -} ----------------------------------------------------------------------------- -- DG: an internal data type for 'decorated graphs' -- TOTALLY internal to Hoopl; each block is decorated with a fact ----------------------------------------------------------------------------- -- @ start dg.tex type Graph = Graph' Block type DG f = Graph' (DBlock f) data DBlock f n e x = DBlock f (Block n e x) -- ^ block decorated with fact -- @ end dg.tex instance NonLocal n => NonLocal (DBlock f n) where entryLabel (DBlock _ b) = entryLabel b successors (DBlock _ b) = successors b --- constructors dgnil :: DG f n O O dgnilC :: DG f n C C dgSplice :: NonLocal n => DG f n e a -> DG f n a x -> DG f n e x ---- observers normalizeGraph :: forall n f e x . NonLocal n => DG f n e x -> (Graph n e x, FactBase f) -- A Graph together with the facts for that graph -- The domains of the two maps should be identical normalizeGraph g = (mapGraphBlocks dropFact g, facts g) where dropFact :: DBlock t t1 t2 t3 -> Block t1 t2 t3 dropFact (DBlock _ b) = b facts :: DG f n e x -> FactBase f facts GNil = noFacts facts (GUnit _) = noFacts facts (GMany _ body exit) = bodyFacts body `mapUnion` exitFacts exit exitFacts :: MaybeO x (DBlock f n C O) -> FactBase f exitFacts NothingO = noFacts exitFacts (JustO (DBlock f b)) = mapSingleton (entryLabel b) f bodyFacts :: LabelMap (DBlock f n C C) -> FactBase f bodyFacts body = mapFoldWithKey f noFacts body where f :: forall t a x. Label -> DBlock a t C x -> LabelMap a -> LabelMap a f lbl (DBlock f _) fb = mapInsert lbl f fb --- implementation of the constructors (boring) dgnil = GNil dgnilC = GMany NothingO emptyBody NothingO dgSplice = splice fzCat where fzCat :: DBlock f n e O -> DBlock t n O x -> DBlock f n e x fzCat (DBlock f b1) (DBlock _ b2) = DBlock f (b1 `blockAppend` b2) ---------------------------------------------------------------- -- Utilities ---------------------------------------------------------------- -- Lifting based on shape: -- - from nodes to blocks -- - from facts to fact-like things -- Lowering back: -- - from fact-like things to facts -- Note that the latter two functions depend only on the entry shape. -- @ start node.tex class ShapeLifter e x where singletonDG :: f -> n e x -> DG f n e x fwdEntryFact :: NonLocal n => n e x -> f -> Fact e f fwdEntryLabel :: NonLocal n => n e x -> MaybeC e [Label] ftransfer :: FwdTransfer n f -> n e x -> f -> Fact x f frewrite :: FwdRewrite m n f -> n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f)) -- @ end node.tex bwdEntryFact :: NonLocal n => DataflowLattice f -> n e x -> Fact e f -> f btransfer :: BwdTransfer n f -> n e x -> Fact x f -> f brewrite :: BwdRewrite m n f -> n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f)) instance ShapeLifter C O where singletonDG f n = gUnitCO (DBlock f (BlockCO n BNil)) fwdEntryFact n f = mapSingleton (entryLabel n) f bwdEntryFact lat n fb = getFact lat (entryLabel n) fb ftransfer (FwdTransfer3 (ft, _, _)) n f = ft n f btransfer (BwdTransfer3 (bt, _, _)) n f = bt n f frewrite (FwdRewrite3 (fr, _, _)) n f = fr n f brewrite (BwdRewrite3 (br, _, _)) n f = br n f fwdEntryLabel n = JustC [entryLabel n] instance ShapeLifter O O where singletonDG f = gUnitOO . DBlock f . BMiddle fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdTransfer3 (_, ft, _)) n f = ft n f btransfer (BwdTransfer3 (_, bt, _)) n f = bt n f frewrite (FwdRewrite3 (_, fr, _)) n f = fr n f brewrite (BwdRewrite3 (_, br, _)) n f = br n f fwdEntryLabel _ = NothingC instance ShapeLifter O C where singletonDG f n = gUnitOC (DBlock f (BlockOC BNil n)) fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdTransfer3 (_, _, ft)) n f = ft n f btransfer (BwdTransfer3 (_, _, bt)) n f = bt n f frewrite (FwdRewrite3 (_, _, fr)) n f = fr n f brewrite (BwdRewrite3 (_, _, br)) n f = br n f fwdEntryLabel _ = NothingC -- Fact lookup: the fact `orelse` bottom getFact :: DataflowLattice f -> Label -> FactBase f -> f getFact lat l fb = case lookupFact l fb of Just f -> f Nothing -> fact_bot lat {- Note [Respects fuel] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} -- $fuel -- A value of type 'FwdRewrite' or 'BwdRewrite' /respects fuel/ if -- any function contained within the value satisfies the following properties: -- -- * When fuel is exhausted, it always returns 'Nothing'. -- -- * When it returns @Just g rw@, it consumes /exactly/ one unit -- of fuel, and new rewrite 'rw' also respects fuel. -- -- Provided that functions passed to 'mkFRewrite', 'mkFRewrite3', -- 'mkBRewrite', and 'mkBRewrite3' are not aware of the fuel supply, -- the results respect fuel. -- -- It is an /unchecked/ run-time error for the argument passed to 'wrapFR', -- 'wrapFR2', 'wrapBR', or 'warpBR2' to return a function that does not respect fuel.
hvr/hoopl
src/Compiler/Hoopl/Dataflow.hs
bsd-3-clause
34,467
34
22
10,558
9,719
5,053
4,666
447
14
{-# LANGUAGE OverloadedStrings #-} module Migrate ( run ) where import Control.Exception import Control.Monad import qualified Data.Text as T import Database.Persist.Sqlite import System.Directory (doesDirectoryExist) import qualified Config import qualified Database.Persist.Sqlite as P import DB run :: IO () run = do d <- doesDirectoryExist "db" unless d $ fail "Directory ./db does not exist. Retry after creating ./db" development <- Config.get (T.unpack "config/database.yml") "development" "database" pool <- P.createSqlitePool development 3 runDB pool $ runMigration migrateAll
fujimura/spot
src/Migrate.hs
bsd-3-clause
690
0
11
179
149
80
69
18
1
{-# language GADTs #-} {-# language TypeOperators #-} {-# language PatternSynonyms #-} {-# language ViewPatterns #-} {-# language FlexibleContexts #-} {-# language ScopedTypeVariables #-} module Feldspar.Software.Optimize where import Feldspar.Representation import Feldspar.Software.Primitive import Feldspar.Software.Expression import Data.Struct import Control.Monad.Writer hiding (Any (..)) import Data.Maybe import Data.Constraint (Dict (..)) import Data.Set (Set) import qualified Data.Monoid as Monoid import qualified Data.Set as Set -- syntactic. import Language.Syntactic import Language.Syntactic.Functional import Language.Syntactic.Functional.Tuple import Language.Syntactic.Functional.Sharing -------------------------------------------------------------------------------- -- * Optimize software expressions. -------------------------------------------------------------------------------- viewLit :: ASTF SoftwareDomain a -> Maybe a viewLit lit | Just (Lit a) <- prj lit = Just a viewLit _ = Nothing witInteger :: ASTF SoftwareDomain a -> Maybe (Dict (Integral a, Ord a)) witInteger a = case getDecor a of ValT (Node Int8ST) -> Just Dict ValT (Node Int16ST) -> Just Dict ValT (Node Int32ST) -> Just Dict ValT (Node Int64ST) -> Just Dict ValT (Node Word8ST) -> Just Dict ValT (Node Word16ST) -> Just Dict ValT (Node Word32ST) -> Just Dict ValT (Node Word64ST) -> Just Dict _ -> Nothing isExact :: ASTF SoftwareDomain a -> Bool isExact = isJust . witInteger -- | projection with a stronger constraint to allow using it in -- bidirectional patterns. prjBi :: (sub :<: sup) => sup sig -> Maybe (sub sig) prjBi = prj -------------------------------------------------------------------------------- pattern SymP t s <- Sym ((prjBi -> Just s) :&: ValT t) where SymP t s = Sym ((inj s) :&: ValT t) pattern VarP t v <- Sym ((prjBi -> Just (VarT v)) :&: t) where VarP t v = Sym (inj (VarT v) :&: t) pattern LamP t v body <- Sym ((prjBi -> Just (LamT v)) :&: t) :$ body where LamP t v body = Sym (inj (LamT v) :&: t) :$ body -------------------------------------------------------------------------------- pattern LitP :: () => (Eq a, Show a) => STypeRep a -> a -> ASTF SoftwareDomain a pattern AddP :: () => (Num a, SoftwarePrimType a) => STypeRep a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a pattern SubP :: () => (Num a, SoftwarePrimType a) => STypeRep a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a pattern MulP :: () => (Num a, SoftwarePrimType a) => STypeRep a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a pattern NegP :: () => (Num a, SoftwarePrimType a) => STypeRep a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a pattern DivP :: () => (Integral a, SoftwarePrimType a) => STypeRep a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a pattern ModP :: () => (Integral a, SoftwarePrimType a) => STypeRep a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a -> ASTF SoftwareDomain a -------------------------------------------------------------------------------- pattern NonLitP <- (viewLit -> Nothing) pattern LitP t a <- Sym ((prj -> Just (Lit a)) :&: ValT t) where LitP t a = Sym (inj (Lit a) :&: ValT t) pattern AddP t a b <- SymP t Add :$ a :$ b where AddP t a b = simplifyUp $ SymP t Add :$ a :$ b pattern SubP t a b <- SymP t Sub :$ a :$ b where SubP t a b = simplifyUp $ SymP t Sub :$ a :$ b pattern MulP t a b <- SymP t Mul :$ a :$ b where MulP t a b = simplifyUp $ SymP t Mul :$ a :$ b pattern NegP t a <- SymP t Neg :$ a where NegP t a = simplifyUp $ SymP t Neg :$ a pattern DivP t a b <- SymP t Div :$ a :$ b where DivP t a b = simplifyUp $ SymP t Div :$ a :$ b pattern ModP t a b <- SymP t Mod :$ a :$ b where ModP t a b = simplifyUp $ SymP t Mod :$ a :$ b -------------------------------------------------------------------------------- simplifyUp :: ASTF SoftwareDomain a -> ASTF SoftwareDomain a -- Addition with zero. simplifyUp (AddP t (LitP _ 0) b) | isExact b = b simplifyUp (AddP t a (LitP _ 0)) | isExact a = a -- Simplify additions with literals. simplifyUp (AddP t (AddP _ a (LitP _ b)) (LitP _ c)) | isExact a = AddP t a (LitP t (b+c)) simplifyUp (AddP t (SubP _ a (LitP _ b)) (LitP _ c)) | isExact a = AddP t a (LitP t (c-b)) simplifyUp (AddP t a (LitP _ b)) | Just Dict <- witInteger a, b < 0 = SubP t a (LitP t (negate b)) -- Subtraction with zero. simplifyUp (SubP t (LitP _ 0) b) | isExact b = NegP t b simplifyUp (SubP t a (LitP _ 0)) | isExact a = a -- Simplify subtractions with literals. simplifyUp (SubP t (AddP _ a (LitP _ b)) (LitP _ c)) | isExact a = AddP t a (LitP t (b-c)) simplifyUp (SubP t (SubP _ a (LitP _ b)) (LitP _ c)) | isExact a = SubP t a (LitP t (b+c)) simplifyUp (SubP t a (LitP _ b)) | Just Dict <- witInteger a, b < 0 = AddP t a (LitP t (negate b)) -- Multiplication with zero. simplifyUp (MulP t (LitP _ 0) b) | isExact b = LitP t 0 simplifyUp (MulP t a (LitP _ 0)) | isExact a = LitP t 0 -- Multiplication with one. simplifyUp (MulP t (LitP _ 1) b) | isExact b = b simplifyUp (MulP t a (LitP _ 1)) | isExact a = a -- Simplify multiplications with literals. simplifyUp (MulP t (MulP _ a (LitP _ b)) (LitP _ c)) | isExact a = MulP t a (LitP t (b*c)) -- Simplify negations. simplifyUp (NegP t (NegP _ a)) | isExact a = a simplifyUp (NegP t (AddP _ a b)) | isExact a = SubP t (NegP t a) b simplifyUp (NegP t (SubP _ a b)) | isExact a = SubP t b a simplifyUp (NegP t (MulP _ a b)) | isExact a = MulP t a (NegP t b) -- Move literals to the right. simplifyUp (AddP t a@(LitP _ _) b@NonLitP) | isExact a = AddP t b a simplifyUp (SubP t a@(LitP _ _) b@NonLitP) | isExact a = AddP t (NegP t b) a simplifyUp (MulP t a@(LitP _ _) b@NonLitP) | isExact a = MulP t b a -- Simplify not-expressions. -- Not sure (yet) why I can't write `simplifyUp (NotP _ (NotP _ a)) = a` simplifyUp (SymP _ Not :$ (SymP _ Not :$ a)) = a simplifyUp (SymP t Not :$ (SymP _ Lt :$ a :$ b)) = simplifyUp $ SymP t Gte :$ a :$ b simplifyUp (SymP t Not :$ (SymP _ Gt :$ a :$ b)) = simplifyUp $ SymP t Lte :$ a :$ b simplifyUp (SymP t Not :$ (SymP _ Lte :$ a :$ b)) = simplifyUp $ SymP t Gt :$ a :$ b simplifyUp (SymP t Not :$ (SymP _ Gte :$ a :$ b)) = simplifyUp $ SymP t Lt :$ a :$ b -- Simplify and-expressions. simplifyUp (SymP _ And :$ LitP t False :$ _) = LitP t False simplifyUp (SymP _ And :$ _ :$ LitP t False) = LitP t False simplifyUp (SymP _ And :$ LitP t True :$ b) = b simplifyUp (SymP _ And :$ a :$ LitP t True) = a -- Simplify or-expressions. simplifyUp (SymP _ Or :$ LitP t False :$ b) = b simplifyUp (SymP _ Or :$ a :$ LitP t False) = a simplifyUp (SymP _ Or :$ LitP t True :$ _) = LitP t True simplifyUp (SymP _ Or :$ _ :$ LitP t True) = LitP t True -- Simplify conditional expressions. simplifyUp (SymP _ Cond :$ LitP _ True :$ t :$ _) = t simplifyUp (SymP _ Cond :$ LitP _ False :$ _ :$ f) = f simplifyUp (SymP _ Cond :$ c :$ t :$ f) | equal t f = t -- Simplify pairs. simplifyUp (SymP t Pair :$ (SymP _ Fst :$ a) :$ (SymP _ Snd :$ b)) | alphaEq a b , ValT t' <- getDecor a , Just Dict <- softwareTypeEq t t' = a simplifyUp (SymP t Fst :$ (SymP _ Pair :$ a :$ _)) = a simplifyUp (SymP t Snd :$ (SymP _ Pair :$ _ :$ a)) = a -- simplifyUp a = constFold a -- `constFold` here ensures that `simplifyUp` does not produce any expressions -- that can be statically constant folded. This property is needed, e.g. to -- fully simplify the expression `negate (2*x)`. The simplification should go -- as follows: -- -- negate (2*x) -> negate (x*2) -> x * negate 2 -> x*(-2) -- -- There is no explicit rule for the last step; it is done by `constFold`. -- Furthermore, this constant folding would not be performed by `simplifyM` -- since it never sees the sub-expression `negate 2`. (Note that the constant -- folding in `simplifyM` is still needed, because constructs such as -- `ForLoop` cannot be folded by simple literal propagation.) -- -- In order to see that `simplifyUp` doesn't produce any "junk" -- (sub-expressions that can be folded by `constFold`), we reason as follows: -- -- * Assume that the arguments of the top-level node are junk-free -- * `simplifyUp` will either apply an explicit rewrite or apply `constFold` -- * In the latter case, the result will be junk-free -- * In case of an explicit rewrite, the resulting expression is constructed -- by applying `simplifyUp` to each newly introduced node; thus the -- resulting expression must be junk-free -------------------------------------------------------------------------------- -- | Reduce an expression to a literal if the following conditions are met: -- -- * The top-most symbol can be evaluated statically (i.g. not a variable or a -- lifted side-effecting program) -- * All immediate sub-terms are literals -- * The type of the expression is an allowed type for literals (e.g. not a -- function) -- -- Note that this function only folds the top-level node of an expressions (if -- possible). It does not reduce an expression like @1+(2+3)@ where the -- sub-expression @2+3@ is not a literal. constFold :: ASTF SoftwareDomain a -> ASTF SoftwareDomain a constFold e | constArgs e, canFold e, ValT t@(Node _) <- getDecor e = LitP t (evalClosed e) where canFold :: ASTF SoftwareDomain a -> Bool canFold = simpleMatch (\(s :&: ValT _) _ -> go s) where go :: SoftwareConstructs sig -> Bool go var | Just (FreeVar _) <- prj var = False go ix | Just (ArrIx _) <- prj ix = False go bid | Just (_ :: BindingT sig) <- prj bid = False go _ = True constFold e = e -- | Check whether all arguments of a symbol are literals constArgs :: AST SoftwareDomain sig -> Bool constArgs (Sym _) = True constArgs (s :$ LitP _ _) = constArgs s constArgs _ = False -------------------------------------------------------------------------------- type Opt = Writer (Set Name, Monoid.Any) freeVar :: Name -> Opt () freeVar v = tell (Set.singleton v, mempty) bindVar :: Name -> Opt a -> Opt a bindVar v = censor (\(vars, unsafe) -> (Set.delete v vars, unsafe)) tellUnsafe :: Opt () tellUnsafe = tell (mempty, Monoid.Any True) simplifyM :: ASTF SoftwareDomain a -> Opt (ASTF SoftwareDomain a) simplifyM exp = case exp of (VarP _ v) -> freeVar v >> return exp (LamP t v body) -> bindVar v $ fmap (LamP t v) $ simplifyM body _ -> simpleMatch (\s@(v :&: t) args -> do (exp', (vars, Monoid.Any unsafe)) <- listen (simplifyUp . appArgs (Sym s) <$> mapArgsM simplifyM args) case () of _ | Just (FreeVar _) <- prj v -> tellUnsafe >> return exp' _ | Just (ArrIx _) <- prj v -> tellUnsafe >> return exp' _ | null vars && not unsafe, ValT t'@(Node _) <- t -> return $ LitP t' $ evalClosed exp' _ -> return exp' ) exp -- Array indexing is actually not unsafe. It's more like -- an expression with a free variable. But setting the -- unsafe flag does the trick. -- Constant fold if expression is closed and does not -- contain unsafe operations. -------------------------------------------------------------------------------- optimize :: ASTF SoftwareDomain a -> ASTF SoftwareDomain a optimize = fst . runWriter . simplifyM --------------------------------------------------------------------------------
markus-git/co-feldspar
src/Feldspar/Software/Optimize.hs
bsd-3-clause
11,670
0
23
2,642
4,260
2,100
2,160
186
9
{-# LANGUAGE ViewPatterns, PatternGuards, TupleSections, RecordWildCards, BangPatterns, ScopedTypeVariables #-} module Input.Cabal(Cabal(..), parseCabalTarball) where import Data.List.Extra import System.FilePath import Control.Applicative import Control.DeepSeq import Control.Exception import System.IO.Extra import Control.Monad.Extra import General.Str import Data.Char import Data.Tuple.Extra import qualified Data.Text as T import qualified Data.Map.Strict as Map import General.Util import General.Conduit import Paths_hoogle import Prelude data Cabal = Cabal {cabalTags :: [(T.Text, T.Text)] -- The Tag information, e.g. (category,Development) (author,Neil Mitchell). ,cabalLibrary :: Bool -- True if the package provides a library (False if it is only an executable with no API) ,cabalSynopsis :: T.Text -- The synposis, grabbed from the top section. ,cabalVersion :: T.Text -- The version, grabbed from the top section. Never empty (will be 0.0 if not found). ,cabalPopularity :: {-# UNPACK #-} !Int -- The number of packages that directly depend on this package. } deriving Show instance NFData Cabal where rnf (Cabal a b c d e) = rnf (a,b,c,d,e) -- | Given the Cabal files we care about, pull out the fields you care about parseCabalTarball :: FilePath -> IO ([String], Map.Map String Cabal) -- items are stored as: -- QuickCheck/2.7.5/QuickCheck.cabal -- QuickCheck/2.7.6/QuickCheck.cabal -- rely on the fact the highest version is last (using lastValues) parseCabalTarball tarfile = do rename <- loadRename runConduit $ (sourceList =<< liftIO (tarballReadFiles tarfile)) =$= mapC (first takeBaseName) =$= groupOnLastC fst =$= mapMC (\x -> do evaluate $ rnf x; return x) =$= pipelineC 10 (mapC (second $ readCabal rename . lstrUnpack) =$= mapMC (\x -> do evaluate $ rnf x; return x) =$= mergeCabals) mergeCabals :: Monad m => Consumer (String, (Cabal, [String])) m ([String], Map.Map String Cabal) mergeCabals = freeze <$> foldC add (Map.empty, Map.empty) where -- Takes imports (Map Name (Int,Name)), where a |-> (i,b) means a has i people who depend on it, b is one of them -- Takes cabals (Map Name Cabal), just the mapping to return at the end add (!imports, !cabals) x@(name,(cabal,depends)) = (imports2, Map.insert name cabal cabals) where imports2 = foldl' (\mp i -> Map.insertWith merge i (1::Int,name) mp) imports depends merge (c1,n1) (c2,n2) = let cc = c1+c2 in cc `seq` (cc, n1) freeze (imports, cabals) = bad `seq` good `seq` (bad, good) where bad = [ user ++ ".cabal: Import of non-existant package " ++ name ++ (if i <= 1 then "" else ", also imported by " ++ show (i-1) ++ " others") | (name,(i,user)) <- Map.toList $ Map.difference imports cabals] good = Map.differenceWith (\c (i,_) -> Just c{cabalPopularity=i}) cabals imports loadRename :: IO (String -> String) loadRename = do dataDir <- getDataDir src <- readFileUTF8 $ dataDir </> "misc/tag-rename.txt" let mp = Map.fromList $ map (both trim . splitPair "=") $ lines src return $ \x -> Map.findWithDefault x x mp -- | Cabal information, plus who I depend on readCabal :: (String -> String) -> String -> (Cabal, [String]) readCabal rename src = (Cabal{..}, nubOrd depends) where mp = Map.fromListWith (++) $ lexCabal src ask x = Map.findWithDefault [] x mp depends = nubOrd $ filter (/= "") $ map (takeWhile $ \x -> isAlphaNum x || x `elem` "-") $ concatMap (split (== ',')) $ ask "build-depends" cabalVersion = T.pack $ head $ dropWhile null (ask "version") ++ ["0.0"] cabalSynopsis = T.pack $ unwords $ words $ unwords $ ask "synopsis" cabalLibrary = "library" `elem` map (lower . trim) (lines src) cabalPopularity = 0 cabalTags = map (both T.pack) $ nubOrd $ concat [ map (head xs,) $ concatMap cleanup $ concatMap ask xs | xs <- [["license"],["category"],["author","maintainer"]]] -- split on things like "," "&" "and", then throw away email addresses, replace spaces with "-" and rename cleanup = filter (/= "") . map (rename . intercalate "-" . filter ('@' `notElem`) . words . takeWhile (`notElem` "<(")) . concatMap (map unwords . split (== "and") . words) . split (`elem` ",&") -- Ignores nesting beacuse it's not interesting for any of the fields I care about lexCabal :: String -> [(String, [String])] lexCabal = f . lines where f (x:xs) | (white,x) <- span isSpace x , (name@(_:_),x) <- span (\c -> isAlpha c || c == '-') x , ':':x <- trim x , (xs1,xs2) <- span (\s -> length (takeWhile isSpace s) > length white) xs = (lower name, trim x : replace ["."] [""] (map (trim . fst . breakOn "--") xs1)) : f xs2 f (x:xs) = f xs f [] = []
wolftune/hoogle
src/Input/Cabal.hs
bsd-3-clause
5,040
0
18
1,242
1,599
871
728
75
3
-- http://adventofcode.com/2016/day/15 module Day_15 where import Data.List.Split import Data.Bifunctor type Position = Int type Positions = Int type Disc = (Position, Positions) main :: IO () main = do fileContents <- readFile "inputs/Day_15_input.txt" print ("Part 1", part 1 fileContents) -- 148737 print ("Part 2", part 2 fileContents) -- 2353212 part :: Int -> String -> Int part n = length . takeWhile (not.allClear) . iterate wait . parseDiscs where parseDiscs = compensate . (++ (if n == 2 then [(0, 11)] else []) ) . (fmap parseDisc) . lines compensate :: [Disc] -> [Disc] compensate = zipWith (\y (a, b)-> (a + y, b)) [1..] wait :: [Disc] -> [Disc] wait = fmap.first $ (+1) allClear :: [Disc] -> Bool allClear = all (\(p, ps) -> (p `mod` ps) == 0) parseDisc :: String -> Disc parseDisc xs = (read $ tok !! 11, read $ tok !! 3) where tok = splitOn " " . init $ xs
MaxwellBo/Advent_Of_Code_2016
Day_15.hs
bsd-3-clause
949
0
14
235
388
219
169
26
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} module Ivory.Language.Module where import Ivory.Language.Area (IvoryArea) import Ivory.Language.MemArea (MemArea(..),ConstMemArea(..)) import Ivory.Language.Proc (Def(..)) import Ivory.Language.Proxy (Proxy(..), ASymbol) import Ivory.Language.String (IvoryString(..)) import Ivory.Language.Struct (IvoryStruct(..),StructDef(..),StructName) import Ivory.Language.Type (IvoryExpr, unwrapExpr) import qualified Ivory.Language.Syntax as I import Control.Monad (forM_) import Control.Applicative import Data.Monoid import MonadLib (ReaderT,WriterT,ReaderM,WriterM,Id,runM,put,ask,local) import MonadLib.Derive (Iso (..),derive_ask,derive_put) import qualified Data.Set as Set -- Modules --------------------------------------------------------------------- data Visible = Public | Private deriving (Show) newtype ModuleM a = Module { unModule :: ReaderT Visible (WriterT I.Module Id) a } deriving (Functor,Monad,Applicative) instance ReaderM ModuleM Visible where ask = derive_ask (Iso Module unModule) instance WriterM ModuleM I.Module where put = derive_put (Iso Module unModule) type ModuleDef = ModuleM () instance Monoid (ModuleM ()) where mempty = return () mappend a b = a >> b -- | Add an element to the public/private list, depending on visibility visAcc :: Visible -> a -> I.Visible a visAcc vis e = case vis of Public -> I.Visible { I.public = [e], I.private = [] } Private -> I.Visible { I.public = [], I.private = [e] } -- | Include a defintion in the module. incl :: Def a -> ModuleDef incl (DefProc p) = do visibility <- ask put (mempty { I.modProcs = visAcc visibility p }) incl (DefImport i) | null (I.importFile i) = error $ "Empty header name for " ++ show i | otherwise = put (mempty { I.modImports = [i] }) -- | Import an externally-defined symbol. inclSym :: IvoryExpr t => t -> ModuleDef inclSym t = case unwrapExpr t of I.ExpExtern sym | null (I.externFile sym) -> error $ "Empty header name for " ++ show sym | otherwise -> put (mempty { I.modExterns = [sym] }) e -> error $ "Cannot import expression " ++ show e -- | Add a dependency on another module. depend :: I.Module -> ModuleDef depend m = put (mempty { I.modDepends = Set.singleton (I.modName m) }) -- | Include the definition of a structure in the module. defStruct :: forall sym. (IvoryStruct sym, ASymbol sym) => Proxy sym -> ModuleDef defStruct _ = case getStructDef def of I.Abstract n "" -> error $ "Empty header name for struct " ++ n str -> do visibility <- ask put (mempty { I.modStructs = visAcc visibility str }) where def :: StructDef sym def = structDef -- | Include the definition of a string type's structure. defStringType :: forall str. (IvoryString str) => Proxy str -> ModuleDef defStringType _ = defStruct (Proxy :: Proxy (StructName str)) -- | Include the definition of a memory area. defMemArea :: IvoryArea area => MemArea area -> ModuleDef defMemArea m = case m of MemImport ia | null (I.aiFile ia) -> error $ "Empty header name for " ++ show ia | otherwise -> put (mempty { I.modAreaImports = [ia] }) MemArea a as -> do visibility <- ask put (mempty { I.modAreas = visAcc visibility a }) forM_ as $ \aux -> do put (mempty { I.modAreas = visAcc Private aux }) -- | Include the definition of a constant memory area. defConstMemArea :: IvoryArea area => ConstMemArea area -> ModuleDef defConstMemArea (ConstMemArea m) = defMemArea m -- | Package the module up. Default visibility is public. package :: String -> ModuleDef -> I.Module package name build = (snd (runM (unModule build) Public)) { I.modName = name } -- | Start a block of definitions that should not be put in the header. private :: ModuleDef -> ModuleDef private build = Module $ local Private (unModule build) -- | Start a block of definitions should be put in the header. This is the -- default, and this function is just included to complement 'private'. public :: ModuleDef -> ModuleDef public build = Module $ local Public (unModule build) -- Accessors ------------------------------------------------------------------- moduleName :: I.Module -> String moduleName = I.modName
Hodapp87/ivory
ivory/src/Ivory/Language/Module.hs
bsd-3-clause
4,364
0
18
810
1,308
705
603
82
2
module TesteGhcPT where class Foo a b where foo :: a -> b -> Int instance Foo Int a instance Foo a b => Foo [a] b g y = let h :: c -> Int h x = foo y x in h y
rodrigogribeiro/mptc
src/Libs/Tests/TesteGhcPT.hs
bsd-3-clause
220
0
9
106
97
47
50
-1
-1
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, ExtendedDefaultRules #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances, OverloadedStrings #-} {-# LANGUAGE QuasiQuotes, StandaloneDeriving, TemplateHaskell #-} {-# LANGUAGE TypeOperators, ViewPatterns #-} {-# OPTIONS_GHC -fwarn-unused-imports -fwarn-unused-binds #-} module ASTUtil (addDecls, addImports, addLanguagePragmas, extractExts, getModules, getQualified) where import Data.Char (isAlpha) import Data.Data (Data) import Data.Generics (mkQ) import Data.Generics (everything) import Data.Generics (extQ) import Data.Text (breakOnEnd) import qualified Data.Text as T import Language.Haskell.Exts (Module (..)) import Language.Haskell.Exts (ImportDecl) import Language.Haskell.Exts (Decl) import Language.Haskell.Exts (name) import Language.Haskell.Exts (ModulePragma (LanguagePragma)) import Language.Haskell.Exts (ModuleName (..)) import Language.Haskell.Exts (ImportDecl (..)) import Language.Haskell.Exts (prettyPrint) import Language.Haskell.Exts (parseExtension) import Language.Haskell.Exts.Extension (Extension) import Language.Haskell.Exts.SrcLoc (noLoc) import qualified Language.Haskell.TH.Syntax as TH addDecls :: [Decl] -> Module -> Module addDecls ds' (Module l n ps mw mex is ds) = Module l n ps mw mex is (ds ++ ds') addImports :: [ImportDecl] -> Module -> Module addImports is' (Module l n ps mw mex is ds) = Module l n ps mw mex (is ++ is') ds addLanguagePragmas :: [String] -> Module -> Module addLanguagePragmas ps' (Module l n ps mw mex is ds) = Module l n (LanguagePragma noLoc (map name ps') : ps) mw mex is ds extractExts :: Module -> [Extension] extractExts (Module _ _ ps _ _ _ _) = do [parseExtension (prettyPrint n) | LanguagePragma _ ns <- ps, n <- ns] getModules0 :: TH.NameFlavour -> [String] getModules0 (TH.NameG _ _ (TH.ModName mn)) = [mn] getModules0 _ = [] getModules1 (TH.Name (TH.OccName n) _) | '.' `elem` n && any isAlpha n = [T.unpack $ T.init $ fst $ breakOnEnd "." $ T.pack n] getModules1 _ = [] getModules :: Data a => a -> [String] getModules = everything (++) (mkQ [] getModules0 `extQ` getModules1) getQualified :: Module -> [String] getQualified (Module _ _ _ _ _ is _) = [ n | ImportDecl _ (ModuleName n) True _ _ _ Nothing _ <- is ] ++ [ n | ImportDecl _ _ _ _ _ _ (Just (ModuleName n)) _ <- is ]
konn/expandth
lib/ASTUtil.hs
bsd-3-clause
2,790
0
13
818
837
464
373
49
1
import Database.HDBC import Database.HDBC.Sqlite3 import ScottyCA import Web.Scotty import Data.ByteString.Lazy (ByteString, append, empty, pack, length, toStrict, fromStrict) import qualified Data.ByteString.Lazy.Char8 as L import Data.Binary import System.IO import Crypto.Cipher.AES import Control.Monad.Trans import qualified Data.Text.Lazy as LazyText import Data.Monoid (mconcat) import qualified Data.Text.Lazy.Encoding as LazyEncoding import qualified Demo3Shared as AD --ArmoredData import TPM import Demo3Shared databaseName = "armoredDB.db" my_id= 19 :: Int main = do putStrLn "hello" conn <- connectSqlite3 databaseName filekey <- readPubEK run conn "INSERT INTO pubkeys VALUES( ?, ?)" [toSql my_id, toSql (AD.jsonEncode filekey)] commit conn disconnect conn putStrLn (show (AD.jsonEncode filekey)) testgetparsing = do putStrLn "beginning..." conn <- connectSqlite3 databaseName res <- quickQuery' conn ("SELECT jsontpmkey from pubkeys where id =" ++ (show my_id)) [] putStrLn "Here is the result of the query:" putStrLn (show res) let res' = (res !! 0) !! 0 convertedRes = fromSql res' :: ByteString putStrLn " Here is the bytestring version: " putStrLn (show convertedRes) let x = jsonEitherDecode convertedRes :: Either String TPM_PUBKEY putStrLn "Here is the JSON decoded version: " putStrLn (show x) case x of (Left err) -> do putStrLn ("Failed to get from DB properly. Error was: " ++ err) --return () (Right k) -> do putStrLn "SUCCESS! Good job. successfully read the TPM_PUBKEY out of the sql db as json and converted to TPM_PUBKEY object" --return () putStrLn "thats all for now"
armoredsoftware/protocol
tpm/mainline/privacyCA/testsql.hs
bsd-3-clause
1,685
8
14
309
447
232
215
45
2
{- | Module : $Header$ - Description : Implementation of logic instance K - Copyright : (c) Daniel Hausmann & Georgel Calin & Lutz Schroeder, DFKI Lab Bremen, - Rob Myers & Dirk Pattinson, Department of Computing, ICL - License : GPLv2 or higher, see LICENSE.txt - Maintainer : hausmann@dfki.de - Stability : provisional - Portability : portable - - Provides the implementation of the matching functions the standard modal logic K. -} module GMP.Logics.K where import List import Ratio import Maybe import Debug.Trace import Text.ParserCombinators.Parsec import GMP.Logics.Generic import GMP.Parser -------------------------------------------------------------------------------- -- instance of feature K -------------------------------------------------------------------------------- data K a = K [Formula a] deriving (Eq, Ord, Show) -- For each positive modal literal, there is a premise containing only one -- sequent. This sequent contains the stripped positive literal and all -- negated stripped negative literals. -- e.g. seq = [ (M K p), !(M K q), (M K !p), !(M K !r)] -- match seq = [ [[ p, !q, r]], [[ !p, !q, r]] ] instance (SigFeature b c d, Eq (b (c d)), Eq (c d)) => NonEmptyFeature K b c d where nefMatch flags seq = let stripnlits = [ Neg (head phi) | (Neg (Mod (K phi))) <- seq] striplits = [ (head phi) | (Mod (K phi)) <- seq] in if (flags!!1) then trace ("\n [K-matching this:] " ++ (pretty_list seq)) $ [ [[(Sequent (pos:stripnlits))]] | pos <- striplits] else [ [[(Sequent (pos:stripnlits))]] | pos <- striplits] nefPretty d = genfPretty d "[K]" nefFeatureFromSignature sig = K nefFeatureFromFormula phi = K nefStripFeature (K phis) = phis -------------------------------------------------------------------------------- -- instance of sigFeature for K -------------------------------------------------------------------------------- instance (SigFeature b c d, Eq (c d), Eq (b (c d))) => NonEmptySigFeature K b c d where neGoOn sig flag = genericPGoOn sig flag
nevrenato/Hets_Fork
GMP/versioning/gmp-coloss-0.0.3/GMP/Logics/K.hs
gpl-2.0
2,198
0
18
511
441
240
201
-1
-1
{-| hledger - a ledger-compatible accounting tool. Copyright (c) 2007-2011 Simon Michael <simon@joyful.com> Released under GPL version 3 or later. hledger is a partial haskell clone of John Wiegley's "ledger". It generates ledger-compatible register & balance reports from a plain text journal, and demonstrates a functional implementation of ledger. For more information, see http:\/\/hledger.org . This module provides the main function for the hledger command-line executable. It is exposed here so that it can be imported by eg benchmark scripts. You can use the command line: > $ hledger --help or ghci: > $ ghci hledger > > Right j <- readJournalFile definputopts "examples/sample.journal" > > register [] ["income","expenses"] j > 2008/01/01 income income:salary $-1 $-1 > 2008/06/01 gift income:gifts $-1 $-2 > 2008/06/03 eat & shop expenses:food $1 $-1 > expenses:supplies $1 0 > > balance [Depth "1"] [] l > $-1 assets > $2 expenses > $-2 income > $1 liabilities > > j <- defaultJournal etc. -} {-# LANGUAGE LambdaCase #-} module Hledger.Cli.Main where import Data.Char (isDigit) import Data.List import Safe import qualified System.Console.CmdArgs.Explicit as C import System.Environment import System.Exit import System.FilePath import System.Process import Text.Printf import Hledger.Cli import Data.Time.Clock.POSIX (getPOSIXTime) -- | The overall cmdargs mode describing hledger's command-line options and subcommands. mainmode addons = defMode { modeNames = [progname ++ " [CMD]"] ,modeArgs = ([], Just $ argsFlag "[ARGS]") ,modeHelp = unlines ["hledger's main command line interface. Runs builtin commands and other hledger executables. Type \"hledger\" to list available commands."] ,modeGroupModes = Group { -- subcommands in the unnamed group, shown first: groupUnnamed = [ ] -- subcommands in named groups: ,groupNamed = [ ] -- subcommands handled but not shown in the help: ,groupHidden = map fst builtinCommands ++ map addonCommandMode addons } ,modeGroupFlags = Group { -- flags in named groups: groupNamed = [ ( "General input flags", inputflags) ,("\nGeneral reporting flags", reportflags) ,("\nGeneral help flags", helpflags) ] -- flags in the unnamed group, shown last: ,groupUnnamed = [] -- flags handled but not shown in the help: ,groupHidden = [detailedversionflag] -- ++ inputflags -- included here so they'll not raise a confusing error if present with no COMMAND } ,modeHelpSuffix = "Examples:" : map (progname ++) [ " list commands" ," CMD [--] [OPTS] [ARGS] run a command (use -- with addon commands)" ,"-CMD [OPTS] [ARGS] or run addon commands directly" ," -h show general usage" ," CMD -h show command usage" ," help [MANUAL] show any of the hledger manuals in various formats" ] } -- | Let's go! main :: IO () main = do progstarttime <- getPOSIXTime -- Choose and run the appropriate internal or external command based -- on the raw command-line arguments, cmdarg's interpretation of -- same, and hledger-* executables in the user's PATH. A somewhat -- complex mishmash of cmdargs and custom processing, hence all the -- debugging support and tests. See also Hledger.Cli.CliOptions and -- command-line.test. -- some preliminary (imperfect) argument parsing to supplement cmdargs args <- getArgs >>= expandArgsAt let args' = moveFlagsAfterCommand $ replaceNumericFlags args isFlag = ("-" `isPrefixOf`) isNonEmptyNonFlag s = not (isFlag s) && not (null s) rawcmd = headDef "" $ takeWhile isNonEmptyNonFlag args' isNullCommand = null rawcmd (argsbeforecmd, argsaftercmd') = break (==rawcmd) args argsaftercmd = drop 1 argsaftercmd' dbgIO :: Show a => String -> a -> IO () dbgIO = ptraceAtIO 8 dbgIO "running" prognameandversion dbgIO "raw args" args dbgIO "raw args rearranged for cmdargs" args' dbgIO "raw command is probably" rawcmd dbgIO "raw args before command" argsbeforecmd dbgIO "raw args after command" argsaftercmd -- Search PATH for add-ons, excluding any that match built-in command names addons' <- hledgerAddons let addons = filter (not . (`elem` builtinCommandNames) . dropExtension) addons' -- parse arguments with cmdargs opts' <- argsToCliOpts args addons let opts = opts'{progstarttime_=progstarttime} -- select an action and run it. let cmd = command_ opts -- the full matched internal or external command name, if any isInternalCommand = cmd `elem` builtinCommandNames -- not (null cmd) && not (cmd `elem` addons) isExternalCommand = not (null cmd) && cmd `elem` addons -- probably isBadCommand = not (null rawcmd) && null cmd hasVersion = ("--version" `elem`) printUsage = putStr $ showModeUsage $ mainmode addons badCommandError = error' ("command "++rawcmd++" is not recognized, run with no command to see a list") >> exitFailure -- PARTIAL: hasHelpFlag args = any (`elem` args) ["-h","--help"] hasManFlag args = any (`elem` args) ["--man"] hasInfoFlag args = any (`elem` args) ["--info"] f `orShowHelp` mode | hasHelpFlag args = putStr $ showModeUsage mode | hasInfoFlag args = runInfoForTopic "hledger" (headMay $ modeNames mode) | hasManFlag args = runManForTopic "hledger" (headMay $ modeNames mode) | otherwise = f -- where -- lastdocflag dbgIO "processed opts" opts dbgIO "command matched" cmd dbgIO "isNullCommand" isNullCommand dbgIO "isInternalCommand" isInternalCommand dbgIO "isExternalCommand" isExternalCommand dbgIO "isBadCommand" isBadCommand dbgIO "period from opts" (period_ . _rsReportOpts $ reportspec_ opts) dbgIO "interval from opts" (interval_ . _rsReportOpts $ reportspec_ opts) dbgIO "query from opts & args" (_rsQuery $ reportspec_ opts) let journallesserror = error $ cmd++" tried to read the journal but is not supposed to" runHledgerCommand -- high priority flags and situations. -h, then --help, then --info are highest priority. | isNullCommand && hasHelpFlag args = dbgIO "" "-h/--help with no command, showing general help" >> printUsage | isNullCommand && hasInfoFlag args = dbgIO "" "--info with no command, showing general info manual" >> runInfoForTopic "hledger" Nothing | isNullCommand && hasManFlag args = dbgIO "" "--man with no command, showing general man page" >> runManForTopic "hledger" Nothing | not (isExternalCommand || hasHelpFlag args || hasInfoFlag args || hasManFlag args) && (hasVersion args) -- || (hasVersion argsaftercmd && isInternalCommand)) = putStrLn prognameandversion -- \| (null externalcmd) && "binary-filename" `inRawOpts` rawopts = putStrLn $ binaryfilename progname -- \| "--browse-args" `elem` args = System.Console.CmdArgs.Helper.execute "cmdargs-browser" mainmode' args >>= (putStr . show) | isNullCommand = dbgIO "" "no command, showing commands list" >> printCommandsList prognameandversion addons | isBadCommand = badCommandError -- builtin commands | Just (cmdmode, cmdaction) <- findCommand cmd = (case True of -- these commands should not require or read the journal _ | cmd `elem` ["test","help"] -> cmdaction opts journallesserror -- these commands should create the journal if missing _ | cmd `elem` ["add","import"] -> do ensureJournalFileExists . head =<< journalFilePathFromOpts opts withJournalDo opts (cmdaction opts) -- other commands read the journal and should fail if it's missing _ -> withJournalDo opts (cmdaction opts) ) `orShowHelp` cmdmode -- addon commands | isExternalCommand = do let externalargs = argsbeforecmd ++ filter (/="--") argsaftercmd let shellcmd = printf "%s-%s %s" progname cmd (unwords' externalargs) :: String dbgIO "external command selected" cmd dbgIO "external command arguments" (map quoteIfNeeded externalargs) dbgIO "running shell command" shellcmd system shellcmd >>= exitWith -- deprecated commands -- cmd == "convert" = error' (modeHelp oldconvertmode) >> exitFailure -- shouldn't reach here | otherwise = usageError ("could not understand the arguments "++show args) >> exitFailure runHledgerCommand -- | Parse hledger CLI options from these command line arguments and -- add-on command names, or raise any error. argsToCliOpts :: [String] -> [String] -> IO CliOpts argsToCliOpts args addons = do let args' = moveFlagsAfterCommand $ replaceNumericFlags args cmdargsopts = either usageError id $ C.process (mainmode addons) args' rawOptsToCliOpts cmdargsopts -- | A hacky workaround for cmdargs not accepting flags before the -- subcommand name: try to detect and move such flags after the -- command. This allows the user to put them in either position. -- The order of options is not preserved, but this should be ok. -- -- Since we're not parsing flags as precisely as cmdargs here, this is -- imperfect. We make a decent effort to: -- - move all no-argument help/input/report flags -- - move all required-argument help/input/report flags along with their values, space-separated or not -- - not confuse things further or cause misleading errors. moveFlagsAfterCommand :: [String] -> [String] moveFlagsAfterCommand args = moveArgs $ ensureDebugHasArg args where -- quickly! make sure --debug has a numeric argument, or this all goes to hell ensureDebugHasArg as = case break (=="--debug") as of (bs,"--debug":c:cs) | null c || not (all isDigit c) -> bs++"--debug=1":c:cs (bs,["--debug"]) -> bs++["--debug=1"] _ -> as moveArgs args = insertFlagsAfterCommand $ moveArgs' (args, []) where -- -f FILE ..., --alias ALIAS ... moveArgs' ((f:v:a:as), flags) | isMovableReqArgFlag f, isValue v = moveArgs' (a:as, flags ++ [f,v]) -- -fFILE ..., --alias=ALIAS ... moveArgs' ((fv:a:as), flags) | isMovableArgFlagAndValue fv = moveArgs' (a:as, flags ++ [fv]) -- -f(missing arg) moveArgs' ((f:a:as), flags) | isMovableReqArgFlag f, not (isValue a) = moveArgs' (a:as, flags ++ [f]) -- -h ..., --version ... moveArgs' ((f:a:as), flags) | isMovableNoArgFlag f = moveArgs' (a:as, flags ++ [f]) -- anything else moveArgs' (as, flags) = (as, flags) insertFlagsAfterCommand ([], flags) = flags insertFlagsAfterCommand (command:args, flags) = [command] ++ flags ++ args isMovableNoArgFlag a = "-" `isPrefixOf` a && dropWhile (=='-') a `elem` optargflagstomove ++ noargflagstomove isMovableReqArgFlag a = "-" `isPrefixOf` a && dropWhile (=='-') a `elem` reqargflagstomove isMovableArgFlagAndValue ('-':'-':a:as) = case break (== '=') (a:as) of (f:fs,_:_) -> (f:fs) `elem` optargflagstomove ++ reqargflagstomove _ -> False isMovableArgFlagAndValue ('-':shortflag:_:_) = [shortflag] `elem` reqargflagstomove isMovableArgFlagAndValue _ = False isValue "-" = True isValue ('-':_) = False isValue _ = True flagstomove = inputflags ++ reportflags ++ helpflags noargflagstomove = concatMap flagNames $ filter ((==FlagNone).flagInfo) flagstomove reqargflagstomove = -- filter (/= "debug") $ concatMap flagNames $ filter ((==FlagReq ).flagInfo) flagstomove optargflagstomove = concatMap flagNames $ filter (isFlagOpt .flagInfo) flagstomove where isFlagOpt = \case FlagOpt _ -> True FlagOptRare _ -> True _ -> False
simonmichael/hledger
hledger/Hledger/Cli/Main.hs
gpl-3.0
12,387
1
21
3,192
2,364
1,240
1,124
154
8
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ar-SA"> <title>Replacer | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/replacer/src/main/javahelp/org/zaproxy/zap/extension/replacer/resources/help_ar_SA/helpset_ar_SA.hs
apache-2.0
970
80
66
159
413
209
204
-1
-1
{-# LANGUAGE QuasiQuotes , DeriveDataTypeable , ScopedTypeVariables , MultiParamTypeClasses , FlexibleInstances , UndecidableInstances #-} {- ** ********************************************************************* * * * (c) Kathleen Fisher <kathleen.fisher@gmail.com> * * John Launchbury <john.launchbury@gmail.com> * * * ************************************************************************ -} module Language.Pads.BaseTypes where import Language.Pads.Source import Language.Pads.Errors import Language.Pads.Generic import Language.Pads.MetaData import Language.Pads.CoreBaseTypes import Language.Pads.Quote import Language.Pads.RegExp import Language.Pads.LazyList {- Libraries to support specific base types -} import Data.Time import System.Locale import Text.PrettyPrint.Mainland (Pretty, ppr, text) import Data.Data (Typeable, Data) import qualified Data.Char as C import qualified Data.List as L import qualified Data.ByteString as B [pads| type Line a = (a, EOR) type StringLn = [Char] terminator (Try EOR) type StringLnP (p :: String -> Bool) = constrain s :: StringLn where <| p s |> type StringESCLn (p :: (Char, [Char])) = StringPESC <|(True, p)|> type StringESC (p :: (Char, [Char])) = StringPESC <|(False, p)|> data PMaybe a = PJust a | PNothing Void obtain Maybe a from PMaybe a using <|(pm2m,m2pm)|> |] pm2m :: Pos -> (PMaybe a, md) -> (Maybe a, md) pm2m p (PJust x, md) = (Just x, md) pm2m p (PNothing,md) = (Nothing,md) m2pm :: (Maybe a, Maybe_md a) -> (PMaybe a, PMaybe_md a) m2pm (Just x, md) = (PJust x, md) m2pm (Nothing,md) = (PNothing,md) [pads| type Lit (x::String) = (Void, x) type LitRE (x::RE) = (Void, x) |] [pads| obtain Bool from Bytes 1 using <|(bTobl,blTob)|> |] bTobl p (bytes,md) = (fromIntegral (bytes `B.index` 0)==1, md) blTob (b,md) = (B.singleton (if b then 1 else 0), md) [pads| type DateFSE (fmt :: String, se :: RE) = obtain UTCTime from StringSE se using <| (strToUTC fmt, utcToStr fmt) |> type DateFC (fmt::String, c::Char) = DateFSE <|(fmt, RE ("[" ++ [c] ++ "]")) |> |] type UTCTime_md = Base_md instance Pretty UTCTime where ppr utc = text (show utc) strToUTC :: String -> Pos -> (StringSE, Base_md) -> (UTCTime, Base_md) strToUTC fmt pos (input, input_bmd) = case parseTime defaultTimeLocale fmt input of Nothing -> (gdef, mergeBaseMDs [errPD, input_bmd]) Just t -> (t, input_bmd) where errPD = mkErrBasePD (TransformToDstFail "DateFSE" input " (conversion failed)") (Just pos) utcToStr :: String -> (UTCTime, Base_md) -> (StringSE, Base_md) utcToStr fmt (utcTime, bmd) = (formatTime defaultTimeLocale fmt utcTime, bmd) [pads| type TimeZoneSE (se :: RE) = obtain TimeZone from StringSE se using <| (strToTz, tzToStr) |> type TimeZoneC (c::Char) = TimeZoneSE <|RE ("[" ++ [c] ++ "]") |> |] type TimeZone_md = Base_md instance Pretty TimeZone where ppr tz = text (show tz) strToTz :: Pos -> (StringSE, Base_md) -> (TimeZone, Base_md) strToTz pos (input, input_bmd) = case parseTime defaultTimeLocale "%z" input of Nothing -> (gdef, mergeBaseMDs [mkErrBasePD (TransformToDstFail "TimeZoneSE" input " (conversion failed)") (Just pos), input_bmd]) Just t -> (t, input_bmd) tzToStr :: (TimeZone, Base_md) -> (StringSE, Base_md) tzToStr (tz, bmd) = (h ++ ":" ++ m, bmd) where (h,m) = splitAt 3 (show tz) [pads| type Phex32FW (size :: Int) = obtain Int from StringFW size using <| (hexStr2Int,int2HexStr size) |> |] hexStr2Int :: Pos -> (StringFW, Base_md) -> (Int, Base_md) hexStr2Int src_pos (s,md) = if good then (intList2Int ints 0, md) else (0, mkErrBasePD (TransformToDstFail "StrHex" s " (non-hex digit)") (Just src_pos)) where hc2int c = if C.isHexDigit c then (C.digitToInt c,True) else (0,False) (ints,bools) = unzip (map hc2int s) good = (L.and bools) && (length ints > 0) intList2Int digits a = case digits of [] -> a (d:ds) -> intList2Int ds ((16 * a) + d) int2HexStr :: Int -> (Int, Base_md) -> (StringFW, Base_md) int2HexStr size (x,md) | length result == size && wasPos = (result, md) | not wasPos = (Prelude.take size result, mkErrBasePD (TransformToSrcFail "StrHex" (show x) (" (Expected positive number)")) Nothing) | otherwise = (Prelude.take size result, mkErrBasePD (TransformToSrcFail "StrHex" (show x) (" (too big to fit in "++ (show size) ++" characters)")) Nothing) where cvt rest a = if rest < 16 then {- reverse $ -} (C.intToDigit rest) : a else cvt (rest `div` 16) (C.intToDigit (rest `mod` 16) : a) (wasPos,x') = if x < 0 then (False, -x) else (True, x) temp = cvt x' [] padding = size - (length temp) stutter c n = if n <= 0 then [] else c : (stutter c (n-1)) result = (stutter '0' padding) ++ temp
GaloisInc/pads-haskell
Language/Pads/BaseTypes.hs
bsd-3-clause
5,149
0
14
1,278
1,422
798
624
81
4
import Database.HaskellDB.HSQL.SQLite import RunTests opts = [("filepath","hsql-sqlite-test.db"),("mode","rw")] main = dbTestMain $ Conn { dbLabel = "hsql-sqlite", dbConn = connect driver opts }
m4dc4p/haskelldb
test/test-hsql-sqlite.hs
bsd-3-clause
277
0
8
104
62
38
24
6
1
{-# LANGUAGE DeriveFunctor #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Tar -- Copyright : (c) 2007 Bjorn Bringert, -- 2008 Andrea Vezzosi, -- 2008-2009 Duncan Coutts -- License : BSD3 -- -- Maintainer : duncan@community.haskell.org -- Portability : portable -- -- Reading, writing and manipulating \"@.tar@\" archive files. -- ----------------------------------------------------------------------------- module Distribution.Client.Tar ( -- * High level \"all in one\" operations createTarGzFile, extractTarGzFile, -- * Converting between internal and external representation read, write, writeEntries, -- * Packing and unpacking files to\/from internal representation pack, unpack, -- * Tar entry and associated types Entry(..), entryPath, EntryContent(..), Ownership(..), FileSize, Permissions, EpochTime, DevMajor, DevMinor, TypeCode, Format(..), buildTreeRefTypeCode, buildTreeSnapshotTypeCode, isBuildTreeRefTypeCode, entrySizeInBlocks, entrySizeInBytes, -- * Constructing simple entry values simpleEntry, fileEntry, directoryEntry, -- * TarPath type TarPath, toTarPath, fromTarPath, -- ** Sequences of tar entries Entries(..), foldrEntries, foldrEntriesM, foldlEntries, unfoldrEntries, mapEntries, filterEntries, filterEntriesM, entriesIndex, ) where import Data.Char (ord) import Data.Int (Int64) import Data.Bits (Bits, shiftL, testBit) import Data.List (foldl') import Data.Monoid (Monoid(..)) import Numeric (readOct, showOct) import Control.Applicative (Applicative(..)) import Control.Monad (MonadPlus(mplus), when, ap, liftM) import Control.Monad.Identity (Identity(..), runIdentity) import Control.Monad.Writer.Lazy (WriterT(..), runWriterT, tell) import qualified Data.Map as Map import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy.Char8 as BS.Char8 import Data.ByteString.Lazy (ByteString) import qualified Codec.Compression.GZip as GZip import qualified Distribution.Client.GZipUtils as GZipUtils import System.FilePath ( (</>) ) import qualified System.FilePath as FilePath.Native import qualified System.FilePath.Windows as FilePath.Windows import qualified System.FilePath.Posix as FilePath.Posix import System.Directory ( getDirectoryContents, doesDirectoryExist , getPermissions, createDirectoryIfMissing, copyFile ) import qualified System.Directory as Permissions ( Permissions(executable) ) import Distribution.Client.Compat.FilePerms ( setFileExecutable ) import System.Posix.Types ( FileMode ) import Distribution.Client.Compat.Time ( EpochTime, getModTime ) import System.IO ( IOMode(ReadMode), openBinaryFile, hFileSize ) import System.IO.Unsafe (unsafeInterleaveIO) import Prelude hiding (read) -- -- * High level operations -- createTarGzFile :: FilePath -- ^ Full Tarball path -> FilePath -- ^ Base directory -> FilePath -- ^ Directory to archive, relative to base dir -> IO () createTarGzFile tar base dir = BS.writeFile tar . GZip.compress . write =<< pack base [dir] extractTarGzFile :: FilePath -- ^ Destination directory -> FilePath -- ^ Expected subdir (to check for tarbombs) -> FilePath -- ^ Tarball -> IO () extractTarGzFile dir expected tar = unpack dir . checkTarbomb expected . read . GZipUtils.maybeDecompress =<< BS.readFile tar -- -- * Entry type -- type FileSize = Int64 type DevMajor = Int type DevMinor = Int type TypeCode = Char type Permissions = FileMode -- | Tar archive entry. -- data Entry = Entry { -- | The path of the file or directory within the archive. This is in a -- tar-specific form. Use 'entryPath' to get a native 'FilePath'. entryTarPath :: !TarPath, -- | The real content of the entry. For 'NormalFile' this includes the -- file data. An entry usually contains a 'NormalFile' or a 'Directory'. entryContent :: !EntryContent, -- | File permissions (Unix style file mode). entryPermissions :: !Permissions, -- | The user and group to which this file belongs. entryOwnership :: !Ownership, -- | The time the file was last modified. entryTime :: !EpochTime, -- | The tar format the archive is using. entryFormat :: !Format } -- | Type code for the local build tree reference entry type. We don't use the -- symbolic link entry type because it allows only 100 ASCII characters for the -- path. buildTreeRefTypeCode :: TypeCode buildTreeRefTypeCode = 'C' -- | Type code for the local build tree snapshot entry type. buildTreeSnapshotTypeCode :: TypeCode buildTreeSnapshotTypeCode = 'S' -- | Is this a type code for a build tree reference? isBuildTreeRefTypeCode :: TypeCode -> Bool isBuildTreeRefTypeCode typeCode | (typeCode == buildTreeRefTypeCode || typeCode == buildTreeSnapshotTypeCode) = True | otherwise = False -- | Native 'FilePath' of the file or directory within the archive. -- entryPath :: Entry -> FilePath entryPath = fromTarPath . entryTarPath -- | Return the size of an entry in bytes. entrySizeInBytes :: Entry -> FileSize entrySizeInBytes = (*512) . fromIntegral . entrySizeInBlocks -- | Return the number of blocks in an entry. entrySizeInBlocks :: Entry -> Int entrySizeInBlocks entry = 1 + case entryContent entry of NormalFile _ size -> bytesToBlocks size OtherEntryType _ _ size -> bytesToBlocks size _ -> 0 where bytesToBlocks s = 1 + ((fromIntegral s - 1) `div` 512) -- | The content of a tar archive entry, which depends on the type of entry. -- -- Portable archives should contain only 'NormalFile' and 'Directory'. -- data EntryContent = NormalFile ByteString !FileSize | Directory | SymbolicLink !LinkTarget | HardLink !LinkTarget | CharacterDevice !DevMajor !DevMinor | BlockDevice !DevMajor !DevMinor | NamedPipe | OtherEntryType !TypeCode ByteString !FileSize data Ownership = Ownership { -- | The owner user name. Should be set to @\"\"@ if unknown. ownerName :: String, -- | The owner group name. Should be set to @\"\"@ if unknown. groupName :: String, -- | Numeric owner user id. Should be set to @0@ if unknown. ownerId :: !Int, -- | Numeric owner group id. Should be set to @0@ if unknown. groupId :: !Int } -- | There have been a number of extensions to the tar file format over the -- years. They all share the basic entry fields and put more meta-data in -- different extended headers. -- data Format = -- | This is the classic Unix V7 tar format. It does not support owner and -- group names, just numeric Ids. It also does not support device numbers. V7Format -- | The \"USTAR\" format is an extension of the classic V7 format. It was -- later standardised by POSIX. It has some restrictions but is the most -- portable format. -- | UstarFormat -- | The GNU tar implementation also extends the classic V7 format, though -- in a slightly different way from the USTAR format. In general for new -- archives the standard USTAR/POSIX should be used. -- | GnuFormat deriving Eq -- | @rw-r--r--@ for normal files ordinaryFilePermissions :: Permissions ordinaryFilePermissions = 0o0644 -- | @rwxr-xr-x@ for executable files executableFilePermissions :: Permissions executableFilePermissions = 0o0755 -- | @rwxr-xr-x@ for directories directoryPermissions :: Permissions directoryPermissions = 0o0755 isExecutable :: Permissions -> Bool isExecutable p = testBit p 0 || testBit p 6 -- user or other executable -- | An 'Entry' with all default values except for the file name and type. It -- uses the portable USTAR/POSIX format (see 'UstarHeader'). -- -- You can use this as a basis and override specific fields, eg: -- -- > (emptyEntry name HardLink) { linkTarget = target } -- simpleEntry :: TarPath -> EntryContent -> Entry simpleEntry tarpath content = Entry { entryTarPath = tarpath, entryContent = content, entryPermissions = case content of Directory -> directoryPermissions _ -> ordinaryFilePermissions, entryOwnership = Ownership "" "" 0 0, entryTime = 0, entryFormat = UstarFormat } -- | A tar 'Entry' for a file. -- -- Entry fields such as file permissions and ownership have default values. -- -- You can use this as a basis and override specific fields. For example if you -- need an executable file you could use: -- -- > (fileEntry name content) { fileMode = executableFileMode } -- fileEntry :: TarPath -> ByteString -> Entry fileEntry name fileContent = simpleEntry name (NormalFile fileContent (BS.length fileContent)) -- | A tar 'Entry' for a directory. -- -- Entry fields such as file permissions and ownership have default values. -- directoryEntry :: TarPath -> Entry directoryEntry name = simpleEntry name Directory -- -- * Tar paths -- -- | The classic tar format allowed just 100 characters for the file name. The -- USTAR format extended this with an extra 155 characters, however it uses a -- complex method of splitting the name between the two sections. -- -- Instead of just putting any overflow into the extended area, it uses the -- extended area as a prefix. The aggravating insane bit however is that the -- prefix (if any) must only contain a directory prefix. That is the split -- between the two areas must be on a directory separator boundary. So there is -- no simple calculation to work out if a file name is too long. Instead we -- have to try to find a valid split that makes the name fit in the two areas. -- -- The rationale presumably was to make it a bit more compatible with old tar -- programs that only understand the classic format. A classic tar would be -- able to extract the file name and possibly some dir prefix, but not the -- full dir prefix. So the files would end up in the wrong place, but that's -- probably better than ending up with the wrong names too. -- -- So it's understandable but rather annoying. -- -- * Tar paths use POSIX format (ie @\'/\'@ directory separators), irrespective -- of the local path conventions. -- -- * The directory separator between the prefix and name is /not/ stored. -- data TarPath = TarPath FilePath -- path name, 100 characters max. FilePath -- path prefix, 155 characters max. deriving (Eq, Ord) -- | Convert a 'TarPath' to a native 'FilePath'. -- -- The native 'FilePath' will use the native directory separator but it is not -- otherwise checked for validity or sanity. In particular: -- -- * The tar path may be invalid as a native path, eg the filename @\"nul\"@ is -- not valid on Windows. -- -- * The tar path may be an absolute path or may contain @\"..\"@ components. -- For security reasons this should not usually be allowed, but it is your -- responsibility to check for these conditions (eg using 'checkSecurity'). -- fromTarPath :: TarPath -> FilePath fromTarPath (TarPath name prefix) = adjustDirectory $ FilePath.Native.joinPath $ FilePath.Posix.splitDirectories prefix ++ FilePath.Posix.splitDirectories name where adjustDirectory | FilePath.Posix.hasTrailingPathSeparator name = FilePath.Native.addTrailingPathSeparator | otherwise = id -- | Convert a native 'FilePath' to a 'TarPath'. -- -- The conversion may fail if the 'FilePath' is too long. See 'TarPath' for a -- description of the problem with splitting long 'FilePath's. -- toTarPath :: Bool -- ^ Is the path for a directory? This is needed because for -- directories a 'TarPath' must always use a trailing @\/@. -> FilePath -> Either String TarPath toTarPath isDir = splitLongPath . addTrailingSep . FilePath.Posix.joinPath . FilePath.Native.splitDirectories where addTrailingSep | isDir = FilePath.Posix.addTrailingPathSeparator | otherwise = id -- | Take a sanitized path, split on directory separators and try to pack it -- into the 155 + 100 tar file name format. -- -- The strategy is this: take the name-directory components in reverse order -- and try to fit as many components into the 100 long name area as possible. -- If all the remaining components fit in the 155 name area then we win. -- splitLongPath :: FilePath -> Either String TarPath splitLongPath path = case packName nameMax (reverse (FilePath.Posix.splitPath path)) of Left err -> Left err Right (name, []) -> Right (TarPath name "") Right (name, first:rest) -> case packName prefixMax remainder of Left err -> Left err Right (_ , _ : _) -> Left "File name too long (cannot split)" Right (prefix, []) -> Right (TarPath name prefix) where -- drop the '/' between the name and prefix: remainder = init first : rest where nameMax, prefixMax :: Int nameMax = 100 prefixMax = 155 packName _ [] = Left "File name empty" packName maxLen (c:cs) | n > maxLen = Left "File name too long" | otherwise = Right (packName' maxLen n [c] cs) where n = length c packName' maxLen n ok (c:cs) | n' <= maxLen = packName' maxLen n' (c:ok) cs where n' = n + length c packName' _ _ ok cs = (FilePath.Posix.joinPath ok, cs) -- | The tar format allows just 100 ASCII characters for the 'SymbolicLink' and -- 'HardLink' entry types. -- newtype LinkTarget = LinkTarget FilePath deriving (Eq, Ord) -- | Convert a tar 'LinkTarget' to a native 'FilePath'. -- fromLinkTarget :: LinkTarget -> FilePath fromLinkTarget (LinkTarget path) = adjustDirectory $ FilePath.Native.joinPath $ FilePath.Posix.splitDirectories path where adjustDirectory | FilePath.Posix.hasTrailingPathSeparator path = FilePath.Native.addTrailingPathSeparator | otherwise = id -- -- * Entries type -- -- | A tar archive is a sequence of entries. data Entries = Next Entry Entries | Done | Fail String unfoldrEntries :: (a -> Either String (Maybe (Entry, a))) -> a -> Entries unfoldrEntries f = unfold where unfold x = case f x of Left err -> Fail err Right Nothing -> Done Right (Just (e, x')) -> Next e (unfold x') foldrEntries :: (Entry -> a -> a) -> a -> (String -> a) -> Entries -> a foldrEntries next done fail' = isoR . foldrEntriesM (isoL .: next) (isoL done) (isoL . fail') where isoL :: a -> WriterT () Identity a isoL = return f .: g = \e -> f . g e isoR :: WriterT () Identity a -> a isoR = fst . runIdentity . runWriterT foldlEntries :: (a -> Entry -> a) -> a -> Entries -> Either String a foldlEntries f = fold where fold a (Next e es) = (fold $! f a e) es fold a Done = Right a fold _ (Fail err) = Left err mapEntries :: (Entry -> Entry) -> Entries -> Entries mapEntries f = foldrEntries (Next . f) Done Fail filterEntries :: (Entry -> Bool) -> Entries -> Entries filterEntries p = isoR . filterEntriesM (return . p) filterEntriesM :: (Monad m) => (Entry -> m Bool) -> Entries -> m Entries filterEntriesM p = foldrEntriesM (\entry rest -> do include <- p entry if include then return $ Next entry rest else return rest) (return Done) (return . Fail) foldrEntriesM :: (Monad m) => (Entry -> a -> m a) -> m a -> (String -> m a) -> Entries -> m a foldrEntriesM next done fail' = fold where fold (Next e es) = fold es >>= next e fold Done = done fold (Fail err) = fail' err checkEntries :: (Entry -> Maybe String) -> Entries -> Entries checkEntries checkEntry = foldrEntries (\entry rest -> case checkEntry entry of Nothing -> Next entry rest Just err -> Fail err) Done Fail entriesIndex :: Entries -> Either String (Map.Map TarPath Entry) entriesIndex = foldlEntries (\m e -> Map.insert (entryTarPath e) e m) Map.empty -- -- * Checking -- -- | This function checks a sequence of tar entries for file name security -- problems. It checks that: -- -- * file paths are not absolute -- -- * file paths do not contain any path components that are \"@..@\" -- -- * file names are valid -- -- These checks are from the perspective of the current OS. That means we check -- for \"@C:\blah@\" files on Windows and \"\/blah\" files on Unix. For archive -- entry types 'HardLink' and 'SymbolicLink' the same checks are done for the -- link target. A failure in any entry terminates the sequence of entries with -- an error. -- checkSecurity :: Entries -> Entries checkSecurity = checkEntries checkEntrySecurity checkTarbomb :: FilePath -> Entries -> Entries checkTarbomb expectedTopDir = checkEntries (checkEntryTarbomb expectedTopDir) checkEntrySecurity :: Entry -> Maybe String checkEntrySecurity entry = case entryContent entry of HardLink link -> check (entryPath entry) `mplus` check (fromLinkTarget link) SymbolicLink link -> check (entryPath entry) `mplus` check (fromLinkTarget link) _ -> check (entryPath entry) where check name | not (FilePath.Native.isRelative name) = Just $ "Absolute file name in tar archive: " ++ show name | not (FilePath.Native.isValid name) = Just $ "Invalid file name in tar archive: " ++ show name | ".." `elem` FilePath.Native.splitDirectories name = Just $ "Invalid file name in tar archive: " ++ show name | otherwise = Nothing checkEntryTarbomb :: FilePath -> Entry -> Maybe String checkEntryTarbomb _ entry | nonFilesystemEntry = Nothing where -- Ignore some special entries we will not unpack anyway nonFilesystemEntry = case entryContent entry of OtherEntryType 'g' _ _ -> True --PAX global header OtherEntryType 'x' _ _ -> True --PAX individual header _ -> False checkEntryTarbomb expectedTopDir entry = case FilePath.Native.splitDirectories (entryPath entry) of (topDir:_) | topDir == expectedTopDir -> Nothing s -> Just $ "File in tar archive is not in the expected directory. " ++ "Expected: " ++ show expectedTopDir ++ " but got the following hierarchy: " ++ show s -- -- * Reading -- read :: ByteString -> Entries read = unfoldrEntries getEntry getEntry :: ByteString -> Either String (Maybe (Entry, ByteString)) getEntry bs | BS.length header < 512 = Left "truncated tar archive" -- Tar files end with at least two blocks of all '0'. Checking this serves -- two purposes. It checks the format but also forces the tail of the data -- which is necessary to close the file if it came from a lazily read file. | BS.head bs == 0 = case BS.splitAt 1024 bs of (end, trailing) | BS.length end /= 1024 -> Left "short tar trailer" | not (BS.all (== 0) end) -> Left "bad tar trailer" | not (BS.all (== 0) trailing) -> Left "tar file has trailing junk" | otherwise -> Right Nothing | otherwise = partial $ do case (chksum_, format_) of (Ok chksum, _ ) | correctChecksum header chksum -> return () (Ok _, Ok _) -> fail "tar checksum error" _ -> fail "data is not in tar format" -- These fields are partial, have to check them format <- format_; mode <- mode_; uid <- uid_; gid <- gid_; size <- size_; mtime <- mtime_; devmajor <- devmajor_; devminor <- devminor_; let content = BS.take size (BS.drop 512 bs) padding = (512 - size) `mod` 512 bs' = BS.drop (512 + size + padding) bs entry = Entry { entryTarPath = TarPath name prefix, entryContent = case typecode of '\0' -> NormalFile content size '0' -> NormalFile content size '1' -> HardLink (LinkTarget linkname) '2' -> SymbolicLink (LinkTarget linkname) '3' -> CharacterDevice devmajor devminor '4' -> BlockDevice devmajor devminor '5' -> Directory '6' -> NamedPipe '7' -> NormalFile content size _ -> OtherEntryType typecode content size, entryPermissions = mode, entryOwnership = Ownership uname gname uid gid, entryTime = mtime, entryFormat = format } return (Just (entry, bs')) where header = BS.take 512 bs name = getString 0 100 header mode_ = getOct 100 8 header uid_ = getOct 108 8 header gid_ = getOct 116 8 header size_ = getOct 124 12 header mtime_ = getOct 136 12 header chksum_ = getOct 148 8 header typecode = getByte 156 header linkname = getString 157 100 header magic = getChars 257 8 header uname = getString 265 32 header gname = getString 297 32 header devmajor_ = getOct 329 8 header devminor_ = getOct 337 8 header prefix = getString 345 155 header -- trailing = getBytes 500 12 header format_ = case magic of "\0\0\0\0\0\0\0\0" -> return V7Format "ustar\NUL00" -> return UstarFormat "ustar \NUL" -> return GnuFormat _ -> fail "tar entry not in a recognised format" correctChecksum :: ByteString -> Int -> Bool correctChecksum header checksum = checksum == checksum' where -- sum of all 512 bytes in the header block, -- treating each byte as an 8-bit unsigned value checksum' = BS.Char8.foldl' (\x y -> x + ord y) 0 header' -- treating the 8 bytes of chksum as blank characters. header' = BS.concat [BS.take 148 header, BS.Char8.replicate 8 ' ', BS.drop 156 header] -- * TAR format primitive input getOct :: (Integral a, Bits a) => Int64 -> Int64 -> ByteString -> Partial a getOct off len header | BS.head bytes == 128 = parseBinInt (BS.unpack (BS.tail bytes)) | null octstr = return 0 | otherwise = case readOct octstr of [(x,[])] -> return x _ -> fail "tar header is malformed (bad numeric encoding)" where bytes = getBytes off len header octstr = BS.Char8.unpack . BS.Char8.takeWhile (\c -> c /= '\NUL' && c /= ' ') . BS.Char8.dropWhile (== ' ') $ bytes -- Some tar programs switch into a binary format when they try to represent -- field values that will not fit in the required width when using the text -- octal format. In particular, the UID/GID fields can only hold up to 2^21 -- while in the binary format can hold up to 2^32. The binary format uses -- '\128' as the header which leaves 7 bytes. Only the last 4 are used. parseBinInt [0, 0, 0, byte3, byte2, byte1, byte0] = return $! shiftL (fromIntegral byte3) 24 + shiftL (fromIntegral byte2) 16 + shiftL (fromIntegral byte1) 8 + shiftL (fromIntegral byte0) 0 parseBinInt _ = fail "tar header uses non-standard number encoding" getBytes :: Int64 -> Int64 -> ByteString -> ByteString getBytes off len = BS.take len . BS.drop off getByte :: Int64 -> ByteString -> Char getByte off bs = BS.Char8.index bs off getChars :: Int64 -> Int64 -> ByteString -> String getChars off len = BS.Char8.unpack . getBytes off len getString :: Int64 -> Int64 -> ByteString -> String getString off len = BS.Char8.unpack . BS.Char8.takeWhile (/='\0') . getBytes off len data Partial a = Error String | Ok a deriving Functor partial :: Partial a -> Either String a partial (Error msg) = Left msg partial (Ok x) = Right x instance Applicative Partial where pure = return (<*>) = ap instance Monad Partial where return = Ok Error m >>= _ = Error m Ok x >>= k = k x fail = Error -- -- * Writing -- -- | Create the external representation of a tar archive by serialising a list -- of tar entries. -- -- * The conversion is done lazily. -- write :: [Entry] -> ByteString write es = BS.concat $ map putEntry es ++ [BS.replicate (512*2) 0] -- | Same as 'write', but for 'Entries'. writeEntries :: Entries -> ByteString writeEntries entries = BS.concat $ foldrEntries (\e res -> putEntry e : res) [BS.replicate (512*2) 0] error entries putEntry :: Entry -> ByteString putEntry entry = case entryContent entry of NormalFile content size -> BS.concat [ header, content, padding size ] OtherEntryType _ content size -> BS.concat [ header, content, padding size ] _ -> header where header = putHeader entry padding size = BS.replicate paddingSize 0 where paddingSize = fromIntegral (negate size `mod` 512) putHeader :: Entry -> ByteString putHeader entry = BS.concat [ BS.take 148 block , BS.Char8.pack $ putOct 7 checksum , BS.Char8.singleton ' ' , BS.drop 156 block ] where -- putHeaderNoChkSum returns a String, so we convert it to the final -- representation before calculating the checksum. block = BS.Char8.pack . putHeaderNoChkSum $ entry checksum = BS.Char8.foldl' (\x y -> x + ord y) 0 block putHeaderNoChkSum :: Entry -> String putHeaderNoChkSum Entry { entryTarPath = TarPath name prefix, entryContent = content, entryPermissions = permissions, entryOwnership = ownership, entryTime = modTime, entryFormat = format } = concat [ putString 100 $ name , putOct 8 $ permissions , putOct 8 $ ownerId ownership , putOct 8 $ groupId ownership , putOct 12 $ contentSize , putOct 12 $ modTime , fill 8 $ ' ' -- dummy checksum , putChar8 $ typeCode , putString 100 $ linkTarget ] ++ case format of V7Format -> fill 255 '\NUL' UstarFormat -> concat [ putString 8 $ "ustar\NUL00" , putString 32 $ ownerName ownership , putString 32 $ groupName ownership , putOct 8 $ deviceMajor , putOct 8 $ deviceMinor , putString 155 $ prefix , fill 12 $ '\NUL' ] GnuFormat -> concat [ putString 8 $ "ustar \NUL" , putString 32 $ ownerName ownership , putString 32 $ groupName ownership , putGnuDev 8 $ deviceMajor , putGnuDev 8 $ deviceMinor , putString 155 $ prefix , fill 12 $ '\NUL' ] where (typeCode, contentSize, linkTarget, deviceMajor, deviceMinor) = case content of NormalFile _ size -> ('0' , size, [], 0, 0) Directory -> ('5' , 0, [], 0, 0) SymbolicLink (LinkTarget link) -> ('2' , 0, link, 0, 0) HardLink (LinkTarget link) -> ('1' , 0, link, 0, 0) CharacterDevice major minor -> ('3' , 0, [], major, minor) BlockDevice major minor -> ('4' , 0, [], major, minor) NamedPipe -> ('6' , 0, [], 0, 0) OtherEntryType code _ size -> (code, size, [], 0, 0) putGnuDev w n = case content of CharacterDevice _ _ -> putOct w n BlockDevice _ _ -> putOct w n _ -> replicate w '\NUL' -- * TAR format primitive output type FieldWidth = Int putString :: FieldWidth -> String -> String putString n s = take n s ++ fill (n - length s) '\NUL' --TODO: check integer widths, eg for large file sizes putOct :: (Show a, Integral a) => FieldWidth -> a -> String putOct n x = let octStr = take (n-1) $ showOct x "" in fill (n - length octStr - 1) '0' ++ octStr ++ putChar8 '\NUL' putChar8 :: Char -> String putChar8 c = [c] fill :: FieldWidth -> Char -> String fill n c = replicate n c -- -- * Unpacking -- unpack :: FilePath -> Entries -> IO () unpack baseDir entries = unpackEntries [] (checkSecurity entries) >>= emulateLinks where -- We're relying here on 'checkSecurity' to make sure we're not scribbling -- files all over the place. unpackEntries _ (Fail err) = fail err unpackEntries links Done = return links unpackEntries links (Next entry es) = case entryContent entry of NormalFile file _ -> extractFile entry path file >> unpackEntries links es Directory -> extractDir path >> unpackEntries links es HardLink link -> (unpackEntries $! saveLink path link links) es SymbolicLink link -> (unpackEntries $! saveLink path link links) es _ -> unpackEntries links es --ignore other file types where path = entryPath entry extractFile entry path content = do -- Note that tar archives do not make sure each directory is created -- before files they contain, indeed we may have to create several -- levels of directory. createDirectoryIfMissing True absDir BS.writeFile absPath content when (isExecutable (entryPermissions entry)) (setFileExecutable absPath) where absDir = baseDir </> FilePath.Native.takeDirectory path absPath = baseDir </> path extractDir path = createDirectoryIfMissing True (baseDir </> path) saveLink path link links = seq (length path) $ seq (length link') $ (path, link'):links where link' = fromLinkTarget link emulateLinks = mapM_ $ \(relPath, relLinkTarget) -> let absPath = baseDir </> relPath absTarget = FilePath.Native.takeDirectory absPath </> relLinkTarget in copyFile absTarget absPath -- -- * Packing -- pack :: FilePath -- ^ Base directory -> [FilePath] -- ^ Files and directories to pack, relative to the base dir -> IO [Entry] pack baseDir paths0 = preparePaths baseDir paths0 >>= packPaths baseDir preparePaths :: FilePath -> [FilePath] -> IO [FilePath] preparePaths baseDir paths = fmap concat $ interleave [ do isDir <- doesDirectoryExist (baseDir </> path) if isDir then do entries <- getDirectoryContentsRecursive (baseDir </> path) return (FilePath.Native.addTrailingPathSeparator path : map (path </>) entries) else return [path] | path <- paths ] packPaths :: FilePath -> [FilePath] -> IO [Entry] packPaths baseDir paths = interleave [ do tarpath <- either fail return (toTarPath isDir relpath) if isDir then packDirectoryEntry filepath tarpath else packFileEntry filepath tarpath | relpath <- paths , let isDir = FilePath.Native.hasTrailingPathSeparator filepath filepath = baseDir </> relpath ] interleave :: [IO a] -> IO [a] interleave = unsafeInterleaveIO . go where go [] = return [] go (x:xs) = do x' <- x xs' <- interleave xs return (x':xs') packFileEntry :: FilePath -- ^ Full path to find the file on the local disk -> TarPath -- ^ Path to use for the tar Entry in the archive -> IO Entry packFileEntry filepath tarpath = do mtime <- getModTime filepath perms <- getPermissions filepath file <- openBinaryFile filepath ReadMode size <- hFileSize file content <- BS.hGetContents file return (simpleEntry tarpath (NormalFile content (fromIntegral size))) { entryPermissions = if Permissions.executable perms then executableFilePermissions else ordinaryFilePermissions, entryTime = mtime } packDirectoryEntry :: FilePath -- ^ Full path to find the file on the local disk -> TarPath -- ^ Path to use for the tar Entry in the archive -> IO Entry packDirectoryEntry filepath tarpath = do mtime <- getModTime filepath return (directoryEntry tarpath) { entryTime = mtime } getDirectoryContentsRecursive :: FilePath -> IO [FilePath] getDirectoryContentsRecursive dir0 = fmap tail (recurseDirectories dir0 [""]) recurseDirectories :: FilePath -> [FilePath] -> IO [FilePath] recurseDirectories _ [] = return [] recurseDirectories base (dir:dirs) = unsafeInterleaveIO $ do (files, dirs') <- collect [] [] =<< getDirectoryContents (base </> dir) files' <- recurseDirectories base (dirs' ++ dirs) return (dir : files ++ files') where collect files dirs' [] = return (reverse files, reverse dirs') collect files dirs' (entry:entries) | ignore entry = collect files dirs' entries collect files dirs' (entry:entries) = do let dirEntry = dir </> entry dirEntry' = FilePath.Native.addTrailingPathSeparator dirEntry isDirectory <- doesDirectoryExist (base </> dirEntry) if isDirectory then collect files (dirEntry':dirs') entries else collect (dirEntry:files) dirs' entries ignore ['.'] = True ignore ['.', '.'] = True ignore _ = False
randen/cabal
cabal-install/Distribution/Client/Tar.hs
bsd-3-clause
33,979
0
19
9,362
7,564
4,020
3,544
623
15
{-# 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.RDS.AuthorizeDBSecurityGroupIngress -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Enables ingress to a DBSecurityGroup using one of two forms of -- authorization. First, EC2 or VPC security groups can be added to the -- DBSecurityGroup if the application using the database is running on EC2 or -- VPC instances. Second, IP ranges are available if the application accessing -- your database is running on the Internet. Required parameters for this API -- are one of CIDR range, EC2SecurityGroupId for VPC, or -- (EC2SecurityGroupOwnerId and either EC2SecurityGroupName or -- EC2SecurityGroupId for non-VPC). -- -- You cannot authorize ingress from an EC2 security group in one Region to an -- Amazon RDS DB instance in another. You cannot authorize ingress from a VPC -- security group in one VPC to an Amazon RDS DB instance in another. For an -- overview of CIDR ranges, go to the <http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing Wikipedia Tutorial>. -- -- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_AuthorizeDBSecurityGroupIngress.html> module Network.AWS.RDS.AuthorizeDBSecurityGroupIngress ( -- * Request AuthorizeDBSecurityGroupIngress -- ** Request constructor , authorizeDBSecurityGroupIngress -- ** Request lenses , adbsgiCIDRIP , adbsgiDBSecurityGroupName , adbsgiEC2SecurityGroupId , adbsgiEC2SecurityGroupName , adbsgiEC2SecurityGroupOwnerId -- * Response , AuthorizeDBSecurityGroupIngressResponse -- ** Response constructor , authorizeDBSecurityGroupIngressResponse -- ** Response lenses , adbsgirDBSecurityGroup ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.RDS.Types import qualified GHC.Exts data AuthorizeDBSecurityGroupIngress = AuthorizeDBSecurityGroupIngress { _adbsgiCIDRIP :: Maybe Text , _adbsgiDBSecurityGroupName :: Text , _adbsgiEC2SecurityGroupId :: Maybe Text , _adbsgiEC2SecurityGroupName :: Maybe Text , _adbsgiEC2SecurityGroupOwnerId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'AuthorizeDBSecurityGroupIngress' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'adbsgiCIDRIP' @::@ 'Maybe' 'Text' -- -- * 'adbsgiDBSecurityGroupName' @::@ 'Text' -- -- * 'adbsgiEC2SecurityGroupId' @::@ 'Maybe' 'Text' -- -- * 'adbsgiEC2SecurityGroupName' @::@ 'Maybe' 'Text' -- -- * 'adbsgiEC2SecurityGroupOwnerId' @::@ 'Maybe' 'Text' -- authorizeDBSecurityGroupIngress :: Text -- ^ 'adbsgiDBSecurityGroupName' -> AuthorizeDBSecurityGroupIngress authorizeDBSecurityGroupIngress p1 = AuthorizeDBSecurityGroupIngress { _adbsgiDBSecurityGroupName = p1 , _adbsgiCIDRIP = Nothing , _adbsgiEC2SecurityGroupName = Nothing , _adbsgiEC2SecurityGroupId = Nothing , _adbsgiEC2SecurityGroupOwnerId = Nothing } -- | The IP range to authorize. adbsgiCIDRIP :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adbsgiCIDRIP = lens _adbsgiCIDRIP (\s a -> s { _adbsgiCIDRIP = a }) -- | The name of the DB security group to add authorization to. adbsgiDBSecurityGroupName :: Lens' AuthorizeDBSecurityGroupIngress Text adbsgiDBSecurityGroupName = lens _adbsgiDBSecurityGroupName (\s a -> s { _adbsgiDBSecurityGroupName = a }) -- | Id of the EC2 security group to authorize. For VPC DB security groups, 'EC2SecurityGroupId' must be provided. Otherwise, EC2SecurityGroupOwnerId and either 'EC2SecurityGroupName' or 'EC2SecurityGroupId' must be provided. adbsgiEC2SecurityGroupId :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adbsgiEC2SecurityGroupId = lens _adbsgiEC2SecurityGroupId (\s a -> s { _adbsgiEC2SecurityGroupId = a }) -- | Name of the EC2 security group to authorize. For VPC DB security groups, 'EC2SecurityGroupId' must be provided. Otherwise, EC2SecurityGroupOwnerId and either 'EC2SecurityGroupName' or 'EC2SecurityGroupId' must be provided. adbsgiEC2SecurityGroupName :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adbsgiEC2SecurityGroupName = lens _adbsgiEC2SecurityGroupName (\s a -> s { _adbsgiEC2SecurityGroupName = a }) -- | AWS Account Number of the owner of the EC2 security group specified in the -- EC2SecurityGroupName parameter. The AWS Access Key ID is not an acceptable -- value. For VPC DB security groups, 'EC2SecurityGroupId' must be provided. -- Otherwise, EC2SecurityGroupOwnerId and either 'EC2SecurityGroupName' or 'EC2SecurityGroupId' must be provided. adbsgiEC2SecurityGroupOwnerId :: Lens' AuthorizeDBSecurityGroupIngress (Maybe Text) adbsgiEC2SecurityGroupOwnerId = lens _adbsgiEC2SecurityGroupOwnerId (\s a -> s { _adbsgiEC2SecurityGroupOwnerId = a }) newtype AuthorizeDBSecurityGroupIngressResponse = AuthorizeDBSecurityGroupIngressResponse { _adbsgirDBSecurityGroup :: Maybe DBSecurityGroup } deriving (Eq, Read, Show) -- | 'AuthorizeDBSecurityGroupIngressResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'adbsgirDBSecurityGroup' @::@ 'Maybe' 'DBSecurityGroup' -- authorizeDBSecurityGroupIngressResponse :: AuthorizeDBSecurityGroupIngressResponse authorizeDBSecurityGroupIngressResponse = AuthorizeDBSecurityGroupIngressResponse { _adbsgirDBSecurityGroup = Nothing } adbsgirDBSecurityGroup :: Lens' AuthorizeDBSecurityGroupIngressResponse (Maybe DBSecurityGroup) adbsgirDBSecurityGroup = lens _adbsgirDBSecurityGroup (\s a -> s { _adbsgirDBSecurityGroup = a }) instance ToPath AuthorizeDBSecurityGroupIngress where toPath = const "/" instance ToQuery AuthorizeDBSecurityGroupIngress where toQuery AuthorizeDBSecurityGroupIngress{..} = mconcat [ "CIDRIP" =? _adbsgiCIDRIP , "DBSecurityGroupName" =? _adbsgiDBSecurityGroupName , "EC2SecurityGroupId" =? _adbsgiEC2SecurityGroupId , "EC2SecurityGroupName" =? _adbsgiEC2SecurityGroupName , "EC2SecurityGroupOwnerId" =? _adbsgiEC2SecurityGroupOwnerId ] instance ToHeaders AuthorizeDBSecurityGroupIngress instance AWSRequest AuthorizeDBSecurityGroupIngress where type Sv AuthorizeDBSecurityGroupIngress = RDS type Rs AuthorizeDBSecurityGroupIngress = AuthorizeDBSecurityGroupIngressResponse request = post "AuthorizeDBSecurityGroupIngress" response = xmlResponse instance FromXML AuthorizeDBSecurityGroupIngressResponse where parseXML = withElement "AuthorizeDBSecurityGroupIngressResult" $ \x -> AuthorizeDBSecurityGroupIngressResponse <$> x .@? "DBSecurityGroup"
kim/amazonka
amazonka-rds/gen/Network/AWS/RDS/AuthorizeDBSecurityGroupIngress.hs
mpl-2.0
7,600
0
9
1,377
718
436
282
86
1
{-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.Eval -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- This module doesn't contains actual eval, see -- 'Yi.Keymap.Vim.vimEval' comment. module Yi.Keymap.Vim.Eval (scheduleActionStringForEval) where import Yi.Editor (EditorM) import Yi.Keymap.Vim.Common (EventString, VimState (vsStringToEval)) import Yi.Keymap.Vim.StateUtils (modifyStateE) scheduleActionStringForEval :: EventString -> EditorM () scheduleActionStringForEval s = modifyStateE $ \st -> st { vsStringToEval = s }
Hi-Angel/yi
yi-keymap-vim/src/Yi/Keymap/Vim/Eval.hs
gpl-2.0
661
0
8
112
103
67
36
7
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="pt-BR"> <title>Complemento de Navegação Forçada</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Conteúdo</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Índice</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Localizar</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoritos</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/bruteforce/src/main/javahelp/org/zaproxy/zap/extension/bruteforce/resources/help_pt_BR/helpset_pt_BR.hs
apache-2.0
986
77
66
158
420
212
208
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sq-AL"> <title>Token Generator | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/tokengen/src/main/javahelp/org/zaproxy/zap/extension/tokengen/resources/help_sq_AL/helpset_sq_AL.hs
apache-2.0
976
78
66
159
413
209
204
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="da-DK"> <title>Active Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Søg</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/ascanrules/src/main/javahelp/org/zaproxy/zap/extension/ascanrules/resources/help_da_DK/helpset_da_DK.hs
apache-2.0
976
78
66
160
418
211
207
-1
-1
{-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables #-} -- -- (c) The University of Glasgow 2002-2006 -- -- Serialized values module Serialized ( -- * Main Serialized data type Serialized, seqSerialized, -- * Going into and out of 'Serialized' toSerialized, fromSerialized, -- * Handy serialization functions serializeWithData, deserializeWithData, ) where import Binary import Outputable import FastString import Util import Data.Bits import Data.Word ( Word8 ) import Data.Data -- | Represents a serialized value of a particular type. Attempts can be made to deserialize it at certain types data Serialized = Serialized TypeRep [Word8] instance Outputable Serialized where ppr (Serialized the_type bytes) = int (length bytes) <+> ptext (sLit "of type") <+> text (show the_type) instance Binary Serialized where put_ bh (Serialized the_type bytes) = do put_ bh the_type put_ bh bytes get bh = do the_type <- get bh bytes <- get bh return (Serialized the_type bytes) -- | Put a Typeable value that we are able to actually turn into bytes into a 'Serialized' value ready for deserialization later toSerialized :: Typeable a => (a -> [Word8]) -> a -> Serialized toSerialized serialize what = Serialized (typeOf what) (serialize what) -- | If the 'Serialized' value contains something of the given type, then use the specified deserializer to return @Just@ that. -- Otherwise return @Nothing@. fromSerialized :: forall a. Typeable a => ([Word8] -> a) -> Serialized -> Maybe a fromSerialized deserialize (Serialized the_type bytes) | the_type == typeOf (undefined :: a) = Just (deserialize bytes) | otherwise = Nothing -- | Force the contents of the Serialized value so weknow it doesn't contain any bottoms seqSerialized :: Serialized -> () seqSerialized (Serialized the_type bytes) = the_type `seq` bytes `seqList` () -- | Use a 'Data' instance to implement a serialization scheme dual to that of 'deserializeWithData' serializeWithData :: Data a => a -> [Word8] serializeWithData what = serializeWithData' what [] serializeWithData' :: Data a => a -> [Word8] -> [Word8] serializeWithData' what = fst $ gfoldl (\(before, a_to_b) a -> (before . serializeWithData' a, a_to_b a)) (\x -> (serializeConstr (constrRep (toConstr what)), x)) what -- | Use a 'Data' instance to implement a deserialization scheme dual to that of 'serializeWithData' deserializeWithData :: Data a => [Word8] -> a deserializeWithData = snd . deserializeWithData' deserializeWithData' :: forall a. Data a => [Word8] -> ([Word8], a) deserializeWithData' bytes = deserializeConstr bytes $ \constr_rep bytes -> gunfold (\(bytes, b_to_r) -> let (bytes', b) = deserializeWithData' bytes in (bytes', b_to_r b)) (\x -> (bytes, x)) (repConstr (dataTypeOf (undefined :: a)) constr_rep) serializeConstr :: ConstrRep -> [Word8] -> [Word8] serializeConstr (AlgConstr ix) = serializeWord8 1 . serializeInt ix serializeConstr (IntConstr i) = serializeWord8 2 . serializeInteger i serializeConstr (FloatConstr r) = serializeWord8 3 . serializeRational r serializeConstr (CharConstr c) = serializeWord8 4 . serializeChar c deserializeConstr :: [Word8] -> (ConstrRep -> [Word8] -> a) -> a deserializeConstr bytes k = deserializeWord8 bytes $ \constr_ix bytes -> case constr_ix of 1 -> deserializeInt bytes $ \ix -> k (AlgConstr ix) 2 -> deserializeInteger bytes $ \i -> k (IntConstr i) 3 -> deserializeRational bytes $ \r -> k (FloatConstr r) 4 -> deserializeChar bytes $ \c -> k (CharConstr c) x -> error $ "deserializeConstr: unrecognised serialized constructor type " ++ show x ++ " in context " ++ show bytes serializeFixedWidthNum :: forall a. (Integral a, FiniteBits a) => a -> [Word8] -> [Word8] serializeFixedWidthNum what = go (finiteBitSize what) what where go :: Int -> a -> [Word8] -> [Word8] go size current rest | size <= 0 = rest | otherwise = fromIntegral (current .&. 255) : go (size - 8) (current `shiftR` 8) rest deserializeFixedWidthNum :: forall a b. (Integral a, FiniteBits a) => [Word8] -> (a -> [Word8] -> b) -> b deserializeFixedWidthNum bytes k = go (finiteBitSize (undefined :: a)) bytes k where go :: Int -> [Word8] -> (a -> [Word8] -> b) -> b go size bytes k | size <= 0 = k 0 bytes | otherwise = case bytes of (byte:bytes) -> go (size - 8) bytes (\x -> k ((x `shiftL` 8) .|. fromIntegral byte)) [] -> error "deserializeFixedWidthNum: unexpected end of stream" serializeEnum :: (Enum a) => a -> [Word8] -> [Word8] serializeEnum = serializeInt . fromEnum deserializeEnum :: Enum a => [Word8] -> (a -> [Word8] -> b) -> b deserializeEnum bytes k = deserializeInt bytes (k . toEnum) serializeWord8 :: Word8 -> [Word8] -> [Word8] serializeWord8 x = (x:) deserializeWord8 :: [Word8] -> (Word8 -> [Word8] -> a) -> a deserializeWord8 (byte:bytes) k = k byte bytes deserializeWord8 [] _ = error "deserializeWord8: unexpected end of stream" serializeInt :: Int -> [Word8] -> [Word8] serializeInt = serializeFixedWidthNum deserializeInt :: [Word8] -> (Int -> [Word8] -> a) -> a deserializeInt = deserializeFixedWidthNum serializeRational :: (Real a) => a -> [Word8] -> [Word8] serializeRational = serializeString . show . toRational deserializeRational :: (Fractional a) => [Word8] -> (a -> [Word8] -> b) -> b deserializeRational bytes k = deserializeString bytes (k . fromRational . read) serializeInteger :: Integer -> [Word8] -> [Word8] serializeInteger = serializeString . show deserializeInteger :: [Word8] -> (Integer -> [Word8] -> a) -> a deserializeInteger bytes k = deserializeString bytes (k . read) serializeChar :: Char -> [Word8] -> [Word8] serializeChar = serializeString . show deserializeChar :: [Word8] -> (Char -> [Word8] -> a) -> a deserializeChar bytes k = deserializeString bytes (k . read) serializeString :: String -> [Word8] -> [Word8] serializeString = serializeList serializeEnum deserializeString :: [Word8] -> (String -> [Word8] -> a) -> a deserializeString = deserializeList deserializeEnum serializeList :: (a -> [Word8] -> [Word8]) -> [a] -> [Word8] -> [Word8] serializeList serialize_element xs = serializeInt (length xs) . foldr (.) id (map serialize_element xs) deserializeList :: forall a b. (forall c. [Word8] -> (a -> [Word8] -> c) -> c) -> [Word8] -> ([a] -> [Word8] -> b) -> b deserializeList deserialize_element bytes k = deserializeInt bytes $ \len bytes -> go len bytes k where go :: Int -> [Word8] -> ([a] -> [Word8] -> b) -> b go len bytes k | len <= 0 = k [] bytes | otherwise = deserialize_element bytes (\elt bytes -> go (len - 1) bytes (k . (elt:)))
acowley/ghc
compiler/utils/Serialized.hs
bsd-3-clause
7,185
0
18
1,750
2,305
1,224
1,081
110
5
module Typed.Reference ( module M , pattern Tref , pattern Tderef , pattern Tassign , pattern Tloc , pattern Kref , Term(ReferenceTerm) , EvalTerm(RefEvalTerm) ) where import Control.Monad import Control.Monad.Catch import qualified Data.Map as M import qualified Data.Tree as T import Preliminaries import Typed.Simply as M (pattern Tval, pattern Tvar, pattern Tabs, pattern Tapp, pattern Karr) import Typed.SimplyExt as M (pattern Tunit, pattern Kunit) pattern Tref t = T.Node "ref {}" [t] pattern Tderef t = T.Node "!{}" [t] pattern Tassign t1 t2 = T.Node "{} := {}" [t1,t2] pattern Tloc l = Tval l pattern Kref t = T.Node "Ref {}" [t] type Loc = String data TypeOfError = ExpectedType StrTree StrTree deriving Show instance Exception TypeOfError instance Calculus "reference" StrTree StrTree (M.Map Var StrTree, M.Map Loc StrTree) where data Term "reference" StrTree = ReferenceTerm StrTree deriving (Eq, Show) isValue (ReferenceTerm t) = go t where go (Tabs _ _ _) = True go Tunit = True go (Tloc _) = True go _ = False typeof arg (ReferenceTerm t) = go arg t where go (ctx,sto) (Tvar x) = return $ ctx M.! x go (ctx,sto) (Tabs x xt t) = do tT <- go (M.insert x xt ctx,sto) t return $ xt `Karr` tT go (ctx,sto) (Tapp t1 t2) = do go (ctx,sto) t1 >>= \case Karr t1T1 t1T2 -> do _ <- join $ liftM2 (expect ExpectedType) (return t1T1) (go (ctx,sto) t2) return $ t1T2 z -> throwM $ ExpectedType (Karr (Tval "_") (Tval "_")) z go (ctx,sto) Tunit = return Kunit go (ctx,sto) (Tloc l) = return $ Kref $ sto M.! l go (ctx,sto) (Tref t) = Kref <$> go (ctx,sto) t go (ctx,sto) (Tderef t) = do go (ctx,sto) t >>= \case Kref tT -> return tT z -> throwM $ ExpectedType (Kref (Tval "_")) z go (ctx,sto) (Tassign t1 t2) = do go (ctx,sto) t1 >>= \case Kref t1T -> do _ <- join $ liftM2 (expect ExpectedType) (return t1T) (go (ctx,sto) t2) return Kunit z -> throwM $ ExpectedType (Kref (Tval "_")) z instance EvCalculus "reference" StrTree StrTree (M.Map Var StrTree, M.Map Loc StrTree) where data EvalTerm "reference" StrTree = RefEvalTerm StrTree (M.Map Loc StrTree) deriving (Eq, Show) eval1ext = go where go (RefEvalTerm (Tapp (Tabs x xt t1) t2) mu) | isValue (ReferenceTerm t2) = return $ RefEvalTerm (subst x t2 t1) mu go (RefEvalTerm (Tapp t1 t2) mu) | isValue (ReferenceTerm t1) = do RefEvalTerm t2' mu' <- go (RefEvalTerm t2 mu) return $ RefEvalTerm (Tapp t1 t2') mu' go (RefEvalTerm (Tapp t1 t2) mu) = do RefEvalTerm t1' mu' <- go (RefEvalTerm t1 mu) return $ RefEvalTerm (Tapp t1' t2) mu' go (RefEvalTerm (Tref v) mu) | isValue (ReferenceTerm v) = do let loc =(++ "'") $ last $ M.keys mu return $ RefEvalTerm (Tloc loc) (M.insert loc v mu) go (RefEvalTerm (Tref t) mu) = do RefEvalTerm t' mu' <- go (RefEvalTerm t mu) return $ RefEvalTerm (Tref t') mu go (RefEvalTerm (Tderef (Tloc l)) mu) = return $ RefEvalTerm (mu M.! l) mu go (RefEvalTerm (Tderef t) mu) = do RefEvalTerm t' mu' <- go (RefEvalTerm t mu) return $ RefEvalTerm (Tderef t') mu' go (RefEvalTerm (Tassign (Tloc l) v) mu) | isValue (ReferenceTerm v) = return $ RefEvalTerm Tunit (M.insert l v mu) go (RefEvalTerm (Tassign t1 t2) mu) | isValue (ReferenceTerm t1) = do RefEvalTerm t2' mu' <- go (RefEvalTerm t2 mu) return $ RefEvalTerm (Tassign t1 t2') mu go (RefEvalTerm (Tassign t1 t2) mu) = do RefEvalTerm t1' mu' <- go (RefEvalTerm t1 mu) return $ RefEvalTerm (Tassign t1' t2) mu go _ = throwM NoRuleApplies subst v p = go where go (Tvar y) | v == y = p | otherwise = Tvar y go (Tabs y yt t) | v == y = Tabs y yt t | otherwise = Tabs y yt (go t) go (Tapp t1 t2) = Tapp (go t1) (go t2) go Tunit = Tunit go (Tref t) = Tref (go t) go (Tderef t) = Tderef (go t) go (Tassign t1 t2) = Tassign (go t1) (go t2)
myuon/typed
tapl/src/Typed/Reference.hs
mit
4,088
0
21
1,105
1,968
974
994
-1
-1
{-# LANGUAGE BangPatterns #-} module Codec.Picture.Ari.Header.ICI where -- ICI stands for Image Content Information import Data.Binary import Data.Binary.Get import Data.Binary.IEEE754 import Control.Applicative import Control.Monad import qualified Data.ByteString as BS import Codec.Picture.Ari.Types -- -- TODO : color matrix encoding to find out -- |Ari header data structure data AriHeaderICIv8 = AriHeaderICIv8 { ariICIValid :: !Int , ariICIVersion :: !BS.ByteString , ariWhiteBalance :: !Int , ariGreenTintFactor :: !Int , ariWhiteBalanceFactorR:: !Float , ariWhiteBalanceFactorG:: !Float , ariWhiteBalanceFactorB:: !Float , ariWBAppliedInCamera :: !Int , ariExposureIndex :: !Int , ariBlackLevel :: !Float , ariWhiteLevel :: !Float -- Color matrix as a raw bytestring , ariColorMatrix :: !BS.ByteString -- , ariColorMatrix00 :: !Float -- , ariColorMatrix01 :: !Float -- , ariColorMatrix02 :: !Float -- , ariColorMatrix10 :: !Float -- , ariColorMatrix11 :: !Float -- , ariColorMatrix12 :: !Float -- , ariColorMatrix20 :: !Float -- , ariColorMatrix21 :: !Float -- , ariColorMatrix22 :: !Float , ariColorMatrixDesatG :: !Float , ariColorMatrixDesatO :: !Float , ariHLDesatFlag :: !Int , ariTargetColorSpace :: !Int , ariSharpness :: !Int , ariPixelAspectRatio :: !Float , ariFlip :: !Int , ariLookFile :: !AriString , ariLookLutMode :: !Int , ariLookLutOffset :: !Int , ariLookLutSize :: !Int , ariLookLutCRC :: !Int , ariLinearSaturation :: !Int , ariCdlSlopeR :: !Float , ariCdlSlopeG :: !Float , ariCdlSlopeB :: !Float , ariCdlOffsetR :: !Float , ariCdlOffsetG :: !Float , ariCdlOffsetB :: !Float , ariCdlPowerR :: !Float , ariCdlPowerG :: !Float , ariCdlPowerB :: !Float , ariPrinterLights :: !BS.ByteString -- 6 bytes... , ariCdlApplicationMode :: !Int } -- |Print functions instance Show AriHeaderICIv8 where show a = "ICI valid: " ++ show (ariICIValid a) ++ "\nwhite balance: " ++ show (ariWhiteBalance a) ++ "K" ++ "\nwhite balance factors: " ++ show (ariWhiteBalanceFactorR a) ++ " " ++ show (ariWhiteBalanceFactorG a) ++ " " ++ show (ariWhiteBalanceFactorB a) ++ "\nwhite balance applied: " ++ show (ariWBAppliedInCamera a) ++ "\nexposure index: " ++ show (ariExposureIndex a) ++ "\nblack level: " ++ show (ariBlackLevel a) ++ "\nwhite level: " ++ show (ariWhiteLevel a) ++ "\nsharpness: " ++ show (ariSharpness a) -- ++ "\ncolor matrix: " ++ show (ariColorMatrix00 a) -- ++ " " ++ show (ariColorMatrix01 a) ++ " " ++ show (ariColorMatrix02 a) ++ "\npixel aspect ratio: " ++ show (ariPixelAspectRatio a) ++ "\ntarget color space: " ++ show (ariTargetColorSpace a) ++ "\nlook file: " ++ show (ariLookFile a) ++ "\ndesat gain: " ++ show (ariColorMatrixDesatG a) ++ "\ndesat offset: " ++ show (ariColorMatrixDesatO a) ++ "\nflip : " ++ show (ariFlip a) ++ "\nlook mode : " ++ show (ariLookLutMode a) ++ "\nlook offset : " ++ show (ariLookLutOffset a) -- |Binary layout decodeAriHeaderICIv8 :: Get AriHeaderICIv8 decodeAriHeaderICIv8 = AriHeaderICIv8 <$> liftM fromIntegral getWord32le -- ariICIValid Valid 0x0054-0x0057 <*> getByteString 4 -- ariVersion Version 0x0058-0x005B <*> liftM fromIntegral getWord32le -- ariWhiteBalance WhiteBalance 0x005C-0x005F <*> liftM fromIntegral getWord32le -- ariGreenTintFactor GreenTintFactor 0x0060-0x0063 <*> getFloat32le -- ariWhiteBalanceFactorR WB R 0x0064-0x0067 <*> getFloat32le -- ariWhiteBalanceFactorG WB G 0x0068-0x006B <*> getFloat32le -- ariWhiteBalanceFactorB WB B 0x006C-0x006F <*> liftM fromIntegral getWord32le -- ariWBAppliedInCamera WB Applied 0x0070-0x0073 <*> liftM fromIntegral getWord32le -- ariExposureIndex Exposure Index 0x0074-0x0077 <*> getFloat32le -- ariBlackLevel Black Level 0x0078-0x007B <*> getFloat32le -- ariWhiteLevel White Level 0x007C-0x007F -- Color matrix 0x0080-0x00AF <*> getByteString 48 -- <*> getFloat32le -- ariColorMatrix00 -- <*> getFloat32le -- ariColorMatrix01 -- <*> getFloat32le -- ariColorMatrix02 -- <*> getFloat32le -- ariColorMatrix10 -- <*> getFloat32le -- ariColorMatrix11 -- <*> getFloat32le -- ariColorMatrix12 -- <*> getFloat32le -- ariColorMatrix20 -- <*> getFloat32le -- ariColorMatrix21 -- <*> getFloat32le -- ariColorMatrix22 <*> getFloat32le -- ariColorMatrixDesatG Desat Gain 0x00B0-0x00B3 <*> getFloat32le -- ariColorMatrixDesatO Desat Offset 0x00B4-0x00B7 <*> liftM fromIntegral getWord32le -- ariHLDesatFlag Highlight desat 0x00B8-0x00BB <*> liftM fromIntegral getWord32le -- ariTargetColorSpace Target CS 0x00BC-0x00BF <*> liftM fromIntegral getWord32le -- ariSharpness Sharpness 0x00C0-0x00C3 <*> getFloat32le -- ariPixelAspectRatio Pix Aspect 0x00C4-0x00C7 <*> liftM fromIntegral getWord32le -- ariFlip Flip 0X00C8-0x00CB <*> getAriString 32 -- ariLookFile Look file 0x00CC-0x00EB <*> liftM fromIntegral getWord32le -- ariLookLutMode Lut mode 0x00EC-0x00EF <*> liftM fromIntegral getWord32le -- ariLookLutOffset 0x00F0-0x00F3 <*> liftM fromIntegral getWord32le -- ariLookLutSize 0x00F4-0x00F7 <*> liftM fromIntegral getWord32le -- ariLookLutCRC 0x00F8-0x00FB <*> liftM fromIntegral getWord32le -- ariLinearSaturation 0x00FC-0x00FF -- ariCdlSlope 3 floats 0x0100-0x010B <*> getFloat32le -- ariCdlSlopeR <*> getFloat32le -- ariCdlSlopeG <*> getFloat32le -- ariCdlSlopeB -- ariCdlOffset 3 floats 0x010C-0x0117 <*> getFloat32le -- ariCdlOffsetR <*> getFloat32le -- ariCdlOffsetG <*> getFloat32le -- ariCdlOffsetB -- ariCdlPower 3 floats 0x0118-0x0123 <*> getFloat32le -- ariCdlPowerR <*> getFloat32le -- ariCdlPowerG <*> getFloat32le -- ariCdlPowerB <*> getByteString 6 -- ariPrinterLights 0x0124-0x0129 <*> (liftM fromIntegral getWord32le -- ariCdlApplicationMode 0x0130-0x0133 <* skip 50) -- Reserved 0x0134-0x015F
cpichard/aritools
src/Codec/Picture/Ari/Header/ICI.hs
mit
8,694
0
44
3,803
963
526
437
178
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.MediaStreamTrack (js_getSources, getSources, js_getConstraints, getConstraints, js_states, states, js_getCapabilities, getCapabilities, js_applyConstraints, applyConstraints, js_clone, clone, js_stop, stop, js_getKind, getKind, js_getId, getId, js_getLabel, getLabel, js_setEnabled, setEnabled, js_getEnabled, getEnabled, js_getMuted, getMuted, mute, unmute, js_get_readonly, get_readonly, js_getRemote, getRemote, js_getReadyState, getReadyState, started, ended, overConstrained, MediaStreamTrack, castToMediaStreamTrack, gTypeMediaStreamTrack, IsMediaStreamTrack, toMediaStreamTrack) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"getSources\"]($2)" js_getSources :: MediaStreamTrack -> Nullable MediaStreamTrackSourcesCallback -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.getSources Mozilla MediaStreamTrack.getSources documentation> getSources :: (MonadIO m, IsMediaStreamTrack self) => self -> Maybe MediaStreamTrackSourcesCallback -> m () getSources self callback = liftIO (js_getSources (toMediaStreamTrack self) (maybeToNullable callback)) foreign import javascript unsafe "$1[\"getConstraints\"]()" js_getConstraints :: MediaStreamTrack -> IO (Nullable MediaTrackConstraints) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.getConstraints Mozilla MediaStreamTrack.getConstraints documentation> getConstraints :: (MonadIO m, IsMediaStreamTrack self) => self -> m (Maybe MediaTrackConstraints) getConstraints self = liftIO (nullableToMaybe <$> (js_getConstraints (toMediaStreamTrack self))) foreign import javascript unsafe "$1[\"states\"]()" js_states :: MediaStreamTrack -> IO (Nullable MediaSourceStates) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.states Mozilla MediaStreamTrack.states documentation> states :: (MonadIO m, IsMediaStreamTrack self) => self -> m (Maybe MediaSourceStates) states self = liftIO (nullableToMaybe <$> (js_states (toMediaStreamTrack self))) foreign import javascript unsafe "$1[\"getCapabilities\"]()" js_getCapabilities :: MediaStreamTrack -> IO (Nullable MediaStreamCapabilities) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.getCapabilities Mozilla MediaStreamTrack.getCapabilities documentation> getCapabilities :: (MonadIO m, IsMediaStreamTrack self) => self -> m (Maybe MediaStreamCapabilities) getCapabilities self = liftIO (nullableToMaybe <$> (js_getCapabilities (toMediaStreamTrack self))) foreign import javascript unsafe "$1[\"applyConstraints\"]($2)" js_applyConstraints :: MediaStreamTrack -> Nullable Dictionary -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.applyConstraints Mozilla MediaStreamTrack.applyConstraints documentation> applyConstraints :: (MonadIO m, IsMediaStreamTrack self, IsDictionary constraints) => self -> Maybe constraints -> m () applyConstraints self constraints = liftIO (js_applyConstraints (toMediaStreamTrack self) (maybeToNullable (fmap toDictionary constraints))) foreign import javascript unsafe "$1[\"clone\"]()" js_clone :: MediaStreamTrack -> IO (Nullable MediaStreamTrack) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.clone Mozilla MediaStreamTrack.clone documentation> clone :: (MonadIO m, IsMediaStreamTrack self) => self -> m (Maybe MediaStreamTrack) clone self = liftIO (nullableToMaybe <$> (js_clone (toMediaStreamTrack self))) foreign import javascript unsafe "$1[\"stop\"]()" js_stop :: MediaStreamTrack -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.stop Mozilla MediaStreamTrack.stop documentation> stop :: (MonadIO m, IsMediaStreamTrack self) => self -> m () stop self = liftIO (js_stop (toMediaStreamTrack self)) foreign import javascript unsafe "$1[\"kind\"]" js_getKind :: MediaStreamTrack -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.kind Mozilla MediaStreamTrack.kind documentation> getKind :: (MonadIO m, IsMediaStreamTrack self, FromJSString result) => self -> m result getKind self = liftIO (fromJSString <$> (js_getKind (toMediaStreamTrack self))) foreign import javascript unsafe "$1[\"id\"]" js_getId :: MediaStreamTrack -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.id Mozilla MediaStreamTrack.id documentation> getId :: (MonadIO m, IsMediaStreamTrack self, FromJSString result) => self -> m result getId self = liftIO (fromJSString <$> (js_getId (toMediaStreamTrack self))) foreign import javascript unsafe "$1[\"label\"]" js_getLabel :: MediaStreamTrack -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.label Mozilla MediaStreamTrack.label documentation> getLabel :: (MonadIO m, IsMediaStreamTrack self, FromJSString result) => self -> m result getLabel self = liftIO (fromJSString <$> (js_getLabel (toMediaStreamTrack self))) foreign import javascript unsafe "$1[\"enabled\"] = $2;" js_setEnabled :: MediaStreamTrack -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.enabled Mozilla MediaStreamTrack.enabled documentation> setEnabled :: (MonadIO m, IsMediaStreamTrack self) => self -> Bool -> m () setEnabled self val = liftIO (js_setEnabled (toMediaStreamTrack self) val) foreign import javascript unsafe "($1[\"enabled\"] ? 1 : 0)" js_getEnabled :: MediaStreamTrack -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.enabled Mozilla MediaStreamTrack.enabled documentation> getEnabled :: (MonadIO m, IsMediaStreamTrack self) => self -> m Bool getEnabled self = liftIO (js_getEnabled (toMediaStreamTrack self)) foreign import javascript unsafe "($1[\"muted\"] ? 1 : 0)" js_getMuted :: MediaStreamTrack -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.muted Mozilla MediaStreamTrack.muted documentation> getMuted :: (MonadIO m, IsMediaStreamTrack self) => self -> m Bool getMuted self = liftIO (js_getMuted (toMediaStreamTrack self)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.onmute Mozilla MediaStreamTrack.onmute documentation> mute :: (IsMediaStreamTrack self, IsEventTarget self) => EventName self Event mute = unsafeEventName (toJSString "mute") -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.onunmute Mozilla MediaStreamTrack.onunmute documentation> unmute :: (IsMediaStreamTrack self, IsEventTarget self) => EventName self Event unmute = unsafeEventName (toJSString "unmute") foreign import javascript unsafe "($1[\"_readonly\"] ? 1 : 0)" js_get_readonly :: MediaStreamTrack -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack._readonly Mozilla MediaStreamTrack._readonly documentation> get_readonly :: (MonadIO m, IsMediaStreamTrack self) => self -> m Bool get_readonly self = liftIO (js_get_readonly (toMediaStreamTrack self)) foreign import javascript unsafe "($1[\"remote\"] ? 1 : 0)" js_getRemote :: MediaStreamTrack -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.remote Mozilla MediaStreamTrack.remote documentation> getRemote :: (MonadIO m, IsMediaStreamTrack self) => self -> m Bool getRemote self = liftIO (js_getRemote (toMediaStreamTrack self)) foreign import javascript unsafe "$1[\"readyState\"]" js_getReadyState :: MediaStreamTrack -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.readyState Mozilla MediaStreamTrack.readyState documentation> getReadyState :: (MonadIO m, IsMediaStreamTrack self) => self -> m MediaStreamTrackState getReadyState self = liftIO ((js_getReadyState (toMediaStreamTrack self)) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.onstarted Mozilla MediaStreamTrack.onstarted documentation> started :: (IsMediaStreamTrack self, IsEventTarget self) => EventName self Event started = unsafeEventName (toJSString "started") -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.onended Mozilla MediaStreamTrack.onended documentation> ended :: (IsMediaStreamTrack self, IsEventTarget self) => EventName self Event ended = unsafeEventName (toJSString "ended") -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack.onoverconstrained Mozilla MediaStreamTrack.onoverconstrained documentation> overConstrained :: (IsMediaStreamTrack self, IsEventTarget self) => EventName self Event overConstrained = unsafeEventName (toJSString "overconstrained")
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaStreamTrack.hs
mit
10,110
102
11
1,644
1,975
1,072
903
159
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RecordWildCards #-} module Goolosh.Game.Interpret where import Prelude(($),Num(..),Floating(..),Float,(.)) import Control.Monad import Data.Maybe import qualified Data.Conduit as C import qualified Data.Sequence as S import Data.Sequence((|>)) import Control.Monad.Trans.State.Strict as ST import Control.Lens((&),(.~)) import Goolosh.Game.State import Goolosh.Geom.Transform import Goolosh.Geom.SceneGraph import Goolosh.Game.Entity import Goolosh.Game.Output stateToScene :: Monad m => C.Conduit GameState m GameOutput stateToScene = loop where loop = do s <- C.await case s of Nothing -> return () Just s' -> do C.yield $ genOutput s' loop genOutput s = baseOutput & (gameScene . sceneChildren) .~ sceneFromState s mobs :: GameState -> SceneGraph Entity mobs s = SceneGraph { _sceneGraphNode = Entity { _entityKind = EntityLayer 1 , _entityAnimation = EntityStaticAnimation } , _sceneTransform = affineIdentity , _sceneDrawBox = Nothing , _sceneChildren = scMap (gameMobs s) $ \m -> SceneGraph { _sceneGraphNode = Entity { _entityKind = EntityMob MobWalker , _entityAnimation = EntityStaticAnimation } , _sceneChildren = S.empty , _sceneTransform = affineTranslate (make2DPoint 1 1) $ affineScale (make2DPoint 0.5 0.5) $ affineTranslate (mobPosition m) $ affineScale sf $ affineIdentity , _sceneDrawBox = Just identityBB } } tiles :: GameState -> SceneGraph Entity tiles s = SceneGraph { _sceneGraphNode = Entity { _entityKind = EntityLayer 2 , _entityAnimation = EntityStaticAnimation } , _sceneTransform = affineIdentity , _sceneDrawBox = Nothing , _sceneChildren = scMap (gameTiles s) $ \t -> SceneGraph { _sceneGraphNode = Entity { _entityKind = EntitySolid $ SolidTile TileKind , _entityAnimation = EntityStaticAnimation } , _sceneChildren = S.empty , _sceneTransform = affineTranslate (make2DPoint 1 1) $ affineScale (make2DPoint 0.5 0.5) $ affineTranslate (tilePosition t) $ affineScale sf $ affineIdentity , _sceneDrawBox = Just identityBB } } player :: GameState -> SceneGraph Entity player s = SceneGraph { _sceneGraphNode = Entity { _entityKind = EntityLayer 3 , _entityAnimation = EntityStaticAnimation } , _sceneTransform = affineIdentity , _sceneDrawBox = Nothing , _sceneChildren = S.empty |> SceneGraph { _sceneGraphNode = Entity { _entityKind = EntityPlayer , _entityAnimation = EntityStaticAnimation } , _sceneChildren = S.empty , _sceneTransform = affineTranslate (make2DPoint 1 1) $ affineScale (make2DPoint 0.5 0.5) $ affineTranslate (playerPosition $ gamePlayer s) $ affineScale sf $ affineIdentity , _sceneDrawBox = Just identityBB } } sceneFromState :: GameState -> S.Seq (SceneGraph Entity) sceneFromState s = S.empty |> mobs s |> tiles s |> player s scMap d f = fmap f d sf = make2DPoint 20 20 baseOutput :: GameOutput baseOutput = GameOutput { _gameScene = SceneGraph { _sceneGraphNode = Entity { _entityKind = EntityScene , _entityAnimation = EntityStaticAnimation } , _sceneChildren = S.empty , _sceneTransform = affineIdentity , _sceneDrawBox = Nothing } , _gameView = makeBB (make2DPoint 0 0) (make2DPoint 100 100) } --
LeviSchuck/Goolosh
src/Goolosh/Game/Interpret.hs
mit
4,473
0
19
1,805
940
528
412
100
2
{-| Module: Capnp.Gen.Capnp Description: Generated modules for the schema that ship with Cap'N Proto The modules under 'Capnp.Gen.Capnp' are generated code for the schema files that ship with the Cap'N Proto reference implementation. -} module Capnp.Gen.Capnp () where
zenhack/haskell-capnp
lib/Capnp/Gen/Capnp.hs
mit
270
0
3
39
11
8
3
1
0
-- Mathematics/Fundamentals/Minimum Draws module Main where import qualified HackerRank.Mathematics.MinimumDraws as M main :: IO () main = M.main
4e6/sandbox
haskell/hackerrank/MinimumDraws.hs
mit
149
0
6
21
31
20
11
4
1
{-# LANGUAGE DeriveGeneric #-} -- TODO This probably should not be a part of Character. module D20.Internal.Character.Action where import GHC.Generics import D20.Character import D20.Internal.Item data ActionTime = AttackAction | MoveAction | FullRoundAction | FreeAction deriving (Show,Eq,Ord,Generic) -- data Action -- = UseSkill -- | UseFeat -- | UseTalent -- | Attack -- | Move -- | StandUp -- | ManipulateObject -- | Charge -- | FullAttack -- | CastSpell -- deriving (Show,Eq,Ord) data CombatAction = Attack {getCombatActionExecutor :: Character ,getCombatActionWieldable :: Wieldable ,getCombatActionTarget :: Character} | -- These are decided by the wielded weapon -- | MeleeAttack -- | RangedAttack -- | UnarmedAttack -- | ArmedAttack ShootIntoMelee | FightDefensively | TotalDefense | StartFullRoundAction | CompleteFullRoundAction deriving (Show,Generic) data MoveAction = Charge | FullAttack | Run | Withdraw deriving (Show,Generic) -- class ActionTarget t -- data ActionTime -- = FullRoundAction -- | MoveAction -- | NonAction -- deriving (Show,Eq,Ord,Generic)
elkorn/d20
src/D20/Internal/Character/Action.hs
mit
1,192
0
8
267
164
110
54
27
0
{- 1. Faça uma função que receba o nome de um aluno e uma lista com suas três notas. A função deve então devolver uma tupla com o nome do aluno e a média das notas. Exemplo: > aprovado "Joao" [80, 60, 100] ("Joao", 80) -} e4 :: String -> [Float] -> (String, Float) e4 nome notas = (nome, sum notas / 3) {- al_media nome notas = (nome, sum notas / fromIntegral(length notas)) -- Para uma média perfeita que conta quantos elementos uma lista possui e retorna um número inteiro para a divisão. -} {- 2. Diga quais são os tipos das seguintes expressões: a) False Main> :type False False :: Bool b) (["foo", "bar"], 'a') Main> :type (["foo", "bar"], 'a') (["foo","bar"],'a') :: ([[Char]],Char) c) [(True, []), (False, [['a']])] Main> :type [(True, []), (False, [['a']])] [(True,[]),(False,[['a']])] :: [(Bool,[[Char]])] d) 2.5 Main> :type 2.5 2.5 :: Fractional a => a e) (1, 1.5, 2.5, 10) Main> :type (1, 1.5, 2.5, 10) (1,1.5,2.5,10) :: (Num a, Fractional b, Fractional c, Num d) => (d,c,b,a) -} {- 3. Crie as seguintes funções em Haskell definindo corretamente os tipos de dados. a) Função para calcular a média de 4 números em ponto flutuante. b) Função soma de 3 números inteiros. c) Função que retorne a raiz quadrada de um número real. Utilize a função sqrt para o cálculo da raiz. -} e3a :: Float -> Float -> Float -> Float -> Float e3a x1 x2 x3 x4 = (x1+x2+x3+x4)/4 e3b :: Int -> Int -> Int -> Int e3b x1 x2 x3 = x1+x2+x3 e3c :: Float -> Float e3c x1 = sqrt(x1) {- 4. Usando as funções head e tail, defina a função terceiro que devolve o terceiro elemento de uma lista de inteiros. Exemplo: > terceiro [1,2,5,6,7] 5 -} terceiro :: [Int] -> Int terceiro [a,b,c,d,e] = head(tail(tail[a,b,c,d,e])) {- 5. Defina uma lista por compreensão onde cada posição é uma tupla (x,y), com x < y, assumindo x como valores pertencentes à lista [1,3,5] e y pertencente a [2,4,6]. -} e5 :: [(Int,Int)] e5 = [(x,y) | x<-[1,3,5], y<-[2,4,6], x<y] {- 6. Defina as listas abaixo por compreensão: a) [1,2,3,4,5,6,7,8,9,10] b) [2,4,6,8,10,12,14,16,18,20] c) [12,14,16,18,20] d) [0,3,6,9,12,15] e) [50,52,54,56,58,60] f) Uma lista com elementos de 10 a 20, exceto os números 13, 15 e 19. -} e6a :: [Int] e6a = [ x | x <- [1..10]] e6b :: [Int] e6b = [ x | x <- [2,4..20]] e6c :: [Int] e6c = [ x | x <- [12,14..20]] e6d :: [Int] e6d = [ x | x <- [0,3..15]] e6e :: [Int] e6e = [ x | x <- [50,52..60]] e6f :: [Int] e6f = [ x | x <- [10..20], x /= 13, x /= 15, x /= 19]
hugonasciutti/Exercises
Haskell/Exercises/pratica3.hs
mit
2,648
0
10
626
512
293
219
24
1
-- (2 балла) module Eval ( Eval, runEval , Error, Store , update, getVar ) where import qualified Data.Map as M import Data.List import Control.Monad import Control.Applicative import Expr type Error = String type Store = M.Map String Value newtype Eval a = Eval { runEval :: Store -> (Maybe a, [Error], Store) } instance Functor Eval where fmap f (Eval m) = Eval undefined instance Applicative Eval where pure x = Eval undefined Eval m <*> Eval k = Eval undefined instance Monad Eval where return x = Eval undefined Eval m >>= k = Eval undefined instance Alternative Eval where empty = Eval undefined Eval l <|> Eval r = Eval undefined -- MonadPlus - аналог Alternative для монад -- mzero - вычисление, которое ничего не делает, сразу завершается неуспехом -- mplus m1 m2 пытается выполнить m1, если тот завершился неуспехом, выполняет m2 -- Примеры использования этого класса есть в Utils.hs instance MonadPlus Eval where mzero = Eval undefined mplus (Eval l) (Eval r) = Eval undefined update :: String -> Value -> Eval () update k v = Eval undefined getVar :: String -> Eval Value getVar v = Eval undefined
SergeyKrivohatskiy/fp_haskell
hw10/Interpreter/Eval.hs
mit
1,336
0
9
257
340
178
162
30
1
module MicroKanren.ExampleMonadic where import Control.Monad import Control.Monad.Trans.State import MicroKanren import MicroKanren.Plain (LVar(..), CanUnify) import MicroKanren.Cons aANDb ∷ Logic (LVar Int) aANDb = do a ← fresh b ← fresh a === LVal 7 mplus (b === LVal 5) (b === LVal 6) runEx1, runEx2, runEx3 ∷ [LVar Int] runEx1 = run $ fresh >>= (=== LVal 5) runEx2 = run aANDb runEx3 = run $ do q ← fresh q === LVal 5 LVal 6 === q fives, sixes ∷ LVar Int → Logic (LVar Int) fives x = mplus (x === LVal 5) (fives x) sixes x = mplus (x === LVal 6) (sixes x) runFives, run5and6 ∷ [LVar Int] runFives = run $ fresh >>= fives run5and6 = run $ do x ← fresh fives x `mplus` sixes x appendo ∷ (CanUnify α, Eq α) ⇒ LVar (LCons α) → LVar (LCons α) → LVar (LCons α) → Logic (LVar (LCons α)) appendo l s out = mplus (do l === LVal empty s === out) (do h ← fresh t ← fresh l === LVal (cons h t) res ← fresh out === LVal (cons h res) appendo t s res) runAppendo ∷ [LVar (LCons Int)] runAppendo = run $ do q ← fresh appendo q q (LVal $ fromList [1, 1]) --membero ∷ Eq α ⇒ LVar (LCons α) → LVar (LCons α) → Logic (LVar (LCons α)) --membero x l = conde -- [do t ← fresh -- x === LVal (LCons x t) -- return t -- ,do t ← fresh -- h ← fresh -- l === LVal (LCons h t) -- membero x t]
Oregu/featherweight
ExampleM.hs
mit
1,584
0
13
527
580
295
285
-1
-1
module Main ( main ) where import Haste main :: IO () main = alert "hello bayhac"
alephcloud/bayhac2014
contrib/hello-bayhac.hs
mit
84
0
6
19
30
17
13
5
1
module Oodle.SymbolTable where import Oodle.Error import Oodle.ParseTree import Oodle.Token type SymbolTable = [Symbol] data Symbol = Symbol { symbol :: String, decl :: Declaration } deriving (Show, Eq) data Declaration -- parent variables methods inherited methods = ClassDecl Token String [Symbol] [Symbol] [(String, Symbol)] -- parameters parameter types variables | MethodDecl Token Type Int [Type] [Symbol] | VarDecl { varToken :: Token, type' :: Type } deriving (Show, Eq) -- Class Method Debug type Scope = (SymbolTable, Symbol, Symbol, Bool) isClassDecl :: Symbol -> Bool isClassDecl (Symbol _ ClassDecl{}) = True isClassDecl _ = False isMethodDecl :: Symbol -> Bool isMethodDecl (Symbol _ MethodDecl{}) = True isMethodDecl _ = False isVarDecl :: Symbol -> Bool isVarDecl (Symbol _ VarDecl{}) = True isVarDecl _ = False getParameterTypes :: Declaration -> [Type] getParameterTypes (MethodDecl _ _ _ types _) = types getType :: Declaration -> Type getType (MethodDecl _ t _ _ _) = t getVariables :: Symbol -> [Symbol] getVariables sym = case decl sym of ClassDecl _ _ vars _ _ -> vars MethodDecl _ _ _ _ vars -> vars getMethods :: Symbol -> [Symbol] getMethods (Symbol _ (ClassDecl _ _ _ methods _)) = methods getInheritedMethods :: Symbol -> [(String, Symbol)] getInheritedMethods (Symbol _ (ClassDecl _ _ _ _ methods)) = methods -- Get a class declaration from a SymbolTable getClassDecl :: SymbolTable -> (String, Token) -> Error Declaration getClassDecl = getNamedDecl -- Get a method declaration from a parent class declaration getMethodDecl :: Declaration -> (String, Token) -> Error Declaration getMethodDecl (ClassDecl _ _ _ methods inherited) = getNamedDecl (methods ++ snd (unzip inherited)) getNamedDecl :: [Symbol] -> (String, Token) -> Error Declaration getNamedDecl symbols sym = do s <- findSymbol symbols sym return $ decl s -- Symbol must exist findSymbol :: [Symbol] -> (String, Token) -> Error Symbol findSymbol symbols (sym, tk) = if not $ null match then return $ head match else fail $ concatMap (\s -> show s ++ "\n") symbols ++ msgWithToken tk "undeclared variable/method" sym where match = dropWhile (\s -> symbol s /= sym) symbols findKnownSymbol :: [Symbol] -> String -> Symbol findKnownSymbol symbols sym = head $ dropWhile (\s -> symbol s /= sym) symbols -- Symbol must exist findDecl :: [Symbol] -> (Declaration, Token) -> Error Symbol findDecl symbols (d, tk) = if not $ null match then return $ head match else fail $ concatMap (\s -> show s ++ "\n") symbols ++ "\n" ++ (msgWithToken tk "couldn't find declaration" (show d)) where match = dropWhile (\s -> decl s /= d) symbols resolveScope :: Scope -> Expression -> Error Declaration resolveScope (st, cls, m, d) scope = case scope of ExpressionNoop -> return (decl cls) ExpressionId tk (Id name) -> do n <- get (name, tk) get (getName n, tk) where get = getNamedDecl (getVariables m ++ getVariables cls ++ st) getName = getIdString . getId . type' ExpressionNew tk (TypeId (Id name)) -> getNamedDecl st (name, tk) ExpressionCall tk callScope (Id name) _ -> do callScope' <- resolveScope (st, cls, m, d) callScope (MethodDecl _ (TypeId (Id t)) _ _ _) <- getMethodDecl callScope' (name, tk) getDeclFromType t ExpressionStr _ _ -> getDeclFromType "String" ExpressionMe _ -> return $ decl cls _ -> fail $ msgWithToken' (getExprToken scope) "scope not a valid expression" where getDeclFromType t = return (decl (deE (findSymbol st (t, fakeToken)))) -- Handles building any kind of array type buildType :: Type -> Type buildType (TypeExp t _) = TypeArray (buildType t) buildType t = t unbuildArray :: Type -> Int -> Type unbuildArray t 0 = t unbuildArray (TypeArray t) i = unbuildArray t (i - 1)
lseelenbinder/oodle-compiler
Oodle/SymbolTable.hs
mit
4,024
0
16
951
1,411
739
672
88
7
import Data.List truncateFromLeft :: Int -> [Int] truncateFromLeft = map read . init . tail . tails . show truncateFromRight :: Int -> [Int] truncateFromRight = map (read . reverse) . init . tail . tails . reverse . show isPrime :: Int -> Bool isPrime n | n == 1 = False | n < 4 = True | n `mod` 2 == 0 = False | n < 9 = True | n `mod` 3 == 0 = False | otherwise = isPrime' where isPrime' = go 5 r = floor $ (sqrt $ fromIntegral n :: Double) go f | f > r = True | n `mod` f == 0 = False | n `mod` (f+2) == 0 = False | otherwise = go (f+6) solve :: Int solve = sum nums where nums = take 11 $ filter filterPrimeTruncatables primes primes = filter isPrime [11..] filterPrimeTruncatables x = (all isPrime $ truncateFromLeft x) && (all isPrime $ truncateFromRight x) main :: IO () main = print solve
jwtouron/haskell-play
ProjectEuler/Problem37.hs
mit
906
0
13
282
404
204
200
25
1
{-# OPTIONS -fexpose-all-unfoldings #-} {-# OPTIONS -funbox-strict-fields #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Game.Graphics.Texture ( Texture (), Sampling (..), Alpha (..), TextureError (..) , loadTexture, texture, freeTexture , texId, texSize ) where import Codec.Picture import Codec.Picture.Types import Control.Applicative import Control.Exception import Control.Monad import Data.Typeable import Data.Word import Foreign.Marshal.Utils import Foreign.Ptr import Foreign.Storable import Game.Graphics.Utils import Graphics.Rendering.OpenGL.Raw.Core32 import Linear.V2 import qualified Data.Vector.Storable as Vector data Texture = Texture { texId :: !GLuint , texSize :: !(V2 Word) } -- | Delete a texture from the GPU. After freeing it, the texture and -- any derived values such as sprites are invalid. freeTexture :: Texture -> IO () freeTexture t = with (texId t) $ glDeleteTextures 1 -- TODO Add support for custom mipmaps, or write a high quality -- mipmapper right here. The main point is that I just don't trust all -- OpenGL drivers to do it right. toSRGB :: Double -> Double toSRGB lin | lin == 1 = 1 | lin <= 0.0031308 = 12.92*lin | otherwise = (1 + transA)*lin**(1/2.4) - transA where transA = 0.055 fromSRGB :: Double -> Double fromSRGB nonLin | nonLin == 1 = 1 | nonLin <= 0.04045 = nonLin/12.92 | otherwise = ((nonLin + transA)/(1 + transA))**2.4 where transA = 0.055 asDouble :: (Bounded a, Integral a) => (Double -> Double) -> a -> a asDouble = (fromDouble .) . (. toDouble) toDouble :: forall a. (Bounded a, Integral a) => a -> Double toDouble = (/ fromIntegral (maxBound :: a)) . fromIntegral fromDouble :: forall a. (Bounded a, Integral a) => Double -> a fromDouble = round . (* fromIntegral (maxBound :: a)) data Sampling = Nearest | Linear deriving (Eq, Ord, Read, Show) setSampling :: Sampling -> IO () setSampling Nearest = do glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $ fromIntegral gl_NEAREST glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $ fromIntegral gl_NEAREST setSampling Linear = do glGenerateMipmap gl_TEXTURE_2D glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $ fromIntegral gl_LINEAR_MIPMAP_LINEAR glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $ fromIntegral gl_LINEAR data TextureError = DimensionsTooLarge { driverLimit :: !Word , actualWidth :: !Word , actualHeight :: !Word } deriving (Show, Typeable) instance Exception TextureError data Alpha = Standard | Premultiplied deriving (Eq, Ord, Read, Show) -- | Create a texture from an image loaded using JuicyPixels. The -- internal format is chosen based on the input format. The color -- spaces for 8 and 16 bit RGB channels are assumed to be sRGB; all -- others are assumed to be in linear color space. -- -- This function will make the following changes to OpenGL state by -- the time it returns: -- -- * GL_TEXTURE_2D will be unbound -- * GL_UNPACK_ALIGNMENT will be set to 1 texture :: Alpha -> Sampling -> DynamicImage -> IO Texture texture alpha sampling dynImg = case dynImg of ImageY8 img -> texImage2D sampling gl_SRGB8 gl_RED gl_UNSIGNED_BYTE img ImageY16 img -> texImage2D sampling gl_RGB16 gl_RED gl_UNSIGNED_SHORT $ (pixelMap.asDouble) fromSRGB img ImageYF img -> texImage2D sampling gl_RGB32F gl_RED gl_FLOAT img ImageYA8 img -> texImage2D sampling gl_SRGB8_ALPHA8 gl_RGBA gl_UNSIGNED_BYTE (promoteImage ((whenShouldPremultiply.pixelMap) (\(PixelYA8 y a) -> PixelYA8 (fromDouble . toSRGB . (* toDouble a) . fromSRGB . toDouble $ y) a) img) :: Image PixelRGBA8) ImageYA16 img -> texImage2D sampling gl_RGBA16 gl_RGBA gl_UNSIGNED_SHORT (promoteImage (pixelMap (\(PixelYA16 y a) -> PixelYA16 (fromDouble . whenShouldPremultiply (* toDouble a) . fromSRGB . toDouble $ y) a) img) :: Image PixelRGBA16) ImageRGB8 img -> texImage2D sampling gl_SRGB8 gl_RGB gl_UNSIGNED_BYTE img ImageRGB16 img -> texImage2D sampling gl_RGB16 gl_RGB gl_UNSIGNED_SHORT $ pixelMap (\(PixelRGB16 r g b) -> let f = asDouble fromSRGB in PixelRGB16 (f r) (f g) (f b)) img ImageRGBF img -> texImage2D sampling gl_RGB32F gl_RGB gl_FLOAT img ImageRGBA8 img -> texImage2D sampling gl_SRGB8_ALPHA8 gl_RGBA gl_UNSIGNED_BYTE $ (whenShouldPremultiply.pixelMap) (\(PixelRGBA8 r g b a) -> let f = fromDouble . toSRGB . (* toDouble a) . fromSRGB . toDouble in PixelRGBA8 (f r) (f g) (f b) a) img ImageRGBA16 img -> texImage2D sampling gl_RGBA16 gl_RGBA gl_UNSIGNED_SHORT $ (whenShouldPremultiply.pixelMap) (\(PixelRGBA16 r g b a) -> let f = fromDouble . toSRGB . (* toDouble a) . fromSRGB . toDouble in PixelRGBA16 (f r) (f g) (f b) a) img ImageYCbCr8 img -> texImage2D sampling gl_SRGB8 gl_RGB gl_UNSIGNED_BYTE (convertImage img :: Image PixelRGB8) ImageCMYK8 img -> texImage2D sampling gl_RGB8 gl_RGB gl_UNSIGNED_BYTE (convertImage img :: Image PixelRGB8) ImageCMYK16 img -> texImage2D sampling gl_RGB16 gl_RGB gl_UNSIGNED_SHORT (convertImage img :: Image PixelRGB16) where whenShouldPremultiply f | alpha == Standard = f | otherwise = id -- | This function will make the following changes to OpenGL state by -- the time it returns: -- -- * GL_TEXTURE_2D will be unbound -- * GL_UNPACK_ALIGNMENT will be set to 1 texImage2D :: Storable (PixelBaseComponent b) => Sampling -> GLenum -> GLenum -> GLenum -> Image b -> IO Texture texImage2D sampling internal format type_ img = do let w, h :: Num a => a w = fromIntegral $ imageWidth img h = fromIntegral $ imageHeight img maxDim <- glGet gl_MAX_TEXTURE_SIZE when (maxDim < w || maxDim < h) . throwIO $ DimensionsTooLarge maxDim w h tid <- glGen glGenTextures glBindTexture gl_TEXTURE_2D tid glPixelStorei gl_UNPACK_ALIGNMENT 1 unsafeWith img $ glTexImage2D gl_TEXTURE_2D 0 (fromIntegral internal) w h 0 format type_ setSampling sampling glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $ fromIntegral gl_CLAMP_TO_EDGE glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $ fromIntegral gl_CLAMP_TO_EDGE glBindTexture gl_TEXTURE_2D 0 return $! Texture tid $ V2 w h where unsafeWith :: Storable (PixelBaseComponent a) => Image a -> (Ptr (PixelBaseComponent a) -> IO b) -> IO b unsafeWith = Vector.unsafeWith . imageData loadTexture' :: (Alpha -> Sampling -> DynamicImage -> IO Texture) -> Alpha -> Sampling -> FilePath -> IO (Either String Texture) loadTexture' f alpha sampling = traverseEither (f alpha sampling) <=< readImage where traverseEither _ (Left l) = return (Left l) traverseEither g (Right r) = Right <$> g r -- | This function will make the following changes to OpenGL state by -- the time it returns: -- -- * GL_TEXTURE_2D will be unbound loadTexture :: Alpha -> Sampling -> FilePath -> IO (Either String Texture) loadTexture = loadTexture' texture
caryoscelus/graphics
src/Game/Graphics/Texture.hs
mit
7,691
0
23
1,992
2,021
1,029
992
130
13
module TeXWriter (writeTeX) where import Ast import Data.List (intercalate) cmd_ :: String -> String cmd_ = ("\\" ++) cmd :: String -> String cmd = cmd_ . (++ " ") cmdargs :: String -> [String] -> String cmdargs c = concat . (cmd_ c:) . map (\a -> "{" ++ a ++ "}") writeConst :: Constant -> String writeConst (Constant cst _) = writeConst_ cst -- Operation symbols where writeConst_ (Letter c) = [c] writeConst_ (Number n) = n writeConst_ (GreekLetter s) = cmd s writeConst_ (StdFun s) = cmd s writeConst_ Add = "+" writeConst_ Sub = "-" writeConst_ Mul = cmd "cdot" writeConst_ Mmul = cmd "ast" writeConst_ Mmmul = cmd "star" writeConst_ Sslash = "/" writeConst_ Bbslash = cmd "backslash" writeConst_ Times = cmd "times" writeConst_ Div = cmd "div" writeConst_ Comp = cmd "circ" writeConst_ Oplus = cmd "oplus" writeConst_ Otimes = cmd "otimes" writeConst_ Odot = cmd "odot" writeConst_ Sum = cmd "sum" writeConst_ Prod = cmd "prod" writeConst_ Wedge = cmd "wedge" writeConst_ Wwedge = cmd "bigwedge" writeConst_ Vv = cmd "vee" writeConst_ Vvv = cmd "bigvee" writeConst_ Nn = cmd "cap" writeConst_ Nnn = cmd "bigcap" writeConst_ Uu = cmd "cup" writeConst_ Uuu = cmd "bigcup" -- Miscellaneous symbols writeConst_ Inte = cmd "int" writeConst_ Oint = cmd "oint" writeConst_ Del = cmd "partial" writeConst_ Grad = cmd "nabla" writeConst_ Addsub = cmd "pm" writeConst_ Void = cmd "emptyset" writeConst_ Infty = cmd "infty" writeConst_ Aleph = cmd "aleph" writeConst_ Angle = cmd "angle" writeConst_ Therefore = cmd "therefore" writeConst_ Abs = "|" writeConst_ Cdots = cmd "cdots" writeConst_ Vdots = cmd "vdots" writeConst_ Ddots = cmd "ddots" writeConst_ Bslash = "\\" writeConst_ Quad = cmd "quad" writeConst_ Space = cmd_ " " writeConst_ Diamond = cmd "diamond" writeConst_ Square = cmd "square" writeConst_ Lfloor = cmd "lfloor" writeConst_ Rfloor = cmd "rfloor" writeConst_ Lceil = cmd "lceil" writeConst_ Rceil = cmd "rceil" writeConst_ Cc = cmdargs "mathbb" ["C"] writeConst_ Ensnn = cmdargs "mathbb" ["N"] writeConst_ Qq = cmdargs "mathbb" ["Q"] writeConst_ Rr = cmdargs "mathbb" ["R"] writeConst_ Zz = cmdargs "mathbb" ["Z"] -- Relation symbols writeConst_ Eq = "=" writeConst_ Neq = cmd "neq" writeConst_ Lt = "<" writeConst_ Gt = ">" writeConst_ Le = cmd "leqslant" writeConst_ Ge = cmd "geqslant" writeConst_ Prec = cmd "prec" writeConst_ Succ = cmd "succ" writeConst_ In = cmd "in" writeConst_ Notin = cmd_ "not" ++ cmd "in" writeConst_ Subset = cmd "subset" writeConst_ Supset = cmd "supset" writeConst_ Subsete = cmd "subseteq" writeConst_ Supsete = cmd "supseteq" writeConst_ Mod = cmd "equiv" writeConst_ Congr = cmd "cong" writeConst_ Approx = cmd "approx" writeConst_ Prop = cmd "propto" -- Logical symbols writeConst_ And = cmdargs "textrm" ["and"] writeConst_ Or = cmdargs "textrm" ["or"] writeConst_ Not = cmd "neg" writeConst_ Implies = cmd "Rightarrow" writeConst_ If = cmdargs "textrm" ["if"] writeConst_ Iff = cmd "Leftrightarrow" writeConst_ Forall = cmd "forall" writeConst_ Exists = cmd "exists" writeConst_ Falsum = cmd "perp" writeConst_ Taut = cmd "top" writeConst_ Turnstile = cmd "vdash" writeConst_ Tturnstile = cmd "models" -- Arrows writeConst_ Uarr = cmd "uparrow" writeConst_ Darr = cmd "downarrow" writeConst_ Larr = cmd "leftarrow" writeConst_ To = cmd "to" writeConst_ Mapsto = cmd "mapsto" writeConst_ Harr = cmd "leftrightarrow" writeConst_ Llarr = cmd "Leftarrow" -- Additionnal symbols writeConst_ Comma = "," writeConst_ Dot = "." writeConst_ Semicolon = ";" writeConst_ Quote = "'" writeConst_ Facto = "!" -- Writes a unary operator writeUnaryOp :: UnaryOp -> String writeUnaryOp (UnaryOp u _) = writeUnaryOp_ u where writeUnaryOp_ Usqrt = "sqrt" writeUnaryOp_ Utext = "textrm" writeUnaryOp_ Ubb = "boldsymbol" writeUnaryOp_ Ubbb = "mathbb" writeUnaryOp_ Ucc = "mathcal" writeUnaryOp_ Utt = "texttt" writeUnaryOp_ Ufr = "mathfrak" writeUnaryOp_ Usf = "mathsf" writeUnaryOp_ Utilde = "tilde" writeUnaryOp_ Uhat = "hat" writeUnaryOp_ Ubar = "overline" writeUnaryOp_ Uul = "underline" writeUnaryOp_ Uvec = "vec" writeUnaryOp_ Udot = "dot" writeUnaryOp_ Uddot = "ddot" -- Writes the delimitors writeLBracket :: LBracket -> String writeRBracket :: RBracket -> String writeLBracket (LBracket l _) = cmd_ "left" ++ aux l where aux LPar = "(" aux LCro = "[" aux LBra = "\\{" aux LChe = cmd "langle" aux LBraCons = "." writeRBracket (RBracket r _) = cmd_ "right" ++ aux r where aux RPar = ")" aux RCro = "]" aux RBra = "\\}" aux RChe = cmd "rangle" aux RBraCons = "." -- Usefull map mmap :: (a -> b) -> [[a]] -> [[b]] mmap f = map (map f) -- Writes a simple expression writeSimpleExpr :: SimpleExpr -> String writeSimpleExpr (SimpleExpr expr _) = writeSimpleExpr_ expr where writeSimpleExpr_ (SEConst c) = writeConst c writeSimpleExpr_ (Matrix t css) = let mt = (if t == RawMatrix then "bmatrix" else "pmatrix") in let textMatrix = mmap writeCode css in let ls = map (intercalate " & ") textMatrix in let text = intercalate " \\\\ " ls in cmdargs "begin" [mt] ++ text ++ cmdargs "end" [mt] writeSimpleExpr_ (Delimited l e r) = writeLBracket l ++ writeCode e ++ writeRBracket r writeSimpleExpr_ (UnaryApp o e) = cmdargs (writeUnaryOp o) [writeSimpleExprND e] writeSimpleExpr_ (BinaryApp (BinaryOp BFrac _) e1 e2) = cmdargs "frac" [writeSimpleExprND e1, writeSimpleExprND e2] writeSimpleExpr_ (BinaryApp (BinaryOp BRoot _) e1 e2) = cmdargs ("sqrt[" ++ writeSimpleExpr e1 ++ "]") [writeSimpleExpr e2] writeSimpleExpr_ (BinaryApp (BinaryOp BStackRel _) e1 e2) = cmdargs "stackrel" [writeSimpleExpr e1, writeSimpleExpr e2] writeSimpleExpr_ (Raw s) = cmdargs "textrm" [s] -- Writes a simple expression after removing the embracing delimiters if present writeSimpleExprND :: SimpleExpr -> String writeSimpleExprND (SimpleExpr (Delimited _ e _) _) = writeCode e writeSimpleExprND e = writeSimpleExpr e -- Writes an expression writeExpr :: Expr -> String writeExpr (Expr e _) = writeExpr_ e where writeExpr_ (Simple se) = writeSimpleExpr se writeExpr_ (Frac e1 e2) = cmdargs "frac" [writeSimpleExprND e1, writeSimpleExprND e2] writeExpr_ (Under e1 e2) = writeSimpleExpr e1 ++ "_{" ++ writeSimpleExprND e2 ++ "}" writeExpr_ (Super e1 e2) = writeSimpleExpr e1 ++ "^{" ++ writeSimpleExprND e2 ++ "}" writeExpr_ (SubSuper e1 e2 e3) = writeSimpleExpr e1 ++ "_{" ++ writeSimpleExprND e2 ++ "}" ++ "^{" ++ writeSimpleExprND e3 ++ "}" -- Writes a code block writeCode :: Code -> String writeCode = foldr (\e s -> writeExpr e ++ s) "" -- The main writer writeTeX :: Code -> String writeTeX = writeCode
Kerl13/AsciiMath
src/lib/TeXWriter.hs
mit
8,686
0
18
3,210
2,311
1,126
1,185
181
97
module Shared where numDigits :: (Integral a, Integral b) => a -> b numDigits n = ceiling $ log (fromIntegral $ n+1) / log 10 digitalSum :: (Integral a) => a -> a digitalSum = sum . map (`mod` 10) . takeWhile (> 0) . iterate (`div` 10) concNumbers :: Integral a => a -> a -> a concNumbers x y = y + x * (10 ^ (numDigits y)) divPrimeTest :: Integral a => a -> Bool divPrimeTest n = not $ any (\x -> n `rem` x == 0) [2.. intSqrt n] intSqrt :: Integral a => a -> a intSqrt = floor . sqrt . fromIntegral allFactors x | null facts = [[x]] | otherwise = [x] : (concatMap (\f -> map ((:) (x `div` f)) $ allFactors f) facts) where facts = filter (\a -> x `rem` a == 0) [2.. x-1]
edwardwas/euler
shared/src/Shared.hs
mit
689
0
16
164
381
204
177
15
1
module Lib.Fresh ( Fresh, new , next ) where import Control.Applicative ((<$>)) import Data.IORef newtype Fresh a = Fresh (IORef a) {-# INLINE new #-} new :: a -> IO (Fresh a) new x = Fresh <$> newIORef x {-# INLINE next #-} next :: Enum a => Fresh a -> IO a next (Fresh ref) = atomicModifyIORef' ref $ \old -> (succ old, old)
nadavshemer/buildsome
src/Lib/Fresh.hs
gpl-2.0
337
0
8
75
141
77
64
12
1
{- | Module : $Header$ Description : compute the theory of a node Copyright : (c) Christian Maeder and DFKI GmbH 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable(Logic) compute the theory of a node -} module Static.ComputeTheory ( computeTheory , globalNodeTheory , getGlobalTheory , theoremsToAxioms , computeDGraphTheories , computeLibEnvTheories , computeLabelTheory , updateLabelTheory , markHiding , markFree , renumberDGLinks , getImportNames ) where import Logic.Prover import Static.GTheory import Static.DevGraph import Static.DgUtils import Static.History import Common.LibName import Common.Result import Data.Graph.Inductive.Graph as Graph import Data.List (sortBy) import qualified Data.Map as Map import qualified Data.Set as Set (fromList, toList) import Data.Ord -- * nodes with incoming hiding definition links nodeHasHiding :: DGraph -> Node -> Bool nodeHasHiding dg = labelHasHiding . labDG dg nodeHasFree :: DGraph -> Node -> Bool nodeHasFree dg = labelHasFree . labDG dg {- | mark all nodes if they have incoming hiding edges. Assume reference nodes to other libraries being properly marked already. -} markFree :: LibEnv -> DGraph -> DGraph markFree le dgraph = foldl (\ dg (n, lbl) -> let ingoingEdges = innDG dg n defEdges = filter (liftE isDefEdge) ingoingEdges freeDefEdges = filter (liftE isFreeEdge ) defEdges in fst $ labelNodeDG (n, lbl { labelHasFree = if isDGRef lbl then nodeHasFree (lookupDGraph (dgn_libname lbl) le) $ dgn_node lbl else not (null freeDefEdges) }) dg) dgraph $ topsortedNodes dgraph markHiding :: LibEnv -> DGraph -> DGraph markHiding le dgraph = foldl (\ dg (n, lbl) -> let ingoingEdges = innDG dg n defEdges = filter (liftE isDefEdge) ingoingEdges hidingDefEdges = filter (liftE isHidingDef ) defEdges next = map (\ (s, _, _) -> s) defEdges in fst $ labelNodeDG (n, lbl { labelHasHiding = if isDGRef lbl then nodeHasHiding (lookupDGraph (dgn_libname lbl) le) $ dgn_node lbl else not (null hidingDefEdges) || any (nodeHasHiding dg) next }) dg) dgraph $ topsortedNodes dgraph computeTheory :: LibEnv -> LibName -> Node -> Maybe G_theory computeTheory libEnv ln = globalNodeTheory $ lookupDGraph ln libEnv theoremsToAxioms :: G_theory -> G_theory theoremsToAxioms (G_theory lid sign ind1 sens ind2) = G_theory lid sign ind1 (markAsAxiom True sens) ind2 getGlobalTheory :: DGNodeLab -> Result G_theory getGlobalTheory = maybe (fail "no global theory") return . globalTheory globalNodeTheory :: DGraph -> Node -> Maybe G_theory globalNodeTheory dg = globalTheory . labDG dg computeLibEnvTheories :: LibEnv -> LibEnv computeLibEnvTheories le = let lns = getTopsortedLibs le upd le' ln = let dg0 = lookupDGraph ln le dg = computeDGraphTheories le' dg0 in Map.insert ln dg le' in foldl upd Map.empty lns computeDGraphTheories :: LibEnv -> DGraph -> DGraph computeDGraphTheories le dgraph = let newDg = computeDGraphTheoriesAux le dgraph in groupHistory dgraph (DGRule "Compute theory") newDg recomputeNodeLabel :: LibEnv -> DGraph -> LNode DGNodeLab -> DGNodeLab recomputeNodeLabel le dg l@(n, lbl) = case computeLabelTheory le dg l of gTh@(Just th) -> let (chg, lbl1) = case globalTheory lbl of Nothing -> (False, lbl) Just oTh -> (True, lbl { dgn_theory = invalidateProofs oTh th $ dgn_theory lbl }) ngTh = if chg then computeLabelTheory le dg (n, lbl1) else gTh in case ngTh of Just nth@(G_theory _ _ _ sens _) -> (if Map.null sens then markNodeConsistent "ByNoSentences" lbl1 else lbl1 { dgn_theory = proveLocalSens nth (dgn_theory lbl1) }) { globalTheory = ngTh } Nothing -> lbl1 Nothing -> lbl computeDGraphTheoriesAux :: LibEnv -> DGraph -> DGraph computeDGraphTheoriesAux le dgraph = foldl (\ dg l@(n, lbl) -> updatePending dg lbl (n, recomputeNodeLabel le dg l)) dgraph $ topsortedNodes dgraph computeLabelTheory :: LibEnv -> DGraph -> LNode DGNodeLab -> Maybe G_theory computeLabelTheory le dg (n, lbl) = let localTh = dgn_theory lbl in fmap reduceTheory . maybeResult $ if isDGRef lbl then case Map.lookup (dgn_libname lbl) le of Nothing -> return localTh -- do not crash here Just dg' -> do refTh <- getGlobalTheory $ labDG dg' $ dgn_node lbl joinG_sentences refTh localTh else do ths <- mapM (\ (s, _, l) -> do th <- let sl = labDG dg s in if isLocalDef $ dgl_type l then return $ dgn_theory sl else getGlobalTheory sl -- translate theory and turn all imported theorems into axioms translateG_theory (dgl_morphism l) $ theoremsToAxioms th) $ sortBy (flip $ comparing (\ (_, _, l) -> dgl_id l)) $ getImports dg n flatG_sentences localTh ths getImports :: DGraph -> Node -> [LEdge DGLinkLab] getImports dg = filter (liftE $ liftOr isGlobalDef isLocalDef) . innDG dg getImportNames :: DGraph -> Node -> [String] getImportNames dg = map (\ (s, _, _) -> getDGNodeName $ labDG dg s) . getImports dg reduceTheory :: G_theory -> G_theory reduceTheory (G_theory lid sig ind sens _) = G_theory lid sig ind (reduceSens sens) startThId updateLabelTheory :: LibEnv -> DGraph -> LNode DGNodeLab -> G_theory -> DGraph updateLabelTheory le dg (i, l) gth = let l' = l { dgn_theory = gth } n = (i, l' { globalTheory = computeLabelTheory le dg (i, l') }) in updatePending dg l n updatePending :: DGraph -> DGNodeLab -- ^ old label -> LNode DGNodeLab -- ^ node with new label -> DGraph updatePending dg l n = let dg0 = changeDGH dg $ SetNodeLab l n dg1 = togglePending dg0 $ changedLocalTheorems dg0 n dg2 = togglePending dg1 $ changedPendingEdges dg1 in groupHistory dg (DGRule "Node proof") dg2 {- | iterate all edgeId entries of the dg and increase all that are equal or above the old lId (1st param) so they will be above the desired nextLId (2nd param) -} renumberDGLinks :: EdgeId -> EdgeId -> DGraph -> DGraph renumberDGLinks (EdgeId i1) (EdgeId i2) dg = if i1 >= i2 then dg else changesDGH dg $ concatMap mkRenumberChange $ labEdgesDG dg where needUpd (EdgeId x) = x >= i1 offset = i2 - i1 add (EdgeId x) = EdgeId $ x + offset mkRenumberChange e@(s, t, l) = let ei = dgl_id l -- update links own id if required (upd, newId) = let b = needUpd ei in (b, if b then add ei else ei) -- make updates to links proof basis if required (upd', newTp) = let pB = getProofBasis l (b, pBids) = foldl (\ (bR, eiR) ei' -> let bi = needUpd ei' in (bR || bi, if bi then add ei' : eiR else ei' : eiR)) (False, []) $ Set.toList $ proofBasis pB in (b, (if b then flip updThmProofBasis . ProofBasis $ Set.fromList pBids else id) $ dgl_type l) -- update in dg unless no updates conducted in if upd || upd' then [DeleteEdge e, InsertEdge (s, t, l { dgl_id = newId, dgl_type = newTp })] else []
nevrenato/Hets_Fork
Static/ComputeTheory.hs
gpl-2.0
7,365
0
25
1,858
2,244
1,163
1,081
153
6
module Promise (Symbol, Constraint, Term, Promise(Thunk, Result)) where import Data import JSON import Store import Text.JSON type Symbol = Address Promise type Constraint = (Symbol, Promise) type Term = Either Symbol Data data Promise = Thunk String [Term] | Result Data instance JSON Promise where showJSON (Thunk str terms) = JSObject $ toJSObject [("function", showJSON str), ("arguments", JSArray $ map showJSON terms)] showJSON (Result dta) = showJSON dta readJSON (JSObject obj) = let pairs = fromJSObject obj in do fct <- property "function" pairs args <- property "arguments" pairs return $ Thunk fct args readJSON jsv = (readJSON jsv) >>= (return . Result)
lachrist/kusasa-hs
promise.hs
gpl-2.0
780
0
11
216
256
137
119
21
0
-- #hide ----------------------------------------------------------------------------- -- | -- Module : Graphics.UI.GLUT.Raw.Tokens -- Copyright : (c) Sven Panne 2009 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : stable -- Portability : portable -- -- All tokens from GLUT and freeglut. -- ----------------------------------------------------------------------------- module Graphics.UI.GLUT.Raw.Tokens where import Foreign.C.Types import Graphics.Rendering.OpenGL ( GLenum ) glut_ACCUM :: CUInt glut_ACCUM = 0x0004 glut_ACTION_CONTINUE_EXECUTION :: CInt glut_ACTION_CONTINUE_EXECUTION = 2 glut_ACTION_EXIT :: CInt glut_ACTION_EXIT = 0 glut_ACTION_GLUTMAINLOOP_RETURNS :: CInt glut_ACTION_GLUTMAINLOOP_RETURNS = 1 glut_ACTION_ON_WINDOW_CLOSE :: GLenum glut_ACTION_ON_WINDOW_CLOSE = 0x01F9 glut_ACTIVE_ALT :: CInt glut_ACTIVE_ALT = 0x0004 glut_ACTIVE_CTRL :: CInt glut_ACTIVE_CTRL = 0x0002 glut_ACTIVE_SHIFT :: CInt glut_ACTIVE_SHIFT = 0x0001 glut_ALLOW_DIRECT_CONTEXT :: CInt glut_ALLOW_DIRECT_CONTEXT = 1 glut_ALPHA :: CUInt glut_ALPHA = 0x0008 glut_AUX :: GLenum glut_AUX = 0x1000 glut_AUX1 :: CUInt glut_AUX1 = 0x1000 glut_AUX2 :: CUInt glut_AUX2 = 0x2000 glut_AUX3 :: CUInt glut_AUX3 = 0x4000 glut_AUX4 :: CUInt glut_AUX4 = 0x8000 glut_BLUE :: CInt glut_BLUE = 0x0002 glut_BORDERLESS :: CUInt glut_BORDERLESS = 0x0800 glut_CAPTIONLESS :: CUInt glut_CAPTIONLESS = 0x0400 glut_CORE_PROFILE :: CInt glut_CORE_PROFILE = 0x0001 glut_COMPATIBILITY_PROFILE :: CInt glut_COMPATIBILITY_PROFILE = 0x0002 glut_CREATE_NEW_CONTEXT :: CInt glut_CREATE_NEW_CONTEXT = 0 glut_CURSOR_BOTTOM_LEFT_CORNER :: CInt glut_CURSOR_BOTTOM_LEFT_CORNER = 0x0013 glut_CURSOR_BOTTOM_RIGHT_CORNER :: CInt glut_CURSOR_BOTTOM_RIGHT_CORNER = 0x0012 glut_CURSOR_BOTTOM_SIDE :: CInt glut_CURSOR_BOTTOM_SIDE = 0x000D glut_CURSOR_CROSSHAIR :: CInt glut_CURSOR_CROSSHAIR = 0x0009 glut_CURSOR_CYCLE :: CInt glut_CURSOR_CYCLE = 0x0005 glut_CURSOR_DESTROY :: CInt glut_CURSOR_DESTROY = 0x0003 glut_CURSOR_FULL_CROSSHAIR :: CInt glut_CURSOR_FULL_CROSSHAIR = 0x0066 glut_CURSOR_HELP :: CInt glut_CURSOR_HELP = 0x0004 glut_CURSOR_INFO :: CInt glut_CURSOR_INFO = 0x0002 glut_CURSOR_INHERIT :: CInt glut_CURSOR_INHERIT = 0x0064 glut_CURSOR_LEFT_ARROW :: CInt glut_CURSOR_LEFT_ARROW = 0x0001 glut_CURSOR_LEFT_RIGHT :: CInt glut_CURSOR_LEFT_RIGHT = 0x000B glut_CURSOR_LEFT_SIDE :: CInt glut_CURSOR_LEFT_SIDE = 0x000E glut_CURSOR_NONE :: CInt glut_CURSOR_NONE = 0x0065 glut_CURSOR_RIGHT_ARROW :: CInt glut_CURSOR_RIGHT_ARROW = 0x0000 glut_CURSOR_RIGHT_SIDE :: CInt glut_CURSOR_RIGHT_SIDE = 0x000F glut_CURSOR_SPRAY :: CInt glut_CURSOR_SPRAY = 0x0006 glut_CURSOR_TEXT :: CInt glut_CURSOR_TEXT = 0x0008 glut_CURSOR_TOP_LEFT_CORNER :: CInt glut_CURSOR_TOP_LEFT_CORNER = 0x0010 glut_CURSOR_TOP_RIGHT_CORNER :: CInt glut_CURSOR_TOP_RIGHT_CORNER = 0x0011 glut_CURSOR_TOP_SIDE :: CInt glut_CURSOR_TOP_SIDE = 0x000C glut_CURSOR_UP_DOWN :: CInt glut_CURSOR_UP_DOWN = 0x000A glut_CURSOR_WAIT :: CInt glut_CURSOR_WAIT = 0x0007 glut_DEBUG :: CInt glut_DEBUG = 0x0001 glut_DEPTH :: CUInt glut_DEPTH = 0x0010 glut_DEVICE_IGNORE_KEY_REPEAT :: GLenum glut_DEVICE_IGNORE_KEY_REPEAT = 0x0262 glut_DEVICE_KEY_REPEAT :: GLenum glut_DEVICE_KEY_REPEAT = 0x0263 glut_DIRECT_RENDERING :: GLenum glut_DIRECT_RENDERING = 0x01FE glut_DISPLAY_MODE_POSSIBLE :: GLenum glut_DISPLAY_MODE_POSSIBLE = 0x0190 glut_DOUBLE :: CUInt glut_DOUBLE = 0x0002 glut_DOWN :: CInt glut_DOWN = 0x0000 glut_ELAPSED_TIME :: GLenum glut_ELAPSED_TIME = 0x02BC glut_ENTERED :: CInt glut_ENTERED = 0x0001 glut_FORCE_DIRECT_CONTEXT :: CInt glut_FORCE_DIRECT_CONTEXT = 3 glut_FORCE_INDIRECT_CONTEXT :: CInt glut_FORCE_INDIRECT_CONTEXT = 0 glut_FORWARD_COMPATIBLE :: CInt glut_FORWARD_COMPATIBLE = 0x0002 glut_FULLY_COVERED :: CInt glut_FULLY_COVERED = 0x0003 glut_FULLY_RETAINED :: CInt glut_FULLY_RETAINED = 0x0001 glut_FULL_SCREEN :: GLenum glut_FULL_SCREEN = 0x01FF glut_GAME_MODE_ACTIVE :: GLenum glut_GAME_MODE_ACTIVE = 0x0000 glut_GAME_MODE_DISPLAY_CHANGED :: GLenum glut_GAME_MODE_DISPLAY_CHANGED = 0x0006 glut_GAME_MODE_HEIGHT :: GLenum glut_GAME_MODE_HEIGHT = 0x0003 glut_GAME_MODE_PIXEL_DEPTH :: GLenum glut_GAME_MODE_PIXEL_DEPTH = 0x0004 glut_GAME_MODE_POSSIBLE :: GLenum glut_GAME_MODE_POSSIBLE = 0x0001 glut_GAME_MODE_REFRESH_RATE :: GLenum glut_GAME_MODE_REFRESH_RATE = 0x0005 glut_GAME_MODE_WIDTH :: GLenum glut_GAME_MODE_WIDTH = 0x0002 glut_GREEN :: CInt glut_GREEN = 0x0001 glut_HAS_DIAL_AND_BUTTON_BOX :: GLenum glut_HAS_DIAL_AND_BUTTON_BOX = 0x025B glut_HAS_JOYSTICK :: GLenum glut_HAS_JOYSTICK = 0x0264 glut_HAS_KEYBOARD :: GLenum glut_HAS_KEYBOARD = 0x0258 glut_HAS_MOUSE :: GLenum glut_HAS_MOUSE = 0x0259 glut_HAS_OVERLAY :: GLenum glut_HAS_OVERLAY = 0x0322 glut_HAS_SPACEBALL :: GLenum glut_HAS_SPACEBALL = 0x025A glut_HAS_TABLET :: GLenum glut_HAS_TABLET = 0x025C glut_HIDDEN :: CInt glut_HIDDEN = 0x0000 glut_INDEX :: CUInt glut_INDEX = 0x0001 glut_INIT_DISPLAY_MODE :: GLenum glut_INIT_DISPLAY_MODE = 0x01F8 glut_INIT_FLAGS :: GLenum glut_INIT_FLAGS = 0x0202 glut_INIT_MAJOR_VERSION :: GLenum glut_INIT_MAJOR_VERSION = 0x0200 glut_INIT_MINOR_VERSION :: GLenum glut_INIT_MINOR_VERSION = 0x0201 glut_INIT_PROFILE :: GLenum glut_INIT_PROFILE = 0x0203 glut_INIT_STATE :: GLenum glut_INIT_STATE = 0x007C glut_INIT_WINDOW_HEIGHT :: GLenum glut_INIT_WINDOW_HEIGHT = 0x01F7 glut_INIT_WINDOW_WIDTH :: GLenum glut_INIT_WINDOW_WIDTH = 0x01F6 glut_INIT_WINDOW_X :: GLenum glut_INIT_WINDOW_X = 0x01F4 glut_INIT_WINDOW_Y :: GLenum glut_INIT_WINDOW_Y = 0x01F5 glut_JOYSTICK_AXES :: GLenum glut_JOYSTICK_AXES = 0x0267 glut_JOYSTICK_BUTTONS :: GLenum glut_JOYSTICK_BUTTONS = 0x0266 glut_JOYSTICK_BUTTON_A :: CUInt glut_JOYSTICK_BUTTON_A = 0x0001 glut_JOYSTICK_BUTTON_B :: CUInt glut_JOYSTICK_BUTTON_B = 0x0002 glut_JOYSTICK_BUTTON_C :: CUInt glut_JOYSTICK_BUTTON_C = 0x0004 glut_JOYSTICK_BUTTON_D :: CUInt glut_JOYSTICK_BUTTON_D = 0x0008 glut_JOYSTICK_POLL_RATE :: GLenum glut_JOYSTICK_POLL_RATE = 0x0268 glut_KEY_BEGIN :: CInt glut_KEY_BEGIN = 0x006E glut_KEY_DELETE :: CInt glut_KEY_DELETE = 0x006F glut_KEY_DOWN :: CInt glut_KEY_DOWN = 0x0067 glut_KEY_END :: CInt glut_KEY_END = 0x006B glut_KEY_F1 :: CInt glut_KEY_F1 = 0x0001 glut_KEY_F10 :: CInt glut_KEY_F10 = 0x000A glut_KEY_F11 :: CInt glut_KEY_F11 = 0x000B glut_KEY_F12 :: CInt glut_KEY_F12 = 0x000C glut_KEY_F2 :: CInt glut_KEY_F2 = 0x0002 glut_KEY_F3 :: CInt glut_KEY_F3 = 0x0003 glut_KEY_F4 :: CInt glut_KEY_F4 = 0x0004 glut_KEY_F5 :: CInt glut_KEY_F5 = 0x0005 glut_KEY_F6 :: CInt glut_KEY_F6 = 0x0006 glut_KEY_F7 :: CInt glut_KEY_F7 = 0x0007 glut_KEY_F8 :: CInt glut_KEY_F8 = 0x0008 glut_KEY_F9 :: CInt glut_KEY_F9 = 0x0009 glut_KEY_HOME :: CInt glut_KEY_HOME = 0x006A glut_KEY_INSERT :: CInt glut_KEY_INSERT = 0x006C glut_KEY_LEFT :: CInt glut_KEY_LEFT = 0x0064 glut_KEY_NUM_LOCK :: CInt glut_KEY_NUM_LOCK = 0x006D glut_KEY_PAGE_DOWN :: CInt glut_KEY_PAGE_DOWN = 0x0069 glut_KEY_PAGE_UP :: CInt glut_KEY_PAGE_UP = 0x0068 glut_KEY_REPEAT_DEFAULT :: CInt glut_KEY_REPEAT_DEFAULT = 0x0002 glut_KEY_REPEAT_OFF :: CInt glut_KEY_REPEAT_OFF = 0x0000 glut_KEY_REPEAT_ON :: CInt glut_KEY_REPEAT_ON = 0x0001 glut_KEY_RIGHT :: CInt glut_KEY_RIGHT = 0x0066 glut_KEY_UP :: CInt glut_KEY_UP = 0x0065 glut_LAYER_IN_USE :: GLenum glut_LAYER_IN_USE = 0x0321 glut_LEFT :: CInt glut_LEFT = 0x0000 glut_LEFT_BUTTON :: CInt glut_LEFT_BUTTON = 0x0000 glut_LUMINANCE :: CUInt glut_LUMINANCE = 0x0200 glut_MENU_IN_USE :: CInt glut_MENU_IN_USE = 0x0001 glut_MENU_NOT_IN_USE :: CInt glut_MENU_NOT_IN_USE = 0x0000 glut_MENU_NUM_ITEMS :: GLenum glut_MENU_NUM_ITEMS = 0x012C glut_MIDDLE_BUTTON :: CInt glut_MIDDLE_BUTTON = 0x0001 glut_MULTISAMPLE :: CUInt glut_MULTISAMPLE = 0x0080 glut_NORMAL :: GLenum glut_NORMAL = 0x0000 glut_NORMAL_DAMAGED :: GLenum glut_NORMAL_DAMAGED = 0x0324 glut_NOT_VISIBLE :: CInt glut_NOT_VISIBLE = 0x0000 glut_NUM_BUTTON_BOX_BUTTONS :: GLenum glut_NUM_BUTTON_BOX_BUTTONS = 0x025F glut_NUM_DIALS :: GLenum glut_NUM_DIALS = 0x0260 glut_NUM_MOUSE_BUTTONS :: GLenum glut_NUM_MOUSE_BUTTONS = 0x025D glut_NUM_SPACEBALL_BUTTONS :: GLenum glut_NUM_SPACEBALL_BUTTONS = 0x025E glut_NUM_TABLET_BUTTONS :: GLenum glut_NUM_TABLET_BUTTONS = 0x0261 glut_OVERLAY :: GLenum glut_OVERLAY = 0x0001 glut_OVERLAY_DAMAGED :: GLenum glut_OVERLAY_DAMAGED = 0x0325 glut_OVERLAY_POSSIBLE :: GLenum glut_OVERLAY_POSSIBLE = 0x0320 glut_OWNS_JOYSTICK :: GLenum glut_OWNS_JOYSTICK = 0x0265 glut_PARTIALLY_RETAINED :: CInt glut_PARTIALLY_RETAINED = 0x0002 glut_RED :: CInt glut_RED = 0x0000 glut_RENDERING_CONTEXT :: GLenum glut_RENDERING_CONTEXT = 0x01FD glut_RGB :: CUInt glut_RGB = 0x0000 glut_RGBA :: CUInt glut_RGBA = 0x0000 glut_RIGHT_BUTTON :: CInt glut_RIGHT_BUTTON = 0x0002 glut_SCREEN_HEIGHT :: GLenum glut_SCREEN_HEIGHT = 0x00C9 glut_SCREEN_HEIGHT_MM :: GLenum glut_SCREEN_HEIGHT_MM = 0x00CB glut_SCREEN_WIDTH :: GLenum glut_SCREEN_WIDTH = 0x00C8 glut_SCREEN_WIDTH_MM :: GLenum glut_SCREEN_WIDTH_MM = 0x00CA glut_SINGLE :: CUInt glut_SINGLE = 0x0000 glut_SRGB :: CUInt glut_SRGB = 0x1000 glut_STENCIL :: CUInt glut_STENCIL = 0x0020 glut_STEREO :: CUInt glut_STEREO = 0x0100 glut_TRANSPARENT_INDEX :: GLenum glut_TRANSPARENT_INDEX = 0x0323 glut_TRY_DIRECT_CONTEXT :: CInt glut_TRY_DIRECT_CONTEXT = 2 glut_UP :: CInt glut_UP = 0x0001 glut_USE_CURRENT_CONTEXT :: CInt glut_USE_CURRENT_CONTEXT = 1 glut_VERSION :: GLenum glut_VERSION = 0x01FC glut_VIDEO_RESIZE_HEIGHT :: GLenum glut_VIDEO_RESIZE_HEIGHT = 0x038D glut_VIDEO_RESIZE_HEIGHT_DELTA :: GLenum glut_VIDEO_RESIZE_HEIGHT_DELTA = 0x0389 glut_VIDEO_RESIZE_IN_USE :: GLenum glut_VIDEO_RESIZE_IN_USE = 0x0385 glut_VIDEO_RESIZE_POSSIBLE :: GLenum glut_VIDEO_RESIZE_POSSIBLE = 0x0384 glut_VIDEO_RESIZE_WIDTH :: GLenum glut_VIDEO_RESIZE_WIDTH = 0x038C glut_VIDEO_RESIZE_WIDTH_DELTA :: GLenum glut_VIDEO_RESIZE_WIDTH_DELTA = 0x0388 glut_VIDEO_RESIZE_X :: GLenum glut_VIDEO_RESIZE_X = 0x038A glut_VIDEO_RESIZE_X_DELTA :: GLenum glut_VIDEO_RESIZE_X_DELTA = 0x0386 glut_VIDEO_RESIZE_Y :: GLenum glut_VIDEO_RESIZE_Y = 0x038B glut_VIDEO_RESIZE_Y_DELTA :: GLenum glut_VIDEO_RESIZE_Y_DELTA = 0x0387 glut_VISIBLE :: CInt glut_VISIBLE = 0x0001 glut_WINDOW_ACCUM_ALPHA_SIZE :: GLenum glut_WINDOW_ACCUM_ALPHA_SIZE = 0x0072 glut_WINDOW_ACCUM_BLUE_SIZE :: GLenum glut_WINDOW_ACCUM_BLUE_SIZE = 0x0071 glut_WINDOW_ACCUM_GREEN_SIZE :: GLenum glut_WINDOW_ACCUM_GREEN_SIZE = 0x0070 glut_WINDOW_ACCUM_RED_SIZE :: GLenum glut_WINDOW_ACCUM_RED_SIZE = 0x006F glut_WINDOW_ALPHA_SIZE :: GLenum glut_WINDOW_ALPHA_SIZE = 0x006E glut_WINDOW_BLUE_SIZE :: GLenum glut_WINDOW_BLUE_SIZE = 0x006D glut_WINDOW_BORDER_WIDTH :: GLenum glut_WINDOW_BORDER_WIDTH = 0x01FA glut_WINDOW_BUFFER_SIZE :: GLenum glut_WINDOW_BUFFER_SIZE = 0x0068 glut_WINDOW_COLORMAP_SIZE :: GLenum glut_WINDOW_COLORMAP_SIZE = 0x0077 glut_WINDOW_CURSOR :: GLenum glut_WINDOW_CURSOR = 0x007A glut_WINDOW_DEPTH_SIZE :: GLenum glut_WINDOW_DEPTH_SIZE = 0x006A glut_WINDOW_DOUBLEBUFFER :: GLenum glut_WINDOW_DOUBLEBUFFER = 0x0073 glut_WINDOW_FORMAT_ID :: GLenum glut_WINDOW_FORMAT_ID = 0x007B glut_WINDOW_GREEN_SIZE :: GLenum glut_WINDOW_GREEN_SIZE = 0x006C glut_WINDOW_HEADER_HEIGHT :: GLenum glut_WINDOW_HEADER_HEIGHT = 0x01FB glut_WINDOW_HEIGHT :: GLenum glut_WINDOW_HEIGHT = 0x0067 glut_WINDOW_NUM_CHILDREN :: GLenum glut_WINDOW_NUM_CHILDREN = 0x0076 glut_WINDOW_NUM_SAMPLES :: GLenum glut_WINDOW_NUM_SAMPLES = 0x0078 glut_WINDOW_PARENT :: GLenum glut_WINDOW_PARENT = 0x0075 glut_WINDOW_RED_SIZE :: GLenum glut_WINDOW_RED_SIZE = 0x006B glut_WINDOW_RGBA :: GLenum glut_WINDOW_RGBA = 0x0074 glut_WINDOW_STENCIL_SIZE :: GLenum glut_WINDOW_STENCIL_SIZE = 0x0069 glut_WINDOW_STEREO :: GLenum glut_WINDOW_STEREO = 0x0079 glut_WINDOW_WIDTH :: GLenum glut_WINDOW_WIDTH = 0x0066 glut_WINDOW_X :: GLenum glut_WINDOW_X = 0x0064 glut_WINDOW_Y :: GLenum glut_WINDOW_Y = 0x0065
ducis/haAni
hs/common/Graphics/UI/GLUT/Raw/Tokens.hs
gpl-2.0
11,973
0
5
1,465
2,020
1,220
800
399
1
data Val = I Integer | S String | L [Val] | F Func | E Expr | ST State | Nil deriving (Show) data Proto = FP [String] Expr deriving (Show) data Func = NF NativeFunc | MF Proto State data Expr = Var String | Value Val | Call Expr [Expr] deriving (Show) type State = [(String, Val)] type NativeFunc = (State, Expr) -> (State, Expr) instance Show Func where show (NF _) = "NF" show (MF p s) = show p getVal :: State -> String -> Val getVal [] _ = Nil getVal ((k, v):xs) t = if t == k then v else getVal xs t add :: (State, Expr) -> (State, Expr) add (s, (Call _ (x:y:[]))) = (s, Value (I (x0 + y0))) where (I x0) = exec2Val s x (I y0) = exec2Val s y def :: (State, Expr) -> (State, Expr) def (s, (Call _ (x:y:[]))) = (ns, (Value value)) where (S name) = (exec2Val ns x) value = (exec2Val ns y) ns = (name, value):s def _ = undefined ifel :: (State, Expr) -> (State, Expr) ifel (s, (Call _ (x:y:z:[]))) = if ret == 0 then exec (s, z) else exec (s, y) where (I ret) = exec2Val s x ifel _ = undefined strlst :: (State, Expr) -> (State, Expr) strlst _ = undefined lmd :: (State, Expr) -> (State, Expr) lmd (s, (Call _ (x:y:[]))) = undefined exec2Val :: State -> Expr -> Val exec2Val s e = let (_, (Value ret)) = exec (s, e) in ret exec :: (State, Expr) -> (State, Expr) exec (s, (Value v)) = case v of (E e) -> exec (s, e) v -> (s, (Value v)) exec (s, (Var name)) = (s, Value $ getVal s name) exec (s, Call e l) = case (exec2Val s e) of (F (NF f)) -> f (s, (Call e l)) (F (MF (FP argv body) ps)) -> (s, ret) where ts = (zip argv (map (exec2Val s) l)) ++ ps (_, ret) = exec (ts, body) fststr :: String -> (String, String) fststr [] = ([], []) fststr ('(':xs) = ("(", xs) fststr (')':xs) = (")", xs) fststr (' ':xs) = ([], xs) fststr (x:xs) = let (y, ys) = fststr xs in if y == [] then (x:y, ys) else if (last y) == ')' then (x:(init y), ')':ys) else (x:y, ys) str2lst :: String -> [String] str2lst [] = [] str2lst s = if x == [] then ys else x:ys where (x, xs) = fststr s ys = str2lst xs str2Val :: String -> Val str2Val s = I (read s) str2expr :: [String] -> (Expr, [String]) str2expr (x:xs) = if (elem (head x) "0123456789") then (Value (str2Val x), xs) else if x == "(" then undefined else if x == ")" then undefined else (Var x, xs) lst2expr :: [String] -> [Expr] lst2expr (x:xs) = undefined parser :: String -> [Expr] parser = undefined func0 = MF (FP ["a", "b"] (Call (Var "+") [Var "a", Var "b"])) state func1 = MF (FP ["n"] (Call (Var "if") [Var "n", Call (Var "+") [Var "n", Call (Var "func1") [Call (Var "+") [Var "n", Value (I (-1))]]], Value (I 0)])) state func2 = MF (FP ["n"] (Call (Var "if") [Var "n", Value (I 1), Value (I 0)])) state func3 = MF (FP ["n"] (Var "n")) state fib = MF (FP ["a", "b", "n"] (Call (Var "if") [Var "n", Call (Var "fib") [Var "b", Call (Var "+") [Var "a", Var "b"], Call (Var "+") [Var "n", Value (I (-1))]], Var "a"])) state state = [("z", I 0), ("a", I 1), ("b", I 2), ("c", I 3), ("d", I 4), ("func0", F func0), ("func1", F func1), ("func2", F func2), ("func3", F func3), ("fib", F fib), ("+", F (NF add)), ("def", F (NF def)), ("if", F (NF ifel))] :: State expr0 = Call (Var "+") [Value (I 1), Var "b"] expr1 = Call (Var "def") [Value (S "a"), Value (I 3)] expr2 = Call (Var "func0") [Var "c", Var "d"] expr3 = Call (Var "func1") [Var "c"] expr4 = Call (Var "func2") [Var "c"] expr5 = Call (Var "fib") [Value (I 0), Value (I 1), Var "d"] originStr = "(def f (lambda (x y) (+ x Y)))"
FiveEye/xlang
proto/proto0.hs
gpl-2.0
3,514
50
21
807
2,319
1,255
1,064
81
4
{-# LANGUAGE TemplateHaskell #-} module Code.Huffman.LR where -- $Id$ import Autolib.ToDoc import Autolib.Reader import Code.Type import Data.Typeable data LR = L | R deriving ( Eq, Ord, Enum, Bounded, Typeable ) $(derives [makeReader, makeToDoc] [''LR]) data Ord a => Letter a = Letter { weight :: Int , codes :: Code a LR } $(derives [makeReader, makeToDoc] [''Letter]) -- local variables: -- mode: haskell -- end;
florianpilz/autotool
src/Code/Huffman/LR.hs
gpl-2.0
468
7
10
117
146
87
59
13
0
{-# LANGUAGE OverloadedStrings #-} module WebParsing.ParsingHelp (CoursePart, (-:), (~:), emptyCourse, preProcess, replaceAll, tagContains, dropBetween, dropBetweenAll, dropAround, isCourse, isCancelled, lowerTag, notCancelled, parseDescription, parseCorequisite, parsePrerequisite, parseExclusion, parseRecommendedPrep, parseDistAndBreadth) where import Text.Regex.Posix ((=~)) import Text.HTML.TagSoup import qualified Data.Text as T import Database.Tables import WebParsing.PrerequisiteParsing type CoursePart = ([Tag T.Text], Course) (-:) :: a -> (a -> a) -> a coursepart -: fn = fn coursepart (~:) :: CoursePart -> ([Tag T.Text] -> [Tag T.Text]) -> CoursePart (tags, course) ~: fn = (fn tags, course) emptyCourse :: Course emptyCourse = Course { breadth = Nothing, description = Nothing, title = Nothing, prereqString = Nothing, fallSession = Nothing, springSession = Nothing, yearSession = Nothing, name = "", exclusions = Nothing, manualTutorialEnrolment = Nothing, manualPracticalEnrolment = Nothing, distribution = Nothing, prereqs = Nothing, coreqs = Nothing, videoUrls = []} replaceAll :: [T.Text] -> T.Text -> T.Text -> T.Text replaceAll matches replacement str = foldl (\foldStr match-> T.replace match replacement foldStr) str matches {------------------------------------------------------------------------------ INPUT: a tag containing string tagtext, and reg, a regex string OUTPUT: True if reg can match tagtext -------------------------------------------------------------------------------} tagContains :: [T.Text] -> Tag T.Text -> Bool tagContains matches (TagText tagtext) = True == foldl (\bool match -> or [(T.isInfixOf match tagtext), bool]) False matches --converts all open and closing tags to lowercase. lowerTag :: Tag T.Text -> Tag T.Text lowerTag (TagOpen tag attrs) = TagOpen (T.toLower tag) (map (\(x, z) -> (T.toLower x, T.toLower z)) attrs) lowerTag (TagClose tag) = TagClose (T.toLower tag) lowerTag text = text --returns true if the the row contains a cancelled lecture or tutorial isCancelled :: [T.Text] -> Bool isCancelled row = foldl (\bool text -> bool || T.isPrefixOf "Cancel" text) False row notCancelled :: [T.Text] -> Bool notCancelled row = not (isCancelled row) {------------------------------------------------------------------------------ splits a list of tags into two pieces at the first matching instance of reg. e.g >>tagBreak "hehe" [TagtText "lol", TagText "lmao", TagText "hehe] >>([TagText "lol", TagText "lmao"], [TagText "hehe"]) if no matches occur >>tagBreak "wat" [TagtText "lol", TagText "lmao", TagText "hehe] >>([TagtText "lol", TagText "lmao", TagText "hehe], []) -------------------------------------------------------------------------------} tagBreak :: [T.Text] -> [Tag T.Text] -> (Maybe [Tag T.Text], [Tag T.Text]) tagBreak reg tags = let first = takeWhile (\tag -> not $ tagContains reg tag) tags second = dropWhile (\tag -> not $ tagContains reg tag) tags in if first == [] then (Nothing, second) else (Just first, second) {------------------------------------------------------------------------------ takes in a possible list of tags that represent a specific field in a Course Record. removes instances of str, and concatenates all tagText into a single Text entity. If nothing needs to be removed, pass Nothing as the Text ------------------------------------------------------------------------------} makeEntry :: Maybe [Tag T.Text] -> Maybe [T.Text] -> Maybe T.Text makeEntry Nothing _ = Nothing makeEntry (Just []) _ = Nothing makeEntry (Just tags) Nothing = Just (T.concat (map fromTagText tags)) makeEntry (Just tags) (Just str) = Just $ T.strip $ (replaceAll str "" (T.concat (map fromTagText tags))) {------------------------------------------------------------------------------ ------------------------------------------------------------------------------} replaceBetween :: Eq a => (a -> Bool) -> (a -> Bool) -> [a] -> [a]-> [a] replaceBetween start end rep lst = let (before, rest) = break start lst (_, after) = break end rest in if (after == []) then before else (concat [before, rep, (drop 1 after)]) replaceBetweenAll :: Eq a => (a -> Bool) -> (a -> Bool) -> [a] -> [a]-> [a] replaceBetweenAll _ _ _ [] = [] replaceBetweenAll start end rep lst = let (before, rest) = break start lst (_, after) = break end rest in if (or [(rest == []), (after == [])]) then lst else (concat [before, rep, (replaceBetweenAll start end rep (drop 1 after))]) {------------------------------------------------------------------------------ DROPBETWEEN removes all elements between the first element satisfying start, and the first element satisfying end inclusive. >>dropBetween (== 'b') (== 'd') "abcde" >>"ae" ------------------------------------------------------------------------------} dropBetween :: Eq a => (a -> Bool) -> (a -> Bool) -> [a] -> [a] dropBetween start end lst = replaceBetween start end [] lst dropBetweenAll :: Eq a => (a -> Bool) -> (a -> Bool) -> [a] -> [a] dropBetweenAll start end lst = replaceBetweenAll start end [] lst {------------------------------------------------------------------------------ DROPAROUND takes a list, returns all elements between the first element satisfies start, and first element after that satisfies end. >>dropAround (== 'b') (=='d') "abcde" >>"c" ------------------------------------------------------------------------------} dropAround :: Eq a => (a->Bool) -> (a-> Bool) -> [a] -> [a] dropAround start end lst = let dropBefore = tail $ dropWhile (\x -> (not $ start x)) lst takeBetween = takeWhile (\x -> (not $ end x)) dropBefore in takeBetween -------------COURSE PARSING FUNCTIONS------------------------------------------ ------------------------------------------------------------------------------- preProcess :: [Tag T.Text] -> [Tag T.Text] preProcess tags = let nobreaks = filter (/= TagText "\r\n") tags removeUseless = filter isntUseless nobreaks removeEnrol = filter (\t -> not $ tagContains ["Enrolment Limits:"] t) removeUseless in map cleanText removeEnrol where cleanText (TagText str) = TagText (replaceAll ["\r\n ", "\n ","\160","\194","\r\n"] "" str) isntUseless (TagText str) = not $ T.all (\c -> or [(c == ' '), (c =='\n')]) str parseDescription :: CoursePart -> CoursePart parseDescription (tags, course) = let (parsed, rest) = tagBreak ["Prerequisite","Corequisite","Exclusion","Recommended","Distribution","Breadth"] tags descriptn = makeEntry parsed Nothing in (rest, course {description = descriptn}) parsePrerequisite :: CoursePart -> CoursePart parsePrerequisite (tags, course) = let (parsed, rest) = tagBreak ["Corequisite","Exclusion","Recommended","Distribution","Breadth"] tags prereqstr = makeEntry parsed (Just ["Prerequisite:"]) prereq = parsePrerequisites prereqstr in (rest, course {prereqString = prereqstr, prereqs = prereq}) parseCorequisite :: CoursePart -> CoursePart parseCorequisite (tags, course) = let (parsed, rest) = tagBreak ["Exclusion","Recommended","Distribution","Breadth"] tags coreq = makeEntry parsed (Just ["Corequisite:"]) in (rest, course {coreqs = coreq}) parseExclusion :: CoursePart -> CoursePart parseExclusion (tags, course) = let (parsed, rest) = tagBreak ["Recommended","Distribution","Breadth"] tags ex = makeEntry parsed (Just ["Exclusion:"]) in (rest, course {exclusions = ex}) parseRecommendedPrep :: CoursePart -> CoursePart parseRecommendedPrep (tags, course) = let (_, rest) = tagBreak ["Distribution","Breadth"] tags in (rest, course) parseDistAndBreadth :: CoursePart -> CoursePart parseDistAndBreadth (tags, course) = let dist = makeEntry (Just (filter (tagContains ["Distribution"]) tags)) (Just ["Distribution Requirement Status: "]) brdth = makeEntry (Just (filter (tagContains ["Breadth"]) tags)) (Just ["Breadth Requirement: "]) in (tail $ tail tags, course {distribution = dist, breadth = brdth}) -- | returns true if text is a valid course code. isCourse :: T.Text -> Bool isCourse text = let pat = "[A-Z]{3}[0-9]{3}[HY][0-9]" :: String in (T.unpack text) =~ pat
arkon/courseography
hs/WebParsing/ParsingHelp.hs
gpl-3.0
8,717
0
16
1,767
2,414
1,317
1,097
144
2
module HLinear.FramedModule.Definition where import HLinear.Utility.Prelude import HLinear.Matrix.Definition ( Matrix(..) ) import HLinear.Hook.EchelonForm ( EchelonForm(..) ) -- we work with echelon forms of row matrices data FramedModule a = FramedModuleBasis (EchelonForm a) (Vector Int) | FramedModuleDual (EchelonForm a) (Vector Int) deriving ( Show )
martinra/hlinear
src/HLinear/FramedModule/Definition.hs
gpl-3.0
370
0
8
56
94
57
37
8
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} module Ampersand.Output.ToJSON.JSONutils (writeJSONFile, JSON(..), ToJSON(..) , module Ampersand.Basics , module Ampersand.Classes , module Ampersand.Core.ParseTree , module Ampersand.Core.ShowAStruct , module Ampersand.FSpec.ToFSpec.Populated , module Ampersand.FSpec.FSpec , module Ampersand.FSpec.SQL , module Ampersand.Misc , module GHC.Generics ) where import Ampersand.Basics import Ampersand.Classes import Ampersand.Core.ParseTree ( Role, ViewHtmlTemplate(ViewHtmlTemplateFile)) import Ampersand.Core.ShowAStruct import Ampersand.FSpec.ToFSpec.Populated import Ampersand.FSpec.FSpec import Ampersand.FSpec.SQL (sqlQuery,sqlQueryWithPlaceholder,placeHolderSQL,broadQueryWithPlaceholder) import Ampersand.Misc import Ampersand.Prototype.ProtoUtil(getGenericsDir) import Data.Aeson hiding (Options) import qualified Data.Aeson.Types as AT import Data.Aeson.Encode.Pretty import qualified Data.ByteString.Lazy as BS import Data.List import GHC.Generics import System.FilePath import System.Directory writeJSONFile :: ToJSON a => Options -> FilePath -> a -> IO() writeJSONFile opts fName x = do verboseLn opts (" Generating "++file) createDirectoryIfMissing True (takeDirectory fullFile) BS.writeFile fullFile (encodePretty x) where file = fName <.> "json" fullFile = getGenericsDir opts </> file -- We use aeson to generate .json in a simple and efficient way. -- For details, see http://hackage.haskell.org/package/aeson/docs/Data-Aeson.html#t:ToJSON class (GToJSON Zero (Rep b), Generic b) => JSON a b | b -> a where fromAmpersand :: MultiFSpecs -> a -> b amp2Jason :: b -> Value amp2Jason = genericToJSON ampersandDefault -- These are the modified defaults, to generate .json ampersandDefault :: AT.Options ampersandDefault = defaultOptions {AT.fieldLabelModifier = alterLabel} where -- The label of a field is modified before it is written in the JSON file. -- this is done because of different restrictions at the Haskell side and at -- the .json side. In our case, we strip all characters upto the first occurence -- of the prefix "JSON" (which is mandatory). in the rest of that string, we -- substitute all underscores with dots. alterLabel str = case filter (isPrefixOf pfx) (tails str) of [] -> fatal ("Label at Haskell side must contain `JSON`: "++str) xs -> replace '_' '.' . snd . splitAt (length pfx) . head $ xs where pfx = "JSON" -- | Replaces all instances of a value in a list by another value. replace :: Eq a => a -- ^ Value to look for -> a -- ^ Value to replace it with -> [a] -- ^ Input list -> [a] -- ^ Output list replace x y = map (\z -> if z == x then y else z)
AmpersandTarski/ampersand
src/Ampersand/Output/ToJSON/JSONutils.hs
gpl-3.0
3,024
0
15
690
598
350
248
55
2
{-# LANGUAGE OverloadedStrings #-} -- Copyright (C) 2011 John Millikin <jmillikin@gmail.com> -- -- 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 -- any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module Anansi.HsColour ( loomHTML , loomLaTeX , looms ) where import qualified Data.Map import Data.Text (Text) import qualified Anansi import Anansi.HsColour.HTML (loomHTML) import Anansi.HsColour.LaTeX (loomLaTeX) -- | Looms which use HsColour to produce colorized code blocks. -- -- Use this with 'Anansi.defaultMain': -- -- > #!/usr/bin/env runhaskell -- > import Anansi -- > import Anansi.HsColour -- > import Data.Map -- > -- > main = defaultMain (unions [Anansi.looms, Anansi.HsColour.looms]) looms :: Data.Map.Map Text Anansi.Loom looms = Data.Map.fromList [ ("anansi-hscolour.html", loomHTML) , ("anansi-hscolour.latex", loomLaTeX) ]
jmillikin/anansi-hscolour
lib/Anansi/HsColour.hs
gpl-3.0
1,411
8
7
249
136
93
43
14
1
module ValueMatrix where import Data.Array.IArray import Data.Array.Base as A ((!)) import Data.Monoid import Data.Tuple import Vector import Control.DeepSeq.Generics type VMKey = (Int,Int) type VMat a = Array VMKey a data ValueMatrix a = VM { vmat :: !(VMat a) } -- deriving Eq -- TODO: newtype instance NFData a => NFData (ValueMatrix a) where rnf (VM arr) = rnf arr instance Functor ValueMatrix where fmap f vm = vm { vmat = amap f (vmat vm) } (#) :: ValueMatrix a -> VMKey -> a vm # key = vmat vm A.! key rows :: ValueMatrix a -> Vector (Vector a) rows vm = vecList cols' where (xdim,ydim) = dim vm mkRow j i | j > ydim = [] | otherwise = vm # (i,j) : mkRow (j+1) i cols' = map (vecList . mkRow 1) [1..xdim] cols :: ValueMatrix a -> Vector (Vector a) cols vm = vecList rows' where (xdim,ydim) = dim vm mkCol i j | i > xdim = [] | otherwise = vm # (i,j) : mkCol (i+1) j rows' = map (vecList . mkCol 1) [1..ydim] fromRows :: Vector (Vector a) -> ValueMatrix a fromRows vecs = VM $ listArray ((1,1),(xdim,ydim)) vals where xdim = vecLength vecs ydim = vecLength $ vecs Vector.! 1 vals = mconcat $ map fillVec $ fillVec vecs fromCols :: Vector (Vector a) -> ValueMatrix a fromCols vecs = transpose $ VM $ listArray ((1,1),(ydim,xdim)) vals where ydim = vecLength vecs xdim = vecLength $ vecs Vector.! 1 vals = mconcat $ map fillVec $ fillVec vecs transpose :: ValueMatrix a -> ValueMatrix a transpose vm = VM $ ixmap ((1,1),dim') swap $ vmat vm where dim' = swap $ dim vm dim :: ValueMatrix a -> VMKey dim = snd . bounds . vmat instance (Show a, Eq a) => Show (ValueMatrix a) where show = show . rows
KiNaudiz/bachelor
CN/ValueMatrix.hs
gpl-3.0
1,859
0
11
570
800
418
382
50
1
module Y2015.R1A.A where import Data.List import Data.Maybe import Data.String.Utils solve :: Problem -> Solution parse :: [String] -> [Problem] data Solution = Solution Int Int deriving (Eq) instance Show Solution where show (Solution y z) = show y ++ " " ++ show z data Problem = Problem { xs :: [Int] } deriving (Eq, Show) parse (_:ss:rest) = let xs = map read $ words ss in Problem xs : parse rest parse [] = [] solve (Problem xs) = Solution eatEmAll eatConstantly where eatEmAll = sum eatings eatConstantly = sum $ map (min (maximum eatings)) $ init xs eatings = filter (>=0) . zipWith (-) xs $ tail xs
joranvar/GoogleCodeJam
Y2015/R1A/A.hs
gpl-3.0
687
0
13
190
284
148
136
20
1
import System.Exit import System.Environment main = getArgs >>= exitWith . ExitFailure . read . head
YoshikuniJujo/hake_haskell
examples/exitTest/exitWith.hs
gpl-3.0
102
0
8
16
32
17
15
3
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Reservations.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes the specified reservation. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.reservations.delete@. module Network.Google.Resource.Compute.Reservations.Delete ( -- * REST Resource ReservationsDeleteResource -- * Creating a Request , reservationsDelete , ReservationsDelete -- * Request Lenses , rdRequestId , rdProject , rdReservation , rdZone ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.reservations.delete@ method which the -- 'ReservationsDelete' request conforms to. type ReservationsDeleteResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "reservations" :> Capture "reservation" Text :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes the specified reservation. -- -- /See:/ 'reservationsDelete' smart constructor. data ReservationsDelete = ReservationsDelete' { _rdRequestId :: !(Maybe Text) , _rdProject :: !Text , _rdReservation :: !Text , _rdZone :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ReservationsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rdRequestId' -- -- * 'rdProject' -- -- * 'rdReservation' -- -- * 'rdZone' reservationsDelete :: Text -- ^ 'rdProject' -> Text -- ^ 'rdReservation' -> Text -- ^ 'rdZone' -> ReservationsDelete reservationsDelete pRdProject_ pRdReservation_ pRdZone_ = ReservationsDelete' { _rdRequestId = Nothing , _rdProject = pRdProject_ , _rdReservation = pRdReservation_ , _rdZone = pRdZone_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). rdRequestId :: Lens' ReservationsDelete (Maybe Text) rdRequestId = lens _rdRequestId (\ s a -> s{_rdRequestId = a}) -- | Project ID for this request. rdProject :: Lens' ReservationsDelete Text rdProject = lens _rdProject (\ s a -> s{_rdProject = a}) -- | Name of the reservation to delete. rdReservation :: Lens' ReservationsDelete Text rdReservation = lens _rdReservation (\ s a -> s{_rdReservation = a}) -- | Name of the zone for this request. rdZone :: Lens' ReservationsDelete Text rdZone = lens _rdZone (\ s a -> s{_rdZone = a}) instance GoogleRequest ReservationsDelete where type Rs ReservationsDelete = Operation type Scopes ReservationsDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient ReservationsDelete'{..} = go _rdProject _rdZone _rdReservation _rdRequestId (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy ReservationsDeleteResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Reservations/Delete.hs
mpl-2.0
4,570
0
17
1,052
552
330
222
85
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Drive.Comments.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a comment. -- -- /See:/ <https://developers.google.com/drive/ Drive API Reference> for @drive.comments.delete@. module Network.Google.Resource.Drive.Comments.Delete ( -- * REST Resource CommentsDeleteResource -- * Creating a Request , commentsDelete , CommentsDelete -- * Request Lenses , cdFileId , cdCommentId ) where import Network.Google.Drive.Types import Network.Google.Prelude -- | A resource alias for @drive.comments.delete@ method which the -- 'CommentsDelete' request conforms to. type CommentsDeleteResource = "drive" :> "v3" :> "files" :> Capture "fileId" Text :> "comments" :> Capture "commentId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Deletes a comment. -- -- /See:/ 'commentsDelete' smart constructor. data CommentsDelete = CommentsDelete' { _cdFileId :: !Text , _cdCommentId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CommentsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cdFileId' -- -- * 'cdCommentId' commentsDelete :: Text -- ^ 'cdFileId' -> Text -- ^ 'cdCommentId' -> CommentsDelete commentsDelete pCdFileId_ pCdCommentId_ = CommentsDelete' {_cdFileId = pCdFileId_, _cdCommentId = pCdCommentId_} -- | The ID of the file. cdFileId :: Lens' CommentsDelete Text cdFileId = lens _cdFileId (\ s a -> s{_cdFileId = a}) -- | The ID of the comment. cdCommentId :: Lens' CommentsDelete Text cdCommentId = lens _cdCommentId (\ s a -> s{_cdCommentId = a}) instance GoogleRequest CommentsDelete where type Rs CommentsDelete = () type Scopes CommentsDelete = '["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"] requestClient CommentsDelete'{..} = go _cdFileId _cdCommentId (Just AltJSON) driveService where go = buildClient (Proxy :: Proxy CommentsDeleteResource) mempty
brendanhay/gogol
gogol-drive/gen/Network/Google/Resource/Drive/Comments/Delete.hs
mpl-2.0
2,937
0
14
685
388
233
155
60
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.Glacier.GetVaultNotifications -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | This operation retrieves the 'notification-configuration' subresource of the -- specified vault. -- -- For information about setting a notification configuration on a vault, see 'SetVaultNotifications'. If a notification configuration for a vault is not set, the operation -- returns a '404 Not Found' error. For more information about vault -- notifications, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/configuring-notifications.html Configuring Vault Notifications in Amazon Glacier>. -- -- An AWS account has full permission to perform all operations (actions). -- However, AWS Identity and Access Management (IAM) users don't have any -- permissions by default. You must grant them explicit permission to perform -- specific actions. For more information, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identityand Access Management (IAM)>. -- -- For conceptual information and underlying REST API, go to <http://docs.aws.amazon.com/amazonglacier/latest/dev/configuring-notifications.html Configuring VaultNotifications in Amazon Glacier> and <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vault-notifications-get.html Get Vault Notification Configuration > in -- the /Amazon Glacier Developer Guide/. -- -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-GetVaultNotifications.html> module Network.AWS.Glacier.GetVaultNotifications ( -- * Request GetVaultNotifications -- ** Request constructor , getVaultNotifications -- ** Request lenses , gvnAccountId , gvnVaultName -- * Response , GetVaultNotificationsResponse -- ** Response constructor , getVaultNotificationsResponse -- ** Response lenses , gvnrVaultNotificationConfig ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.RestJSON import Network.AWS.Glacier.Types import qualified GHC.Exts data GetVaultNotifications = GetVaultNotifications { _gvnAccountId :: Text , _gvnVaultName :: Text } deriving (Eq, Ord, Read, Show) -- | 'GetVaultNotifications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gvnAccountId' @::@ 'Text' -- -- * 'gvnVaultName' @::@ 'Text' -- getVaultNotifications :: Text -- ^ 'gvnAccountId' -> Text -- ^ 'gvnVaultName' -> GetVaultNotifications getVaultNotifications p1 p2 = GetVaultNotifications { _gvnAccountId = p1 , _gvnVaultName = p2 } -- | The 'AccountId' is the AWS Account ID. You can specify either the AWS Account -- ID or optionally a '-', in which case Amazon Glacier uses the AWS Account ID -- associated with the credentials used to sign the request. If you specify your -- Account ID, do not include hyphens in it. gvnAccountId :: Lens' GetVaultNotifications Text gvnAccountId = lens _gvnAccountId (\s a -> s { _gvnAccountId = a }) -- | The name of the vault. gvnVaultName :: Lens' GetVaultNotifications Text gvnVaultName = lens _gvnVaultName (\s a -> s { _gvnVaultName = a }) newtype GetVaultNotificationsResponse = GetVaultNotificationsResponse { _gvnrVaultNotificationConfig :: Maybe VaultNotificationConfig } deriving (Eq, Read, Show) -- | 'GetVaultNotificationsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gvnrVaultNotificationConfig' @::@ 'Maybe' 'VaultNotificationConfig' -- getVaultNotificationsResponse :: GetVaultNotificationsResponse getVaultNotificationsResponse = GetVaultNotificationsResponse { _gvnrVaultNotificationConfig = Nothing } -- | Returns the notification configuration set on the vault. gvnrVaultNotificationConfig :: Lens' GetVaultNotificationsResponse (Maybe VaultNotificationConfig) gvnrVaultNotificationConfig = lens _gvnrVaultNotificationConfig (\s a -> s { _gvnrVaultNotificationConfig = a }) instance ToPath GetVaultNotifications where toPath GetVaultNotifications{..} = mconcat [ "/" , toText _gvnAccountId , "/vaults/" , toText _gvnVaultName , "/notification-configuration" ] instance ToQuery GetVaultNotifications where toQuery = const mempty instance ToHeaders GetVaultNotifications instance ToJSON GetVaultNotifications where toJSON = const (toJSON Empty) instance AWSRequest GetVaultNotifications where type Sv GetVaultNotifications = Glacier type Rs GetVaultNotifications = GetVaultNotificationsResponse request = get response = jsonResponse instance FromJSON GetVaultNotificationsResponse where parseJSON = withObject "GetVaultNotificationsResponse" $ \o -> GetVaultNotificationsResponse <$> o .:? "vaultNotificationConfig"
kim/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/GetVaultNotifications.hs
mpl-2.0
5,802
0
9
1,070
539
333
206
68
1
import System.Environment import System.Directory import System.IO import Data.List import Control.Exception dispatch :: String -> [String] -> IO () dispatch "add" = add dispatch "view" = view dispatch "remove" = remove main = do (command:argList) <- getArgs dispatch command argList add :: [String] -> IO () add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n") view :: [String] -> IO () view [fileName] = do contents <- readFile fileName let todoTasks = lines contents numberedTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks putStr $ unlines numberedTasks remove :: [String] -> IO () remove [fileName, numberString] = do contents <- readFile fileName let todoTasks = lines contents numberedTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks putStrLn "These are your TO-DO items:" mapM_ putStrLn numberedTasks let number = read numberString newTodoItems = unlines $ delete (todoTasks !! number) todoTasks bracketOnError (openTempFile "." "temp") (\(tempName, tempHandle) -> do hClose tempHandle removeFile tempName) (\(tempName, tempHandle) -> do hPutStr tempHandle newTodoItems hClose tempHandle removeFile "todo.txt" renameFile tempName "todo.txt")
alexliew/learn_you_a_haskell
code/todo2.hs
unlicense
1,352
0
15
327
459
227
232
40
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} module Lib where import qualified Data.ByteString as B (ByteString) import qualified Data.ByteString.Char8 as BC (putStrLn) import qualified Pipes as P (Consumer', MonadIO, Producer', Proxy, each, for, for, lift, runEffect, (>->)) import qualified Pipes.ByteString as PB (fromHandle, stdout) import qualified Pipes.HTTP as PH (defaultManagerSettings, method, newManager, parseUrl, requestBody, requestHeaders, responseBody, stream, withHTTP) import qualified Pipes.Network.TCP as PN (SockAddr, Socket, closeSock, connectSock, fromSocket, send, toSocket) import qualified Pipes.Prelude as PP (take) import qualified Pipes.Safe as PS (SafeT, bracket, runSafeT) import Prelude as PL hiding (readFile) import qualified System.IO as IO (IOMode (ReadMode), hClose, openFile, withFile) ------------------------------------------------------------------------------ connect :: P.MonadIO m => m (PN.Socket, PN.SockAddr) connect = PN.connectSock "127.0.0.1" "3000" close :: P.MonadIO m => PN.Socket -> m () close = PN.closeSock mkP :: P.MonadIO m => PN.Socket -> P.Producer' B.ByteString m () mkP s = PN.fromSocket s 4096 mkC :: P.MonadIO m => PN.Socket -> P.Consumer' B.ByteString m r mkC = PN.toSocket sendIt :: P.MonadIO m => PN.Socket -> m () sendIt soc = do let c = mkC soc -- P.runEffect $ PB.stdin P.>-> PP.take 1 P.>-> c P.runEffect $ P.each ["a", "b", "c", "\n"] P.>-> c tt :: P.MonadIO m => m () tt = P.runEffect $ P.each ["a", "b", "c", "\n"] P.>-> PB.stdout recIt :: PN.Socket -> IO () recIt soc = do let p = mkP soc P.runEffect $ doRecv p doRecv :: P.Proxy x' x () B.ByteString IO a' -> P.Proxy x' x c' c IO a' -- doRecv :: P.Producer' B.ByteString IO () -> P.Effect IO () doRecv p = P.for p $ \b -> P.lift $ BC.putStrLn b -- uses pipes to send and receive doit :: IO () doit = do c <- Lib.connect let s = fst c sendIt s recIt s close s -- uses socket directly to send / receives with pipes doit2 :: IO () doit2 = do c <- Lib.connect let s = fst c p = mkP s PN.send s "foo\n" P.runEffect $ doRecv p close s return () ------------------------------------------------------------------------------ fi :: FilePath fi = "TAGS" dox :: FilePath -> IO () dox filename = IO.withFile filename IO.ReadMode $ \hIn -> do r <- PH.parseUrl "http://127.0.0.1:3000/validator/validate" let req = r { PH.method = "POST" , PH.requestHeaders = [ ("Accept" , "application/json") , ("Content-Type", "application/swagger+json; version=2.0") ] , PH.requestBody = PH.stream (PB.fromHandle hIn) } m <- PH.newManager PH.defaultManagerSettings PH.withHTTP req m $ \resp -> P.runEffect $ PH.responseBody resp P.>-> PB.stdout return () ------------------------------------------------------------------------------ -- TODO : make a 'readFile' with this signature: -- readFile :: FilePath -> P.Producer' B.ByteString IO () readFile :: FilePath -> P.Producer' B.ByteString (PS.SafeT IO) () readFile file = PS.bracket (do h <- IO.openFile file IO.ReadMode PL.putStrLn $ "{" ++ file ++ " open}" return h ) (\h -> do IO.hClose h PL.putStrLn $ "{" ++ file ++ " closed}" ) PB.fromHandle test :: IO () test = PS.runSafeT $ P.runEffect $ readFile "src/Lib.hs" P.>-> PP.take 4 P.>-> PB.stdout {- java -cp ~/.m2/repository/ws-commons/tcpmon/1.0/tcpmon-1.0.jar org.apache.ws.commons.tcpmon.TCPMon 2999 127.0.0.1 3000 & stream :: Pipes.Core.Producer ByteString IO () -> RequestBody (PB.stdin >-> PP.take 1) :: Control.Monad.IO.Class.MonadIO m => Pipes.Internal.Proxy a' a () ByteString m () type Pipes.Core.Producer b = Pipes.Internal.Proxy Pipes.Internal.X () () b -}
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/streaming/pipes/src/Lib.hs
unlicense
4,500
0
17
1,412
1,146
610
536
83
1