code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Control.Concurrent (forkIO, killThread, threadDelay)
import Control.Concurrent.Async (forConcurrently)
import Control.Exception (throwIO)
import Data.Binary (Binary)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import Data.Data (Data)
import Data.Functor.Contravariant (contramap)
import GHC.Generics (Generic)
import Network.Transport (closeTransport)
import qualified Network.Transport.TCP as TCP
import Node
import Node.Message.Binary (BinaryP, binaryPacking)
import Pos.Util.Trace (stdoutTrace)
import System.Random
-- | Type for messages from the workers to the listeners.
data Ping = Ping
deriving instance Generic Ping
deriving instance Data Ping
deriving instance Show Ping
instance Binary Ping
instance Message Ping where
messageCode _ = 0
formatMessage _ = "Ping"
-- | Type for messages from the listeners to the workers.
data Pong = Pong BS.ByteString
deriving instance Generic Pong
deriving instance Show Pong
instance Binary Pong
type Packing = BinaryP
worker
:: NodeId
-> StdGen
-> [NodeId]
-> Converse Packing BS.ByteString
-> IO ()
worker anId generator peerIds = pingWorker generator
where
pingWorker
:: StdGen
-> Converse Packing BS.ByteString
-> IO ()
pingWorker gen converse = loop gen
where
loop :: StdGen -> IO ()
loop g = do
let (us, gen') = randomR (0,1000000) g
threadDelay us
let pong :: NodeId -> ConversationActions Ping Pong -> IO ()
pong peerId cactions = do
putStrLn $ show anId ++ " sent PING to " ++ show peerId
received <- recv cactions maxBound
case received of
Just (Pong _) -> putStrLn $ show anId ++ " heard PONG from " ++ show peerId
Nothing -> error "Unexpected end of input"
_ <- forConcurrently peerIds $ \peerId ->
converseWith converse peerId (\_ -> Conversation (pong peerId))
loop gen'
listeners
:: NodeId
-> BS.ByteString
-> [Listener Packing BS.ByteString]
listeners anId peerData = [pongListener]
where
pongListener :: Listener Packing BS.ByteString
pongListener = Listener $ \_ peerId (cactions :: ConversationActions Pong Ping) -> do
putStrLn $ show anId ++ " heard PING from " ++ show peerId ++ " with peer data " ++ B8.unpack peerData
send cactions (Pong "")
putStrLn $ show anId ++ " sent PONG to " ++ show peerId
main :: IO ()
main = do
let params = TCP.defaultTCPParameters { TCP.tcpCheckPeerHost = True }
transport <- do
transportOrError <-
TCP.createTransport (TCP.defaultTCPAddr "127.0.0.1" "10128") params
either throwIO return transportOrError
let prng1 = mkStdGen 0
let prng2 = mkStdGen 1
let prng3 = mkStdGen 2
let prng4 = mkStdGen 3
putStrLn $ "Starting nodes"
node (contramap snd stdoutTrace) (simpleNodeEndPoint transport) (const noReceiveDelay) (const noReceiveDelay)
prng1 binaryPacking (B8.pack "I am node 1") defaultNodeEnvironment $ \node1 ->
NodeAction (listeners . nodeId $ node1) $ \converse1 -> do
node (contramap snd stdoutTrace) (simpleNodeEndPoint transport) (const noReceiveDelay) (const noReceiveDelay)
prng2 binaryPacking (B8.pack "I am node 2") defaultNodeEnvironment $ \node2 ->
NodeAction (listeners . nodeId $ node2) $ \converse2 -> do
tid1 <- forkIO $ worker (nodeId node1) prng3 [nodeId node2] converse1
tid2 <- forkIO $ worker (nodeId node2) prng4 [nodeId node1] converse2
putStrLn $ "Hit return to stop"
_ <- getChar
killThread tid1
killThread tid2
putStrLn $ "Stopping nodes"
putStrLn $ "All done."
closeTransport transport
| input-output-hk/pos-haskell-prototype | networking/examples/PingPong.hs | mit | 4,585 | 0 | 23 | 1,359 | 1,148 | 579 | 569 | 104 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.DirectConnect.Types
-- Copyright : (c) 2013-2015 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.AWS.DirectConnect.Types
(
-- * Service Configuration
directConnect
-- * Errors
, _DirectConnectClientException
, _DirectConnectServerException
-- * ConnectionState
, ConnectionState (..)
-- * InterconnectState
, InterconnectState (..)
-- * VirtualInterfaceState
, VirtualInterfaceState (..)
-- * Connection
, Connection
, connection
, cVlan
, cLocation
, cConnectionId
, cPartnerName
, cConnectionName
, cBandwidth
, cOwnerAccount
, cRegion
, cConnectionState
-- * Connections
, Connections
, connections
, cConnections
-- * Interconnect
, Interconnect
, interconnect
, iInterconnectId
, iLocation
, iInterconnectName
, iBandwidth
, iInterconnectState
, iRegion
-- * Location
, Location
, location
, lLocationName
, lLocationCode
-- * NewPrivateVirtualInterface
, NewPrivateVirtualInterface
, newPrivateVirtualInterface
, nCustomerAddress
, nAmazonAddress
, nAuthKey
, nVirtualInterfaceName
, nVlan
, nAsn
, nVirtualGatewayId
-- * NewPrivateVirtualInterfaceAllocation
, NewPrivateVirtualInterfaceAllocation
, newPrivateVirtualInterfaceAllocation
, npviaCustomerAddress
, npviaAmazonAddress
, npviaAuthKey
, npviaVirtualInterfaceName
, npviaVlan
, npviaAsn
-- * NewPublicVirtualInterface
, NewPublicVirtualInterface
, newPublicVirtualInterface
, npviAuthKey
, npviVirtualInterfaceName
, npviVlan
, npviAsn
, npviAmazonAddress
, npviCustomerAddress
, npviRouteFilterPrefixes
-- * NewPublicVirtualInterfaceAllocation
, NewPublicVirtualInterfaceAllocation
, newPublicVirtualInterfaceAllocation
, newAuthKey
, newVirtualInterfaceName
, newVlan
, newAsn
, newAmazonAddress
, newCustomerAddress
, newRouteFilterPrefixes
-- * RouteFilterPrefix
, RouteFilterPrefix
, routeFilterPrefix
, rfpCidr
-- * VirtualGateway
, VirtualGateway
, virtualGateway
, vgVirtualGatewayId
, vgVirtualGatewayState
-- * VirtualInterface
, VirtualInterface
, virtualInterface
, viVirtualGatewayId
, viRouteFilterPrefixes
, viCustomerAddress
, viVlan
, viLocation
, viAmazonAddress
, viVirtualInterfaceState
, viConnectionId
, viVirtualInterfaceType
, viAsn
, viAuthKey
, viCustomerRouterConfig
, viOwnerAccount
, viVirtualInterfaceName
, viVirtualInterfaceId
) where
import Network.AWS.DirectConnect.Types.Product
import Network.AWS.DirectConnect.Types.Sum
import Network.AWS.Prelude
import Network.AWS.Sign.V4
-- | API version '2012-10-25' of the Amazon Direct Connect SDK configuration.
directConnect :: Service
directConnect =
Service
{ _svcAbbrev = "DirectConnect"
, _svcSigner = v4
, _svcPrefix = "directconnect"
, _svcVersion = "2012-10-25"
, _svcEndpoint = defaultEndpoint directConnect
, _svcTimeout = Just 70
, _svcCheck = statusSuccess
, _svcError = parseJSONError
, _svcRetry = retry
}
where
retry =
Exponential
{ _retryBase = 5.0e-2
, _retryGrowth = 2
, _retryAttempts = 5
, _retryCheck = check
}
check e
| has (hasCode "ThrottlingException" . hasStatus 400) e =
Just "throttling_exception"
| has (hasCode "Throttling" . hasStatus 400) e = Just "throttling"
| has (hasStatus 503) e = Just "service_unavailable"
| has (hasStatus 500) e = Just "general_server_error"
| has (hasStatus 509) e = Just "limit_exceeded"
| otherwise = Nothing
-- | The API was called with invalid parameters. The error message will
-- contain additional details about the cause.
_DirectConnectClientException :: AsError a => Getting (First ServiceError) a ServiceError
_DirectConnectClientException =
_ServiceError . hasCode "DirectConnectClientException"
-- | A server-side error occurred during the API call. The error message will
-- contain additional details about the cause.
_DirectConnectServerException :: AsError a => Getting (First ServiceError) a ServiceError
_DirectConnectServerException =
_ServiceError . hasCode "DirectConnectServerException"
| fmapfmapfmap/amazonka | amazonka-directconnect/gen/Network/AWS/DirectConnect/Types.hs | mpl-2.0 | 4,771 | 0 | 13 | 1,170 | 677 | 414 | 263 | 130 | 1 |
-- | Specification of 'Pos.Chain.Block.Creation' module.
module Test.Pos.Block.Logic.CreationSpec
( spec
) where
import Universum
import Data.Default (def)
import Serokell.Data.Memory.Units (Byte, Gigabyte, convertUnit,
fromBytes)
import Test.Hspec (Spec, describe, runIO)
import Test.Hspec.QuickCheck (modifyMaxSuccess, prop)
import Test.QuickCheck (Gen, Property, Testable, arbitrary, choose,
counterexample, elements, forAll, generate, listOf,
listOf1, oneof, property)
import Pos.Binary.Class (biSize)
import Pos.Chain.Block (BlockHeader, MainBlock)
import Pos.Chain.Delegation (DlgPayload, ProxySKBlockInfo)
import Pos.Chain.Genesis as Genesis (Config (..), GenesisData (..))
import Pos.Chain.Ssc (SscPayload (..), defaultSscPayload,
mkVssCertificatesMapLossy)
import Pos.Chain.Txp (TxAux)
import Pos.Chain.Update (BlockVersionData (..),
HasUpdateConfiguration, UpdatePayload (..),
updateConfiguration)
import qualified Pos.Communication ()
import Pos.Core (SlotId (..), kEpochSlots, localSlotIndexMinBound,
pcBlkSecurityParam, unsafeMkLocalSlotIndex)
import Pos.Crypto (ProtocolMagic (..), RequiresNetworkMagic (..),
SecretKey)
import Pos.DB.Block (RawPayload (..), createMainBlockPure)
import Test.Pos.Chain.Block.Arbitrary ()
import Test.Pos.Chain.Delegation.Arbitrary (genDlgPayload)
import Test.Pos.Chain.Ssc.Arbitrary (commitmentMapEpochGen,
vssCertificateEpochGen)
import Test.Pos.Chain.Txp.Arbitrary (GoodTx, goodTxToTxAux)
import Test.Pos.Configuration (withProvidedMagicConfig)
import Test.Pos.Util.QuickCheck (SmallGenerator (..), makeSmall)
spec :: Spec
spec = do
runWithMagic RequiresNoMagic
runWithMagic RequiresMagic
runWithMagic :: RequiresNetworkMagic -> Spec
runWithMagic rnm = do
pm <- (\ident -> ProtocolMagic ident rnm) <$> runIO (generate arbitrary)
describe ("(requiresNetworkMagic=" ++ show rnm ++ ")") $
specBody pm
specBody :: ProtocolMagic -> Spec
specBody pm = withProvidedMagicConfig pm $ \genesisConfig _ _ ->
describe "Block.Logic.Creation" $ do
-- Sampling the minimum empty block size
(sk0,prevHeader0) <- runIO $ generate arbitrary
-- We multiply by 1.5 because there are different possible
-- combinations of empty constructors and there's no out-of-box
-- way to get maximum of them. Some settings produce 390b empty
-- block, some -- 431b.
let emptyBSize0 :: Byte
emptyBSize0 = biSize (noSscBlock genesisConfig infLimit prevHeader0 [] def def sk0) -- in bytes
emptyBSize :: Integral n => n
emptyBSize = round $ (1.5 * fromIntegral emptyBSize0 :: Double)
describe "createMainBlockPure" $ modifyMaxSuccess (const 1000) $ do
prop "empty block size is sane" $ emptyBlk genesisConfig $ \blk0 -> leftToCounter blk0 $ \blk ->
let s = biSize blk
in counterexample ("Real block size: " <> show s <>
"\n\nBlock: " <> show blk) $
-- Various hashes and signatures in the block take 416
-- bytes; this is *completely* independent of encoding used.
-- Empirically, empty blocks don't get bigger than 550
-- bytes.
s <= 550 && s <= bvdMaxBlockSize (gdBlockVersionData $ configGenesisData genesisConfig)
prop "doesn't create blocks bigger than the limit" $
forAll (choose (emptyBSize, emptyBSize * 10)) $ \(fromBytes -> limit) ->
forAll arbitrary $ \(prevHeader, sk, updatePayload) ->
forAll (validSscPayloadGen genesisConfig) $ \(sscPayload, slotId) ->
forAll (genDlgPayload pm (siEpoch slotId)) $ \dlgPayload ->
forAll (makeSmall $ listOf1 genTxAux) $ \txs ->
let blk = producePureBlock genesisConfig limit prevHeader txs Nothing slotId
dlgPayload sscPayload updatePayload sk
in leftToCounter blk $ \b ->
let s = biSize b
in counterexample ("Real block size: " <> show s) $
s <= fromIntegral limit
prop "removes transactions when necessary" $
forAll arbitrary $ \(prevHeader, sk) ->
forAll (makeSmall $ listOf1 genTxAux) $ \txs ->
forAll (elements [0,0.5,0.9]) $ \(delta :: Double) ->
let blk0 = noSscBlock genesisConfig infLimit prevHeader [] def def sk
blk1 = noSscBlock genesisConfig infLimit prevHeader txs def def sk
in leftToCounter ((,) <$> blk0 <*> blk1) $ \(b0, b1) ->
let s = biSize b0 +
round ((fromIntegral $ biSize b1 - biSize b0) * delta)
blk2 = noSscBlock genesisConfig s prevHeader txs def def sk
in counterexample ("Tested with block size limit: " <> show s) $
leftToCounter blk2 (const True)
prop "strips ssc data when necessary" $
forAll arbitrary $ \(prevHeader, sk) ->
forAll (validSscPayloadGen genesisConfig) $ \(sscPayload, slotId) ->
forAll (elements [0,0.5,0.9]) $ \(delta :: Double) ->
let blk0 = producePureBlock genesisConfig infLimit prevHeader [] Nothing
slotId def (defSscPld genesisConfig slotId) def sk
withPayload lim =
producePureBlock genesisConfig lim prevHeader [] Nothing slotId def sscPayload def sk
blk1 = withPayload infLimit
in leftToCounter ((,) <$> blk0 <*> blk1) $ \(b0,b1) ->
let s = biSize b0 +
round ((fromIntegral $ biSize b1 - biSize b0) * delta)
blk2 = withPayload s
in counterexample ("Tested with block size limit: " <> show s) $
leftToCounter blk2 (const True)
where
defSscPld :: Genesis.Config -> SlotId -> SscPayload
defSscPld genesisConfig sId = do
let k = pcBlkSecurityParam $ configProtocolConstants genesisConfig
defaultSscPayload k $ siSlot sId
infLimit = convertUnit @Gigabyte @Byte 1
leftToCounter :: (ToString s, Testable p) => Either s a -> (a -> p) -> Property
leftToCounter x c = either (\t -> counterexample (toString t) False) (property . c) x
emptyBlk
:: (HasUpdateConfiguration, Testable p)
=> Genesis.Config
-> (Either Text MainBlock -> p)
-> Property
emptyBlk genesisConfig foo =
forAll arbitrary $ \(prevHeader, sk, slotId) ->
foo $ producePureBlock genesisConfig infLimit prevHeader [] Nothing slotId def (defSscPld genesisConfig slotId) def sk
genTxAux :: Gen TxAux
genTxAux =
goodTxToTxAux . getSmallGenerator <$> (arbitrary :: Gen (SmallGenerator GoodTx))
noSscBlock
:: HasUpdateConfiguration
=> Genesis.Config
-> Byte
-> BlockHeader
-> [TxAux]
-> DlgPayload
-> UpdatePayload
-> SecretKey
-> Either Text MainBlock
noSscBlock genesisConfig limit prevHeader txs proxyCerts updatePayload sk =
let k = pcBlkSecurityParam $ configProtocolConstants genesisConfig
epochSlots = kEpochSlots k
neutralSId = SlotId 0 (unsafeMkLocalSlotIndex epochSlots $ fromIntegral $ k * 2)
in producePureBlock
genesisConfig limit prevHeader txs Nothing neutralSId proxyCerts (defSscPld genesisConfig neutralSId) updatePayload sk
producePureBlock
:: HasUpdateConfiguration
=> Genesis.Config
-> Byte
-> BlockHeader
-> [TxAux]
-> ProxySKBlockInfo
-> SlotId
-> DlgPayload
-> SscPayload
-> UpdatePayload
-> SecretKey
-> Either Text MainBlock
producePureBlock genesisConfig limit prev txs psk slot dlgPay sscPay usPay sk =
flip runReaderT updateConfiguration $
createMainBlockPure genesisConfig limit prev psk slot sk $
RawPayload txs sscPay dlgPay usPay
validSscPayloadGen :: Genesis.Config -> Gen (SscPayload, SlotId)
validSscPayloadGen genesisConfig = do
let pm = configProtocolMagic genesisConfig
protocolConstants = configProtocolConstants genesisConfig
k = pcBlkSecurityParam protocolConstants
epochSlots = kEpochSlots k
vssCerts <- makeSmall $ fmap mkVssCertificatesMapLossy $ listOf $
vssCertificateEpochGen pm protocolConstants 0
let mkSlot i = SlotId 0 (unsafeMkLocalSlotIndex epochSlots (fromIntegral i))
oneof [ do commMap <- makeSmall $ commitmentMapEpochGen pm 0
pure (CommitmentsPayload commMap vssCerts , SlotId 0 localSlotIndexMinBound)
, do openingsMap <- makeSmall arbitrary
pure (OpeningsPayload openingsMap vssCerts, mkSlot (4 * k + 1))
, do sharesMap <- makeSmall arbitrary
pure (SharesPayload sharesMap vssCerts, mkSlot (8 * k))
, pure (CertificatesPayload vssCerts, mkSlot (7 * k))
]
| input-output-hk/cardano-sl | generator/test/Test/Pos/Block/Logic/CreationSpec.hs | apache-2.0 | 9,423 | 0 | 34 | 2,844 | 2,381 | 1,251 | 1,130 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[TypeRep]{Type - friends' interface}
Note [The Type-related module hierarchy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class
TyCon imports Class
TypeRep
TysPrim imports TypeRep ( including mkTyConTy )
Kind imports TysPrim ( mainly for primitive kinds )
Type imports Kind
Coercion imports Type
-}
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
DeriveTraversable #-}
{-# OPTIONS_HADDOCK hide #-}
-- We expose the relevant stuff from this module via the Type module
module TypeRep (
TyThing(..),
Type(..),
TyLit(..),
KindOrType, Kind, SuperKind,
PredType, ThetaType, -- Synonyms
-- Functions over types
mkTyConTy, mkTyVarTy, mkTyVarTys,
isLiftedTypeKind, isSuperKind, isTypeVar, isKindVar,
-- Pretty-printing
pprType, pprParendType, pprTypeApp, pprTvBndr, pprTvBndrs,
pprTyThing, pprTyThingCategory, pprSigmaType,
pprTheta, pprForAll, pprUserForAll,
pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprTyLit, suppressKinds,
TyPrec(..), maybeParen, pprTcApp,
pprPrefixApp, pprArrowChain, ppr_type,
-- Free variables
tyVarsOfType, tyVarsOfTypes, closeOverKinds, varSetElemsKvsFirst,
-- * Tidying type related things up for printing
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyVarBndr, tidyTyVarBndrs, tidyFreeTyVars,
tidyOpenTyVar, tidyOpenTyVars,
tidyTyVarOcc,
tidyTopType,
tidyKind,
-- Substitutions
TvSubst(..), TvSubstEnv
) where
#include "HsVersions.h"
import {-# SOURCE #-} DataCon( dataConTyCon )
import {-# SOURCE #-} ConLike ( ConLike(..) )
import {-# SOURCE #-} Type( isPredTy ) -- Transitively pulls in a LOT of stuff, better to break the loop
-- friends:
import Var
import VarEnv
import VarSet
import Name
import BasicTypes
import TyCon
import Class
import CoAxiom
-- others
import PrelNames
import Outputable
import FastString
import Util
import DynFlags
import StaticFlags( opt_PprStyle_Debug )
-- libraries
import Data.List( mapAccumL, partition )
import qualified Data.Data as Data hiding ( TyCon )
{-
************************************************************************
* *
\subsection{The data type}
* *
************************************************************************
-}
-- | The key representation of types within the compiler
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Type
= TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)
| AppTy -- See Note [AppTy rep]
Type
Type -- ^ Type application to something other than a 'TyCon'. Parameters:
--
-- 1) Function: must /not/ be a 'TyConApp',
-- must be another 'AppTy', or 'TyVarTy'
--
-- 2) Argument type
| TyConApp -- See Note [AppTy rep]
TyCon
[KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
-- Invariant: saturated applications of 'FunTyCon' must
-- use 'FunTy' and saturated synonyms must use their own
-- constructors. However, /unsaturated/ 'FunTyCon's
-- do appear as 'TyConApp's.
-- Parameters:
--
-- 1) Type constructor being applied to.
--
-- 2) Type arguments. Might not have enough type arguments
-- here to saturate the constructor.
-- Even type synonyms are not necessarily saturated;
-- for example unsaturated type synonyms
-- can appear as the right hand side of a type synonym.
| FunTy
Type
Type -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@
-- See Note [Equality-constrained types]
| ForAllTy
Var -- Type or kind variable
Type -- ^ A polymorphic type
| LitTy TyLit -- ^ Type literals are similar to type constructors.
deriving (Data.Data, Data.Typeable)
-- NOTE: Other parts of the code assume that type literals do not contain
-- types or type variables.
data TyLit
= NumTyLit Integer
| StrTyLit FastString
deriving (Eq, Ord, Data.Data, Data.Typeable)
type KindOrType = Type -- See Note [Arguments to type constructors]
-- | The key type representing kinds in the compiler.
-- Invariant: a kind is always in one of these forms:
--
-- > FunTy k1 k2
-- > TyConApp PrimTyCon [...]
-- > TyVar kv -- (during inference only)
-- > ForAll ... -- (for top-level coercions)
type Kind = Type
-- | "Super kinds", used to help encode 'Kind's as types.
-- Invariant: a super kind is always of this form:
--
-- > TyConApp SuperKindTyCon ...
type SuperKind = Type
{-
Note [The kind invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~
The kinds
# UnliftedTypeKind
OpenKind super-kind of *, #
can never appear under an arrow or type constructor in a kind; they
can only be at the top level of a kind. It follows that primitive TyCons,
which have a naughty pseudo-kind
State# :: * -> #
must always be saturated, so that we can never get a type whose kind
has a UnliftedTypeKind or ArgTypeKind underneath an arrow.
Nor can we abstract over a type variable with any of these kinds.
k :: = kk | # | ArgKind | (#) | OpenKind
kk :: = * | kk -> kk | T kk1 ... kkn
So a type variable can only be abstracted kk.
Note [Arguments to type constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because of kind polymorphism, in addition to type application we now
have kind instantiation. We reuse the same notations to do so.
For example:
Just (* -> *) Maybe
Right * Nat Zero
are represented by:
TyConApp (PromotedDataCon Just) [* -> *, Maybe]
TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)]
Important note: Nat is used as a *kind* and not as a type. This can be
confusing, since type-level Nat and kind-level Nat are identical. We
use the kind of (PromotedDataCon Right) to know if its arguments are
kinds or types.
This kind instantiation only happens in TyConApp currently.
Note [Equality-constrained types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type forall ab. (a ~ [b]) => blah
is encoded like this:
ForAllTy (a:*) $ ForAllTy (b:*) $
FunTy (TyConApp (~) [a, [b]]) $
blah
-------------------------------------
Note [PredTy]
-}
-- | A type of the form @p@ of kind @Constraint@ represents a value whose type is
-- the Haskell predicate @p@, where a predicate is what occurs before
-- the @=>@ in a Haskell type.
--
-- We use 'PredType' as documentation to mark those types that we guarantee to have
-- this kind.
--
-- It can be expanded into its representation, but:
--
-- * The type checker must treat it as opaque
--
-- * The rest of the compiler treats it as transparent
--
-- Consider these examples:
--
-- > f :: (Eq a) => a -> Int
-- > g :: (?x :: Int -> Int) => a -> Int
-- > h :: (r\l) => {r} => {l::Int | r}
--
-- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
type PredType = Type
-- | A collection of 'PredType's
type ThetaType = [PredType]
{-
(We don't support TREX records yet, but the setup is designed
to expand to allow them.)
A Haskell qualified type, such as that for f,g,h above, is
represented using
* a FunTy for the double arrow
* with a type of kind Constraint as the function argument
The predicate really does turn into a real extra argument to the
function. If the argument has type (p :: Constraint) then the predicate p is
represented by evidence of type p.
************************************************************************
* *
Simple constructors
* *
************************************************************************
These functions are here so that they can be used by TysPrim,
which in turn is imported by Type
-}
mkTyVarTy :: TyVar -> Type
mkTyVarTy = TyVarTy
mkTyVarTys :: [TyVar] -> [Type]
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
-- | Create the plain type constructor type which has been applied to no type arguments at all.
mkTyConTy :: TyCon -> Type
mkTyConTy tycon = TyConApp tycon []
-- Some basic functions, put here to break loops eg with the pretty printer
isLiftedTypeKind :: Kind -> Bool
isLiftedTypeKind (TyConApp tc []) = tc `hasKey` liftedTypeKindTyConKey
isLiftedTypeKind _ = False
-- | Is this a super-kind (i.e. a type-of-kinds)?
isSuperKind :: Type -> Bool
isSuperKind (TyConApp skc []) = skc `hasKey` superKindTyConKey
isSuperKind _ = False
isTypeVar :: Var -> Bool
isTypeVar v = isTKVar v && not (isSuperKind (varType v))
isKindVar :: Var -> Bool
isKindVar v = isTKVar v && isSuperKind (varType v)
{-
************************************************************************
* *
Free variables of types and coercions
* *
************************************************************************
-}
tyVarsOfType :: Type -> VarSet
-- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
-- tyVarsOfType returns free variables of a type, including kind variables.
tyVarsOfType (TyVarTy v) = unitVarSet v
tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
tyVarsOfType (LitTy {}) = emptyVarSet
tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
`unionVarSet` tyVarsOfType (tyVarKind tyvar)
tyVarsOfTypes :: [Type] -> TyVarSet
tyVarsOfTypes = mapUnionVarSet tyVarsOfType
closeOverKinds :: TyVarSet -> TyVarSet
-- Add the kind variables free in the kinds
-- of the tyvars in the given set
closeOverKinds tvs
= foldVarSet (\tv ktvs -> tyVarsOfType (tyVarKind tv) `unionVarSet` ktvs)
tvs tvs
varSetElemsKvsFirst :: VarSet -> [TyVar]
-- {k1,a,k2,b} --> [k1,k2,a,b]
varSetElemsKvsFirst set
= kvs ++ tvs
where
(kvs, tvs) = partition isKindVar (varSetElems set)
{-
************************************************************************
* *
TyThing
* *
************************************************************************
Despite the fact that DataCon has to be imported via a hi-boot route,
this module seems the right place for TyThing, because it's needed for
funTyCon and all the types in TysPrim.
Note [ATyCon for classes]
~~~~~~~~~~~~~~~~~~~~~~~~~
Both classes and type constructors are represented in the type environment
as ATyCon. You can tell the difference, and get to the class, with
isClassTyCon :: TyCon -> Bool
tyConClass_maybe :: TyCon -> Maybe Class
The Class and its associated TyCon have the same Name.
-}
-- | A global typecheckable-thing, essentially anything that has a name.
-- Not to be confused with a 'TcTyThing', which is also a typecheckable
-- thing but in the *local* context. See 'TcEnv' for how to retrieve
-- a 'TyThing' given a 'Name'.
data TyThing
= AnId Id
| AConLike ConLike
| ATyCon TyCon -- TyCons and classes; see Note [ATyCon for classes]
| ACoAxiom (CoAxiom Branched)
deriving (Eq, Ord)
instance Outputable TyThing where
ppr = pprTyThing
pprTyThing :: TyThing -> SDoc
pprTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
pprTyThingCategory :: TyThing -> SDoc
pprTyThingCategory (ATyCon tc)
| isClassTyCon tc = ptext (sLit "Class")
| otherwise = ptext (sLit "Type constructor")
pprTyThingCategory (ACoAxiom _) = ptext (sLit "Coercion axiom")
pprTyThingCategory (AnId _) = ptext (sLit "Identifier")
pprTyThingCategory (AConLike (RealDataCon _)) = ptext (sLit "Data constructor")
pprTyThingCategory (AConLike (PatSynCon _)) = ptext (sLit "Pattern synonym")
instance NamedThing TyThing where -- Can't put this with the type
getName (AnId id) = getName id -- decl, because the DataCon instance
getName (ATyCon tc) = getName tc -- isn't visible there
getName (ACoAxiom cc) = getName cc
getName (AConLike cl) = getName cl
{-
************************************************************************
* *
Substitutions
Data type defined here to avoid unnecessary mutual recursion
* *
************************************************************************
-}
-- | Type substitution
--
-- #tvsubst_invariant#
-- The following invariants must hold of a 'TvSubst':
--
-- 1. The in-scope set is needed /only/ to
-- guide the generation of fresh uniques
--
-- 2. In particular, the /kind/ of the type variables in
-- the in-scope set is not relevant
--
-- 3. The substitution is only applied ONCE! This is because
-- in general such application will not reach a fixed point.
data TvSubst
= TvSubst InScopeSet -- The in-scope type and kind variables
TvSubstEnv -- Substitutes both type and kind variables
-- See Note [Apply Once]
-- and Note [Extending the TvSubstEnv]
-- | A substitution of 'Type's for 'TyVar's
-- and 'Kind's for 'KindVar's
type TvSubstEnv = TyVarEnv Type
-- A TvSubstEnv is used both inside a TvSubst (with the apply-once
-- invariant discussed in Note [Apply Once]), and also independently
-- in the middle of matching, and unification (see Types.Unify)
-- So you have to look at the context to know if it's idempotent or
-- apply-once or whatever
{-
Note [Apply Once]
~~~~~~~~~~~~~~~~~
We use TvSubsts to instantiate things, and we might instantiate
forall a b. ty
\with the types
[a, b], or [b, a].
So the substitution might go [a->b, b->a]. A similar situation arises in Core
when we find a beta redex like
(/\ a /\ b -> e) b a
Then we also end up with a substitution that permutes type variables. Other
variations happen to; for example [a -> (a, b)].
***************************************************
*** So a TvSubst must be applied precisely once ***
***************************************************
A TvSubst is not idempotent, but, unlike the non-idempotent substitution
we use during unifications, it must not be repeatedly applied.
Note [Extending the TvSubst]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #tvsubst_invariant# for the invariants that must hold.
This invariant allows a short-cut when the TvSubstEnv is empty:
if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
then (substTy subst ty) does nothing.
For example, consider:
(/\a. /\b:(a~Int). ...b..) Int
We substitute Int for 'a'. The Unique of 'b' does not change, but
nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
This invariant has several crucial consequences:
* In substTyVarBndr, we need extend the TvSubstEnv
- if the unique has changed
- or if the kind has changed
* In substTyVar, we do not need to consult the in-scope set;
the TvSubstEnv is enough
* In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
************************************************************************
* *
Pretty-printing types
Defined very early because of debug printing in assertions
* *
************************************************************************
@pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
defined to use this. @pprParendType@ is the same, except it puts
parens around the type, except for the atomic cases. @pprParendType@
works just by setting the initial context precedence very high.
Note [Precedence in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't keep the fixity of type operators in the operator. So the pretty printer
operates the following precedene structre:
Type constructor application binds more tightly than
Oerator applications which bind more tightly than
Function arrow
So we might see a :+: T b -> c
meaning (a :+: (T b)) -> c
Maybe operator applications should bind a bit less tightly?
Anyway, that's the current story, and it is used consistently for Type and HsType
-}
data TyPrec -- See Note [Prededence in types]
= TopPrec -- No parens
| FunPrec -- Function args; no parens for tycon apps
| TyOpPrec -- Infix operator
| TyConPrec -- Tycon args; no parens for atomic
deriving( Eq, Ord )
maybeParen :: TyPrec -> TyPrec -> SDoc -> SDoc
maybeParen ctxt_prec inner_prec pretty
| ctxt_prec < inner_prec = pretty
| otherwise = parens pretty
------------------
pprType, pprParendType :: Type -> SDoc
pprType ty = ppr_type TopPrec ty
pprParendType ty = ppr_type TyConPrec ty
pprTyLit :: TyLit -> SDoc
pprTyLit = ppr_tylit TopPrec
pprKind, pprParendKind :: Kind -> SDoc
pprKind = pprType
pprParendKind = pprParendType
------------
pprClassPred :: Class -> [Type] -> SDoc
pprClassPred clas tys = pprTypeApp (classTyCon clas) tys
------------
pprTheta :: ThetaType -> SDoc
pprTheta [pred] = ppr_type TopPrec pred -- I'm in two minds about this
pprTheta theta = parens (sep (punctuate comma (map (ppr_type TopPrec) theta)))
pprThetaArrowTy :: ThetaType -> SDoc
pprThetaArrowTy [] = empty
pprThetaArrowTy [pred] = ppr_type TyOpPrec pred <+> darrow
-- TyOpPrec: Num a => a -> a does not need parens
-- bug (a :~: b) => a -> b currently does
-- Trac # 9658
pprThetaArrowTy preds = parens (fsep (punctuate comma (map (ppr_type TopPrec) preds)))
<+> darrow
-- Notice 'fsep' here rather that 'sep', so that
-- type contexts don't get displayed in a giant column
-- Rather than
-- instance (Eq a,
-- Eq b,
-- Eq c,
-- Eq d,
-- Eq e,
-- Eq f,
-- Eq g,
-- Eq h,
-- Eq i,
-- Eq j,
-- Eq k,
-- Eq l) =>
-- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
-- we get
--
-- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i,
-- Eq j, Eq k, Eq l) =>
-- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
------------------
instance Outputable Type where
ppr ty = pprType ty
instance Outputable TyLit where
ppr = pprTyLit
------------------
-- OK, here's the main printer
ppr_type :: TyPrec -> Type -> SDoc
ppr_type _ (TyVarTy tv) = ppr_tvar tv
ppr_type p (TyConApp tc tys) = pprTyTcApp p tc tys
ppr_type p (LitTy l) = ppr_tylit p l
ppr_type p ty@(ForAllTy {}) = ppr_forall_type p ty
ppr_type p (AppTy t1 t2) = maybeParen p TyConPrec $
ppr_type FunPrec t1 <+> ppr_type TyConPrec t2
ppr_type p fun_ty@(FunTy ty1 ty2)
| isPredTy ty1
= ppr_forall_type p fun_ty
| otherwise
= pprArrowChain p (ppr_type FunPrec ty1 : ppr_fun_tail ty2)
where
-- We don't want to lose synonyms, so we mustn't use splitFunTys here.
ppr_fun_tail (FunTy ty1 ty2)
| not (isPredTy ty1) = ppr_type FunPrec ty1 : ppr_fun_tail ty2
ppr_fun_tail other_ty = [ppr_type TopPrec other_ty]
ppr_forall_type :: TyPrec -> Type -> SDoc
ppr_forall_type p ty
= maybeParen p FunPrec $ ppr_sigma_type True ty
-- True <=> we always print the foralls on *nested* quantifiers
-- Opt_PrintExplicitForalls only affects top-level quantifiers
-- False <=> we don't print an extra-constraints wildcard
ppr_tvar :: TyVar -> SDoc
ppr_tvar tv -- Note [Infix type variables]
= parenSymOcc (getOccName tv) (ppr tv)
ppr_tylit :: TyPrec -> TyLit -> SDoc
ppr_tylit _ tl =
case tl of
NumTyLit n -> integer n
StrTyLit s -> text (show s)
-------------------
ppr_sigma_type :: Bool -> Type -> SDoc
-- First Bool <=> Show the foralls unconditionally
-- Second Bool <=> Show an extra-constraints wildcard
ppr_sigma_type show_foralls_unconditionally ty
= sep [ if show_foralls_unconditionally
then pprForAll tvs
else pprUserForAll tvs
, pprThetaArrowTy ctxt
, pprType tau ]
where
(tvs, rho) = split1 [] ty
(ctxt, tau) = split2 [] rho
split1 tvs (ForAllTy tv ty) = split1 (tv:tvs) ty
split1 tvs ty = (reverse tvs, ty)
split2 ps (ty1 `FunTy` ty2) | isPredTy ty1 = split2 (ty1:ps) ty2
split2 ps ty = (reverse ps, ty)
pprSigmaType :: Type -> SDoc
pprSigmaType ty = ppr_sigma_type False ty
pprUserForAll :: [TyVar] -> SDoc
-- Print a user-level forall; see Note [When to print foralls]
pprUserForAll tvs
= sdocWithDynFlags $ \dflags ->
ppWhen (any tv_has_kind_var tvs || gopt Opt_PrintExplicitForalls dflags) $
pprForAll tvs
where
tv_has_kind_var tv = not (isEmptyVarSet (tyVarsOfType (tyVarKind tv)))
pprForAll :: [TyVar] -> SDoc
pprForAll [] = empty
pprForAll tvs = forAllLit <+> pprTvBndrs tvs <> dot
pprTvBndrs :: [TyVar] -> SDoc
pprTvBndrs tvs = sep (map pprTvBndr tvs)
pprTvBndr :: TyVar -> SDoc
pprTvBndr tv
| isLiftedTypeKind kind = ppr_tvar tv
| otherwise = parens (ppr_tvar tv <+> dcolon <+> pprKind kind)
where
kind = tyVarKind tv
{-
Note [When to print foralls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mostly we want to print top-level foralls when (and only when) the user specifies
-fprint-explicit-foralls. But when kind polymorphism is at work, that suppresses
too much information; see Trac #9018.
So I'm trying out this rule: print explicit foralls if
a) User specifies -fprint-explicit-foralls, or
b) Any of the quantified type variables has a kind
that mentions a kind variable
This catches common situations, such as a type siguature
f :: m a
which means
f :: forall k. forall (m :: k->*) (a :: k). m a
We really want to see both the "forall k" and the kind signatures
on m and a. The latter comes from pprTvBndr.
Note [Infix type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
With TypeOperators you can say
f :: (a ~> b) -> b
and the (~>) is considered a type variable. However, the type
pretty-printer in this module will just see (a ~> b) as
App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b")
So it'll print the type in prefix form. To avoid confusion we must
remember to parenthesise the operator, thus
(~>) a b -> b
See Trac #2766.
-}
pprTypeApp :: TyCon -> [Type] -> SDoc
pprTypeApp tc tys = pprTyTcApp TopPrec tc tys
-- We have to use ppr on the TyCon (not its name)
-- so that we get promotion quotes in the right place
pprTyTcApp :: TyPrec -> TyCon -> [Type] -> SDoc
-- Used for types only; so that we can make a
-- special case for type-level lists
pprTyTcApp p tc tys
| tc `hasKey` ipTyConKey
, [LitTy (StrTyLit n),ty] <- tys
= maybeParen p FunPrec $
char '?' <> ftext n <> ptext (sLit "::") <> ppr_type TopPrec ty
| tc `hasKey` consDataConKey
, [_kind,ty1,ty2] <- tys
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PrintExplicitKinds dflags then pprTcApp p ppr_type tc tys
else pprTyList p ty1 ty2
| otherwise
= pprTcApp p ppr_type tc tys
pprTcApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc
-- Used for both types and coercions, hence polymorphism
pprTcApp _ pp tc [ty]
| tc `hasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty)
| tc `hasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty)
pprTcApp p pp tc tys
| Just sort <- tyConTuple_maybe tc
, tyConArity tc == length tys
= pprTupleApp p pp tc sort tys
| Just dc <- isPromotedDataCon_maybe tc
, let dc_tc = dataConTyCon dc
, Just tup_sort <- tyConTuple_maybe dc_tc
, let arity = tyConArity dc_tc -- E.g. 3 for (,,) k1 k2 k3 t1 t2 t3
ty_args = drop arity tys -- Drop the kind args
, ty_args `lengthIs` arity -- Result is saturated
= pprPromotionQuote tc <>
(tupleParens tup_sort $ pprWithCommas (pp TopPrec) ty_args)
| otherwise
= sdocWithDynFlags (pprTcApp_help p pp tc tys)
pprTupleApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> TupleSort -> [a] -> SDoc
-- Print a saturated tuple
pprTupleApp p pp tc sort tys
| null tys
, ConstraintTuple <- sort
= if opt_PprStyle_Debug then ptext (sLit "(%%)")
else maybeParen p FunPrec $
ptext (sLit "() :: Constraint")
| otherwise
= pprPromotionQuote tc <>
tupleParens sort (pprWithCommas (pp TopPrec) tys)
pprTcApp_help :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> DynFlags -> SDoc
-- This one has accss to the DynFlags
pprTcApp_help p pp tc tys dflags
| not (isSymOcc (nameOccName (tyConName tc)))
= pprPrefixApp p (ppr tc) (map (pp TyConPrec) tys_wo_kinds)
| [ty1,ty2] <- tys_wo_kinds -- Infix, two arguments;
-- we know nothing of precedence though
= pprInfixApp p pp (ppr tc) ty1 ty2
| tc `hasKey` liftedTypeKindTyConKey
|| tc `hasKey` unliftedTypeKindTyConKey
= ASSERT( null tys ) ppr tc -- Do not wrap *, # in parens
| otherwise
= pprPrefixApp p (parens (ppr tc)) (map (pp TyConPrec) tys_wo_kinds)
where
tys_wo_kinds = suppressKinds dflags (tyConKind tc) tys
------------------
suppressKinds :: DynFlags -> Kind -> [a] -> [a]
-- Given the kind of a TyCon, and the args to which it is applied,
-- suppress the args that are kind args
-- C.f. Note [Suppressing kinds] in IfaceType
suppressKinds dflags kind xs
| gopt Opt_PrintExplicitKinds dflags = xs
| otherwise = suppress kind xs
where
suppress (ForAllTy _ kind) (_ : xs) = suppress kind xs
suppress (FunTy _ res) (x:xs) = x : suppress res xs
suppress _ xs = xs
----------------
pprTyList :: TyPrec -> Type -> Type -> SDoc
-- Given a type-level list (t1 ': t2), see if we can print
-- it in list notation [t1, ...].
pprTyList p ty1 ty2
= case gather ty2 of
(arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma
(map (ppr_type TopPrec) (ty1:arg_tys))))
(arg_tys, Just tl) -> maybeParen p FunPrec $
hang (ppr_type FunPrec ty1)
2 (fsep [ colon <+> ppr_type FunPrec ty | ty <- arg_tys ++ [tl]])
where
gather :: Type -> ([Type], Maybe Type)
-- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn]
-- = (tys, Just tl) means ty is of form t1:t2:...tn:tl
gather (TyConApp tc tys)
| tc `hasKey` consDataConKey
, [_kind, ty1,ty2] <- tys
, (args, tl) <- gather ty2
= (ty1:args, tl)
| tc `hasKey` nilDataConKey
= ([], Nothing)
gather ty = ([], Just ty)
----------------
pprInfixApp :: TyPrec -> (TyPrec -> a -> SDoc) -> SDoc -> a -> a -> SDoc
pprInfixApp p pp pp_tc ty1 ty2
= maybeParen p TyOpPrec $
sep [pp TyOpPrec ty1, pprInfixVar True pp_tc <+> pp TyOpPrec ty2]
pprPrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc
pprPrefixApp p pp_fun pp_tys
| null pp_tys = pp_fun
| otherwise = maybeParen p TyConPrec $
hang pp_fun 2 (sep pp_tys)
----------------
pprArrowChain :: TyPrec -> [SDoc] -> SDoc
-- pprArrowChain p [a,b,c] generates a -> b -> c
pprArrowChain _ [] = empty
pprArrowChain p (arg:args) = maybeParen p FunPrec $
sep [arg, sep (map (arrow <+>) args)]
{-
************************************************************************
* *
\subsection{TidyType}
* *
************************************************************************
Tidying is here because it has a special case for FlatSkol
-}
-- | This tidies up a type for printing in an error message, or in
-- an interface file.
--
-- It doesn't change the uniques at all, just the print names.
tidyTyVarBndrs :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyTyVarBndrs env tvs = mapAccumL tidyTyVarBndr env tvs
tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyTyVarBndr tidy_env@(occ_env, subst) tyvar
= case tidyOccName occ_env occ1 of
(tidy', occ') -> ((tidy', subst'), tyvar')
where
subst' = extendVarEnv subst tyvar tyvar'
tyvar' = setTyVarKind (setTyVarName tyvar name') kind'
name' = tidyNameOcc name occ'
kind' = tidyKind tidy_env (tyVarKind tyvar)
where
name = tyVarName tyvar
occ = getOccName name
-- System Names are for unification variables;
-- when we tidy them we give them a trailing "0" (or 1 etc)
-- so that they don't take precedence for the un-modified name
-- Plus, indicating a unification variable in this way is a
-- helpful clue for users
occ1 | isSystemName name = mkTyVarOcc (occNameString occ ++ "0")
| otherwise = occ
---------------
tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
-- ^ Add the free 'TyVar's to the env in tidy form,
-- so that we can tidy the type they are free in
tidyFreeTyVars (full_occ_env, var_env) tyvars
= fst (tidyOpenTyVars (full_occ_env, var_env) (varSetElems tyvars))
---------------
tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
---------------
tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
-- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
-- using the environment if one has not already been allocated. See
-- also 'tidyTyVarBndr'
tidyOpenTyVar env@(_, subst) tyvar
= case lookupVarEnv subst tyvar of
Just tyvar' -> (env, tyvar') -- Already substituted
Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
---------------
tidyTyVarOcc :: TidyEnv -> TyVar -> TyVar
tidyTyVarOcc (_, subst) tv
= case lookupVarEnv subst tv of
Nothing -> tv
Just tv' -> tv'
---------------
tidyTypes :: TidyEnv -> [Type] -> [Type]
tidyTypes env tys = map (tidyType env) tys
---------------
tidyType :: TidyEnv -> Type -> Type
tidyType _ (LitTy n) = LitTy n
tidyType env (TyVarTy tv) = TyVarTy (tidyTyVarOcc env tv)
tidyType env (TyConApp tycon tys) = let args = tidyTypes env tys
in args `seqList` TyConApp tycon args
tidyType env (AppTy fun arg) = (AppTy $! (tidyType env fun)) $! (tidyType env arg)
tidyType env (FunTy fun arg) = (FunTy $! (tidyType env fun)) $! (tidyType env arg)
tidyType env (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
where
(envp, tvp) = tidyTyVarBndr env tv
---------------
-- | Grabs the free type variables, tidies them
-- and then uses 'tidyType' to work over the type itself
tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
tidyOpenType env ty
= (env', tidyType (trimmed_occ_env, var_env) ty)
where
(env'@(_, var_env), tvs') = tidyOpenTyVars env (varSetElems (tyVarsOfType ty))
trimmed_occ_env = initTidyOccEnv (map getOccName tvs')
-- The idea here was that we restrict the new TidyEnv to the
-- _free_ vars of the type, so that we don't gratuitously rename
-- the _bound_ variables of the type.
---------------
tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
---------------
-- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
tidyTopType :: Type -> Type
tidyTopType ty = tidyType emptyTidyEnv ty
---------------
tidyOpenKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
tidyOpenKind = tidyOpenType
tidyKind :: TidyEnv -> Kind -> Kind
tidyKind = tidyType
| AlexanderPankiv/ghc | compiler/types/TypeRep.hs | bsd-3-clause | 33,175 | 0 | 17 | 8,971 | 5,258 | 2,829 | 2,429 | 367 | 4 |
{-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances #-}
module Main where
import UU.Parsing
import System
data Token
= TkIdent String
| TkKeyword String
| TkString String
instance Show Token where
show (TkIdent _) = "identifier"
show (TkKeyword s) = s
show (TkString _) = "literal string"
instance Eq Token where
(TkIdent _) == (TkIdent _) = True
(TkString _) == (TkString _) = True
(TkKeyword s) == (TkKeyword r) = s == r
_ == _ = False
instance Ord Token where
compare (TkIdent _) (TkIdent _) = EQ
compare (TkIdent _) (TkKeyword _) = LT
compare (TkIdent _) (TkString _) = LT
compare (TkKeyword s) (TkKeyword r) = compare s r
compare (TkKeyword _) (TkString _) = LT
compare (TkString _) (TkString _) = EQ
compare _ _ = GT
instance Symbol Token
pIdent :: Parser Token String
pIdent = (\(TkIdent s) -> s) <$> pSym (TkIdent "invented_identifier")
pKey :: String -> Parser Token String
pKey sToMatch = (\(TkKeyword s) -> s) <$> pSym (TkKeyword sToMatch)
pString :: Parser Token String
pString = (\(TkString s) -> s) <$> pSym (TkString "\"invented string \"")
runParser :: Show a => Parser Token a -> [Token] -> IO String
runParser p inp
= do result <- parseIO p inp
return (show result)
testTokens :: [Token]
testTokens = [TkKeyword "begin", TkString "hello world", TkKeyword "end"]
testParser :: Parser Token Int
testParser = length <$ pKey "begin" <*> pString <* pKey "end"
test :: IO ()
test = do s <- runParser testParser testTokens
if s == "11"
then exitWith ExitSuccess
else exitFailure
main :: IO ()
main = test
| UU-ComputerScience/uulib | test/Main.hs | bsd-3-clause | 1,691 | 0 | 9 | 429 | 658 | 331 | 327 | 47 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
-----------------------------------------------------------------------------------------
-- |
-- Module : FRP.Yampa.AffineSpace
-- Copyright : (c) Antony Courtney and Henrik Nilsson, Yale University, 2003
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : nilsson@cs.yale.edu
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
-- Affine space type relation.
--
-----------------------------------------------------------------------------------------
module FRP.Yampa.AffineSpace where
import FRP.Yampa.VectorSpace
------------------------------------------------------------------------------
-- Affine Space type relation
------------------------------------------------------------------------------
infix 6 .+^, .-^, .-.
-- Maybe origin should not be a class method, even though an origin
-- can be assocoated with any affine space.
-- Maybe distance should not be a class method, in which case the constraint
-- on the coefficient space (a) could be Fractional (i.e., a Field), which
-- seems closer to the mathematical definition of affine space, provided
-- the constraint on the coefficient space for VectorSpace is also Fractional.
-- Minimal instance: origin, .+^, .^.
class (Floating a, VectorSpace v a) => AffineSpace p v a | p -> v, v -> a where
origin :: p
(.+^) :: p -> v -> p
(.-^) :: p -> v -> p
(.-.) :: p -> p -> v
distance :: p -> p -> a
p .-^ v = p .+^ (negateVector v)
distance p1 p2 = norm (p1 .-. p2)
| meimisaki/Yampa | src/FRP/Yampa/AffineSpace.hs | bsd-3-clause | 1,635 | 0 | 9 | 286 | 193 | 120 | 73 | 12 | 0 |
module API where
data Num t => Interface t = D t
| abuiles/turbinado-blog | tmp/dependencies/hs-plugins-1.3.1/testsuite/pdynload/numclass/api/API.hs | bsd-3-clause | 52 | 0 | 6 | 15 | 21 | 12 | 9 | 2 | 0 |
{-# LANGUAGE GADTs, EmptyDataDecls, KindSignatures #-}
module ShouldCompile where
-- Various forms of empty data type declarations
data T1
data T2 where
data T3 :: * -> *
data T4 a :: * -> *
data T5 a :: * -> * where
| rahulmutt/ghcvm | tests/suite/typecheck/compile/tc247.hs | bsd-3-clause | 226 | 0 | 5 | 52 | 46 | 31 | 15 | -1 | -1 |
module Plugins (
FrontendPlugin(..), defaultFrontendPlugin,
Plugin(..), CommandLineOption,
defaultPlugin
) where
import CoreMonad ( CoreToDo, CoreM )
import TcRnTypes ( TcPlugin )
import GhcMonad
import DriverPhases
-- | Command line options gathered from the -PModule.Name:stuff syntax
-- are given to you as this type
type CommandLineOption = String
-- | 'Plugin' is the core compiler plugin data type. Try to avoid
-- constructing one of these directly, and just modify some fields of
-- 'defaultPlugin' instead: this is to try and preserve source-code
-- compatibility when we add fields to this.
--
-- Nonetheless, this API is preliminary and highly likely to change in
-- the future.
data Plugin = Plugin {
installCoreToDos :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
-- ^ Modify the Core pipeline that will be used for compilation.
-- This is called as the Core pipeline is built for every module
-- being compiled, and plugins get the opportunity to modify the
-- pipeline in a nondeterministic order.
, tcPlugin :: [CommandLineOption] -> Maybe TcPlugin
-- ^ An optional typechecker plugin, which may modify the
-- behaviour of the constraint solver.
}
-- | Default plugin: does nothing at all! For compatibility reasons
-- you should base all your plugin definitions on this default value.
defaultPlugin :: Plugin
defaultPlugin = Plugin {
installCoreToDos = const return
, tcPlugin = const Nothing
}
type FrontendPluginAction = [String] -> [(String, Maybe Phase)] -> Ghc ()
data FrontendPlugin = FrontendPlugin {
frontend :: FrontendPluginAction
}
defaultFrontendPlugin :: FrontendPlugin
defaultFrontendPlugin = FrontendPlugin { frontend = \_ _ -> return () }
| olsner/ghc | compiler/main/Plugins.hs | bsd-3-clause | 1,772 | 0 | 12 | 350 | 237 | 148 | 89 | 21 | 1 |
{-# LANGUAGE DataKinds, KindSignatures, GADTs, TypeFamilies #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-overlapping-patterns #-}
module T8970 where
import Data.Kind (Type)
data K = Foo
| Bar
data D1 :: K -> Type where
F1 :: D1 Foo
B1 :: D1 Bar
class C (a :: K -> Type) where
data D2 a :: K -> Type
foo :: a k -> D2 a k -> Bool
instance C D1 where
data D2 D1 k where
F2 :: D2 D1 Foo
B2 :: D2 D1 Bar
foo F1 F2 = True
foo B1 B2 = True
| sdiehl/ghc | testsuite/tests/pmcheck/should_compile/T8970.hs | bsd-3-clause | 511 | 0 | 9 | 162 | 162 | 88 | 74 | 18 | 0 |
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE GADTs #-}
module Test10399 where
type MPI = ?mpi_secret :: MPISecret
mkPoli = mkBila . map ((,,(),,()) <$> P.base <*> P.pos <*> P.form)
data MaybeDefault v where
SetTo :: forall v . ( Eq v, Show v ) => !v -> MaybeDefault v
SetTo4 :: forall v a. (( Eq v, Show v ) => v -> MaybeDefault v
-> a -> MaybeDefault [a])
TestParens :: (forall v . (Eq v) -> MaybeDefault v)
[t| Map.Map T.Text $tc |]
bar $( [p| x |] ) = x
| sdiehl/ghc | testsuite/tests/ghc-api/annotations/Test10399.hs | bsd-3-clause | 681 | 0 | 12 | 174 | 203 | 119 | 84 | -1 | -1 |
module Goo () where
import Language.Haskell.Liquid.Prelude
{-@ type BoundedNat N = {v:Nat | v < N } @-}
{-@ predicate Foo V N = V < N @-}
-- TODO: Test fails when this second alias is ALSO defined.
-- FIX: should WARN that there are duplicate aliases!
{-@ type BoundedNat N = {v:Nat | v <= N } @-}
{-@ predicate Foo V N = V <= N @-}
{-@ foo :: n:Int -> m:(BoundedNat n) -> Nat @-}
foo :: Int -> Int -> Int
foo n m = liquidAssert (m < n) m
| mightymoose/liquidhaskell | tests/crash/typeAliasDup.hs | bsd-3-clause | 467 | 0 | 7 | 124 | 56 | 35 | 21 | 4 | 1 |
module Idris.REPLParser (parseCmd, help, allHelp) where
import System.FilePath ((</>))
import System.Console.ANSI (Color(..))
import Idris.Colours
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.Help
import qualified Idris.Parser as P
import Control.Applicative
import Control.Monad.State.Strict
import Text.Parser.Combinators
import Text.Parser.Char(anyChar,oneOf)
import Text.Trifecta(Result, parseString)
import Text.Trifecta.Delta
import Debug.Trace
import Data.List
import Data.List.Split(splitOn)
import Data.Char(isSpace, toLower)
import qualified Data.ByteString.UTF8 as UTF8
parseCmd :: IState -> String -> String -> Result (Either String Command)
parseCmd i inputname = P.runparser pCmd i inputname . trim
where trim = f . f
where f = reverse . dropWhile isSpace
type CommandTable = [ ( [String], CmdArg, String
, String -> P.IdrisParser (Either String Command) ) ]
help :: [([String], CmdArg, String)]
help = (["<expr>"], NoArg, "Evaluate an expression") :
[ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ]
allHelp :: [([String], CmdArg, String)]
allHelp = [ (map (':' :) names, args, text)
| (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ]
parserCommandsForHelp :: CommandTable
parserCommandsForHelp =
[ exprArgCmd ["t", "type"] Check "Check the type of an expression"
, exprArgCmd ["core"] Core "View the core language representation of a term"
, nameArgCmd ["miss", "missing"] Missing "Show missing clauses"
, (["doc"], NameArg, "Show internal documentation", cmd_doc)
, (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"
, genArg "namespace" (many anyChar) MakeDoc)
, (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"
, cmd_apropos)
, (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg
, " Search for values by type", cmd_search)
, nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name"
, nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name"
, namespaceArgCmd ["browse"] Browse "List the contents of some namespace"
, nameArgCmd ["total"] TotCheck "Check the totality of a name"
, noArgCmd ["r", "reload"] Reload "Reload current file"
, (["l", "load"], FileArg, "Load a new file"
, strArg (\f -> Load f Nothing))
, (["cd"], FileArg, "Change working directory"
, strArg ChangeDirectory)
, (["module"], ModuleArg, "Import an extra module", moduleArg ModImport) -- NOTE: dragons
, noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL"
, noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables or holes)"
, (["p", "prove"], MetaVarArg, "Prove a metavariable"
, nameArg (Prove False))
, (["elab"], MetaVarArg, "Build a metavariable using the elaboration shell"
, nameArg (Prove True))
, (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof)
, (["rmproof"], NameArg, "Remove proof from proof stack"
, nameArg RmProof)
, (["showproof"], NameArg, "Show proof"
, nameArg ShowProof)
, noArgCmd ["proofs"] Proofs "Show available proofs"
, exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
, (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
, (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
, (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
, (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
, noArgCmd ["?", "h", "help"] Help "Display this help text"
, optArgCmd ["set"] SetOpt "Set an option (errorcontext, showimplicits)"
, optArgCmd ["unset"] UnsetOpt "Unset an option"
, (["color", "colour"], ColourArg
, "Turn REPL colours on or off; set a specific colour"
, cmd_colour)
, (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)
, (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth)
, noArgCmd ["q", "quit"] Quit "Exit the Idris system"
, noArgCmd ["w", "warranty"] Warranty "Displays warranty information"
, (["let"], ManyArgs DeclArg
, "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"
, cmd_let)
, (["unlet", "undefine"], ManyArgs NameArg
, "Remove the listed repl definitions, or all repl definitions if no names given"
, cmd_unlet)
, nameArgCmd ["printdef"] PrintDef "Show the definition of a function"
, (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
, "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
, cmd_pprint)
]
parserCommands =
[ noArgCmd ["u", "universes"] Universes "Display universe constraints"
, noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers"
, nameArgCmd ["d", "def"] Defn "Display a name's internal definitions"
, nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name"
, nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name"
, exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression"
, exprArgCmd ["spec"] Spec "?"
, exprArgCmd ["whnf"] WHNF "(Debugging) Show weak head normal form of an expression"
, exprArgCmd ["inline"] TestInline "?"
, proofArgCmd ["cs", "casesplit"] CaseSplitAt
":cs <line> <name> splits the pattern variable on the line"
, proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom
":apc <line> <name> adds a pattern-matching proof clause to name on line"
, proofArgCmd ["ac", "addclause"] AddClauseFrom
":ac <line> <name> adds a clause for the definition of the name on the line"
, proofArgCmd ["am", "addmissing"] AddMissing
":am <line> <name> adds all missing pattern matches for the name on the line"
, proofArgCmd ["mw", "makewith"] MakeWith
":mw <line> <name> adds a with clause for the definition of the name on the line"
, proofArgCmd ["mc", "makecase"] MakeCase
":mc <line> <name> adds a case block for the definition of the metavariable on the line"
, proofArgCmd ["ml", "makelemma"] MakeLemma "?"
, (["log"], NumberArg, "Set logging verbosity level", cmd_log)
, (["lto", "loadto"], SeqArgs NumberArg FileArg
, "Load file up to line number", cmd_loadto)
, (["ps", "proofsearch"], NoArg
, ":ps <line> <name> <names> does proof search for name on line, with names as hints"
, cmd_proofsearch)
, (["ref", "refine"], NoArg
, ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable"
, cmd_refine)
, (["debugunify"], SeqArgs ExprArg ExprArg
, "(Debugging) Try to unify two expressions", const $ do
l <- P.simpleExpr defaultSyntax
r <- P.simpleExpr defaultSyntax
eof
return (Right (DebugUnify l r))
)
]
noArgCmd names command doc =
(names, NoArg, doc, noArgs command)
nameArgCmd names command doc =
(names, NameArg, doc, fnNameArg command)
namespaceArgCmd names command doc =
(names, NamespaceArg, doc, namespaceArg command)
exprArgCmd names command doc =
(names, ExprArg, doc, exprArg command)
metavarArgCmd names command doc =
(names, MetaVarArg, doc, fnNameArg command)
optArgCmd names command doc =
(names, OptionArg, doc, optArg command)
proofArgCmd names command doc =
(names, NoArg, doc, proofArg command)
pCmd :: P.IdrisParser (Either String Command)
pCmd = choice [ do c <- cmd names; parser c
| (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]
<|> unrecognized
<|> nop
<|> eval
where nop = do eof; return (Right NOP)
eval = exprArg Eval ""
unrecognized = do
P.lchar ':'
cmd <- many anyChar
let cmd' = takeWhile (/=' ') cmd
return (Left $ "Unrecognized command: " ++ cmd')
cmd :: [String] -> P.IdrisParser String
cmd xs = try $ do
P.lchar ':'
docmd sorted_xs
where docmd [] = fail "Could not parse command"
docmd (x:xs) = try (P.reserved x >> return x) <|> docmd xs
sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs
noArgs :: Command -> String -> P.IdrisParser (Either String Command)
noArgs cmd name = do
let emptyArgs = do
eof
return (Right cmd)
let failure = return (Left $ ":" ++ name ++ " takes no arguments")
emptyArgs <|> failure
exprArg :: (PTerm -> Command) -> String -> P.IdrisParser (Either String Command)
exprArg cmd name = do
let noArg = do
eof
return $ Left ("Usage is :" ++ name ++ " <expression>")
let properArg = do
t <- P.fullExpr defaultSyntax
return $ Right (cmd t)
try noArg <|> properArg
genArg :: String -> P.IdrisParser a -> (a -> Command)
-> String -> P.IdrisParser (Either String Command)
genArg argName argParser cmd name = do
let emptyArgs = do eof; failure
oneArg = do arg <- argParser
eof
return (Right (cmd arg))
try emptyArgs <|> oneArg <|> failure
where
failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">")
nameArg, fnNameArg :: (Name -> Command) -> String -> P.IdrisParser (Either String Command)
nameArg = genArg "name" $ fst <$> P.name
fnNameArg = genArg "functionname" $ fst <$> P.fnName
strArg :: (String -> Command) -> String -> P.IdrisParser (Either String Command)
strArg = genArg "string" (many anyChar)
moduleArg :: (FilePath -> Command) -> String -> P.IdrisParser (Either String Command)
moduleArg = genArg "module" (fmap (toPath . fst) P.identifier)
where
toPath n = foldl1' (</>) $ splitOn "." n
namespaceArg :: ([String] -> Command) -> String -> P.IdrisParser (Either String Command)
namespaceArg = genArg "namespace" (fmap (toNS . fst) P.identifier)
where
toNS = splitOn "."
optArg :: (Opt -> Command) -> String -> P.IdrisParser (Either String Command)
optArg cmd name = do
let emptyArgs = do
eof
return $ Left ("Usage is :" ++ name ++ " <option>")
let oneArg = do
o <- pOption
P.whiteSpace
eof
return (Right (cmd o))
let failure = return $ Left "Unrecognized setting"
try emptyArgs <|> oneArg <|> failure
where
pOption :: P.IdrisParser Opt
pOption = do discard (P.symbol "errorcontext"); return ErrContext
<|> do discard (P.symbol "showimplicits"); return ShowImpl
<|> do discard (P.symbol "originalerrors"); return ShowOrigErr
<|> do discard (P.symbol "autosolve"); return AutoSolve
<|> do discard (P.symbol "nobanner") ; return NoBanner
<|> do discard (P.symbol "warnreach"); return WarnReach
<|> do discard (P.symbol "evaltypes"); return EvalTypes
proofArg :: (Bool -> Int -> Name -> Command) -> String -> P.IdrisParser (Either String Command)
proofArg cmd name = do
upd <- option False $ do
P.lchar '!'
return True
l <- fst <$> P.natural
n <- fst <$> P.name;
return (Right (cmd upd (fromInteger l) n))
cmd_doc :: String -> P.IdrisParser (Either String Command)
cmd_doc name = do
let constant = do
c <- fmap fst P.constant
eof
return $ Right (DocStr (Right c) FullDocs)
let pType = do
P.reserved "Type"
eof
return $ Right (DocStr (Left $ P.mkName ("Type", "")) FullDocs)
let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
try constant <|> pType <|> fnName
cmd_consolewidth :: String -> P.IdrisParser (Either String Command)
cmd_consolewidth name = do
w <- pConsoleWidth
return (Right (SetConsoleWidth w))
where
pConsoleWidth :: P.IdrisParser ConsoleWidth
pConsoleWidth = do discard (P.symbol "auto"); return AutomaticWidth
<|> do discard (P.symbol "infinite"); return InfinitelyWide
<|> do n <- fmap (fromInteger . fst) P.natural
return (ColsWide n)
cmd_printdepth :: String -> P.IdrisParser (Either String Command)
cmd_printdepth _ = do d <- optional (fmap (fromInteger . fst) P.natural)
return (Right $ SetPrinterDepth d)
cmd_execute :: String -> P.IdrisParser (Either String Command)
cmd_execute name = do
tm <- option maintm (P.fullExpr defaultSyntax)
return (Right (Execute tm))
where
maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"])
cmd_dynamic :: String -> P.IdrisParser (Either String Command)
cmd_dynamic name = do
let optArg = do l <- many anyChar
if (l /= "")
then return $ Right (DynamicLink l)
else return $ Right ListDynamic
let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
try optArg <|> failure
cmd_pprint :: String -> P.IdrisParser (Either String Command)
cmd_pprint name = do
fmt <- ppFormat
P.whiteSpace
n <- fmap (fromInteger . fst) P.natural
P.whiteSpace
t <- P.fullExpr defaultSyntax
return (Right (PPrint fmt n t))
where
ppFormat :: P.IdrisParser OutputFmt
ppFormat = (discard (P.symbol "html") >> return HTMLOutput)
<|> (discard (P.symbol "latex") >> return LaTeXOutput)
cmd_compile :: String -> P.IdrisParser (Either String Command)
cmd_compile name = do
let defaultCodegen = Via "c"
let codegenOption :: P.IdrisParser Codegen
codegenOption = do
let bytecodeCodegen = discard (P.symbol "bytecode") *> return Bytecode
viaCodegen = do x <- fst <$> P.identifier
return (Via (map toLower x))
bytecodeCodegen <|> viaCodegen
let hasOneArg = do
i <- get
f <- fst <$> P.identifier
eof
return $ Right (Compile defaultCodegen f)
let hasTwoArgs = do
i <- get
codegen <- codegenOption
f <- fst <$> P.identifier
eof
return $ Right (Compile codegen f)
let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
try hasTwoArgs <|> try hasOneArg <|> failure
cmd_addproof :: String -> P.IdrisParser (Either String Command)
cmd_addproof name = do
n <- option Nothing $ do
x <- fst <$> P.name
return (Just x)
eof
return (Right (AddProof n))
cmd_log :: String -> P.IdrisParser (Either String Command)
cmd_log name = do
i <- fmap (fromIntegral . fst) P.natural
eof
return (Right (LogLvl i))
cmd_let :: String -> P.IdrisParser (Either String Command)
cmd_let name = do
defn <- concat <$> many (P.decl defaultSyntax)
return (Right (NewDefn defn))
cmd_unlet :: String -> P.IdrisParser (Either String Command)
cmd_unlet name = (Right . Undefine) `fmap` many (fst <$> P.name)
cmd_loadto :: String -> P.IdrisParser (Either String Command)
cmd_loadto name = do
toline <- fmap (fromInteger . fst) P.natural
f <- many anyChar;
return (Right (Load f (Just toline)))
cmd_colour :: String -> P.IdrisParser (Either String Command)
cmd_colour name = fmap Right pSetColourCmd
where
colours :: [(String, Maybe Color)]
colours = [ ("black", Just Black)
, ("red", Just Red)
, ("green", Just Green)
, ("yellow", Just Yellow)
, ("blue", Just Blue)
, ("magenta", Just Magenta)
, ("cyan", Just Cyan)
, ("white", Just White)
, ("default", Nothing)
]
pSetColourCmd :: P.IdrisParser Command
pSetColourCmd = (do c <- pColourType
let defaultColour = IdrisColour Nothing True False False False
opts <- sepBy pColourMod (P.whiteSpace)
let colour = foldr ($) defaultColour $ reverse opts
return $ SetColour c colour)
<|> try (P.symbol "on" >> return ColourOn)
<|> try (P.symbol "off" >> return ColourOff)
pColour :: P.IdrisParser (Maybe Color)
pColour = doColour colours
where doColour [] = fail "Unknown colour"
doColour ((s, c):cs) = (try (P.symbol s) >> return c) <|> doColour cs
pColourMod :: P.IdrisParser (IdrisColour -> IdrisColour)
pColourMod = try (P.symbol "vivid" >> return doVivid)
<|> try (P.symbol "dull" >> return doDull)
<|> try (P.symbol "underline" >> return doUnderline)
<|> try (P.symbol "nounderline" >> return doNoUnderline)
<|> try (P.symbol "bold" >> return doBold)
<|> try (P.symbol "nobold" >> return doNoBold)
<|> try (P.symbol "italic" >> return doItalic)
<|> try (P.symbol "noitalic" >> return doNoItalic)
<|> try (pColour >>= return . doSetColour)
where doVivid i = i { vivid = True }
doDull i = i { vivid = False }
doUnderline i = i { underline = True }
doNoUnderline i = i { underline = False }
doBold i = i { bold = True }
doNoBold i = i { bold = False }
doItalic i = i { italic = True }
doNoItalic i = i { italic = False }
doSetColour c i = i { colour = c }
-- | Generate the colour type names using the default Show instance.
colourTypes :: [(String, ColourType)]
colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
enumFromTo minBound maxBound
pColourType :: P.IdrisParser ColourType
pColourType = doColourType colourTypes
where doColourType [] = fail $ "Unknown colour category. Options: " ++
(concat . intersperse ", " . map fst) colourTypes
doColourType ((s,ct):cts) = (try (P.symbol s) >> return ct) <|> doColourType cts
idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
cmd_apropos :: String -> P.IdrisParser (Either String Command)
cmd_apropos = packageBasedCmd (some idChar) Apropos
packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command)
-> String -> P.IdrisParser (Either String Command)
packageBasedCmd valParser cmd name =
try (do P.lchar '('
pkgs <- sepBy (some idChar) (P.lchar ',')
P.lchar ')'
val <- valParser
return (Right (cmd pkgs val)))
<|> do val <- valParser
return (Right (cmd [] val))
cmd_search :: String -> P.IdrisParser (Either String Command)
cmd_search = packageBasedCmd
(P.typeExpr (defaultSyntax { implicitAllowed = True })) Search
cmd_proofsearch :: String -> P.IdrisParser (Either String Command)
cmd_proofsearch name = do
upd <- option False (do P.lchar '!'; return True)
l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
hints <- many (fst <$> P.fnName)
return (Right (DoProofSearch upd True l n hints))
cmd_refine :: String -> P.IdrisParser (Either String Command)
cmd_refine name = do
upd <- option False (do P.lchar '!'; return True)
l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
hint <- fst <$> P.fnName
return (Right (DoProofSearch upd False l n [hint]))
| stevejb71/Idris-dev | src/Idris/REPLParser.hs | bsd-3-clause | 19,769 | 0 | 21 | 5,132 | 6,238 | 3,210 | 3,028 | -1 | -1 |
module Rn066_A where
{-# WARNING C "Are you sure you want to do that?" #-}
{-# WARNING op "Is that really a good idea?" #-}
data T = C | D
class Foo a where
op :: a -> a
bop :: a -> a
| siddhanathan/ghc | testsuite/tests/rename/should_compile/Rn066_A.hs | bsd-3-clause | 191 | 0 | 7 | 52 | 43 | 25 | 18 | 7 | 0 |
{-# LANGUAGE ImplicitParams, FlexibleContexts #-}
module ShouldFail where
class (?imp :: Int) => D t where
methodD :: t -> t
instance (?imp :: Int) => D Int where
methodD x = x + ?imp
test :: D Int => Int -- Requires FlexibleContexts
test = methodD ?imp
-- Should get reasonable error about unbound ?imp
use :: IO ()
use = print test
| urbanslug/ghc | testsuite/tests/typecheck/should_fail/tcfail211.hs | bsd-3-clause | 347 | 0 | 7 | 77 | 101 | 56 | 45 | 10 | 1 |
{-
H-99 Problems
Copyright 2015 (c) Adrian Nwankwo (Arcaed0x)
Problem : 10
Description : Run-length encoding of a list. Use the result of problem P09
to implement the so-called run-length encoding data
compression method. Consecutive duplicates of elements
are encoded as lists (N E) where N is the number of
duplicates of the element E.
License : MIT (See LICENSE file)
-}
countAlike :: (Eq a) => [a] -> [(Int, a)]
countAlike l = [(length x, head x) | x <- groupedAlikeList]
where groupedAlikeList = sameCongregate l
sameCongregate :: (Eq a) => [a] -> [[a]]
sameCongregate [] = []
sameCongregate lst = firstAlikeElems : sameCongregate restOfList
where restOfList = drop (length firstAlikeElems) lst
firstAlikeElems = takeAlikeElems lst
takeAlikeElems [x] = [x]
takeAlikeElems (x:xs) = if x == (head xs)
then x : takeAlikeElems xs
else [x]
| Arcaed0x/H-99-Solutions | src/prob10.hs | mit | 1,055 | 0 | 10 | 351 | 210 | 113 | 97 | 12 | 3 |
import System.Environment (getArgs)
import VM
import Parser
main :: IO ()
main = do args <- getArgs
case args of
("help":_) -> showHelp
("-h":_) -> showHelp
("--help":_) -> showHelp
(path:_) -> readFile path >>= run path
_ -> if null args
then getContents >>= run "STDIN"
else showHelp
run :: FilePath -> String -> IO ()
run path content = do instructions <- readInstructions path content
print . takeResult $ runVM instructions
readInstructions :: FilePath -> String -> IO [Instruction]
readInstructions path str = case parse instructionsParser path str of
Left e -> error $ show e
Right v -> return v
showHelp :: IO ()
showHelp = do putStrLn "Usage:"
putStrLn " hs-vm PATH\n"
putStrLn "From STDIN:"
putStrLn " hs-vm"
| taiki45/hs-vm | src/Main.hs | mit | 1,028 | 0 | 12 | 430 | 293 | 141 | 152 | 25 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module Ptt.Time.Date
( ParsedDateSelector(..)
, DateSelector(..)
, parseFromText
, selectorFromText
, toSelector
, toSelectorWithDay
, currentDay
, parseDay
, formatDay
) where
import Prelude as P
import qualified Data.Text as T
import Control.Monad
import Control.Applicative
import Data.Time
import System.Locale (defaultTimeLocale)
data ParsedDateSelector
= DefaultDate
| DSelector DateSelector
deriving (Eq, Show)
data DateSelector
= AllDates
| SingleDate Day
| DateRange Day Day
deriving (Eq, Show)
toSelector :: ParsedDateSelector -> IO DateSelector
toSelector pds = (`toSelectorWithDay` pds) <$> currentDay
toSelectorWithDay :: Day -> ParsedDateSelector -> DateSelector
toSelectorWithDay day pds =
case pds of
DefaultDate -> SingleDate day
DSelector s -> s
parseFromText :: T.Text -> Maybe ParsedDateSelector
parseFromText s = parseDefaultDate s <|> (DSelector <$> selectorFromText s)
selectorFromText :: T.Text -> Maybe DateSelector
selectorFromText s =
parseAllDates s
<|> dateFromText s
<|> dateRangeFromText s
parseDefaultDate :: T.Text -> Maybe ParsedDateSelector
parseDefaultDate s =
if T.null s || s == "default"
then Just DefaultDate
else Nothing
parseAllDates :: T.Text -> Maybe DateSelector
parseAllDates s = if s == "all" then Just AllDates else Nothing
dateFromText :: T.Text -> Maybe DateSelector
dateFromText s = SingleDate <$> parseDay s
dateRangeFromText :: T.Text -> Maybe DateSelector
dateRangeFromText s =
case T.splitOn ".." s of
(from:to:[]) -> DateRange <$> parseDay from <*> parseDay to
_ -> Nothing
currentDay :: IO Day
currentDay = liftM utctDay getCurrentTime
parseDay :: T.Text -> Maybe Day
parseDay s = parseTime defaultTimeLocale "%F" (T.unpack s)
formatDay :: Day -> T.Text
formatDay = T.pack . formatTime defaultTimeLocale "%F"
| jkpl/ptt | src/Ptt/Time/Date.hs | mit | 1,882 | 0 | 11 | 330 | 555 | 294 | 261 | 60 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Importer
import Control.Monad(when)
import System.Environment
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import Database (openConnection,closeConnection,saveNodes,saveWays,saveRelation)
main :: IO ()
main = do
args <- getArgs
when (length args < 3) $ showUsage
let dbconnection = args !! 0
let dbname = args !! 1
let filename = args !! 2
startMongoImport dbconnection dbname filename
return ()
startMongoImport :: String -> String -> String -> IO ()
startMongoImport dbconnection dbname filename = do
pipe <- openConnection dbconnection
let dbNodecommand = saveNodes pipe dbname
let dbWaycommand = saveWays pipe dbname
let dbRelationcommand = saveRelation pipe dbname
performImport filename dbNodecommand dbWaycommand dbRelationcommand
closeConnection pipe
showUsage :: IO ()
showUsage = do
hPutStrLn stderr "usage: dbconnection dbname filename"
hPutStrLn stderr "example: OSMImport '127.0.0.1:27017' 'geo_data' './download/england-latest.osm.pbf'"
exitFailure
| ederoyd46/OSMImport | src/Main.hs | mit | 1,080 | 0 | 11 | 177 | 300 | 145 | 155 | 29 | 1 |
-- | Module: Capnp.New.Constraints
-- Description: convenience shorthands for various constraints.
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Capnp.New.Constraints where
import qualified Capnp.New.Classes as C
import qualified Capnp.Repr as R
import qualified Capnp.Repr.Parsed as RP
-- | Constraints needed for @a@ to be a capnproto type parameter.
type TypeParam a =
( R.IsPtr a
, C.Parse a (RP.Parsed a)
)
| zenhack/haskell-capnp | lib/Capnp/New/Constraints.hs | mit | 497 | 0 | 9 | 93 | 72 | 49 | 23 | 10 | 0 |
module HcPlot where
import HcPlot.Names
import HcPlot.Molecule
import System.Random
import Data.List
{-| How long can a sidechain be at xth C molecule |-}
maxSideChainLen :: Int -> [Int]
maxSideChainLen x = undefined
where half = concat . map (\a -> [a,a])
| Henning-Klatt/alkan-plotter | HcPlot-hs/src/HcPlot.hs | mit | 263 | 0 | 11 | 47 | 73 | 43 | 30 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module UI.Graphics
(
GraphicsHandle,
Input(..),
initUI,
render,
getInput,
getPassiveInput,
showMessageWindow,
cleanup
) where
import Control.Monad (join, liftM2, forM_, guard, zipWithM_)
import Control.Monad.IO.Class
import Data.Function (on)
import Data.List (zip3)
import qualified Data.Text as T
import qualified Data.Vector as V
import Foreign.C.Types (CInt)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr
import Foreign.Storable (peek)
import SDL
import SDL.Internal.Types (Window(..))
import SDL.Raw.Video (glGetDrawableSize)
import System.Environment (setEnv)
import Linear (V2(..), V4(..))
import Linear.Affine (Point(..))
import Board
-- |Data type containing SDL data structures.
data GraphicsHandle = GraphicsHandle
{
ghWindow :: Window,
ghRenderer :: Renderer,
ghTexture :: Texture,
ghTexture2x :: Texture
}
-- |Data type that represents a input from the user.
data Input = Exit | Restart | ColSelected Int deriving (Show)
-- Define dimensions of the various GUI elements:
squareSize, srcSquareSize, borderSize, boardWidth, boardHeight, buttonWidth,
buttonHeight, windowWidth, windowHeight :: Integral a => a
-- |Width and height (in pixels) of each square in the window.
squareSize = 64
-- |Width and height (in pixels) of each square in the texture.
srcSquareSize = 64
-- |Width/Height of border of the board
borderSize = 16
-- |Board width.
boardWidth = boardCols * squareSize
-- |Board height.
boardHeight = boardRows * squareSize
-- |Button width.
buttonWidth = 192
-- |Button height.
buttonHeight = 32
-- |Width of contents of the window.
windowWidth = squareSize * boardCols + 2*borderSize
-- |Height of contents of the window.
windowHeight = squareSize * boardRows + 2*borderSize + buttonHeight
-- Some auxiliary functions.
-- | Function that creates a SDL rectangle given two tuples: (x0, y0) and
-- (width, height). This allows to eliminate some boilerplate code when we
-- create rectangles.
mkRect :: Num a => (a, a) -> (a, a) -> Rectangle a
mkRect (x0, y0) (w, h) = Rectangle (P (V2 x0 y0)) (V2 w h)
-- |Gets the size of the drawable contents of the window. This may differ
-- from the window size in HiDPI screens.
getDrawableSize :: MonadIO m => GraphicsHandle -> m (Int, Int)
getDrawableSize uiHandle =
-- Since we are using SDL low level (raw) bindings, we have to do some
-- magic. We allocate two variables that will contain the results of
-- the 'glGetDrawableSize' call. Then, we extract the values of said
-- variables (represented as pointers) and return them in a tuple.
liftIO $ alloca $ \widthPtr -> (alloca $ \heightPtr -> do
glGetDrawableSize windowPtr widthPtr heightPtr
liftM2 (,) (fromPtr widthPtr) (fromPtr heightPtr)
)
where -- Unwrap the window type (returning a pointer to the Window data
-- structure in memory)
windowPtr = case ghWindow uiHandle of
Window ptr -> ptr
-- Extract a value from pointer. The type of this is:
-- Num a, Integral b => Ptr a -> IO b
fromPtr = fmap fromIntegral . peek
-- |Checks whether a point is inside a rectangle.
withinRect :: (Num a, Ord a) => Point V2 a -> Rectangle a -> Bool
withinRect (P (V2 x y)) (Rectangle (P (V2 x0 y0)) (V2 w h)) =
and [ x0 < x, x < x0 + w, y0 < y, y < y0 + h ]
-- Rects of the graphical elements
boardRect, restartButtonRect, exitButtonRect :: Integral a => Rectangle a
-- |Rect of the board.
boardRect = mkRect (borderSize, borderSize) (boardWidth, boardHeight)
-- |Rect of the restart button.
restartButtonRect = mkRect ( windowWidth `div` 2 - buttonWidth
, windowHeight - buttonHeight)
(buttonWidth, buttonHeight)
-- |Rect ot the exit button.
exitButtonRect = mkRect (windowWidth `div` 2, windowHeight - buttonHeight)
(buttonWidth, buttonHeight)
-- |Configuration for the SDL window.
windowConfig :: WindowConfig
windowConfig = WindowConfig
True -- Window border?
True -- Allow high DPI?
False -- Window input grabbed?
Windowed -- Window mode.
Nothing -- OpenGL config.
Wherever -- Window pos.
False -- Resizable?
(V2 windowWidth windowHeight) -- Window size.
-- |Initialize the SDL subsystem and return a handle
initUI :: MonadIO m => m GraphicsHandle
initUI = do
-- Set some useful environment variables.
liftIO $ do
-- Set linear interpolation when rendering.
-- Setting the environment variable because I cannot get the API
-- function that sets the hint to work.
setEnv "SDL_RENDER_SCALE_QUALITY" "1"
-- Also, disable fullscreen in OS X
setEnv "SDL_VIDEO_MAC_FULLSCREEN_SPACES" "0"
-- SDL initialization.
initialize [InitEverything]
window <- createWindow "Connect 4 Haskell" windowConfig
renderer <- createRenderer window (-1) defaultRenderer
rendererDrawColor renderer $= V4 0xFF 0xFF 0xFF 0x00
-- Set logical size. Useful for resizing.
rendererLogicalSize renderer $= Just (V2 windowWidth windowHeight)
-- Create texture from BMP.
texture <- loadTexture renderer "assets/balls.bmp"
texture2x <- loadTexture renderer "assets/balls2x.bmp"
return $ GraphicsHandle window renderer texture texture2x
where loadTexture renderer path = do
surfaceTexture <- loadBMP path
texture <- createTextureFromSurface renderer surfaceTexture
freeSurface surfaceTexture
return texture
-- |Wrapper around the 'copy' SDL function that converts the 'Rectangle's
-- inner type from Int to CInt before calling the function.
copy' :: MonadIO m =>
GraphicsHandle -> Rectangle Int -> Rectangle Int -> m ()
copy' uiHandle srcRec dstRec = do
let renderer = ghRenderer uiHandle
texture = ghTexture uiHandle
texture2x = ghTexture2x uiHandle
(drawableWidth, drawableHeight) <- getDrawableSize uiHandle
let gDiv = (/) `on` fromIntegral
scaleFactor = min (drawableWidth `gDiv` windowWidth)
(drawableHeight `gDiv` windowHeight)
(usedTexture, srcScale) = if scaleFactor > 1.0
then (texture2x, 2)
else (texture, 1)
copy renderer usedTexture
(Just . fmap ((*srcScale) . fromIntegral) $ srcRec)
(Just . fmap fromIntegral $ dstRec)
-- |Renders a block consisting of the same source tile.
renderSame :: MonadIO m
=> GraphicsHandle
-> Rectangle Int -> Rectangle Int
-> Int -> Int
-> m ()
renderSame uih srcRect dstRect rows cols = do
-- Iterate in both dimensions to obtain the list of all destination rects,
let col = take rows $ iterate incrementDstRow dstRect
dstRects = concat . take cols $ iterate (map incrementDstCol) col
-- Map the drawing action to each rectangle.
forM_ dstRects $ \dstRect -> copy' uih srcRect dstRect
where -- Increment a rectangle in the positive Y axis.
incrementDstRow rect = case rect of
Rectangle (P (V2 x y)) (V2 width height) ->
mkRect (x, y+height) (width, height)
-- Increment a rectangle in the positive X axis.
incrementDstCol rect = case rect of
Rectangle (P (V2 x y)) (V2 width height) ->
mkRect (x+width, y) (width, height)
-- Render the border of the board.
renderBorder :: MonadIO m => GraphicsHandle -> m ()
renderBorder uiHandle = do
-- Edges.
forM_ (zip3 borderSrcTiles dstInitialRects dstHowMany) $
\(src, dst, counts) -> do
let (howManyRows, howManyCols) = counts
renderSame uiHandle src dst howManyRows howManyCols
-- Corners.
zipWithM_ (copy' uiHandle) cornerSrcTiles cornerDstRects
where -- top-left, bottom-left, top-right, bottom-right
-- Here I use the applicative property of lists to save a few
-- keystrokes.
cornerSrcTiles = map (toRectangle . toTextureCoords) $
(,) <$> [0, 2] <*> [0, 2]
cornerDstRects = map toRectangle $
(,) <$> [0, borderSize+boardWidth]
<*> [0, borderSize+boardHeight]
-- left, top, bottom, right
borderSrcTiles = map (toRectangle . toTextureCoords)
[(0, 1), (1, 0), (1, 2), (2, 1)]
dstInitialRects = map toRectangle
[ (0, borderSize)
, (borderSize, 0)
, (borderSize, borderSize+boardHeight)
, (borderSize+boardWidth, borderSize) ]
-- How many tiles to copy in each direction. Defines length of edges
-- of the board.
dstHowMany = [ (boardHeight `div` borderSize, 1)
, (1, boardWidth `div` borderSize)
, (1, boardWidth `div` borderSize)
, (boardHeight `div` borderSize, 1) ]
-- Converts from tuple to rectangle. Resulting rectangles have fixed
-- (= borderSize) area.
toRectangle = flip mkRect (borderSize, borderSize)
-- Maps from local tile coordinates to coordinates in the actual
-- texture image.
toTextureCoords (tileX, tileY) =
(borderSize*tileX, srcSquareSize + borderSize*tileY)
-- |Render the buttons at the bottom of the window.
renderButtons :: MonadIO m => GraphicsHandle -> m ()
renderButtons uiHandle = do
let -- Calculate source and destination rects.
srcRectRestartBut = mkRect (0, squareSize+3*borderSize)
(buttonWidth, buttonHeight)
srcRectExitBut = mkRect (0, squareSize+3*borderSize+buttonHeight)
(buttonWidth, buttonHeight)
zipWithM_ (copy' uiHandle) [srcRectRestartBut, srcRectExitBut]
[restartButtonRect, exitButtonRect]
-- |Present the contents of the board to the window.
render :: MonadIO m => Board -> GraphicsHandle -> m ()
render board uiHandle = do
let renderer = ghRenderer uiHandle
-- Set whole backbuffer to the background color (in our case, white)
clear renderer
-- We obtain a list of board coordinates along with their contents.
let twoDim = V.fromList [(i,j) | j <- [0..boardRows-1],
i <- [0..boardCols-1]]
indexedBoard = V.zip twoDim (join board)
-- Map the drawing action to each square in the aforementioned list.
forM_ indexedBoard $ \((col, row), sq) -> do
let -- Calculate source (from texture) and destination rects for the
-- square.
dstRec = Rectangle (P (V2 (col * squareSize + borderSize)
(row * squareSize + borderSize)))
(V2 squareSize squareSize)
srcRec = Rectangle (P (V2 (textureXCoord sq) 0))
(V2 srcSquareSize srcSquareSize)
-- Do the rendering.
copy' uiHandle srcRec dstRec
-- Render the border of the board.
renderBorder uiHandle
-- Render the buttons at the bottom.
renderButtons uiHandle
-- Swap buffers, so what we have rendered is shown to the screen.
present renderer
where textureXCoord (Just X) = 0 * srcSquareSize
textureXCoord (Just O) = 1 * srcSquareSize
textureXCoord Nothing = 2 * srcSquareSize
-- |Handle a left click event.
handleClick :: MouseButtonEventData -> Maybe Input
handleClick mouse
| withinBounds mouse boardRect = Just . ColSelected
. fromIntegral . getPressedCol $ mouse
| withinBounds mouse exitButtonRect = Just Exit
| withinBounds mouse restartButtonRect = Just Restart
| otherwise = Nothing
where getPressedCol mouseEvent =
case mouseButtonEventPos mouseEvent of
P (V2 x _) -> (x - borderSize) `div` squareSize
withinBounds mouseEvent rect =
let point = mouseButtonEventPos mouseEvent
in withinRect point rect
-- |Handle a SDL Event.
handleEvent :: MonadIO m => Event -> Board -> GraphicsHandle -> m (Maybe Input)
handleEvent ev board uiHandle = case eventPayload ev of
WindowResizedEvent _ -> render board uiHandle >> return Nothing
WindowMovedEvent _ -> render board uiHandle >> return Nothing
-- 'Exit application' events.
KeyboardEvent keyboardEvent ->
return $ if isQPressed keyboardEvent then Just Exit
else Nothing
WindowClosedEvent _ -> return $ Just Exit
QuitEvent -> return $ Just Exit
-- Mouse events
MouseButtonEvent mouseEvent ->
return $ do
guard $ isLeftClickPressed mouseEvent
handleClick mouseEvent
_ -> return Nothing
where
isQPressed kbdEvent =
keyboardEventKeyMotion kbdEvent == Pressed &&
keysymKeycode (keyboardEventKeysym kbdEvent) == KeycodeQ
isLeftClickPressed mouseEvent =
mouseButtonEventButton mouseEvent == ButtonLeft &&
mouseButtonEventMotion mouseEvent == Pressed
-- |Gets input from user.
getInput, getPassiveInput :: MonadIO m => Board -> GraphicsHandle -> m Input
getInput board uiHandle = do
event <- waitEvent
mInput <- handleEvent event board uiHandle
case mInput of
Nothing -> getInput board uiHandle
Just input -> return input
-- |Gets input from the user, but discarding the ones regarding the board.
-- That is, only close and restart are allowed.
getPassiveInput board uiHandle = discardSelectedCols $ getInput board uiHandle
where
discardSelectedCols ioInput = do
input <- ioInput
case input of
ColSelected _ -> getPassiveInput board uiHandle
otherInput -> return otherInput
-- |Shows a simple message in a dialog.
showMessageWindow :: MonadIO m => T.Text -> T.Text -> GraphicsHandle -> m ()
showMessageWindow title msg uiHandle =
showSimpleMessageBox (Just $ ghWindow uiHandle) Information title msg
-- |Free the resources created by SDL.
cleanup :: MonadIO m => GraphicsHandle -> m ()
cleanup uiHandle = do
destroyTexture $ ghTexture uiHandle
destroyTexture $ ghTexture2x uiHandle
destroyRenderer $ ghRenderer uiHandle
destroyWindow $ ghWindow uiHandle
quit
| joslugd/connect4-haskell | src/UI/Graphics.hs | mit | 14,831 | 0 | 21 | 4,296 | 3,220 | 1,712 | 1,508 | 236 | 8 |
module Spear.Sys.Store
(
Store
, Index
, emptyStore
, store
, storel
, storeFree
, storeFreel
, element
, setElement
, withElement
)
where
import Data.List as L (find)
import Data.Maybe (isJust, isNothing)
import Data.Vector as V
import Control.Monad.State -- test
import Text.Printf -- test
type Index = Int
data Store a = Store
{ objects :: Vector (Maybe a) -- ^ An array of objects.
, last :: Index -- ^ The greatest index assigned so far.
}
deriving Show
instance Functor Store where
fmap f (Store objects last) = Store (fmap (fmap f) objects) last
-- | Create an empty store.
emptyStore :: Store a
emptyStore = Store V.empty (-1)
-- | Store the given element in the store.
store :: a -> Store a -> (Index, Store a)
store elem s@(Store objects last) =
if last == V.length objects - 1
then case findIndex isNothing objects of
Just i -> assign i elem s
Nothing -> store elem $ Store (objects V.++ V.replicate (max 1 last + 1) Nothing) last
else
assign (last+1) elem s
-- Assign a slot the given element in the store.
assign :: Index -> a -> Store a -> (Index, Store a)
assign i elem (Store objects last) =
let objects' = objects // [(i,Just elem)]
in (i, Store objects' (max last i))
-- | Store the given elements in the store.
storel :: [a] -> Store a -> ([Index], Store a)
storel elems s@(Store objects last) =
let n = Prelude.length elems
(count, slots) = freeSlots objects
in
let -- place count elements in free slots.
(is, s'') = storeInSlots slots (Prelude.take count elems) s
-- append the remaining elements
(is', s') = append (Prelude.drop count elems) s''
in
(is Prelude.++ is', s')
-- Count and return the free slots.
freeSlots :: Vector (Maybe a) -> (Int, Vector Int)
freeSlots v = let is = findIndices isNothing v in (V.length is, is)
-- Store the given elements in the given slots.
-- Pre: valid indices.
storeInSlots :: Vector Int -> [a] -> Store a -> ([Index], Store a)
storeInSlots is elems (Store objects last) =
let objects' = V.update_ objects is (V.fromList $ fmap Just elems)
last' = let i = V.length is - 1
in if i < 0 then last else max last $ is ! i
in
(V.toList is, Store objects' last')
-- Append the given elements to the last slot of the store, making space if necessary.
append :: [a] -> Store a -> ([Index], Store a)
append elems (Store objects last) =
let n = Prelude.length elems
indices = [last+1..last+n]
objects'' = if V.length objects <= last+n
then objects V.++ V.replicate n Nothing
else objects
objects' = objects'' // (Prelude.zipWith (,) indices (fmap Just elems))
in
(indices, Store objects' $ last+n)
-- | Free the given slot.
storeFree :: Index -> Store a -> Store a
storeFree i (Store objects last) =
let objects' = objects // [(i,Nothing)]
in if i == last
then case findLastIndex isJust objects' of
Just j -> Store objects' j
Nothing -> Store objects' 0
else
Store objects' last
findLastIndex :: (a -> Bool) -> Vector a -> Maybe Index
findLastIndex p v = findLastIndex' p v Nothing 0
where
findLastIndex' p v current i =
if i >= V.length v then current
else if p $ v V.! i then let x = Just i in x `seq` findLastIndex' p v x (i+1)
else findLastIndex' p v current (i+1)
-- | Free the given slots.
storeFreel :: [Index] -> Store a -> Store a
storeFreel is (Store objects last) =
let objects' = objects // Prelude.zipWith (,) is (repeat Nothing)
last' = case L.find (==last) is of
Nothing -> last
Just _ -> case findLastIndex isJust objects' of
Just j -> j
Nothing -> (-1)
in
Store objects' last'
-- | Access the element in the given slot.
element :: Index -> Store a -> Maybe a
element index (Store objects _) = objects V.! index
-- | Set the element in the given slot.
setElement :: Index -> a -> Store a -> Store a
setElement index elem s = s { objects = objects s // [(index,Just elem)] }
-- | Apply a function to the element in the given slot.
withElement :: Index -> Store a -> (a -> a) -> Store a
withElement index store f = store { objects = objects' }
where
objects' = objects store // [(index, obj')]
obj' = case element index store of
Nothing -> Nothing
Just x -> Just $ f x
-- test
test :: IO ()
test = evalStateT test' emptyStore
test' :: StateT (Store Int) IO ()
test' = do
x <- store' 1
y <- store' 2
z <- store' 3
w <- store' 4
free y
store' 5
free w
store' 6
a <- store' 7
free a
store' 8
return ()
store' :: Int -> StateT (Store Int) IO Int
store' elem = do
s <- get
let (i, s') = store elem s
put s'
lift $ printf "%d stored at %d; %s\n" elem i (show s')
return i
free :: Index -> StateT (Store Int) IO ()
free i = do
s <- get
let s' = storeFree i s
put s'
lift $ printf "Slot %d freed; %s\n" i (show s')
| jeannekamikaze/Spear | Spear/Sys/Store.hs | mit | 5,466 | 0 | 16 | 1,786 | 1,931 | 981 | 950 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Ledger.Commodity.Pool where
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Ledger.Types
type CommodityPool = IntMap Commodity
dollars :: Commodity
dollars = Commodity { cmdtySymbol = "$"
, cmdtyPrecision = 2
, cmdtySuffixed = False
, cmdtySeparated = False
, cmdtyThousands = True
, cmdtyDecimalComma = False
, cmdtyNoMarket = True
, cmdtyBuiltin = False
, cmdtyKnown = True
, cmdtyPrimary = True }
testPool :: CommodityPool
testPool = IntMap.fromList [(1, dollars)] | ledger/commodities | Data/Commodity/Pool.hs | mit | 780 | 0 | 7 | 321 | 136 | 87 | 49 | 19 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Sqlite (createSqlitePool, runSqlPool,
sqlDatabase, sqlPoolSize)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.Article
import Handler.Articles
import Handler.Langs
import Handler.Tag
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and return a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createSqlitePool
(sqlDatabase $ appDatabaseConf appSettings)
(sqlPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applyng some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadAppSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadAppSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
| builtinnya/lambdar-website | Application.hs | mit | 6,697 | 0 | 16 | 1,726 | 1,029 | 551 | 478 | -1 | -1 |
module Bot.Time (
pretty
) where
import Control.Arrow
import Data.List
import System.Time
-- | Pretty print a TimeDiff.
pretty :: TimeDiff -> String
pretty td = unwords
$ map (uncurry (++) . first show)
$ if null diffs
then [(0, "s")]
else diffs
where
merge (tot,acc) (sec,typ) =
let (sec', tot') = divMod tot sec
in (tot', (sec', typ):acc)
metrics = [(86400,"d"),(3600,"h"),(60,"m"),(1,"s")]
diffs = filter ((/=0) . fst)
$ reverse
$ snd
$ foldl' merge (tdSec td, []) metrics
| numberten/zhenya_bot | Bot/Time.hs | mit | 627 | 2 | 13 | 230 | 245 | 140 | 105 | 19 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Interface.Sequence (
outputSequenceMenue
) where
import Sequences.General
import Interface.General
import Control.Monad
import Control.Exception
import System.IO
outputSequenceMenue :: (Real a, Show a) => Sequence a -> IO ()
outputSequenceMenue seq = do
putStrLn "Folge ausgeben"
putStrLn "<1> Bestimmtes Element ausgeben"
putStrLn "<2> Bestimmte Anzahl von Elementen angeben"
putStrLn "<3> Summe einer bestimmten Anzahl von Elementen ausgeben"
putStrLn "<4> Grenzwert suchen"
putStrLn "<5> Partialsummenfolge bilden"
putStrLn "<6> Beenden"
putStr "Auswahl: "
hFlush stdout
option <- getLine
putChar '\n'
state <- performAction seq option
when (state == Redo) $ outputSequenceMenue seq
performAction :: (Real a, Show a) => Sequence a -> String -> IO MenueState
performAction seq ('1':_) = do
putStr "Elementnummer: "
hFlush stdout
elementStr <- getLine
let
element = read elementStr
output = do
print $ seq !! element
putChar '\n'
return Redo
output `catch` (\(e :: SomeException) -> return Redo)
performAction seq ('2':_) = do
putStr "Anzahl von Elementen: "
hFlush stdout
ammountStr <- getLine
let
ammount = read ammountStr
output = do
print $ take ammount seq
putChar '\n'
return Redo
output `catch` (\(e :: SomeException) -> return Redo)
performAction seq ('3':_) = do
putStr "Anzahl von Elementen: "
hFlush stdout
ammountStr <- getLine
let
ammount = read ammountStr
output = do
print $ sumUntil ammount seq
putChar '\n'
return Redo
output `catch` (\(e :: SomeException) -> return Redo)
performAction seq ('4':_) = do
putStr "Größe der Epsilonumgebung: "
hFlush stdout
epsStr <- getLine
putStr "Minimale Anzahl von Elementen inerhalb der Epsilonumgebung: "
hFlush stdout
nfStr <- getLine
putStr "Maximale Anzahl an durchsuchten Elementen: "
hFlush stdout
nmaxStr <- getLine
let
eps = read epsStr
nf = read nfStr
nmax = read nmaxStr
output = do
print $ limit seq eps nf nmax
putChar '\n'
return Redo
output `catch` (\(e :: SomeException) -> return Redo)
performAction seq ('5':_) = do
putStrLn "Partialsummenfolge:"
outputSequenceMenue $ partialSumSequence seq
putChar '\n'
return Redo
performAction _ _ = return Done
| DevWurm/numeric-sequences-haskell | src/Interface/Sequence.hs | mit | 4,440 | 0 | 13 | 2,595 | 741 | 338 | 403 | 82 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Kantour.MiniJson.Parser where
import Prelude hiding (takeWhile)
import qualified Data.Text as T
import Data.Attoparsec.Text
import Control.Applicative
import Data.Char
import Data.Functor
import Control.Monad
import Kantour.MiniJson.Types
-- all following parsers assume a non-space at beginning
pPair :: Parser (T.Text, JValue)
pPair = do
(JText k) <- pStr
skipSpace >> void (char ':') >> skipSpace
v <- pValue
pure (k,v)
pValue :: Parser JValue
pValue = do
ahead <- peekChar'
case ahead of
'"' -> pStr
'{' -> pObj
'[' -> pArr
't' -> JBool True <$ "true"
'f' -> JBool False <$ "false"
'n' -> JNull <$ "null"
'-' -> pNum
_ | isDigit ahead -> pNum
_ -> fail $ "unexpected leading character: " ++ [ahead]
pStr, pObj, pNum, pArr :: Parser JValue
pObj =
char '{' >>
(JObject <$> pPair `sepBy` (skipSpace >> char ',' >> skipSpace)) <*
char '}'
pArr =
char '[' >>
(JArray <$> pValue `sepBy` (skipSpace >> char ',' >> skipSpace)) <*
char ']'
pStr =
char '"' >>
JText . T.pack <$> many pChar <*
char '"'
where
toChr :: String -> Char
toChr xs = chr $ sum $ zipWith (*) (map digitToInt $ reverse xs) hexs
where
hexs = 1 : map (* 16) hexs
pChar :: Parser Char
pChar = do
ahead <- peekChar'
case ahead of
'"' -> mzero
'\\' ->
char '\\' >>
( ('"' <$ char '"')
<|> ('\\' <$ char '\\')
<|> (char '/' <* pure '/')
<|> (char 'b' <* pure '\b')
<|> (char 'f' <* pure '\f')
<|> (char 'n' <* pure '\n')
<|> (char 'r' <* pure '\r')
<|> (char 't' <* pure '\t')
<|> (char 'u' >> toChr <$> replicateM 4 (satisfy isHexDigit))
)
_ | isControl ahead -> mzero
_ -> anyChar
pNum = do
-- sign
sign <- option False (True <$ char '-')
-- before dot
let isDigit1to9 x = x /= '0' && isDigit x
beforeDot <- ("0" >> pure 0)
<|> (do
-- look ahead just to make sure the first digit
-- is 1~9
ahead <- peekChar'
guard (isDigit1to9 ahead)
decimal
)
-- after dot
afterDot <- option Nothing (char '.' >> Just <$> decimal)
-- exp part
ep <- option Nothing $ do
void $ char 'e' <|> char 'E'
signE <- option False ((False <$ char '+')
<|> (True <$ char '-'))
ds <- decimal
pure (Just (signE, ds))
pure (JNum sign beforeDot afterDot ep)
| Javran/tuppence | src/Kantour/MiniJson/Parser.hs | mit | 2,999 | 0 | 24 | 1,269 | 923 | 462 | 461 | 79 | 9 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE PatternSynonyms #-}
module Data.Tag
( Tag(..), Tagged(..)
, FixTagged, FixTagged'(..)
, pattern FTag
, untagged, wrapTag, wrapTags, addTag, addProv, newTag, newProv, getTag, getTags
, Unique, TagGraph(..), toTagGraph
) where
import qualified Data.Foldable as F (Foldable, foldr)
import qualified Data.Traversable as T (Traversable, traverse)
import Data.Function
import Data.Fix
import Data.List
import Data.Data
import Control.Monad.State
import Control.Applicative ((<$>))
data Tag a = NoTag
| Tag !a (Tag a)
| ProvTag String (Tag a)
| MergeTags [Tag a]
deriving (Show, Eq, Ord, Typeable, Data)
data Tagged tag x = WithTag { maybeTag :: !(Tag tag)
, stripTag :: x }
deriving (Typeable, Data)
instance Eq a => Eq (Tagged tag a) where
x == y = stripTag x == stripTag y
instance Ord a => Ord (Tagged tag a) where
compare = compare `on` stripTag
instance Functor (Tagged tag) where
fmap f (WithTag mt a) = WithTag mt (f a)
instance F.Foldable (Tagged tag) where
foldr f z x = f (stripTag x) z
instance T.Traversable (Tagged tag) where
traverse f (WithTag tag a) = WithTag tag <$> f a
data FixTagged' tag t a = FixTagged' (Tagged tag (t a))
deriving (Typeable, Data)
instance Functor t => Functor (FixTagged' tag t) where
fmap f (FixTagged' x) = FixTagged' (fmap (fmap f) x)
instance F.Foldable t => F.Foldable (FixTagged' tag t) where
foldr f z (FixTagged' x) = F.foldr f z (stripTag x)
instance T.Traversable t => T.Traversable (FixTagged' tag t) where
traverse f (FixTagged' (WithTag tag a)) = FixTagged' . WithTag tag <$> T.traverse f a
instance Show (t a) => Show (FixTagged' tag t a) where
show (FixTagged' x) = "(" ++ show (stripTag x) ++ ")"
type FixTagged tag t = Fix (FixTagged' tag t)
pattern FTag tag a = Fix (FixTagged' (WithTag tag a))
instance Eq (t a) => Eq (FixTagged' tag t a) where
(FixTagged' x) == (FixTagged' y) = stripTag x == stripTag y
instance Ord (t a) => Ord (FixTagged' tag t a) where
compare (FixTagged' x) (FixTagged' y) = (compare `on` stripTag) x y
-- | Lifts an untagged type to the fixed tagged type.
untagged :: t (FixTagged tag t) -> FixTagged tag t
untagged x = FTag NoTag x
-- | Lifts an untagged type to the fixed tagged type by adding a given tag.
wrapTag :: Tag tag -> t (FixTagged tag t) -> FixTagged tag t
wrapTag = FTag
-- | Lifts an untagged type to the fixed tagged type by adding a number of tags.
wrapTags :: [Tag tag] -> t (FixTagged tag t) -> FixTagged tag t
wrapTags tags = FTag (MergeTags tags)
-- | Add a tag of the base tag type to the front of the tag list
addTag :: tag -> FixTagged tag t -> FixTagged tag t
addTag tag' (FTag mt x) = FTag (Tag tag' mt) x
-- | Add a provenance tag to the front of the tag list
addProv :: String -> FixTagged tag t -> FixTagged tag t
addProv prov (FTag mt x) = FTag (ProvTag prov mt) x
-- | Add a new tag of the base tag type to an untagged tree
newTag :: tag -> t (FixTagged tag t) -> FixTagged tag t
newTag tag x = addTag tag $ untagged x
-- | Add provenance to an untagged tree
newProv :: String -> t (FixTagged tag t) -> FixTagged tag t
newProv prov x = addProv prov $ untagged x
getTag :: FixTagged tag t -> Tag tag
getTag (FTag mt _) = mt
-- | Gets all tags from a tag node
getTags :: Tag t -> [t]
getTags NoTag = []
getTags (Tag t mt) = t : getTags mt
getTags (ProvTag _ mt) = getTags mt
getTags (MergeTags tags) = tags >>= getTags
-- Making a graph
newtype Unique = Unique Int
data TagGraph tag t = TagGraph [(Unique, Tag tag, t Unique)]
instance Show Unique where
show (Unique i) = "#" ++ show i
instance (Show tag, Show (t Unique)) => Show (TagGraph tag t) where
show (TagGraph xs) = "TagGraph [\n" ++ intercalate "\n" (map f xs) ++ "\n]"
where f (i, msp, expr) = " " ++ show i
++ " = " ++ show expr ++ ";"
++ " \t[" ++ show_tag msp ++ "]"
show_tag NoTag = ""
show_tag (Tag pos msp) = show pos ++ "; " ++ show_tag msp
show_tag (ProvTag s msp) = show msp ++ "; " ++ show_tag msp
show_tag (MergeTags tags) = "Merged: [" ++ intercalate ", " (map show_tag tags) ++ "]"
toTagGraph :: T.Traversable t => FixTagged tag t -> TagGraph tag t
toTagGraph x = TagGraph $ evalState (f x >> get) []
where f (FTag tag e) = do
e' <- T.traverse f e
i <- Unique . length <$> get
modify (++ [(i, tag, e')])
return i
| swift-nav/plover | src/Data/Tag.hs | mit | 4,674 | 0 | 15 | 1,191 | 1,818 | 930 | 888 | 97 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Server where
import Logic
import Types
import Web.Scotty
import Data.Monoid (mconcat)
startServer :: IO ()
startServer = scotty 8000 server
server :: ScottyM ()
server = do
post "/analyse" $ do
setHeader "Access-Control-Allow-Origin" "*"
j <- jsonData
json (respondAnalysis (j :: AnalysisReq))
post "/review" $ do
setHeader "Access-Control-Allow-Origin" "*"
j <- jsonData
json (respondReview (j :: ReviewReq))
| evansb/sacred | sacred/Server.hs | mit | 513 | 0 | 13 | 123 | 147 | 73 | 74 | 18 | 1 |
{-|
Module : Sivi.GCode.Parser
Description : GCode parser
Copyright : (c) Maxime ANDRE, 2015
License : GPL-2
Maintainer : iemxblog@gmail.com
Stability : experimental
Portability : POSIX
-}
module Sivi.GCode.Parser
(
parseGCode
) where
import Text.Parsec
import Sivi.GCode.Base
import Sivi.Misc.SharedParsers
import Control.Applicative((<*), (*>))
import Control.Monad
-- | Parses a GCode word.
word :: Char -- ^ Name of the word (X or Y or Z, ...)
-> Parsec String () (Maybe Double) -- ^ Result is Nothing if word is not mentioned, or (Just value)
word wn = optionMaybe (do
char wn
double)
<?> "GCode word"
-- | Parses a list of GCode words. Fails if all words are absent.
pParams :: [Char] -- ^ The names of the words
-> Parsec String () [Maybe Double] -- ^ The list of word values
pParams = condition (not . all (==Nothing)) . mapM (lexeme . word)
-- | Parses a G00 (rapid move)
pG00 :: Parsec String () GCodeInstruction
pG00 = do
symbol "G00"
[x, y, z] <- pParams "XYZ"
return $ G00 x y z
-- | Parses a G01 (linear interpolation)
pG01 :: Parsec String () GCodeInstruction
pG01 = do
symbol "G01"
[x, y, z, f] <- pParams "XYZF"
return $ G01 x y z f
-- | Parses a G02 (clockwise circular interpolation)
pG02 :: Parsec String () GCodeInstruction
pG02 = do
symbol "G02"
[x, y, z, i, j, k, f] <- pParams "XYZIJKF"
return $ G02 x y z i j k f
-- | Parses a G03 (counter-clockwise circular interpolation)
pG03 :: Parsec String () GCodeInstruction
pG03 = do
symbol "G03"
[x, y, z, i, j, k, f] <- pParams "XYZIJKF"
return $ G03 x y z i j k f
-- | Parses a comment
pComment :: Parsec String () GCodeInstruction
pComment = do
string "("
c <- manyTill anyChar (try (string ")"))
return $ GComment c
<?> "comment"
-- | Parses a M00 (pause)
pM00 :: Parsec String () GCodeInstruction
pM00 = symbol "M00" >> return M00
-- | Parses a G38.2 (probe)
pG38d2 :: Parsec String () GCodeInstruction
pG38d2 = do
symbol "G38.2"
[x, y, z, f] <- pParams "XYZF"
return $ G38d2 x y z f
-- | Parses a G92
pG92 :: Parsec String () GCodeInstruction
pG92 = do
symbol "G92"
[x, y, z] <- pParams "XYZ"
return $ G92 x y z
-- | Parses a line with only parameters, and no command
pCLine :: Parsec String () GCodeInstruction
pCLine = do
[x, y, z, i, j, k, f] <- pParams "XYZIJKF"
return $ CLine x y z i j k f
-- | Parses a GCode command
pGCode :: Parsec String () GCodeInstruction
pGCode = try pG00 <|> try pG01 <|> try pG02 <|> try pG03 <|> try pComment <|> try pM00 <|> try pG38d2 <|> try pG92 <|> pCLine
-- | Parses a line
pProgramLine :: Parsec String () GCodeInstruction
pProgramLine = pGCode <* many1 endOfLine
-- | Parses a GCode program (list of commands)
pProgram :: Parsec String () GCode
pProgram = liftM GCode (many pProgramLine <* eof)
-- | Parses a GCode program.
parseGCode :: String -- ^ The GCode program
-> Either String GCode -- ^ The resulting GCode data structure (or parse error)
parseGCode text = case parse pProgram "(gcode)" text of
Left pe -> Left (show pe)
Right gcode -> Right gcode
| iemxblog/sivi-haskell | src/Sivi/GCode/Parser.hs | gpl-2.0 | 3,652 | 0 | 13 | 1,238 | 947 | 485 | 462 | 70 | 2 |
module Logic.SeparationLogic.Macro (
module Logic.SeparationLogic.Macro
, module Macro.BussProofs
) where
import Functions.Application.Macro
import qualified Logic.HoareLogic.Macro as HL
import Macro.Arrows
import Macro.BussProofs
import Macro.Math
import Macro.MetaMacro
import Macro.Text (cs)
import Types
-- | Empty heap
emp :: Note
emp = "emp"
-- * Separating conjunction
-- | Separating conjunction
sepconj :: Note -> Note -> Note
sepconj = binop "*"
-- | Infix operator for separating conjunction
(.*) :: Note -> Note -> Note
(.*) = sepconj
-- * Separating implication
-- | Separating implication
sepimp :: Note -> Note -> Note
sepimp = binop $ rightarrow <> negspace <> "*"
where negspace = commS "kern" <> raw "-8pt"
-- | Infix operator for separating implication
(-*) :: Note -> Note -> Note
(-*) = sepimp
-- * Satisfaction
satis :: Note -- ^ Program state
-> Note -- ^ Heap
-> Note -- ^ Assertion
-> Note
satis s h = HL.satis (cs [s, h])
-- * Pointer resulotion
-- | The location of a variable's value
resolve :: Note -- ^ Heap
-> Note -- ^ Variable
-> Note
resolve heap variable = sqbrac variable !: heap
-- | Infix operator for @resolve@
(.&) :: Note -- ^ Variable
-> Note -- ^ Heap
-> Note
(.&) var heap = resolve heap var
-- * Heap allocation
-- | Allocate space for, and store, a sequence of values
cons :: [Note] -> Note
cons = fn "cons" . cs
-- * Pointer disposal
-- | Dispose of a variable
dispose :: Note -> Note
dispose = fn "dispose"
-- * Frame rule
framerule :: Note -> Note -> Note
framerule = unaryInf "[frame]"
| NorfairKing/the-notes | src/Logic/SeparationLogic/Macro.hs | gpl-2.0 | 1,705 | 0 | 8 | 443 | 383 | 227 | 156 | 41 | 1 |
{-# LANGUAGE BangPatterns #-}
module Files (
FileHandles(..),
runTests
) where
import Pruebas
import Results
import System.IO
import Data.Array
import Control.Monad(when, mapM_)
import Database.HDBC
import Database.HDBC.Sqlite3
import System.Posix.Signals
import qualified Data.List as DL
import qualified System.Process as SP
import qualified System.Directory as SD
import qualified Data.ByteString.Char8 as BS
-- | Descriptores de los archivos.
data FileHandles = FH { hlog :: Handle
, hinfo :: Handle
, hresult :: Connection
}
-- | Si la corrida ha sido terminada o no.
data RunState = FINISHED | UNFINISHED
deriving(Eq, Show, Read)
-- | Linea de la corrida.
type Log = (RunState, String, Int)
-- | Estado actual de las pruebas.
type CurrentState = (FileHandles, Int)
-- | Signal Handler del cierre de archivos.
endTester :: IConnection conn
=> Handle -- * Handle del log.
-> Handle -- * Handle del .info.
-> conn -- * Handle del .result.
-> IO ()
endTester lh li lr = do
putStrLn "Finalizando..."
hClose lh
hClose li
disconnect lr
-- | Inicializa el programa de pruebas.
getState :: FilePath -- * Archivo de log.
-> String -- * Nombre de la prueba.
-> FilePath -- * Opciones de corrida.
-> IO CurrentState -- * Estado actual del programa.
getState l n fsource = do
let finfo = (n ++ ".info")
let fresult = (n ++ ".db")
bh <- SD.doesFileExist l
case bh of
True -> do
putStrLn "Leyendo Log..."
logs <- BS.readFile l
let logs' = reverse $ map (\x -> read x :: Log) $ lines $ BS.unpack logs
let last = head $ filter (\(u, s, _) -> finfo == s) logs'
case last of
(FINISHED, _, _) -> do
putStrLn $ "No hay corridas pendientes con el nombre: " ++ n
putStrLn $ "Generando nueva corrida..."
-- Generar un nuevo log, archivo .info y .result y ejecutar.
os <- BS.readFile fsource
let os' = (read (BS.unpack os) :: [Options])
let cmds = BS.pack $ unlines $ concat $ map (genPrograms) os'
BS.writeFile finfo cmds
lh <- openFile l AppendMode
li <- openFile finfo ReadMode
lr <- connectDB fresult
installHandler sigINT (Catch $ endTester lh li lr) Nothing
hPutStrLn lh $ show $ (UNFINISHED, finfo, 0)
return $ ((FH lh li lr), 0)
(UNFINISHED, _, i) -> do
putStrLn $ "Existe una corrida no terminada."
putStrLn $ "Si cree que esto no es así borre el archivo: " ++ l
putStrLn $ "Se continuará desde la línea " ++ (show (i + 1)) ++ " de " ++ finfo ++ "..."
-- Continuar ejecución del log.
lh <- openFile l AppendMode
li <- openFile finfo ReadMode
lr <- connectDB fresult
installHandler sigINT (Catch $ endTester lh li lr) Nothing
return $ ((FH lh li lr), i)
False -> do
putStrLn $ "Generando log y nueva corrida..."
-- Generar un nuevo log, archivo .info y .result y ejecutar.
os <- BS.readFile fsource
let os' = (read (BS.unpack os) :: [Options])
let cmds = BS.pack $ unlines $ concat $ map (genPrograms) os'
BS.writeFile finfo cmds
lh <- openFile l AppendMode
li <- openFile finfo ReadWriteMode
lr <- connectDB fresult
installHandler sigINT (Catch $ endTester lh li lr) Nothing
hPutStrLn lh $ show $ (UNFINISHED, finfo, 0)
return $ ((FH lh li lr), 0)
-- | Genera y corre las pruebas.
runTests l n fsource = do
(hs, i) <- getState l n fsource
!cmds <- BS.hGetContents $ hinfo hs
let cmds' = lines $ BS.unpack cmds
let cmds'' = listArray (0, (length cmds' - 1)) cmds'
let top = 1 + (snd $ bounds cmds'')
run' l n hs cmds'' (i , top)
putStrLn "Liberando recursos..."
hClose $ hlog hs
hClose $ hinfo hs
disconnect $ hresult hs
putStrLn "Finalizado =D"
-- | Ejecuta los programas.
run' :: FilePath
-> String
-> FileHandles
-> Array Int String
-> (Int, Int)
-> IO ()
run' l n hs cmds (i, f) = do
case (i == f) of
True -> do
hPutStrLn (hlog hs) $ show $ (FINISHED, (n ++ ".info"), i)
return ()
False -> do
let (e:o) = words $ cmds ! i
s <- SP.readProcess e o ""
let s' = case parseResult s of
Left c -> "Hubo un error al recolectar los datos."
Right r -> r
insert (hresult hs) (prepareResults (e:o) s')
hPutStrLn (hlog hs) $ show $ (UNFINISHED, (n ++ ".info"), i + 1)
run' l n hs cmds (i + 1, f)
data AlgDB = KmeansDB [SqlValue] | GeneticDB [SqlValue] [SqlValue]
-- | Conecta con la base de datos y crea las tablas si no existen.
connectDB :: FilePath -- ^ Archivo de la base de datos.
-> IO Connection -- ^ Conexión con la base de datos.
connectDB fp = do
dbh <- connectSqlite3 fp
prepDB dbh
return dbh
-- | Prepara la base de datos.
prepDB :: IConnection conn
=> conn
-> IO ()
prepDB dbh = do
tables <- getTables dbh
when (not ("geneticop" `elem` tables)) $
do run dbh gapDB []
return ()
when (not ("genetico" `elem` tables)) $
do run dbh gaDB []
return ()
when (not ("kmeans" `elem` tables)) $
do run dbh kmeansDB []
return ()
commit dbh
putStrLn "Tablas Creadas."
-- | SQL genético.
-- | Comando SQL para crear una tabla de parámetros del genético.
gapDB :: String
gapDB = "CREATE TABLE geneticop (\
\ gap_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\
\ gap_i INTEGER NOT NULL,\
\ gap_ts INTEGER NOT NULL,\
\ gap_cr REAL NOT NULL,\
\ gap_mr REAL NOT NULL)"
-- | Comando SQL para crear una tabla de resultados del genético.
gaDB :: String
gaDB = "CREATE TABLE genetico (\
\ ga_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\
\ ga_ki INTEGER NOT NULL,\
\ ga_kf INTEGER NOT NULL,\
\ ga_db REAL NOT NULL,\
\ ga_eval INTEGER NOT NULL,\
\ ga_turi REAL NOT NULL,\
\ ga_time REAL NOT NULL,\
\ ga_type INTEGER NULL,\
\ FOREIGN KEY(ga_type) REFERENCES geneticop(gap_id))"
kmeansDB :: String
kmeansDB = "CREATE TABLE kmeans (\
\ kmeans_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\
\ kmeans_ki INTEGER NOT NULL,\
\ kmeans_kf INTEGER NOT NULL,\
\ kmeans_db REAL NOT NULL,\
\ kmeans_eval INTEGER NOT NULL,\
\ kmeans_turi REAL NOT NULL,\
\ kmeans_time REAL NOT NULL)"
-- | Comando para encontrar el ID de un conjunto de parámetros.
selectParamGA :: String
selectParamGA = "SELECT gap_id\
\ FROM geneticop WHERE\
\ gap_i = ?\
\ AND gap_cr = ?\
\ AND gap_mr = ?\
\ AND gap_ts = ?"
-- | Comando para insertar un conjunto de parámetros.
insertParamGA :: String
insertParamGA = "INSERT INTO geneticop \
\ (gap_i, gap_cr, gap_mr, gap_ts)\
\ VALUES (?, ?, ?, ?)"
-- i ts cr mr
-- i cr mr t
-- | Comando para insertar los resultados.
insertResultGA :: String
insertResultGA = "INSERT INTO genetico \
\ (ga_ki, ga_kf, ga_db, ga_eval, ga_turi, ga_time, ga_type)\
\ VALUES (?, ?, ?, ?, ?, ?, ?)"
insertResultKmeans :: String
insertResultKmeans = "INSERT INTO kmeans \
\ (kmeans_ki, kmeans_kf, kmeans_db, kmeans_eval, kmeans_turi, kmeans_time)\
\ VALUES (?, ?, ?, ?, ?, ?)"
prepareResults :: [String] -> String -> AlgDB
prepareResults l r = res
where l' = snd $ DL.break (== "-I") l
r' = words r
res = case l' of
[] -> KmeansDB (genResultSQL r')
xs -> GeneticDB (genResultSQL r') (genParamSQL $ extractParams l')
genResultSQL (a:b:c:d:e:f:_) =
[ toSql (read a :: Int)
, toSql (read b :: Int)
, toSql (read c :: Double)
, toSql (read d :: Int)
, toSql (read e :: Double)
, toSql (read f :: Double)
]
genParamSQL (a:b:c:d:_) =
[ toSql (read a :: Int)
, toSql (read b :: Double)
, toSql (read c :: Double)
, toSql (read d :: Int)
]
extractParams xs = filter (\x -> x /= "-I" && x /= "-c" && x /= "-m" && x /= "-t") xs
insert :: IConnection conn
=> conn
-> AlgDB
-> IO ()
insert dbh (KmeansDB xs) = do
run dbh insertResultKmeans xs
commit dbh
insert dbh (GeneticDB xs ys) = do
stmt <- prepare dbh selectParamGA
execute stmt ys
mRes <- fetchRow stmt
case mRes of
Nothing -> do
run dbh insertParamGA ys
execute stmt ys
(Just [res]) <- fetchRow stmt
run dbh insertResultGA (xs ++ [res])
commit dbh
(Just x) -> do
run dbh insertResultGA (xs ++ x)
commit dbh
| fedep3/Metaheuriscticas-Data-Clustering | Tests/src/Files.hs | gpl-2.0 | 9,475 | 0 | 24 | 3,333 | 2,426 | 1,221 | 1,205 | 192 | 3 |
module Roller.Core (main) where
import Roller.Types
import Roller.Parse
import Roller.CLI
import Control.Applicative
import Control.Monad (join, replicateM, replicateM_)
import System.Environment (getArgs)
import Data.Word
rollEm :: CLI (IO ())
rollEm verbose n args = maybe parseFail rollMany (parse input)
where
input = concat args
rollMany = replicateM_ n . rollOnce
rollOnce exp = summary <$> (rolls exp) >>= putStrLn
summary = if verbose then showVerbose else show . sum
showVerbose = (\x -> (show . sum $ x) ++ " " ++ show x)
parseFail = putStrLn $ "Could not parse \"" ++ input ++ "\" as dice expression!"
main :: IO ()
main = join . withOpts $ rollEm
| PiotrJustyna/roller | Roller/Core.hs | gpl-2.0 | 739 | 0 | 13 | 188 | 239 | 130 | 109 | 18 | 2 |
--
-- Copyright (c) 2014 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Migrations ( getMigrationFromVer ) where
import Data.List
import Data.Maybe
import UpgradeEngine
import qualified Migrations.M_1
import qualified Migrations.M_2
import qualified Migrations.M_3
import qualified Migrations.M_4
import qualified Migrations.M_5
import qualified Migrations.M_6
import qualified Migrations.M_7
import qualified Migrations.M_8
import qualified Migrations.M_9
import qualified Migrations.M_10
import qualified Migrations.M_11
import qualified Migrations.M_12
import qualified Migrations.M_13
import qualified Migrations.M_14
import qualified Migrations.M_15
import qualified Migrations.M_16
import qualified Migrations.M_17
import qualified Migrations.M_18
import qualified Migrations.M_19
import qualified Migrations.M_20
import qualified Migrations.M_21
import qualified Migrations.M_22
import qualified Migrations.M_23
import qualified Migrations.M_24
import qualified Migrations.M_25
import qualified Migrations.M_26
migrations :: [Migration]
migrations = [ Migrations.M_1.migration
, Migrations.M_2.migration
, Migrations.M_3.migration
, Migrations.M_4.migration
, Migrations.M_5.migration
, Migrations.M_6.migration
, Migrations.M_7.migration
, Migrations.M_8.migration
, Migrations.M_9.migration
, Migrations.M_10.migration
, Migrations.M_11.migration
, Migrations.M_12.migration
, Migrations.M_13.migration
, Migrations.M_14.migration
, Migrations.M_15.migration
, Migrations.M_16.migration
, Migrations.M_17.migration
, Migrations.M_18.migration
, Migrations.M_19.migration
, Migrations.M_20.migration
, Migrations.M_21.migration
, Migrations.M_22.migration
, Migrations.M_23.migration
, Migrations.M_24.migration
, Migrations.M_25.migration
, Migrations.M_26.migration
]
getMigrationFromVer :: Int -> Migration
getMigrationFromVer version =
let Just m = find pred migrations in m
where
pred m = sourceVersion m == version
| crogers1/manager | upgrade-db/Migrations.hs | gpl-2.0 | 2,984 | 0 | 9 | 667 | 418 | 272 | 146 | 61 | 1 |
module LexML.Version where
version = "1685M"
| lexml/lexml-linker | src/main/haskell/LexML/Version.hs | gpl-2.0 | 46 | 0 | 4 | 7 | 11 | 7 | 4 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright (C) 2006-2014 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.AsciiDoc
Copyright : Copyright (C) 2006-2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to asciidoc.
Note that some information may be lost in conversion, due to
expressive limitations of asciidoc. Footnotes and table cells with
paragraphs (or other block items) are not possible in asciidoc.
If pandoc encounters one of these, it will insert a message indicating
that it has omitted the construct.
AsciiDoc: <http://www.methods.co.nz/asciidoc/>
-}
module Text.Pandoc.Writers.AsciiDoc (writeAsciiDoc) where
import Text.Pandoc.Definition
import Text.Pandoc.Templates (renderTemplate')
import Text.Pandoc.Shared
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Options
import Text.Pandoc.Parsing hiding (blankline, space)
import Data.List ( isPrefixOf, intersperse, intercalate )
import Text.Pandoc.Pretty
import Control.Monad.State
import qualified Data.Map as M
import Data.Aeson (Value(String), fromJSON, toJSON, Result(..))
import qualified Data.Text as T
data WriterState = WriterState { defListMarker :: String
, orderedListLevel :: Int
, bulletListLevel :: Int
}
-- | Convert Pandoc to AsciiDoc.
writeAsciiDoc :: WriterOptions -> Pandoc -> String
writeAsciiDoc opts document =
evalState (pandocToAsciiDoc opts document) WriterState{
defListMarker = "::"
, orderedListLevel = 1
, bulletListLevel = 1
}
-- | Return asciidoc representation of document.
pandocToAsciiDoc :: WriterOptions -> Pandoc -> State WriterState String
pandocToAsciiDoc opts (Pandoc meta blocks) = do
let titleblock = not $ null (docTitle meta) && null (docAuthors meta) &&
null (docDate meta)
let colwidth = if writerWrapText opts
then Just $ writerColumns opts
else Nothing
metadata <- metaToJSON opts
(fmap (render colwidth) . blockListToAsciiDoc opts)
(fmap (render colwidth) . inlineListToAsciiDoc opts)
meta
let addTitleLine (String t) = String $
t <> "\n" <> T.replicate (T.length t) "="
addTitleLine x = x
let metadata' = case fromJSON metadata of
Success m -> toJSON $ M.adjust addTitleLine
("title" :: T.Text) m
_ -> metadata
body <- blockListToAsciiDoc opts blocks
let main = render colwidth body
let context = defField "body" main
$ defField "toc"
(writerTableOfContents opts && writerStandalone opts)
$ defField "titleblock" titleblock
$ metadata'
if writerStandalone opts
then return $ renderTemplate' (writerTemplate opts) context
else return main
-- | Escape special characters for AsciiDoc.
escapeString :: String -> String
escapeString = escapeStringUsing escs
where escs = backslashEscapes "{"
-- | Ordered list start parser for use in Para below.
olMarker :: Parser [Char] ParserState Char
olMarker = do (start, style', delim) <- anyOrderedListMarker
if delim == Period &&
(style' == UpperAlpha || (style' == UpperRoman &&
start `elem` [1, 5, 10, 50, 100, 500, 1000]))
then spaceChar >> spaceChar
else spaceChar
-- | True if string begins with an ordered list marker
beginsWithOrderedListMarker :: String -> Bool
beginsWithOrderedListMarker str =
case runParser olMarker defaultParserState "para start" (take 10 str) of
Left _ -> False
Right _ -> True
-- | Convert Pandoc block element to asciidoc.
blockToAsciiDoc :: WriterOptions -- ^ Options
-> Block -- ^ Block element
-> State WriterState Doc
blockToAsciiDoc _ Null = return empty
blockToAsciiDoc opts (Plain inlines) = do
contents <- inlineListToAsciiDoc opts inlines
return $ contents <> cr
blockToAsciiDoc opts (Para [Image alt (src,'f':'i':'g':':':tit)]) =
blockToAsciiDoc opts (Para [Image alt (src,tit)])
blockToAsciiDoc opts (Para inlines) = do
contents <- inlineListToAsciiDoc opts inlines
-- escape if para starts with ordered list marker
let esc = if beginsWithOrderedListMarker (render Nothing contents)
then text "\\"
else empty
return $ esc <> contents <> blankline
blockToAsciiDoc _ (RawBlock f s)
| f == "asciidoc" = return $ text s
| otherwise = return empty
blockToAsciiDoc _ HorizontalRule =
return $ blankline <> text "'''''" <> blankline
blockToAsciiDoc opts (Header level (ident,_,_) inlines) = do
contents <- inlineListToAsciiDoc opts inlines
let len = offset contents
-- ident seem to be empty most of the time and asciidoc will generate them automatically
-- so lets make them not show up when null
let identifier = if (null ident) then empty else ("[[" <> text ident <> "]]")
let setext = writerSetextHeaders opts
return $
(if setext
then
identifier $$ contents $$
(case level of
1 -> text $ replicate len '-'
2 -> text $ replicate len '~'
3 -> text $ replicate len '^'
4 -> text $ replicate len '+'
_ -> empty) <> blankline
else
identifier $$ text (replicate level '=') <> space <> contents <> blankline)
blockToAsciiDoc _ (CodeBlock (_,classes,_) str) = return $
flush (attrs <> dashes <> space <> attrs <> cr <> text str <>
cr <> dashes) <> blankline
where dashes = text $ replicate (maximum $ map length $ lines str) '-'
attrs = if null classes
then empty
else text $ intercalate "," $ "code" : classes
blockToAsciiDoc opts (BlockQuote blocks) = do
contents <- blockListToAsciiDoc opts blocks
let isBlock (BlockQuote _) = True
isBlock _ = False
-- if there are nested block quotes, put in an open block
let contents' = if any isBlock blocks
then "--" $$ contents $$ "--"
else contents
let cols = offset contents'
let bar = text $ replicate cols '_'
return $ bar $$ chomp contents' $$ bar <> blankline
blockToAsciiDoc opts (Table caption aligns widths headers rows) = do
caption' <- inlineListToAsciiDoc opts caption
let caption'' = if null caption
then empty
else "." <> caption' <> cr
let isSimple = all (== 0) widths
let relativePercentWidths = if isSimple
then widths
else map (/ (sum widths)) widths
let widths'' :: [Integer]
widths'' = map (floor . (* 100)) relativePercentWidths
-- ensure that the widths sum to 100
let widths' = case widths'' of
_ | isSimple -> widths''
(w:ws) | sum (w:ws) < 100
-> (100 - sum ws) : ws
ws -> ws
let totalwidth :: Integer
totalwidth = floor $ sum widths * 100
let colspec al wi = (case al of
AlignLeft -> "<"
AlignCenter -> "^"
AlignRight -> ">"
AlignDefault -> "") ++
if wi == 0 then "" else (show wi ++ "%")
let headerspec = if all null headers
then empty
else text "options=\"header\","
let widthspec = if totalwidth == 0
then empty
else text "width="
<> doubleQuotes (text $ show totalwidth ++ "%")
<> text ","
let tablespec = text "["
<> widthspec
<> text "cols="
<> doubleQuotes (text $ intercalate ","
$ zipWith colspec aligns widths')
<> text ","
<> headerspec <> text "]"
let makeCell [Plain x] = do d <- blockListToAsciiDoc opts [Plain x]
return $ text "|" <> chomp d
makeCell [Para x] = makeCell [Plain x]
makeCell [] = return $ text "|"
makeCell bs = do d <- blockListToAsciiDoc opts bs
return $ text "a|" $$ d
let makeRow cells = hsep `fmap` mapM makeCell cells
rows' <- mapM makeRow rows
head' <- makeRow headers
let head'' = if all null headers then empty else head'
let colwidth = if writerWrapText opts
then writerColumns opts
else 100000
let maxwidth = maximum $ map offset (head':rows')
let body = if maxwidth > colwidth then vsep rows' else vcat rows'
let border = text $ "|" ++ replicate (max 5 (min maxwidth colwidth) - 1) '='
return $
caption'' $$ tablespec $$ border $$ head'' $$ body $$ border $$ blankline
blockToAsciiDoc opts (BulletList items) = do
contents <- mapM (bulletListItemToAsciiDoc opts) items
return $ cat contents <> blankline
blockToAsciiDoc opts (OrderedList (_start, sty, _delim) items) = do
let sty' = case sty of
UpperRoman -> UpperAlpha
LowerRoman -> LowerAlpha
x -> x
let markers = orderedListMarkers (1, sty', Period) -- start num not used
let markers' = map (\m -> if length m < 3
then m ++ replicate (3 - length m) ' '
else m) markers
contents <- mapM (\(item, num) -> orderedListItemToAsciiDoc opts item num) $
zip markers' items
return $ cat contents <> blankline
blockToAsciiDoc opts (DefinitionList items) = do
contents <- mapM (definitionListItemToAsciiDoc opts) items
return $ cat contents <> blankline
blockToAsciiDoc opts (Div _ bs) = blockListToAsciiDoc opts bs
-- | Convert bullet list item (list of blocks) to asciidoc.
bulletListItemToAsciiDoc :: WriterOptions -> [Block] -> State WriterState Doc
bulletListItemToAsciiDoc opts blocks = do
let addBlock :: Doc -> Block -> State WriterState Doc
addBlock d b | isEmpty d = chomp `fmap` blockToAsciiDoc opts b
addBlock d b@(BulletList _) = do x <- blockToAsciiDoc opts b
return $ d <> cr <> chomp x
addBlock d b@(OrderedList _ _) = do x <- blockToAsciiDoc opts b
return $ d <> cr <> chomp x
addBlock d b = do x <- blockToAsciiDoc opts b
return $ d <> cr <> text "+" <> cr <> chomp x
lev <- bulletListLevel `fmap` get
modify $ \s -> s{ bulletListLevel = lev + 1 }
contents <- foldM addBlock empty blocks
modify $ \s -> s{ bulletListLevel = lev }
let marker = text (replicate lev '*')
return $ marker <> space <> contents <> cr
-- | Convert ordered list item (a list of blocks) to asciidoc.
orderedListItemToAsciiDoc :: WriterOptions -- ^ options
-> String -- ^ list item marker
-> [Block] -- ^ list item (list of blocks)
-> State WriterState Doc
orderedListItemToAsciiDoc opts marker blocks = do
let addBlock :: Doc -> Block -> State WriterState Doc
addBlock d b | isEmpty d = chomp `fmap` blockToAsciiDoc opts b
addBlock d b@(BulletList _) = do x <- blockToAsciiDoc opts b
return $ d <> cr <> chomp x
addBlock d b@(OrderedList _ _) = do x <- blockToAsciiDoc opts b
return $ d <> cr <> chomp x
addBlock d b = do x <- blockToAsciiDoc opts b
return $ d <> cr <> text "+" <> cr <> chomp x
lev <- orderedListLevel `fmap` get
modify $ \s -> s{ orderedListLevel = lev + 1 }
contents <- foldM addBlock empty blocks
modify $ \s -> s{ orderedListLevel = lev }
return $ text marker <> space <> contents <> cr
-- | Convert definition list item (label, list of blocks) to asciidoc.
definitionListItemToAsciiDoc :: WriterOptions
-> ([Inline],[[Block]])
-> State WriterState Doc
definitionListItemToAsciiDoc opts (label, defs) = do
labelText <- inlineListToAsciiDoc opts label
marker <- defListMarker `fmap` get
if marker == "::"
then modify (\st -> st{ defListMarker = ";;"})
else modify (\st -> st{ defListMarker = "::"})
let divider = cr <> text "+" <> cr
let defsToAsciiDoc :: [Block] -> State WriterState Doc
defsToAsciiDoc ds = (vcat . intersperse divider . map chomp)
`fmap` mapM (blockToAsciiDoc opts) ds
defs' <- mapM defsToAsciiDoc defs
modify (\st -> st{ defListMarker = marker })
let contents = nest 2 $ vcat $ intersperse divider $ map chomp defs'
return $ labelText <> text marker <> cr <> contents <> cr
-- | Convert list of Pandoc block elements to asciidoc.
blockListToAsciiDoc :: WriterOptions -- ^ Options
-> [Block] -- ^ List of block elements
-> State WriterState Doc
blockListToAsciiDoc opts blocks = cat `fmap` mapM (blockToAsciiDoc opts) blocks
-- | Convert list of Pandoc inline elements to asciidoc.
inlineListToAsciiDoc :: WriterOptions -> [Inline] -> State WriterState Doc
inlineListToAsciiDoc opts lst =
mapM (inlineToAsciiDoc opts) lst >>= return . cat
-- | Convert Pandoc inline element to asciidoc.
inlineToAsciiDoc :: WriterOptions -> Inline -> State WriterState Doc
inlineToAsciiDoc opts (Emph lst) = do
contents <- inlineListToAsciiDoc opts lst
return $ "_" <> contents <> "_"
inlineToAsciiDoc opts (Strong lst) = do
contents <- inlineListToAsciiDoc opts lst
return $ "*" <> contents <> "*"
inlineToAsciiDoc opts (Strikeout lst) = do
contents <- inlineListToAsciiDoc opts lst
return $ "[line-through]*" <> contents <> "*"
inlineToAsciiDoc opts (Superscript lst) = do
contents <- inlineListToAsciiDoc opts lst
return $ "^" <> contents <> "^"
inlineToAsciiDoc opts (Subscript lst) = do
contents <- inlineListToAsciiDoc opts lst
return $ "~" <> contents <> "~"
inlineToAsciiDoc opts (SmallCaps lst) = inlineListToAsciiDoc opts lst
inlineToAsciiDoc opts (Quoted SingleQuote lst) = do
contents <- inlineListToAsciiDoc opts lst
return $ "`" <> contents <> "'"
inlineToAsciiDoc opts (Quoted DoubleQuote lst) = do
contents <- inlineListToAsciiDoc opts lst
return $ "``" <> contents <> "''"
inlineToAsciiDoc _ (Code _ str) = return $
text "`" <> text (escapeStringUsing (backslashEscapes "`") str) <> "`"
inlineToAsciiDoc _ (Str str) = return $ text $ escapeString str
inlineToAsciiDoc _ (Math InlineMath str) =
return $ "latexmath:[$" <> text str <> "$]"
inlineToAsciiDoc _ (Math DisplayMath str) =
return $ "latexmath:[\\[" <> text str <> "\\]]"
inlineToAsciiDoc _ (RawInline f s)
| f == "asciidoc" = return $ text s
| otherwise = return empty
inlineToAsciiDoc _ (LineBreak) = return $ " +" <> cr
inlineToAsciiDoc _ Space = return space
inlineToAsciiDoc opts (Cite _ lst) = inlineListToAsciiDoc opts lst
inlineToAsciiDoc opts (Link txt (src, _tit)) = do
-- relative: link:downloads/foo.zip[download foo.zip]
-- abs: http://google.cod[Google]
-- or my@email.com[email john]
linktext <- inlineListToAsciiDoc opts txt
let isRelative = ':' `notElem` src
let prefix = if isRelative
then text "link:"
else empty
let srcSuffix = if isPrefixOf "mailto:" src then drop 7 src else src
let useAuto = case txt of
[Str s] | escapeURI s == srcSuffix -> True
_ -> False
return $ if useAuto
then text srcSuffix
else prefix <> text src <> "[" <> linktext <> "]"
inlineToAsciiDoc opts (Image alternate (src, tit)) = do
-- image:images/logo.png[Company logo, title="blah"]
let txt = if (null alternate) || (alternate == [Str ""])
then [Str "image"]
else alternate
linktext <- inlineListToAsciiDoc opts txt
let linktitle = if null tit
then empty
else text $ ",title=\"" ++ tit ++ "\""
return $ "image:" <> text src <> "[" <> linktext <> linktitle <> "]"
inlineToAsciiDoc opts (Note [Para inlines]) =
inlineToAsciiDoc opts (Note [Plain inlines])
inlineToAsciiDoc opts (Note [Plain inlines]) = do
contents <- inlineListToAsciiDoc opts inlines
return $ text "footnote:[" <> contents <> "]"
-- asciidoc can't handle blank lines in notes
inlineToAsciiDoc _ (Note _) = return "[multiblock footnote omitted]"
inlineToAsciiDoc opts (Span _ ils) = inlineListToAsciiDoc opts ils
| nickbart1980/pandoc | src/Text/Pandoc/Writers/AsciiDoc.hs | gpl-2.0 | 17,588 | 0 | 19 | 5,167 | 4,851 | 2,401 | 2,450 | 317 | 30 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
main :: IO ()
main = fail "not implemented"
| Tuplanolla/contents | ContentsConfig.hs | gpl-3.0 | 101 | 0 | 6 | 18 | 23 | 13 | 10 | 4 | 1 |
import Test.QuickCheck
import Data.List
myEncode :: Eq a => [a] -> [(Int, a)]
myEncode xs = [(length x, head x) | x <- group xs]
testMyEncode :: [Char] -> Bool
testMyEncode x =
(myEncode x == (map (\xs -> (length xs, head xs)) . group $ x)) &&
((length . myEncode $ x) == (length . group $ x))
main = quickCheck testMyEncode
| CmdrMoozy/haskell99 | 010.hs | gpl-3.0 | 330 | 4 | 15 | 68 | 182 | 97 | 85 | 9 | 1 |
{-# LANGUAGE TemplateHaskell, FlexibleInstances, FlexibleContexts, ViewPatterns, RecordWildCards, NamedFieldPuns, ScopedTypeVariables, TypeSynonymInstances, NoMonomorphismRestriction, TupleSections, StandaloneDeriving, GeneralizedNewtypeDeriving #-}
{-# OPTIONS -Wall -fno-warn-orphans #-}
module Triangulation.Random
(
randT,randomClosed,
randomManifoldT,
arbitraryTriangulation,arbitraryClosedTriangulation,shrinkTriangulation,
genTet, arbitraryManifoldTriangulation,
ClosedTriangulation(..),
ManifoldTriangulation(..),
randomTriangulation,
)
where
import ClosedOrCensus6
import ClosedNorCensus8
import Collections(elemOfSetAt,deleteAt)
import Control.Applicative
import Control.Monad.State
import Data.Set(Set)
import System.Random
import THUtil
import Test.QuickCheck
import Test.QuickCheck.Gen
import Triangulation
import Util
import qualified Data.Set as S
import Data.Maybe
import QuickCheckUtil
import Triangulation.Class
import Triangulation.VertexLink
import Data.SumType
import Triangulation.PreTriangulation
import TriangulationCxtObject
arbitraryTriangulation :: Gen Triangulation
arbitraryTriangulation = arbitraryTriangulationG (\nTets -> choose (0,2*nTets))
arbitraryClosedTriangulation :: Gen Triangulation
arbitraryClosedTriangulation = arbitraryTriangulationG (\nTets -> return (2*nTets))
newtype ClosedTriangulation = ClosedTriangulation Triangulation
deriving (ToTriangulation,Show)
instance Arbitrary ClosedTriangulation where
arbitrary = ClosedTriangulation <$> arbitraryClosedTriangulation
arbitraryTriangulationG :: (Int -> Gen Int) -> Gen Triangulation
arbitraryTriangulationG nGluingsGen =
sized (\n ->
let
small = (<= max 1 (n `div` 5)) . tNumberOfTetrahedra
in
frequency $
(2,
do
nTets <- choose (1::Int,max 1 (n`div`5))
nGluings <- nGluingsGen nTets
randT nTets nGluings)
: mapMaybe
(\(w,census) ->
case filter small . map snd $ census of
[] -> Nothing
ts -> Just (w, elements ts))
[(2, closedOrCensus6)
,(1, closedNorCensus8)]
)
shrinkTriangulation :: Triangulation -> [Triangulation]
shrinkTriangulation t =
-- concatMap removeTet (tTetrahedra_ t) ++
mkTriangulation (tNumberOfTetrahedra t) <$> shrink (tGluingsIrredundant t)
randT :: Int -> Int -> Gen Triangulation
randT nTets nGluings =
$(assrt [| nTets > 0 |] 'nTets) $
$(assrt [| nGluings >= 0 |] 'nGluings) $
$(assrt [| nGluings <= 2*nTets |] ['nGluings,'nTets]) $
generateUntilJust (sumTypeToMaybe <$> go)
where
go = do
let
tets = (tindex . fromIntegral) <$> [0..nTets-1]
loop :: [Gluing] -> Int -> StateT (Set ITriangle) Gen [Gluing]
loop acc 0 = return acc
loop acc j = do
t1 <- takeTriangle
t2 <- takeTriangle
g <- lift arbitrary
loop ((t1,packOrderedFace t2 g):acc) (j-1)
takeTriangle = do
trianglesLeft <- get
ix <- lift (choose (0, S.size trianglesLeft-1))
let res = elemOfSetAt ix trianglesLeft
put (deleteAt ix trianglesLeft)
return res
pairs <- evalStateT (loop [] nGluings) (S.fromList ((./) <$> tets <*> allTriangles))
return $ mkTriangulationSafe (fi nTets) pairs
randomClosed :: Int -> IO Triangulation
randomClosed n = randomTriangulation n (2*n)
randomTriangulation :: Int -> Int -> IO Triangulation
randomTriangulation nTets nGluings = do
g <- newStdGen
return $ unGen (randT nTets nGluings) g 0 --(error "randomTriangulation: undefined")
instance Arbitrary Triangulation where
arbitrary = arbitraryTriangulation
shrink = shrinkTriangulation
genI :: Arbitrary a => Triangulation -> Gen (I a)
genI t = liftM2 I (genTet t) arbitrary
genTet :: Triangulation -> Gen TIndex
genTet = elements . tTetrahedra_
newtype ManifoldTriangulation t = ManifoldTriangulation t
deriving (Show,ToTriangulation)
-- | Uses ' arbitraryManifoldTriangulation '
instance (Arbitrary t, ToTriangulation t) => Arbitrary (ManifoldTriangulation t) where
arbitrary = ManifoldTriangulation <$> arbitraryManifoldTriangulation
-- | Generates only manifold triangulations.
arbitraryManifoldTriangulation :: (Arbitrary t, ToTriangulation t) => Gen t
arbitraryManifoldTriangulation = arbitrary `suchThat` isManifoldTriangulation
randomManifoldT :: Int -> Int -> Int -> Gen Triangulation
randomManifoldT n minGl maxGl =
(randT n =<< choose (minGl,maxGl)) `suchThat` isManifoldTriangulation
genT
:: (Show a,
PreTriangulation t,
TriangulationDSnakeItem a,
ToTriangulation t) =>
(t -> [a]) -> t -> Maybe (Gen (T a))
genT getTs tr
| numberOfTetrahedra_ tr == 0 = Nothing
| otherwise = Just (pMap tr <$> elements (getTs tr))
arbitraryTriangulationContextObject
:: (Show a, TriangulationDSnakeItem a) =>
(Triangulation -> [a]) -> Gen (T a)
arbitraryTriangulationContextObject getTs =
generateUntilJust $ do
(tr :: Triangulation) <- arbitrary
promote (genT getTs tr)
instance Arbitrary TVertex where
arbitrary = arbitraryTriangulationContextObject tIVertices
instance Arbitrary TEdge where
arbitrary = arbitraryTriangulationContextObject tIEdges
instance Arbitrary TTriangle where
arbitrary = arbitraryTriangulationContextObject tITriangles
| DanielSchuessler/hstri | Triangulation/Random.hs | gpl-3.0 | 5,908 | 0 | 21 | 1,588 | 1,478 | 782 | 696 | 128 | 2 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Test.AWS.Gen.IAM
-- Copyright : (c) 2013-2015 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 Test.AWS.Gen.IAM where
import Data.Proxy
import Test.AWS.Fixture
import Test.AWS.Prelude
import Test.Tasty
import Network.AWS.IAM
import Test.AWS.IAM.Internal
-- Auto-generated: the actual test selection needs to be manually placed into
-- the top-level so that real test data can be incrementally added.
--
-- This commented snippet is what the entire set should look like:
-- fixtures :: TestTree
-- fixtures =
-- [ testGroup "request"
-- [ testListPolicies $
-- listPolicies
--
-- , testCreatePolicy $
-- createPolicy
--
-- , testListInstanceProfilesForRole $
-- listInstanceProfilesForRole
--
-- , testAttachGroupPolicy $
-- attachGroupPolicy
--
-- , testCreateAccessKey $
-- createAccessKey
--
-- , testListSSHPublicKeys $
-- listSSHPublicKeys
--
-- , testListOpenIdConnectProviders $
-- listOpenIdConnectProviders
--
-- , testCreateVirtualMFADevice $
-- createVirtualMFADevice
--
-- , testDeleteAccountPasswordPolicy $
-- deleteAccountPasswordPolicy
--
-- , testUpdateAccountPasswordPolicy $
-- updateAccountPasswordPolicy
--
-- , testAttachRolePolicy $
-- attachRolePolicy
--
-- , testUpdateSSHPublicKey $
-- updateSSHPublicKey
--
-- , testDeleteSSHPublicKey $
-- deleteSSHPublicKey
--
-- , testGetUserPolicy $
-- getUserPolicy
--
-- , testListAttachedRolePolicies $
-- listAttachedRolePolicies
--
-- , testGetRole $
-- getRole
--
-- , testDeactivateMFADevice $
-- deactivateMFADevice
--
-- , testCreateOpenIdConnectProvider $
-- createOpenIdConnectProvider
--
-- , testDeleteVirtualMFADevice $
-- deleteVirtualMFADevice
--
-- , testListRoles $
-- listRoles
--
-- , testListUserPolicies $
-- listUserPolicies
--
-- , testUploadSSHPublicKey $
-- uploadSSHPublicKey
--
-- , testDeleteRole $
-- deleteRole
--
-- , testListUsers $
-- listUsers
--
-- , testUpdateOpenIdConnectProviderThumbprint $
-- updateOpenIdConnectProviderThumbprint
--
-- , testPutUserPolicy $
-- putUserPolicy
--
-- , testGetSSHPublicKey $
-- getSSHPublicKey
--
-- , testDetachGroupPolicy $
-- detachGroupPolicy
--
-- , testGetOpenIdConnectProvider $
-- getOpenIdConnectProvider
--
-- , testDeleteUserPolicy $
-- deleteUserPolicy
--
-- , testCreateRole $
-- createRole
--
-- , testGetCredentialReport $
-- getCredentialReport
--
-- , testGetAccountSummary $
-- getAccountSummary
--
-- , testListGroupPolicies $
-- listGroupPolicies
--
-- , testDeletePolicyVersion $
-- deletePolicyVersion
--
-- , testDeleteInstanceProfile $
-- deleteInstanceProfile
--
-- , testDetachRolePolicy $
-- detachRolePolicy
--
-- , testRemoveRoleFromInstanceProfile $
-- removeRoleFromInstanceProfile
--
-- , testCreatePolicyVersion $
-- createPolicyVersion
--
-- , testCreateInstanceProfile $
-- createInstanceProfile
--
-- , testCreateSAMLProvider $
-- createSAMLProvider
--
-- , testGetAccountAuthorizationDetails $
-- getAccountAuthorizationDetails
--
-- , testDeleteAccountAlias $
-- deleteAccountAlias
--
-- , testDetachUserPolicy $
-- detachUserPolicy
--
-- , testRemoveUserFromGroup $
-- removeUserFromGroup
--
-- , testDeleteGroupPolicy $
-- deleteGroupPolicy
--
-- , testPutGroupPolicy $
-- putGroupPolicy
--
-- , testGetLoginProfile $
-- getLoginProfile
--
-- , testGetGroupPolicy $
-- getGroupPolicy
--
-- , testChangePassword $
-- changePassword
--
-- , testListServerCertificates $
-- listServerCertificates
--
-- , testDeletePolicy $
-- deletePolicy
--
-- , testUpdateAssumeRolePolicy $
-- updateAssumeRolePolicy
--
-- , testGetInstanceProfile $
-- getInstanceProfile
--
-- , testCreateLoginProfile $
-- createLoginProfile
--
-- , testGetSAMLProvider $
-- getSAMLProvider
--
-- , testAddRoleToInstanceProfile $
-- addRoleToInstanceProfile
--
-- , testListGroupsForUser $
-- listGroupsForUser
--
-- , testListEntitiesForPolicy $
-- listEntitiesForPolicy
--
-- , testAddUserToGroup $
-- addUserToGroup
--
-- , testGetPolicyVersion $
-- getPolicyVersion
--
-- , testDeleteOpenIdConnectProvider $
-- deleteOpenIdConnectProvider
--
-- , testGetUser $
-- getUser
--
-- , testListSigningCertificates $
-- listSigningCertificates
--
-- , testDeleteSigningCertificate $
-- deleteSigningCertificate
--
-- , testUpdateSigningCertificate $
-- updateSigningCertificate
--
-- , testListAttachedUserPolicies $
-- listAttachedUserPolicies
--
-- , testRemoveClientIdFromOpenIdConnectProvider $
-- removeClientIdFromOpenIdConnectProvider
--
-- , testAttachUserPolicy $
-- attachUserPolicy
--
-- , testListVirtualMFADevices $
-- listVirtualMFADevices
--
-- , testResyncMFADevice $
-- resyncMFADevice
--
-- , testDeleteAccessKey $
-- deleteAccessKey
--
-- , testUpdateAccessKey $
-- updateAccessKey
--
-- , testListAccessKeys $
-- listAccessKeys
--
-- , testGetRolePolicy $
-- getRolePolicy
--
-- , testCreateUser $
-- createUser
--
-- , testPutRolePolicy $
-- putRolePolicy
--
-- , testUploadSigningCertificate $
-- uploadSigningCertificate
--
-- , testDeleteRolePolicy $
-- deleteRolePolicy
--
-- , testGetAccountPasswordPolicy $
-- getAccountPasswordPolicy
--
-- , testGetAccessKeyLastUsed $
-- getAccessKeyLastUsed
--
-- , testUpdateUser $
-- updateUser
--
-- , testDeleteUser $
-- deleteUser
--
-- , testAddClientIdToOpenIdConnectProvider $
-- addClientIdToOpenIdConnectProvider
--
-- , testListRolePolicies $
-- listRolePolicies
--
-- , testCreateAccountAlias $
-- createAccountAlias
--
-- , testListInstanceProfiles $
-- listInstanceProfiles
--
-- , testEnableMFADevice $
-- enableMFADevice
--
-- , testListAccountAliases $
-- listAccountAliases
--
-- , testDeleteSAMLProvider $
-- deleteSAMLProvider
--
-- , testUpdateSAMLProvider $
-- updateSAMLProvider
--
-- , testCreateGroup $
-- createGroup
--
-- , testListMFADevices $
-- listMFADevices
--
-- , testUploadServerCertificate $
-- uploadServerCertificate
--
-- , testSetDefaultPolicyVersion $
-- setDefaultPolicyVersion
--
-- , testListPolicyVersions $
-- listPolicyVersions
--
-- , testListSAMLProviders $
-- listSAMLProviders
--
-- , testGetServerCertificate $
-- getServerCertificate
--
-- , testDeleteGroup $
-- deleteGroup
--
-- , testUpdateGroup $
-- updateGroup
--
-- , testListGroups $
-- listGroups
--
-- , testGenerateCredentialReport $
-- generateCredentialReport
--
-- , testGetPolicy $
-- getPolicy
--
-- , testUpdateLoginProfile $
-- updateLoginProfile
--
-- , testDeleteLoginProfile $
-- deleteLoginProfile
--
-- , testGetGroup $
-- getGroup
--
-- , testDeleteServerCertificate $
-- deleteServerCertificate
--
-- , testUpdateServerCertificate $
-- updateServerCertificate
--
-- , testListAttachedGroupPolicies $
-- listAttachedGroupPolicies
--
-- ]
-- , testGroup "response"
-- [ testListPoliciesResponse $
-- listPoliciesResponse
--
-- , testCreatePolicyResponse $
-- createPolicyResponse
--
-- , testListInstanceProfilesForRoleResponse $
-- listInstanceProfilesForRoleResponse
--
-- , testAttachGroupPolicyResponse $
-- attachGroupPolicyResponse
--
-- , testCreateAccessKeyResponse $
-- createAccessKeyResponse
--
-- , testListSSHPublicKeysResponse $
-- listSSHPublicKeysResponse
--
-- , testListOpenIdConnectProvidersResponse $
-- listOpenIdConnectProvidersResponse
--
-- , testCreateVirtualMFADeviceResponse $
-- createVirtualMFADeviceResponse
--
-- , testDeleteAccountPasswordPolicyResponse $
-- deleteAccountPasswordPolicyResponse
--
-- , testUpdateAccountPasswordPolicyResponse $
-- updateAccountPasswordPolicyResponse
--
-- , testAttachRolePolicyResponse $
-- attachRolePolicyResponse
--
-- , testUpdateSSHPublicKeyResponse $
-- updateSSHPublicKeyResponse
--
-- , testDeleteSSHPublicKeyResponse $
-- deleteSSHPublicKeyResponse
--
-- , testGetUserPolicyResponse $
-- getUserPolicyResponse
--
-- , testListAttachedRolePoliciesResponse $
-- listAttachedRolePoliciesResponse
--
-- , testGetRoleResponse $
-- getRoleResponse
--
-- , testDeactivateMFADeviceResponse $
-- deactivateMFADeviceResponse
--
-- , testCreateOpenIdConnectProviderResponse $
-- createOpenIdConnectProviderResponse
--
-- , testDeleteVirtualMFADeviceResponse $
-- deleteVirtualMFADeviceResponse
--
-- , testListRolesResponse $
-- listRolesResponse
--
-- , testListUserPoliciesResponse $
-- listUserPoliciesResponse
--
-- , testUploadSSHPublicKeyResponse $
-- uploadSSHPublicKeyResponse
--
-- , testDeleteRoleResponse $
-- deleteRoleResponse
--
-- , testListUsersResponse $
-- listUsersResponse
--
-- , testUpdateOpenIdConnectProviderThumbprintResponse $
-- updateOpenIdConnectProviderThumbprintResponse
--
-- , testPutUserPolicyResponse $
-- putUserPolicyResponse
--
-- , testGetSSHPublicKeyResponse $
-- getSSHPublicKeyResponse
--
-- , testDetachGroupPolicyResponse $
-- detachGroupPolicyResponse
--
-- , testGetOpenIdConnectProviderResponse $
-- getOpenIdConnectProviderResponse
--
-- , testDeleteUserPolicyResponse $
-- deleteUserPolicyResponse
--
-- , testCreateRoleResponse $
-- createRoleResponse
--
-- , testGetCredentialReportResponse $
-- getCredentialReportResponse
--
-- , testGetAccountSummaryResponse $
-- getAccountSummaryResponse
--
-- , testListGroupPoliciesResponse $
-- listGroupPoliciesResponse
--
-- , testDeletePolicyVersionResponse $
-- deletePolicyVersionResponse
--
-- , testDeleteInstanceProfileResponse $
-- deleteInstanceProfileResponse
--
-- , testDetachRolePolicyResponse $
-- detachRolePolicyResponse
--
-- , testRemoveRoleFromInstanceProfileResponse $
-- removeRoleFromInstanceProfileResponse
--
-- , testCreatePolicyVersionResponse $
-- createPolicyVersionResponse
--
-- , testCreateInstanceProfileResponse $
-- createInstanceProfileResponse
--
-- , testCreateSAMLProviderResponse $
-- createSAMLProviderResponse
--
-- , testGetAccountAuthorizationDetailsResponse $
-- getAccountAuthorizationDetailsResponse
--
-- , testDeleteAccountAliasResponse $
-- deleteAccountAliasResponse
--
-- , testDetachUserPolicyResponse $
-- detachUserPolicyResponse
--
-- , testRemoveUserFromGroupResponse $
-- removeUserFromGroupResponse
--
-- , testDeleteGroupPolicyResponse $
-- deleteGroupPolicyResponse
--
-- , testPutGroupPolicyResponse $
-- putGroupPolicyResponse
--
-- , testGetLoginProfileResponse $
-- getLoginProfileResponse
--
-- , testGetGroupPolicyResponse $
-- getGroupPolicyResponse
--
-- , testChangePasswordResponse $
-- changePasswordResponse
--
-- , testListServerCertificatesResponse $
-- listServerCertificatesResponse
--
-- , testDeletePolicyResponse $
-- deletePolicyResponse
--
-- , testUpdateAssumeRolePolicyResponse $
-- updateAssumeRolePolicyResponse
--
-- , testGetInstanceProfileResponse $
-- getInstanceProfileResponse
--
-- , testCreateLoginProfileResponse $
-- createLoginProfileResponse
--
-- , testGetSAMLProviderResponse $
-- getSAMLProviderResponse
--
-- , testAddRoleToInstanceProfileResponse $
-- addRoleToInstanceProfileResponse
--
-- , testListGroupsForUserResponse $
-- listGroupsForUserResponse
--
-- , testListEntitiesForPolicyResponse $
-- listEntitiesForPolicyResponse
--
-- , testAddUserToGroupResponse $
-- addUserToGroupResponse
--
-- , testGetPolicyVersionResponse $
-- getPolicyVersionResponse
--
-- , testDeleteOpenIdConnectProviderResponse $
-- deleteOpenIdConnectProviderResponse
--
-- , testGetUserResponse $
-- getUserResponse
--
-- , testListSigningCertificatesResponse $
-- listSigningCertificatesResponse
--
-- , testDeleteSigningCertificateResponse $
-- deleteSigningCertificateResponse
--
-- , testUpdateSigningCertificateResponse $
-- updateSigningCertificateResponse
--
-- , testListAttachedUserPoliciesResponse $
-- listAttachedUserPoliciesResponse
--
-- , testRemoveClientIdFromOpenIdConnectProviderResponse $
-- removeClientIdFromOpenIdConnectProviderResponse
--
-- , testAttachUserPolicyResponse $
-- attachUserPolicyResponse
--
-- , testListVirtualMFADevicesResponse $
-- listVirtualMFADevicesResponse
--
-- , testResyncMFADeviceResponse $
-- resyncMFADeviceResponse
--
-- , testDeleteAccessKeyResponse $
-- deleteAccessKeyResponse
--
-- , testUpdateAccessKeyResponse $
-- updateAccessKeyResponse
--
-- , testListAccessKeysResponse $
-- listAccessKeysResponse
--
-- , testGetRolePolicyResponse $
-- getRolePolicyResponse
--
-- , testCreateUserResponse $
-- createUserResponse
--
-- , testPutRolePolicyResponse $
-- putRolePolicyResponse
--
-- , testUploadSigningCertificateResponse $
-- uploadSigningCertificateResponse
--
-- , testDeleteRolePolicyResponse $
-- deleteRolePolicyResponse
--
-- , testGetAccountPasswordPolicyResponse $
-- getAccountPasswordPolicyResponse
--
-- , testGetAccessKeyLastUsedResponse $
-- getAccessKeyLastUsedResponse
--
-- , testUpdateUserResponse $
-- updateUserResponse
--
-- , testDeleteUserResponse $
-- deleteUserResponse
--
-- , testAddClientIdToOpenIdConnectProviderResponse $
-- addClientIdToOpenIdConnectProviderResponse
--
-- , testListRolePoliciesResponse $
-- listRolePoliciesResponse
--
-- , testCreateAccountAliasResponse $
-- createAccountAliasResponse
--
-- , testListInstanceProfilesResponse $
-- listInstanceProfilesResponse
--
-- , testEnableMFADeviceResponse $
-- enableMFADeviceResponse
--
-- , testListAccountAliasesResponse $
-- listAccountAliasesResponse
--
-- , testDeleteSAMLProviderResponse $
-- deleteSAMLProviderResponse
--
-- , testUpdateSAMLProviderResponse $
-- updateSAMLProviderResponse
--
-- , testCreateGroupResponse $
-- createGroupResponse
--
-- , testListMFADevicesResponse $
-- listMFADevicesResponse
--
-- , testUploadServerCertificateResponse $
-- uploadServerCertificateResponse
--
-- , testSetDefaultPolicyVersionResponse $
-- setDefaultPolicyVersionResponse
--
-- , testListPolicyVersionsResponse $
-- listPolicyVersionsResponse
--
-- , testListSAMLProvidersResponse $
-- listSAMLProvidersResponse
--
-- , testGetServerCertificateResponse $
-- getServerCertificateResponse
--
-- , testDeleteGroupResponse $
-- deleteGroupResponse
--
-- , testUpdateGroupResponse $
-- updateGroupResponse
--
-- , testListGroupsResponse $
-- listGroupsResponse
--
-- , testGenerateCredentialReportResponse $
-- generateCredentialReportResponse
--
-- , testGetPolicyResponse $
-- getPolicyResponse
--
-- , testUpdateLoginProfileResponse $
-- updateLoginProfileResponse
--
-- , testDeleteLoginProfileResponse $
-- deleteLoginProfileResponse
--
-- , testGetGroupResponse $
-- getGroupResponse
--
-- , testDeleteServerCertificateResponse $
-- deleteServerCertificateResponse
--
-- , testUpdateServerCertificateResponse $
-- updateServerCertificateResponse
--
-- , testListAttachedGroupPoliciesResponse $
-- listAttachedGroupPoliciesResponse
--
-- ]
-- ]
-- Requests
testListPolicies :: ListPolicies -> TestTree
testListPolicies = req
"ListPolicies"
"fixture/ListPolicies.yaml"
testCreatePolicy :: CreatePolicy -> TestTree
testCreatePolicy = req
"CreatePolicy"
"fixture/CreatePolicy.yaml"
testListInstanceProfilesForRole :: ListInstanceProfilesForRole -> TestTree
testListInstanceProfilesForRole = req
"ListInstanceProfilesForRole"
"fixture/ListInstanceProfilesForRole.yaml"
testAttachGroupPolicy :: AttachGroupPolicy -> TestTree
testAttachGroupPolicy = req
"AttachGroupPolicy"
"fixture/AttachGroupPolicy.yaml"
testCreateAccessKey :: CreateAccessKey -> TestTree
testCreateAccessKey = req
"CreateAccessKey"
"fixture/CreateAccessKey.yaml"
testListSSHPublicKeys :: ListSSHPublicKeys -> TestTree
testListSSHPublicKeys = req
"ListSSHPublicKeys"
"fixture/ListSSHPublicKeys.yaml"
testListOpenIdConnectProviders :: ListOpenIdConnectProviders -> TestTree
testListOpenIdConnectProviders = req
"ListOpenIdConnectProviders"
"fixture/ListOpenIdConnectProviders.yaml"
testCreateVirtualMFADevice :: CreateVirtualMFADevice -> TestTree
testCreateVirtualMFADevice = req
"CreateVirtualMFADevice"
"fixture/CreateVirtualMFADevice.yaml"
testDeleteAccountPasswordPolicy :: DeleteAccountPasswordPolicy -> TestTree
testDeleteAccountPasswordPolicy = req
"DeleteAccountPasswordPolicy"
"fixture/DeleteAccountPasswordPolicy.yaml"
testUpdateAccountPasswordPolicy :: UpdateAccountPasswordPolicy -> TestTree
testUpdateAccountPasswordPolicy = req
"UpdateAccountPasswordPolicy"
"fixture/UpdateAccountPasswordPolicy.yaml"
testAttachRolePolicy :: AttachRolePolicy -> TestTree
testAttachRolePolicy = req
"AttachRolePolicy"
"fixture/AttachRolePolicy.yaml"
testUpdateSSHPublicKey :: UpdateSSHPublicKey -> TestTree
testUpdateSSHPublicKey = req
"UpdateSSHPublicKey"
"fixture/UpdateSSHPublicKey.yaml"
testDeleteSSHPublicKey :: DeleteSSHPublicKey -> TestTree
testDeleteSSHPublicKey = req
"DeleteSSHPublicKey"
"fixture/DeleteSSHPublicKey.yaml"
testGetUserPolicy :: GetUserPolicy -> TestTree
testGetUserPolicy = req
"GetUserPolicy"
"fixture/GetUserPolicy.yaml"
testListAttachedRolePolicies :: ListAttachedRolePolicies -> TestTree
testListAttachedRolePolicies = req
"ListAttachedRolePolicies"
"fixture/ListAttachedRolePolicies.yaml"
testGetRole :: GetRole -> TestTree
testGetRole = req
"GetRole"
"fixture/GetRole.yaml"
testDeactivateMFADevice :: DeactivateMFADevice -> TestTree
testDeactivateMFADevice = req
"DeactivateMFADevice"
"fixture/DeactivateMFADevice.yaml"
testCreateOpenIdConnectProvider :: CreateOpenIdConnectProvider -> TestTree
testCreateOpenIdConnectProvider = req
"CreateOpenIdConnectProvider"
"fixture/CreateOpenIdConnectProvider.yaml"
testDeleteVirtualMFADevice :: DeleteVirtualMFADevice -> TestTree
testDeleteVirtualMFADevice = req
"DeleteVirtualMFADevice"
"fixture/DeleteVirtualMFADevice.yaml"
testListRoles :: ListRoles -> TestTree
testListRoles = req
"ListRoles"
"fixture/ListRoles.yaml"
testListUserPolicies :: ListUserPolicies -> TestTree
testListUserPolicies = req
"ListUserPolicies"
"fixture/ListUserPolicies.yaml"
testUploadSSHPublicKey :: UploadSSHPublicKey -> TestTree
testUploadSSHPublicKey = req
"UploadSSHPublicKey"
"fixture/UploadSSHPublicKey.yaml"
testDeleteRole :: DeleteRole -> TestTree
testDeleteRole = req
"DeleteRole"
"fixture/DeleteRole.yaml"
testListUsers :: ListUsers -> TestTree
testListUsers = req
"ListUsers"
"fixture/ListUsers.yaml"
testUpdateOpenIdConnectProviderThumbprint :: UpdateOpenIdConnectProviderThumbprint -> TestTree
testUpdateOpenIdConnectProviderThumbprint = req
"UpdateOpenIdConnectProviderThumbprint"
"fixture/UpdateOpenIdConnectProviderThumbprint.yaml"
testPutUserPolicy :: PutUserPolicy -> TestTree
testPutUserPolicy = req
"PutUserPolicy"
"fixture/PutUserPolicy.yaml"
testGetSSHPublicKey :: GetSSHPublicKey -> TestTree
testGetSSHPublicKey = req
"GetSSHPublicKey"
"fixture/GetSSHPublicKey.yaml"
testDetachGroupPolicy :: DetachGroupPolicy -> TestTree
testDetachGroupPolicy = req
"DetachGroupPolicy"
"fixture/DetachGroupPolicy.yaml"
testGetOpenIdConnectProvider :: GetOpenIdConnectProvider -> TestTree
testGetOpenIdConnectProvider = req
"GetOpenIdConnectProvider"
"fixture/GetOpenIdConnectProvider.yaml"
testDeleteUserPolicy :: DeleteUserPolicy -> TestTree
testDeleteUserPolicy = req
"DeleteUserPolicy"
"fixture/DeleteUserPolicy.yaml"
testCreateRole :: CreateRole -> TestTree
testCreateRole = req
"CreateRole"
"fixture/CreateRole.yaml"
testGetCredentialReport :: GetCredentialReport -> TestTree
testGetCredentialReport = req
"GetCredentialReport"
"fixture/GetCredentialReport.yaml"
testGetAccountSummary :: GetAccountSummary -> TestTree
testGetAccountSummary = req
"GetAccountSummary"
"fixture/GetAccountSummary.yaml"
testListGroupPolicies :: ListGroupPolicies -> TestTree
testListGroupPolicies = req
"ListGroupPolicies"
"fixture/ListGroupPolicies.yaml"
testDeletePolicyVersion :: DeletePolicyVersion -> TestTree
testDeletePolicyVersion = req
"DeletePolicyVersion"
"fixture/DeletePolicyVersion.yaml"
testDeleteInstanceProfile :: DeleteInstanceProfile -> TestTree
testDeleteInstanceProfile = req
"DeleteInstanceProfile"
"fixture/DeleteInstanceProfile.yaml"
testDetachRolePolicy :: DetachRolePolicy -> TestTree
testDetachRolePolicy = req
"DetachRolePolicy"
"fixture/DetachRolePolicy.yaml"
testRemoveRoleFromInstanceProfile :: RemoveRoleFromInstanceProfile -> TestTree
testRemoveRoleFromInstanceProfile = req
"RemoveRoleFromInstanceProfile"
"fixture/RemoveRoleFromInstanceProfile.yaml"
testCreatePolicyVersion :: CreatePolicyVersion -> TestTree
testCreatePolicyVersion = req
"CreatePolicyVersion"
"fixture/CreatePolicyVersion.yaml"
testCreateInstanceProfile :: CreateInstanceProfile -> TestTree
testCreateInstanceProfile = req
"CreateInstanceProfile"
"fixture/CreateInstanceProfile.yaml"
testCreateSAMLProvider :: CreateSAMLProvider -> TestTree
testCreateSAMLProvider = req
"CreateSAMLProvider"
"fixture/CreateSAMLProvider.yaml"
testGetAccountAuthorizationDetails :: GetAccountAuthorizationDetails -> TestTree
testGetAccountAuthorizationDetails = req
"GetAccountAuthorizationDetails"
"fixture/GetAccountAuthorizationDetails.yaml"
testDeleteAccountAlias :: DeleteAccountAlias -> TestTree
testDeleteAccountAlias = req
"DeleteAccountAlias"
"fixture/DeleteAccountAlias.yaml"
testDetachUserPolicy :: DetachUserPolicy -> TestTree
testDetachUserPolicy = req
"DetachUserPolicy"
"fixture/DetachUserPolicy.yaml"
testRemoveUserFromGroup :: RemoveUserFromGroup -> TestTree
testRemoveUserFromGroup = req
"RemoveUserFromGroup"
"fixture/RemoveUserFromGroup.yaml"
testDeleteGroupPolicy :: DeleteGroupPolicy -> TestTree
testDeleteGroupPolicy = req
"DeleteGroupPolicy"
"fixture/DeleteGroupPolicy.yaml"
testPutGroupPolicy :: PutGroupPolicy -> TestTree
testPutGroupPolicy = req
"PutGroupPolicy"
"fixture/PutGroupPolicy.yaml"
testGetLoginProfile :: GetLoginProfile -> TestTree
testGetLoginProfile = req
"GetLoginProfile"
"fixture/GetLoginProfile.yaml"
testGetGroupPolicy :: GetGroupPolicy -> TestTree
testGetGroupPolicy = req
"GetGroupPolicy"
"fixture/GetGroupPolicy.yaml"
testChangePassword :: ChangePassword -> TestTree
testChangePassword = req
"ChangePassword"
"fixture/ChangePassword.yaml"
testListServerCertificates :: ListServerCertificates -> TestTree
testListServerCertificates = req
"ListServerCertificates"
"fixture/ListServerCertificates.yaml"
testDeletePolicy :: DeletePolicy -> TestTree
testDeletePolicy = req
"DeletePolicy"
"fixture/DeletePolicy.yaml"
testUpdateAssumeRolePolicy :: UpdateAssumeRolePolicy -> TestTree
testUpdateAssumeRolePolicy = req
"UpdateAssumeRolePolicy"
"fixture/UpdateAssumeRolePolicy.yaml"
testGetInstanceProfile :: GetInstanceProfile -> TestTree
testGetInstanceProfile = req
"GetInstanceProfile"
"fixture/GetInstanceProfile.yaml"
testCreateLoginProfile :: CreateLoginProfile -> TestTree
testCreateLoginProfile = req
"CreateLoginProfile"
"fixture/CreateLoginProfile.yaml"
testGetSAMLProvider :: GetSAMLProvider -> TestTree
testGetSAMLProvider = req
"GetSAMLProvider"
"fixture/GetSAMLProvider.yaml"
testAddRoleToInstanceProfile :: AddRoleToInstanceProfile -> TestTree
testAddRoleToInstanceProfile = req
"AddRoleToInstanceProfile"
"fixture/AddRoleToInstanceProfile.yaml"
testListGroupsForUser :: ListGroupsForUser -> TestTree
testListGroupsForUser = req
"ListGroupsForUser"
"fixture/ListGroupsForUser.yaml"
testListEntitiesForPolicy :: ListEntitiesForPolicy -> TestTree
testListEntitiesForPolicy = req
"ListEntitiesForPolicy"
"fixture/ListEntitiesForPolicy.yaml"
testAddUserToGroup :: AddUserToGroup -> TestTree
testAddUserToGroup = req
"AddUserToGroup"
"fixture/AddUserToGroup.yaml"
testGetPolicyVersion :: GetPolicyVersion -> TestTree
testGetPolicyVersion = req
"GetPolicyVersion"
"fixture/GetPolicyVersion.yaml"
testDeleteOpenIdConnectProvider :: DeleteOpenIdConnectProvider -> TestTree
testDeleteOpenIdConnectProvider = req
"DeleteOpenIdConnectProvider"
"fixture/DeleteOpenIdConnectProvider.yaml"
testGetUser :: GetUser -> TestTree
testGetUser = req
"GetUser"
"fixture/GetUser.yaml"
testListSigningCertificates :: ListSigningCertificates -> TestTree
testListSigningCertificates = req
"ListSigningCertificates"
"fixture/ListSigningCertificates.yaml"
testDeleteSigningCertificate :: DeleteSigningCertificate -> TestTree
testDeleteSigningCertificate = req
"DeleteSigningCertificate"
"fixture/DeleteSigningCertificate.yaml"
testUpdateSigningCertificate :: UpdateSigningCertificate -> TestTree
testUpdateSigningCertificate = req
"UpdateSigningCertificate"
"fixture/UpdateSigningCertificate.yaml"
testListAttachedUserPolicies :: ListAttachedUserPolicies -> TestTree
testListAttachedUserPolicies = req
"ListAttachedUserPolicies"
"fixture/ListAttachedUserPolicies.yaml"
testRemoveClientIdFromOpenIdConnectProvider :: RemoveClientIdFromOpenIdConnectProvider -> TestTree
testRemoveClientIdFromOpenIdConnectProvider = req
"RemoveClientIdFromOpenIdConnectProvider"
"fixture/RemoveClientIdFromOpenIdConnectProvider.yaml"
testAttachUserPolicy :: AttachUserPolicy -> TestTree
testAttachUserPolicy = req
"AttachUserPolicy"
"fixture/AttachUserPolicy.yaml"
testListVirtualMFADevices :: ListVirtualMFADevices -> TestTree
testListVirtualMFADevices = req
"ListVirtualMFADevices"
"fixture/ListVirtualMFADevices.yaml"
testResyncMFADevice :: ResyncMFADevice -> TestTree
testResyncMFADevice = req
"ResyncMFADevice"
"fixture/ResyncMFADevice.yaml"
testDeleteAccessKey :: DeleteAccessKey -> TestTree
testDeleteAccessKey = req
"DeleteAccessKey"
"fixture/DeleteAccessKey.yaml"
testUpdateAccessKey :: UpdateAccessKey -> TestTree
testUpdateAccessKey = req
"UpdateAccessKey"
"fixture/UpdateAccessKey.yaml"
testListAccessKeys :: ListAccessKeys -> TestTree
testListAccessKeys = req
"ListAccessKeys"
"fixture/ListAccessKeys.yaml"
testGetRolePolicy :: GetRolePolicy -> TestTree
testGetRolePolicy = req
"GetRolePolicy"
"fixture/GetRolePolicy.yaml"
testCreateUser :: CreateUser -> TestTree
testCreateUser = req
"CreateUser"
"fixture/CreateUser.yaml"
testPutRolePolicy :: PutRolePolicy -> TestTree
testPutRolePolicy = req
"PutRolePolicy"
"fixture/PutRolePolicy.yaml"
testUploadSigningCertificate :: UploadSigningCertificate -> TestTree
testUploadSigningCertificate = req
"UploadSigningCertificate"
"fixture/UploadSigningCertificate.yaml"
testDeleteRolePolicy :: DeleteRolePolicy -> TestTree
testDeleteRolePolicy = req
"DeleteRolePolicy"
"fixture/DeleteRolePolicy.yaml"
testGetAccountPasswordPolicy :: GetAccountPasswordPolicy -> TestTree
testGetAccountPasswordPolicy = req
"GetAccountPasswordPolicy"
"fixture/GetAccountPasswordPolicy.yaml"
testGetAccessKeyLastUsed :: GetAccessKeyLastUsed -> TestTree
testGetAccessKeyLastUsed = req
"GetAccessKeyLastUsed"
"fixture/GetAccessKeyLastUsed.yaml"
testUpdateUser :: UpdateUser -> TestTree
testUpdateUser = req
"UpdateUser"
"fixture/UpdateUser.yaml"
testDeleteUser :: DeleteUser -> TestTree
testDeleteUser = req
"DeleteUser"
"fixture/DeleteUser.yaml"
testAddClientIdToOpenIdConnectProvider :: AddClientIdToOpenIdConnectProvider -> TestTree
testAddClientIdToOpenIdConnectProvider = req
"AddClientIdToOpenIdConnectProvider"
"fixture/AddClientIdToOpenIdConnectProvider.yaml"
testListRolePolicies :: ListRolePolicies -> TestTree
testListRolePolicies = req
"ListRolePolicies"
"fixture/ListRolePolicies.yaml"
testCreateAccountAlias :: CreateAccountAlias -> TestTree
testCreateAccountAlias = req
"CreateAccountAlias"
"fixture/CreateAccountAlias.yaml"
testListInstanceProfiles :: ListInstanceProfiles -> TestTree
testListInstanceProfiles = req
"ListInstanceProfiles"
"fixture/ListInstanceProfiles.yaml"
testEnableMFADevice :: EnableMFADevice -> TestTree
testEnableMFADevice = req
"EnableMFADevice"
"fixture/EnableMFADevice.yaml"
testListAccountAliases :: ListAccountAliases -> TestTree
testListAccountAliases = req
"ListAccountAliases"
"fixture/ListAccountAliases.yaml"
testDeleteSAMLProvider :: DeleteSAMLProvider -> TestTree
testDeleteSAMLProvider = req
"DeleteSAMLProvider"
"fixture/DeleteSAMLProvider.yaml"
testUpdateSAMLProvider :: UpdateSAMLProvider -> TestTree
testUpdateSAMLProvider = req
"UpdateSAMLProvider"
"fixture/UpdateSAMLProvider.yaml"
testCreateGroup :: CreateGroup -> TestTree
testCreateGroup = req
"CreateGroup"
"fixture/CreateGroup.yaml"
testListMFADevices :: ListMFADevices -> TestTree
testListMFADevices = req
"ListMFADevices"
"fixture/ListMFADevices.yaml"
testUploadServerCertificate :: UploadServerCertificate -> TestTree
testUploadServerCertificate = req
"UploadServerCertificate"
"fixture/UploadServerCertificate.yaml"
testSetDefaultPolicyVersion :: SetDefaultPolicyVersion -> TestTree
testSetDefaultPolicyVersion = req
"SetDefaultPolicyVersion"
"fixture/SetDefaultPolicyVersion.yaml"
testListPolicyVersions :: ListPolicyVersions -> TestTree
testListPolicyVersions = req
"ListPolicyVersions"
"fixture/ListPolicyVersions.yaml"
testListSAMLProviders :: ListSAMLProviders -> TestTree
testListSAMLProviders = req
"ListSAMLProviders"
"fixture/ListSAMLProviders.yaml"
testGetServerCertificate :: GetServerCertificate -> TestTree
testGetServerCertificate = req
"GetServerCertificate"
"fixture/GetServerCertificate.yaml"
testDeleteGroup :: DeleteGroup -> TestTree
testDeleteGroup = req
"DeleteGroup"
"fixture/DeleteGroup.yaml"
testUpdateGroup :: UpdateGroup -> TestTree
testUpdateGroup = req
"UpdateGroup"
"fixture/UpdateGroup.yaml"
testListGroups :: ListGroups -> TestTree
testListGroups = req
"ListGroups"
"fixture/ListGroups.yaml"
testGenerateCredentialReport :: GenerateCredentialReport -> TestTree
testGenerateCredentialReport = req
"GenerateCredentialReport"
"fixture/GenerateCredentialReport.yaml"
testGetPolicy :: GetPolicy -> TestTree
testGetPolicy = req
"GetPolicy"
"fixture/GetPolicy.yaml"
testUpdateLoginProfile :: UpdateLoginProfile -> TestTree
testUpdateLoginProfile = req
"UpdateLoginProfile"
"fixture/UpdateLoginProfile.yaml"
testDeleteLoginProfile :: DeleteLoginProfile -> TestTree
testDeleteLoginProfile = req
"DeleteLoginProfile"
"fixture/DeleteLoginProfile.yaml"
testGetGroup :: GetGroup -> TestTree
testGetGroup = req
"GetGroup"
"fixture/GetGroup.yaml"
testDeleteServerCertificate :: DeleteServerCertificate -> TestTree
testDeleteServerCertificate = req
"DeleteServerCertificate"
"fixture/DeleteServerCertificate.yaml"
testUpdateServerCertificate :: UpdateServerCertificate -> TestTree
testUpdateServerCertificate = req
"UpdateServerCertificate"
"fixture/UpdateServerCertificate.yaml"
testListAttachedGroupPolicies :: ListAttachedGroupPolicies -> TestTree
testListAttachedGroupPolicies = req
"ListAttachedGroupPolicies"
"fixture/ListAttachedGroupPolicies.yaml"
-- Responses
testListPoliciesResponse :: ListPoliciesResponse -> TestTree
testListPoliciesResponse = res
"ListPoliciesResponse"
"fixture/ListPoliciesResponse.proto"
iAM
(Proxy :: Proxy ListPolicies)
testCreatePolicyResponse :: CreatePolicyResponse -> TestTree
testCreatePolicyResponse = res
"CreatePolicyResponse"
"fixture/CreatePolicyResponse.proto"
iAM
(Proxy :: Proxy CreatePolicy)
testListInstanceProfilesForRoleResponse :: ListInstanceProfilesForRoleResponse -> TestTree
testListInstanceProfilesForRoleResponse = res
"ListInstanceProfilesForRoleResponse"
"fixture/ListInstanceProfilesForRoleResponse.proto"
iAM
(Proxy :: Proxy ListInstanceProfilesForRole)
testAttachGroupPolicyResponse :: AttachGroupPolicyResponse -> TestTree
testAttachGroupPolicyResponse = res
"AttachGroupPolicyResponse"
"fixture/AttachGroupPolicyResponse.proto"
iAM
(Proxy :: Proxy AttachGroupPolicy)
testCreateAccessKeyResponse :: CreateAccessKeyResponse -> TestTree
testCreateAccessKeyResponse = res
"CreateAccessKeyResponse"
"fixture/CreateAccessKeyResponse.proto"
iAM
(Proxy :: Proxy CreateAccessKey)
testListSSHPublicKeysResponse :: ListSSHPublicKeysResponse -> TestTree
testListSSHPublicKeysResponse = res
"ListSSHPublicKeysResponse"
"fixture/ListSSHPublicKeysResponse.proto"
iAM
(Proxy :: Proxy ListSSHPublicKeys)
testListOpenIdConnectProvidersResponse :: ListOpenIdConnectProvidersResponse -> TestTree
testListOpenIdConnectProvidersResponse = res
"ListOpenIdConnectProvidersResponse"
"fixture/ListOpenIdConnectProvidersResponse.proto"
iAM
(Proxy :: Proxy ListOpenIdConnectProviders)
testCreateVirtualMFADeviceResponse :: CreateVirtualMFADeviceResponse -> TestTree
testCreateVirtualMFADeviceResponse = res
"CreateVirtualMFADeviceResponse"
"fixture/CreateVirtualMFADeviceResponse.proto"
iAM
(Proxy :: Proxy CreateVirtualMFADevice)
testDeleteAccountPasswordPolicyResponse :: DeleteAccountPasswordPolicyResponse -> TestTree
testDeleteAccountPasswordPolicyResponse = res
"DeleteAccountPasswordPolicyResponse"
"fixture/DeleteAccountPasswordPolicyResponse.proto"
iAM
(Proxy :: Proxy DeleteAccountPasswordPolicy)
testUpdateAccountPasswordPolicyResponse :: UpdateAccountPasswordPolicyResponse -> TestTree
testUpdateAccountPasswordPolicyResponse = res
"UpdateAccountPasswordPolicyResponse"
"fixture/UpdateAccountPasswordPolicyResponse.proto"
iAM
(Proxy :: Proxy UpdateAccountPasswordPolicy)
testAttachRolePolicyResponse :: AttachRolePolicyResponse -> TestTree
testAttachRolePolicyResponse = res
"AttachRolePolicyResponse"
"fixture/AttachRolePolicyResponse.proto"
iAM
(Proxy :: Proxy AttachRolePolicy)
testUpdateSSHPublicKeyResponse :: UpdateSSHPublicKeyResponse -> TestTree
testUpdateSSHPublicKeyResponse = res
"UpdateSSHPublicKeyResponse"
"fixture/UpdateSSHPublicKeyResponse.proto"
iAM
(Proxy :: Proxy UpdateSSHPublicKey)
testDeleteSSHPublicKeyResponse :: DeleteSSHPublicKeyResponse -> TestTree
testDeleteSSHPublicKeyResponse = res
"DeleteSSHPublicKeyResponse"
"fixture/DeleteSSHPublicKeyResponse.proto"
iAM
(Proxy :: Proxy DeleteSSHPublicKey)
testGetUserPolicyResponse :: GetUserPolicyResponse -> TestTree
testGetUserPolicyResponse = res
"GetUserPolicyResponse"
"fixture/GetUserPolicyResponse.proto"
iAM
(Proxy :: Proxy GetUserPolicy)
testListAttachedRolePoliciesResponse :: ListAttachedRolePoliciesResponse -> TestTree
testListAttachedRolePoliciesResponse = res
"ListAttachedRolePoliciesResponse"
"fixture/ListAttachedRolePoliciesResponse.proto"
iAM
(Proxy :: Proxy ListAttachedRolePolicies)
testGetRoleResponse :: GetRoleResponse -> TestTree
testGetRoleResponse = res
"GetRoleResponse"
"fixture/GetRoleResponse.proto"
iAM
(Proxy :: Proxy GetRole)
testDeactivateMFADeviceResponse :: DeactivateMFADeviceResponse -> TestTree
testDeactivateMFADeviceResponse = res
"DeactivateMFADeviceResponse"
"fixture/DeactivateMFADeviceResponse.proto"
iAM
(Proxy :: Proxy DeactivateMFADevice)
testCreateOpenIdConnectProviderResponse :: CreateOpenIdConnectProviderResponse -> TestTree
testCreateOpenIdConnectProviderResponse = res
"CreateOpenIdConnectProviderResponse"
"fixture/CreateOpenIdConnectProviderResponse.proto"
iAM
(Proxy :: Proxy CreateOpenIdConnectProvider)
testDeleteVirtualMFADeviceResponse :: DeleteVirtualMFADeviceResponse -> TestTree
testDeleteVirtualMFADeviceResponse = res
"DeleteVirtualMFADeviceResponse"
"fixture/DeleteVirtualMFADeviceResponse.proto"
iAM
(Proxy :: Proxy DeleteVirtualMFADevice)
testListRolesResponse :: ListRolesResponse -> TestTree
testListRolesResponse = res
"ListRolesResponse"
"fixture/ListRolesResponse.proto"
iAM
(Proxy :: Proxy ListRoles)
testListUserPoliciesResponse :: ListUserPoliciesResponse -> TestTree
testListUserPoliciesResponse = res
"ListUserPoliciesResponse"
"fixture/ListUserPoliciesResponse.proto"
iAM
(Proxy :: Proxy ListUserPolicies)
testUploadSSHPublicKeyResponse :: UploadSSHPublicKeyResponse -> TestTree
testUploadSSHPublicKeyResponse = res
"UploadSSHPublicKeyResponse"
"fixture/UploadSSHPublicKeyResponse.proto"
iAM
(Proxy :: Proxy UploadSSHPublicKey)
testDeleteRoleResponse :: DeleteRoleResponse -> TestTree
testDeleteRoleResponse = res
"DeleteRoleResponse"
"fixture/DeleteRoleResponse.proto"
iAM
(Proxy :: Proxy DeleteRole)
testListUsersResponse :: ListUsersResponse -> TestTree
testListUsersResponse = res
"ListUsersResponse"
"fixture/ListUsersResponse.proto"
iAM
(Proxy :: Proxy ListUsers)
testUpdateOpenIdConnectProviderThumbprintResponse :: UpdateOpenIdConnectProviderThumbprintResponse -> TestTree
testUpdateOpenIdConnectProviderThumbprintResponse = res
"UpdateOpenIdConnectProviderThumbprintResponse"
"fixture/UpdateOpenIdConnectProviderThumbprintResponse.proto"
iAM
(Proxy :: Proxy UpdateOpenIdConnectProviderThumbprint)
testPutUserPolicyResponse :: PutUserPolicyResponse -> TestTree
testPutUserPolicyResponse = res
"PutUserPolicyResponse"
"fixture/PutUserPolicyResponse.proto"
iAM
(Proxy :: Proxy PutUserPolicy)
testGetSSHPublicKeyResponse :: GetSSHPublicKeyResponse -> TestTree
testGetSSHPublicKeyResponse = res
"GetSSHPublicKeyResponse"
"fixture/GetSSHPublicKeyResponse.proto"
iAM
(Proxy :: Proxy GetSSHPublicKey)
testDetachGroupPolicyResponse :: DetachGroupPolicyResponse -> TestTree
testDetachGroupPolicyResponse = res
"DetachGroupPolicyResponse"
"fixture/DetachGroupPolicyResponse.proto"
iAM
(Proxy :: Proxy DetachGroupPolicy)
testGetOpenIdConnectProviderResponse :: GetOpenIdConnectProviderResponse -> TestTree
testGetOpenIdConnectProviderResponse = res
"GetOpenIdConnectProviderResponse"
"fixture/GetOpenIdConnectProviderResponse.proto"
iAM
(Proxy :: Proxy GetOpenIdConnectProvider)
testDeleteUserPolicyResponse :: DeleteUserPolicyResponse -> TestTree
testDeleteUserPolicyResponse = res
"DeleteUserPolicyResponse"
"fixture/DeleteUserPolicyResponse.proto"
iAM
(Proxy :: Proxy DeleteUserPolicy)
testCreateRoleResponse :: CreateRoleResponse -> TestTree
testCreateRoleResponse = res
"CreateRoleResponse"
"fixture/CreateRoleResponse.proto"
iAM
(Proxy :: Proxy CreateRole)
testGetCredentialReportResponse :: GetCredentialReportResponse -> TestTree
testGetCredentialReportResponse = res
"GetCredentialReportResponse"
"fixture/GetCredentialReportResponse.proto"
iAM
(Proxy :: Proxy GetCredentialReport)
testGetAccountSummaryResponse :: GetAccountSummaryResponse -> TestTree
testGetAccountSummaryResponse = res
"GetAccountSummaryResponse"
"fixture/GetAccountSummaryResponse.proto"
iAM
(Proxy :: Proxy GetAccountSummary)
testListGroupPoliciesResponse :: ListGroupPoliciesResponse -> TestTree
testListGroupPoliciesResponse = res
"ListGroupPoliciesResponse"
"fixture/ListGroupPoliciesResponse.proto"
iAM
(Proxy :: Proxy ListGroupPolicies)
testDeletePolicyVersionResponse :: DeletePolicyVersionResponse -> TestTree
testDeletePolicyVersionResponse = res
"DeletePolicyVersionResponse"
"fixture/DeletePolicyVersionResponse.proto"
iAM
(Proxy :: Proxy DeletePolicyVersion)
testDeleteInstanceProfileResponse :: DeleteInstanceProfileResponse -> TestTree
testDeleteInstanceProfileResponse = res
"DeleteInstanceProfileResponse"
"fixture/DeleteInstanceProfileResponse.proto"
iAM
(Proxy :: Proxy DeleteInstanceProfile)
testDetachRolePolicyResponse :: DetachRolePolicyResponse -> TestTree
testDetachRolePolicyResponse = res
"DetachRolePolicyResponse"
"fixture/DetachRolePolicyResponse.proto"
iAM
(Proxy :: Proxy DetachRolePolicy)
testRemoveRoleFromInstanceProfileResponse :: RemoveRoleFromInstanceProfileResponse -> TestTree
testRemoveRoleFromInstanceProfileResponse = res
"RemoveRoleFromInstanceProfileResponse"
"fixture/RemoveRoleFromInstanceProfileResponse.proto"
iAM
(Proxy :: Proxy RemoveRoleFromInstanceProfile)
testCreatePolicyVersionResponse :: CreatePolicyVersionResponse -> TestTree
testCreatePolicyVersionResponse = res
"CreatePolicyVersionResponse"
"fixture/CreatePolicyVersionResponse.proto"
iAM
(Proxy :: Proxy CreatePolicyVersion)
testCreateInstanceProfileResponse :: CreateInstanceProfileResponse -> TestTree
testCreateInstanceProfileResponse = res
"CreateInstanceProfileResponse"
"fixture/CreateInstanceProfileResponse.proto"
iAM
(Proxy :: Proxy CreateInstanceProfile)
testCreateSAMLProviderResponse :: CreateSAMLProviderResponse -> TestTree
testCreateSAMLProviderResponse = res
"CreateSAMLProviderResponse"
"fixture/CreateSAMLProviderResponse.proto"
iAM
(Proxy :: Proxy CreateSAMLProvider)
testGetAccountAuthorizationDetailsResponse :: GetAccountAuthorizationDetailsResponse -> TestTree
testGetAccountAuthorizationDetailsResponse = res
"GetAccountAuthorizationDetailsResponse"
"fixture/GetAccountAuthorizationDetailsResponse.proto"
iAM
(Proxy :: Proxy GetAccountAuthorizationDetails)
testDeleteAccountAliasResponse :: DeleteAccountAliasResponse -> TestTree
testDeleteAccountAliasResponse = res
"DeleteAccountAliasResponse"
"fixture/DeleteAccountAliasResponse.proto"
iAM
(Proxy :: Proxy DeleteAccountAlias)
testDetachUserPolicyResponse :: DetachUserPolicyResponse -> TestTree
testDetachUserPolicyResponse = res
"DetachUserPolicyResponse"
"fixture/DetachUserPolicyResponse.proto"
iAM
(Proxy :: Proxy DetachUserPolicy)
testRemoveUserFromGroupResponse :: RemoveUserFromGroupResponse -> TestTree
testRemoveUserFromGroupResponse = res
"RemoveUserFromGroupResponse"
"fixture/RemoveUserFromGroupResponse.proto"
iAM
(Proxy :: Proxy RemoveUserFromGroup)
testDeleteGroupPolicyResponse :: DeleteGroupPolicyResponse -> TestTree
testDeleteGroupPolicyResponse = res
"DeleteGroupPolicyResponse"
"fixture/DeleteGroupPolicyResponse.proto"
iAM
(Proxy :: Proxy DeleteGroupPolicy)
testPutGroupPolicyResponse :: PutGroupPolicyResponse -> TestTree
testPutGroupPolicyResponse = res
"PutGroupPolicyResponse"
"fixture/PutGroupPolicyResponse.proto"
iAM
(Proxy :: Proxy PutGroupPolicy)
testGetLoginProfileResponse :: GetLoginProfileResponse -> TestTree
testGetLoginProfileResponse = res
"GetLoginProfileResponse"
"fixture/GetLoginProfileResponse.proto"
iAM
(Proxy :: Proxy GetLoginProfile)
testGetGroupPolicyResponse :: GetGroupPolicyResponse -> TestTree
testGetGroupPolicyResponse = res
"GetGroupPolicyResponse"
"fixture/GetGroupPolicyResponse.proto"
iAM
(Proxy :: Proxy GetGroupPolicy)
testChangePasswordResponse :: ChangePasswordResponse -> TestTree
testChangePasswordResponse = res
"ChangePasswordResponse"
"fixture/ChangePasswordResponse.proto"
iAM
(Proxy :: Proxy ChangePassword)
testListServerCertificatesResponse :: ListServerCertificatesResponse -> TestTree
testListServerCertificatesResponse = res
"ListServerCertificatesResponse"
"fixture/ListServerCertificatesResponse.proto"
iAM
(Proxy :: Proxy ListServerCertificates)
testDeletePolicyResponse :: DeletePolicyResponse -> TestTree
testDeletePolicyResponse = res
"DeletePolicyResponse"
"fixture/DeletePolicyResponse.proto"
iAM
(Proxy :: Proxy DeletePolicy)
testUpdateAssumeRolePolicyResponse :: UpdateAssumeRolePolicyResponse -> TestTree
testUpdateAssumeRolePolicyResponse = res
"UpdateAssumeRolePolicyResponse"
"fixture/UpdateAssumeRolePolicyResponse.proto"
iAM
(Proxy :: Proxy UpdateAssumeRolePolicy)
testGetInstanceProfileResponse :: GetInstanceProfileResponse -> TestTree
testGetInstanceProfileResponse = res
"GetInstanceProfileResponse"
"fixture/GetInstanceProfileResponse.proto"
iAM
(Proxy :: Proxy GetInstanceProfile)
testCreateLoginProfileResponse :: CreateLoginProfileResponse -> TestTree
testCreateLoginProfileResponse = res
"CreateLoginProfileResponse"
"fixture/CreateLoginProfileResponse.proto"
iAM
(Proxy :: Proxy CreateLoginProfile)
testGetSAMLProviderResponse :: GetSAMLProviderResponse -> TestTree
testGetSAMLProviderResponse = res
"GetSAMLProviderResponse"
"fixture/GetSAMLProviderResponse.proto"
iAM
(Proxy :: Proxy GetSAMLProvider)
testAddRoleToInstanceProfileResponse :: AddRoleToInstanceProfileResponse -> TestTree
testAddRoleToInstanceProfileResponse = res
"AddRoleToInstanceProfileResponse"
"fixture/AddRoleToInstanceProfileResponse.proto"
iAM
(Proxy :: Proxy AddRoleToInstanceProfile)
testListGroupsForUserResponse :: ListGroupsForUserResponse -> TestTree
testListGroupsForUserResponse = res
"ListGroupsForUserResponse"
"fixture/ListGroupsForUserResponse.proto"
iAM
(Proxy :: Proxy ListGroupsForUser)
testListEntitiesForPolicyResponse :: ListEntitiesForPolicyResponse -> TestTree
testListEntitiesForPolicyResponse = res
"ListEntitiesForPolicyResponse"
"fixture/ListEntitiesForPolicyResponse.proto"
iAM
(Proxy :: Proxy ListEntitiesForPolicy)
testAddUserToGroupResponse :: AddUserToGroupResponse -> TestTree
testAddUserToGroupResponse = res
"AddUserToGroupResponse"
"fixture/AddUserToGroupResponse.proto"
iAM
(Proxy :: Proxy AddUserToGroup)
testGetPolicyVersionResponse :: GetPolicyVersionResponse -> TestTree
testGetPolicyVersionResponse = res
"GetPolicyVersionResponse"
"fixture/GetPolicyVersionResponse.proto"
iAM
(Proxy :: Proxy GetPolicyVersion)
testDeleteOpenIdConnectProviderResponse :: DeleteOpenIdConnectProviderResponse -> TestTree
testDeleteOpenIdConnectProviderResponse = res
"DeleteOpenIdConnectProviderResponse"
"fixture/DeleteOpenIdConnectProviderResponse.proto"
iAM
(Proxy :: Proxy DeleteOpenIdConnectProvider)
testGetUserResponse :: GetUserResponse -> TestTree
testGetUserResponse = res
"GetUserResponse"
"fixture/GetUserResponse.proto"
iAM
(Proxy :: Proxy GetUser)
testListSigningCertificatesResponse :: ListSigningCertificatesResponse -> TestTree
testListSigningCertificatesResponse = res
"ListSigningCertificatesResponse"
"fixture/ListSigningCertificatesResponse.proto"
iAM
(Proxy :: Proxy ListSigningCertificates)
testDeleteSigningCertificateResponse :: DeleteSigningCertificateResponse -> TestTree
testDeleteSigningCertificateResponse = res
"DeleteSigningCertificateResponse"
"fixture/DeleteSigningCertificateResponse.proto"
iAM
(Proxy :: Proxy DeleteSigningCertificate)
testUpdateSigningCertificateResponse :: UpdateSigningCertificateResponse -> TestTree
testUpdateSigningCertificateResponse = res
"UpdateSigningCertificateResponse"
"fixture/UpdateSigningCertificateResponse.proto"
iAM
(Proxy :: Proxy UpdateSigningCertificate)
testListAttachedUserPoliciesResponse :: ListAttachedUserPoliciesResponse -> TestTree
testListAttachedUserPoliciesResponse = res
"ListAttachedUserPoliciesResponse"
"fixture/ListAttachedUserPoliciesResponse.proto"
iAM
(Proxy :: Proxy ListAttachedUserPolicies)
testRemoveClientIdFromOpenIdConnectProviderResponse :: RemoveClientIdFromOpenIdConnectProviderResponse -> TestTree
testRemoveClientIdFromOpenIdConnectProviderResponse = res
"RemoveClientIdFromOpenIdConnectProviderResponse"
"fixture/RemoveClientIdFromOpenIdConnectProviderResponse.proto"
iAM
(Proxy :: Proxy RemoveClientIdFromOpenIdConnectProvider)
testAttachUserPolicyResponse :: AttachUserPolicyResponse -> TestTree
testAttachUserPolicyResponse = res
"AttachUserPolicyResponse"
"fixture/AttachUserPolicyResponse.proto"
iAM
(Proxy :: Proxy AttachUserPolicy)
testListVirtualMFADevicesResponse :: ListVirtualMFADevicesResponse -> TestTree
testListVirtualMFADevicesResponse = res
"ListVirtualMFADevicesResponse"
"fixture/ListVirtualMFADevicesResponse.proto"
iAM
(Proxy :: Proxy ListVirtualMFADevices)
testResyncMFADeviceResponse :: ResyncMFADeviceResponse -> TestTree
testResyncMFADeviceResponse = res
"ResyncMFADeviceResponse"
"fixture/ResyncMFADeviceResponse.proto"
iAM
(Proxy :: Proxy ResyncMFADevice)
testDeleteAccessKeyResponse :: DeleteAccessKeyResponse -> TestTree
testDeleteAccessKeyResponse = res
"DeleteAccessKeyResponse"
"fixture/DeleteAccessKeyResponse.proto"
iAM
(Proxy :: Proxy DeleteAccessKey)
testUpdateAccessKeyResponse :: UpdateAccessKeyResponse -> TestTree
testUpdateAccessKeyResponse = res
"UpdateAccessKeyResponse"
"fixture/UpdateAccessKeyResponse.proto"
iAM
(Proxy :: Proxy UpdateAccessKey)
testListAccessKeysResponse :: ListAccessKeysResponse -> TestTree
testListAccessKeysResponse = res
"ListAccessKeysResponse"
"fixture/ListAccessKeysResponse.proto"
iAM
(Proxy :: Proxy ListAccessKeys)
testGetRolePolicyResponse :: GetRolePolicyResponse -> TestTree
testGetRolePolicyResponse = res
"GetRolePolicyResponse"
"fixture/GetRolePolicyResponse.proto"
iAM
(Proxy :: Proxy GetRolePolicy)
testCreateUserResponse :: CreateUserResponse -> TestTree
testCreateUserResponse = res
"CreateUserResponse"
"fixture/CreateUserResponse.proto"
iAM
(Proxy :: Proxy CreateUser)
testPutRolePolicyResponse :: PutRolePolicyResponse -> TestTree
testPutRolePolicyResponse = res
"PutRolePolicyResponse"
"fixture/PutRolePolicyResponse.proto"
iAM
(Proxy :: Proxy PutRolePolicy)
testUploadSigningCertificateResponse :: UploadSigningCertificateResponse -> TestTree
testUploadSigningCertificateResponse = res
"UploadSigningCertificateResponse"
"fixture/UploadSigningCertificateResponse.proto"
iAM
(Proxy :: Proxy UploadSigningCertificate)
testDeleteRolePolicyResponse :: DeleteRolePolicyResponse -> TestTree
testDeleteRolePolicyResponse = res
"DeleteRolePolicyResponse"
"fixture/DeleteRolePolicyResponse.proto"
iAM
(Proxy :: Proxy DeleteRolePolicy)
testGetAccountPasswordPolicyResponse :: GetAccountPasswordPolicyResponse -> TestTree
testGetAccountPasswordPolicyResponse = res
"GetAccountPasswordPolicyResponse"
"fixture/GetAccountPasswordPolicyResponse.proto"
iAM
(Proxy :: Proxy GetAccountPasswordPolicy)
testGetAccessKeyLastUsedResponse :: GetAccessKeyLastUsedResponse -> TestTree
testGetAccessKeyLastUsedResponse = res
"GetAccessKeyLastUsedResponse"
"fixture/GetAccessKeyLastUsedResponse.proto"
iAM
(Proxy :: Proxy GetAccessKeyLastUsed)
testUpdateUserResponse :: UpdateUserResponse -> TestTree
testUpdateUserResponse = res
"UpdateUserResponse"
"fixture/UpdateUserResponse.proto"
iAM
(Proxy :: Proxy UpdateUser)
testDeleteUserResponse :: DeleteUserResponse -> TestTree
testDeleteUserResponse = res
"DeleteUserResponse"
"fixture/DeleteUserResponse.proto"
iAM
(Proxy :: Proxy DeleteUser)
testAddClientIdToOpenIdConnectProviderResponse :: AddClientIdToOpenIdConnectProviderResponse -> TestTree
testAddClientIdToOpenIdConnectProviderResponse = res
"AddClientIdToOpenIdConnectProviderResponse"
"fixture/AddClientIdToOpenIdConnectProviderResponse.proto"
iAM
(Proxy :: Proxy AddClientIdToOpenIdConnectProvider)
testListRolePoliciesResponse :: ListRolePoliciesResponse -> TestTree
testListRolePoliciesResponse = res
"ListRolePoliciesResponse"
"fixture/ListRolePoliciesResponse.proto"
iAM
(Proxy :: Proxy ListRolePolicies)
testCreateAccountAliasResponse :: CreateAccountAliasResponse -> TestTree
testCreateAccountAliasResponse = res
"CreateAccountAliasResponse"
"fixture/CreateAccountAliasResponse.proto"
iAM
(Proxy :: Proxy CreateAccountAlias)
testListInstanceProfilesResponse :: ListInstanceProfilesResponse -> TestTree
testListInstanceProfilesResponse = res
"ListInstanceProfilesResponse"
"fixture/ListInstanceProfilesResponse.proto"
iAM
(Proxy :: Proxy ListInstanceProfiles)
testEnableMFADeviceResponse :: EnableMFADeviceResponse -> TestTree
testEnableMFADeviceResponse = res
"EnableMFADeviceResponse"
"fixture/EnableMFADeviceResponse.proto"
iAM
(Proxy :: Proxy EnableMFADevice)
testListAccountAliasesResponse :: ListAccountAliasesResponse -> TestTree
testListAccountAliasesResponse = res
"ListAccountAliasesResponse"
"fixture/ListAccountAliasesResponse.proto"
iAM
(Proxy :: Proxy ListAccountAliases)
testDeleteSAMLProviderResponse :: DeleteSAMLProviderResponse -> TestTree
testDeleteSAMLProviderResponse = res
"DeleteSAMLProviderResponse"
"fixture/DeleteSAMLProviderResponse.proto"
iAM
(Proxy :: Proxy DeleteSAMLProvider)
testUpdateSAMLProviderResponse :: UpdateSAMLProviderResponse -> TestTree
testUpdateSAMLProviderResponse = res
"UpdateSAMLProviderResponse"
"fixture/UpdateSAMLProviderResponse.proto"
iAM
(Proxy :: Proxy UpdateSAMLProvider)
testCreateGroupResponse :: CreateGroupResponse -> TestTree
testCreateGroupResponse = res
"CreateGroupResponse"
"fixture/CreateGroupResponse.proto"
iAM
(Proxy :: Proxy CreateGroup)
testListMFADevicesResponse :: ListMFADevicesResponse -> TestTree
testListMFADevicesResponse = res
"ListMFADevicesResponse"
"fixture/ListMFADevicesResponse.proto"
iAM
(Proxy :: Proxy ListMFADevices)
testUploadServerCertificateResponse :: UploadServerCertificateResponse -> TestTree
testUploadServerCertificateResponse = res
"UploadServerCertificateResponse"
"fixture/UploadServerCertificateResponse.proto"
iAM
(Proxy :: Proxy UploadServerCertificate)
testSetDefaultPolicyVersionResponse :: SetDefaultPolicyVersionResponse -> TestTree
testSetDefaultPolicyVersionResponse = res
"SetDefaultPolicyVersionResponse"
"fixture/SetDefaultPolicyVersionResponse.proto"
iAM
(Proxy :: Proxy SetDefaultPolicyVersion)
testListPolicyVersionsResponse :: ListPolicyVersionsResponse -> TestTree
testListPolicyVersionsResponse = res
"ListPolicyVersionsResponse"
"fixture/ListPolicyVersionsResponse.proto"
iAM
(Proxy :: Proxy ListPolicyVersions)
testListSAMLProvidersResponse :: ListSAMLProvidersResponse -> TestTree
testListSAMLProvidersResponse = res
"ListSAMLProvidersResponse"
"fixture/ListSAMLProvidersResponse.proto"
iAM
(Proxy :: Proxy ListSAMLProviders)
testGetServerCertificateResponse :: GetServerCertificateResponse -> TestTree
testGetServerCertificateResponse = res
"GetServerCertificateResponse"
"fixture/GetServerCertificateResponse.proto"
iAM
(Proxy :: Proxy GetServerCertificate)
testDeleteGroupResponse :: DeleteGroupResponse -> TestTree
testDeleteGroupResponse = res
"DeleteGroupResponse"
"fixture/DeleteGroupResponse.proto"
iAM
(Proxy :: Proxy DeleteGroup)
testUpdateGroupResponse :: UpdateGroupResponse -> TestTree
testUpdateGroupResponse = res
"UpdateGroupResponse"
"fixture/UpdateGroupResponse.proto"
iAM
(Proxy :: Proxy UpdateGroup)
testListGroupsResponse :: ListGroupsResponse -> TestTree
testListGroupsResponse = res
"ListGroupsResponse"
"fixture/ListGroupsResponse.proto"
iAM
(Proxy :: Proxy ListGroups)
testGenerateCredentialReportResponse :: GenerateCredentialReportResponse -> TestTree
testGenerateCredentialReportResponse = res
"GenerateCredentialReportResponse"
"fixture/GenerateCredentialReportResponse.proto"
iAM
(Proxy :: Proxy GenerateCredentialReport)
testGetPolicyResponse :: GetPolicyResponse -> TestTree
testGetPolicyResponse = res
"GetPolicyResponse"
"fixture/GetPolicyResponse.proto"
iAM
(Proxy :: Proxy GetPolicy)
testUpdateLoginProfileResponse :: UpdateLoginProfileResponse -> TestTree
testUpdateLoginProfileResponse = res
"UpdateLoginProfileResponse"
"fixture/UpdateLoginProfileResponse.proto"
iAM
(Proxy :: Proxy UpdateLoginProfile)
testDeleteLoginProfileResponse :: DeleteLoginProfileResponse -> TestTree
testDeleteLoginProfileResponse = res
"DeleteLoginProfileResponse"
"fixture/DeleteLoginProfileResponse.proto"
iAM
(Proxy :: Proxy DeleteLoginProfile)
testGetGroupResponse :: GetGroupResponse -> TestTree
testGetGroupResponse = res
"GetGroupResponse"
"fixture/GetGroupResponse.proto"
iAM
(Proxy :: Proxy GetGroup)
testDeleteServerCertificateResponse :: DeleteServerCertificateResponse -> TestTree
testDeleteServerCertificateResponse = res
"DeleteServerCertificateResponse"
"fixture/DeleteServerCertificateResponse.proto"
iAM
(Proxy :: Proxy DeleteServerCertificate)
testUpdateServerCertificateResponse :: UpdateServerCertificateResponse -> TestTree
testUpdateServerCertificateResponse = res
"UpdateServerCertificateResponse"
"fixture/UpdateServerCertificateResponse.proto"
iAM
(Proxy :: Proxy UpdateServerCertificate)
testListAttachedGroupPoliciesResponse :: ListAttachedGroupPoliciesResponse -> TestTree
testListAttachedGroupPoliciesResponse = res
"ListAttachedGroupPoliciesResponse"
"fixture/ListAttachedGroupPoliciesResponse.proto"
iAM
(Proxy :: Proxy ListAttachedGroupPolicies)
| fmapfmapfmap/amazonka | amazonka-iam/test/Test/AWS/Gen/IAM.hs | mpl-2.0 | 61,728 | 0 | 7 | 11,639 | 6,280 | 3,650 | 2,630 | 1,099 | 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.DFAReporting.PlacementGroups.Update
-- 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)
--
-- Updates an existing placement group.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.placementGroups.update@.
module Network.Google.Resource.DFAReporting.PlacementGroups.Update
(
-- * REST Resource
PlacementGroupsUpdateResource
-- * Creating a Request
, placementGroupsUpdate
, PlacementGroupsUpdate
-- * Request Lenses
, pguProFileId
, pguPayload
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.placementGroups.update@ method which the
-- 'PlacementGroupsUpdate' request conforms to.
type PlacementGroupsUpdateResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"placementGroups" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PlacementGroup :>
Put '[JSON] PlacementGroup
-- | Updates an existing placement group.
--
-- /See:/ 'placementGroupsUpdate' smart constructor.
data PlacementGroupsUpdate = PlacementGroupsUpdate'
{ _pguProFileId :: !(Textual Int64)
, _pguPayload :: !PlacementGroup
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'PlacementGroupsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pguProFileId'
--
-- * 'pguPayload'
placementGroupsUpdate
:: Int64 -- ^ 'pguProFileId'
-> PlacementGroup -- ^ 'pguPayload'
-> PlacementGroupsUpdate
placementGroupsUpdate pPguProFileId_ pPguPayload_ =
PlacementGroupsUpdate'
{ _pguProFileId = _Coerce # pPguProFileId_
, _pguPayload = pPguPayload_
}
-- | User profile ID associated with this request.
pguProFileId :: Lens' PlacementGroupsUpdate Int64
pguProFileId
= lens _pguProFileId (\ s a -> s{_pguProFileId = a})
. _Coerce
-- | Multipart request metadata.
pguPayload :: Lens' PlacementGroupsUpdate PlacementGroup
pguPayload
= lens _pguPayload (\ s a -> s{_pguPayload = a})
instance GoogleRequest PlacementGroupsUpdate where
type Rs PlacementGroupsUpdate = PlacementGroup
type Scopes PlacementGroupsUpdate =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient PlacementGroupsUpdate'{..}
= go _pguProFileId (Just AltJSON) _pguPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy PlacementGroupsUpdateResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/PlacementGroups/Update.hs | mpl-2.0 | 3,449 | 0 | 14 | 760 | 406 | 242 | 164 | 64 | 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.SSM.DeleteAssociation
-- 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.
-- | Disassociates the specified configuration document from the specified
-- instance.
--
-- When you disassociate a configuration document from an instance, it does not
-- change the configuration of the instance. To change the configuration state
-- of an instance after you disassociate a configuration document, you must
-- create a new configuration document with the desired configuration and
-- associate it with the instance.
--
-- <http://docs.aws.amazon.com/ssm/latest/APIReference/API_DeleteAssociation.html>
module Network.AWS.SSM.DeleteAssociation
(
-- * Request
DeleteAssociation
-- ** Request constructor
, deleteAssociation
-- ** Request lenses
, da1InstanceId
, da1Name
-- * Response
, DeleteAssociationResponse
-- ** Response constructor
, deleteAssociationResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SSM.Types
import qualified GHC.Exts
data DeleteAssociation = DeleteAssociation
{ _da1InstanceId :: Text
, _da1Name :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'DeleteAssociation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'da1InstanceId' @::@ 'Text'
--
-- * 'da1Name' @::@ 'Text'
--
deleteAssociation :: Text -- ^ 'da1Name'
-> Text -- ^ 'da1InstanceId'
-> DeleteAssociation
deleteAssociation p1 p2 = DeleteAssociation
{ _da1Name = p1
, _da1InstanceId = p2
}
-- | The ID of the instance.
da1InstanceId :: Lens' DeleteAssociation Text
da1InstanceId = lens _da1InstanceId (\s a -> s { _da1InstanceId = a })
-- | The name of the configuration document.
da1Name :: Lens' DeleteAssociation Text
da1Name = lens _da1Name (\s a -> s { _da1Name = a })
data DeleteAssociationResponse = DeleteAssociationResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteAssociationResponse' constructor.
deleteAssociationResponse :: DeleteAssociationResponse
deleteAssociationResponse = DeleteAssociationResponse
instance ToPath DeleteAssociation where
toPath = const "/"
instance ToQuery DeleteAssociation where
toQuery = const mempty
instance ToHeaders DeleteAssociation
instance ToJSON DeleteAssociation where
toJSON DeleteAssociation{..} = object
[ "Name" .= _da1Name
, "InstanceId" .= _da1InstanceId
]
instance AWSRequest DeleteAssociation where
type Sv DeleteAssociation = SSM
type Rs DeleteAssociation = DeleteAssociationResponse
request = post "DeleteAssociation"
response = nullResponse DeleteAssociationResponse
| dysinger/amazonka | amazonka-ssm/gen/Network/AWS/SSM/DeleteAssociation.hs | mpl-2.0 | 3,655 | 0 | 9 | 802 | 416 | 255 | 161 | 54 | 1 |
module Handler.Notification where
import Import
import Model.Notification
import Model.Project
import Model.User
import Widgets.Time
getNotificationsR :: Handler Html
getNotificationsR = do
user_id <- requireAuthId
notifs <- runDB $ do
userReadNotificationsDB user_id
fetchUserNotificationsDB user_id
defaultLayout $ do
setTitle "Notifications | Snowdrift.coop"
$(widgetFile "notifications")
getArchivedNotificationsR :: Handler Html
getArchivedNotificationsR = do
user_id <- requireAuthId
notifs <- runDB (fetchUserArchivedNotificationsDB user_id)
defaultLayout $ do
setTitle "Notifications | Snowdrift.coop"
$(widgetFile "notifications")
postArchiveNotificationR :: NotificationId -> Handler ()
postArchiveNotificationR notif_id = do
user_id <- requireAuthId
runYDB $ do
notif <- get404 notif_id
unless (user_id == notificationTo notif) $
lift (permissionDenied "You can't archive this notification.")
archiveNotificationDB notif_id
| Happy0/snowdrift | Handler/Notification.hs | agpl-3.0 | 1,096 | 0 | 14 | 261 | 235 | 108 | 127 | 30 | 1 |
module Main where
import Data.Monoid
import Test.Hspec
data Optional a =
Nada
| Only a
deriving (Eq, Show)
instance Monoid a => Monoid (Optional a) where
mempty = Nada
mappend Nada x = x
mappend x Nada = x
mappend (Only x) (Only y) = Only (x <> y)
main :: IO ()
main = hspec $ do
describe "Monoid Optional" $ do
it "Only (Sum 1) `mappend` Only (Sum 1) equals Only (Sum {getSum = 2})" $ do
Only (Sum 1) `mappend` Only (Sum 1) `shouldBe` Only (Sum {getSum = 2})
it "Only (Product 4) `mappend` Only (Product 2) equals Only (Product {getProduct = 8})" $ do
Only (Product 4) `mappend` Only (Product 2) `shouldBe` Only (Product {getProduct = 8})
it "Only (Sum 1) `mappend` Nada equals Only (Sum {getSum = 1})" $ do
Only (Sum 1) `mappend` Nada `shouldBe` Only (Sum {getSum = 1})
it "Only [1] `mappend` Nada equals Only [1]" $ do
Only [1] `mappend` Nada `shouldBe` Only [1]
it "Nada `mappend` Only (Sum 1) equals Only (Sum {getSum = 1})" $ do
Nada `mappend` Only (Sum 1) `shouldBe` Only (Sum {getSum = 1}) | thewoolleyman/haskellbook | 15/10/maor/OptionalMonoid.hs | unlicense | 1,068 | 0 | 18 | 258 | 392 | 203 | 189 | 25 | 1 |
{-
Created : 2013 Dec 15 (Sun) 21:08:32 by carr.
Last Modified : 2013 Dec 18 (Wed) 18:30:59 by carr.
-}
import Control.Concurrent
import Control.Monad (when)
import Data.Numbers.Primes (isPrime)
import Data.Time.Clock
import System.Environment
import System.IO.Unsafe -- for unit tests
import Test.HUnit as T
import Test.HUnit.Util as U -- https://github.com/haroldcarr/test-hunit-util
import Text.Printf
default (Integer)
{-
Example from
_The Art of Multiprocessor Programming, Revised Reprint_, Maurice Herlihy, Nir Shavit
Section 1.1
-- Primes
-- http://answers.yahoo.com/question/index?qid=1006050901081
-}
------------------------------------------------------------------------------
listNumPrimesInRangesTo :: Integral a => a -> IO [Int]
listNumPrimesInRangesTo block = do
numPrimesFoundInEachBlock <- newMVar []
children <- newMVar []
listNumPrimesInRangesTo' children 0 numPrimesFoundInEachBlock
waitForChildren children
takeMVar numPrimesFoundInEachBlock
where -- the algorithm requires always forking 10 children
listNumPrimesInRangesTo' c i np | i <= 9 = do forkChild c (numPrimesInRangeIO i block np)
listNumPrimesInRangesTo' c (i+1) np
| otherwise = return ()
listNumPrimesInRangesToSequential :: Integral a => a -> [Int]
listNumPrimesInRangesToSequential block = lnps 0 []
where
lnps i acc | i <= 9 = lnps (i + 1) ((numPrimesInRange i block):acc)
| otherwise = acc
numPrimesInRange :: Integral a => a -> a -> Int
numPrimesInRange i block = numPrimesInRange' ((i * block) + 1) []
where
numPrimesInRange' j acc
| j <= (i + 1) * block = numPrimesInRange' (j + 1) (if isPrime j then j:acc else acc)
| otherwise = length acc -- could calculate length at each step, but WANT to take the unnecessary time hit here
numPrimesInRangeIO :: Integral a => a -> a -> MVar [Int] -> IO ()
numPrimesInRangeIO i block primes = do
let p = numPrimesInRange i block
push p primes
-- tid <- myThreadId
-- forkIO (putStrLn ("id: " ++ (show tid) ++ " ; prime: " ++ (show p)))
-- putStrLn (show tid ++ " DONE")
-- return ()
{-
numPrimesInRange 0 (10^9)
numPrimesInRange 0 (10^7)
=> Segmentation fault: 11
10^5
=> 100000
(0 * (10^5)) + 1
1
(0 + 1) * (10^5)
100000
(1 * (10^5)) + 1
100001
(1 + 1) * (10^5)
200000
(5 * (10^5)) + 1
500001
(5 + 1) * (10^5)
600000
(9 * (10^5)) + 1
900001
(9 + 1) * (10^5)
1000000
-}
tr0 :: [T.Test]
tr0 = U.t "tr0"
(numPrimesInRange 0 (10^5))
9592
tr1 :: [T.Test]
tr1 = U.t "tr1"
(numPrimesInRange 2 (10^5))
8013
tr2 :: [T.Test]
tr2 = U.t "tr2"
(numPrimesInRange 4 (10^5))
7678
trExpectedResult :: [Int]
trExpectedResult = [7224,7323,7408,7445,7560,7678,7863,8013,8392,9592]
testSequential :: [Int]
testSequential = listNumPrimesInRangesToSequential (10^5)
trs :: [T.Test]
trs = U.t "trs"
testSequential
trExpectedResult
testParallelRange :: IO [Int]
testParallelRange = listNumPrimesInRangesTo (10^5)
tr :: [T.Test]
tr = U.t "tr"
(unsafePerformIO testParallelRange)
trExpectedResult
------------------------------------------------------------------------------
findPrimesTo :: (Num a, Ord a) => a -> Int -> IO (Int, Int)
findPrimesTo numChildren limit = do -- numChildren is 0-based
intSupply <- newMVar 2
numPrimesFound <- newMVar 0
children <- newMVar []
findPrimesTo' children 0 intSupply numPrimesFound
waitForChildren children
ri <- takeMVar intSupply
rp <- takeMVar numPrimesFound
return (ri, rp)
where
findPrimesTo' c i ints primes | i <= numChildren = do forkChild c (findPrime limit ints primes)
findPrimesTo' c (i+1) ints primes
| otherwise = return ()
findPrime :: Int -> MVar Int -> MVar Int -> IO ()
findPrime limit ints primes = do
i <- getAndInc ints
when (i < limit) $ do
when (isPrime i) $ do
getAndInc primes
return ()
findPrime limit ints primes
testFork0 :: IO (Int, Int)
testFork0 = findPrimesTo 0 (10^6)
tfp0 :: [T.Test]
tfp0 = U.t "tfp0"
(unsafePerformIO testFork0)
(1000001, sum trExpectedResult)
testFork4 :: IO (Int, Int)
testFork4 = findPrimesTo 4 (10^6)
tfp1 :: [T.Test]
tfp1 = U.t "tfp1"
(unsafePerformIO testFork4)
(1000005, sum trExpectedResult)
------------------------------------------------------------------------------
push :: Int -> MVar [Int] -> IO ()
push x numPrimesFoundInEachBlock = do
v <- takeMVar numPrimesFoundInEachBlock
putMVar numPrimesFoundInEachBlock (x:v)
getAndInc :: MVar Int -> IO Int
getAndInc count = do { v <- takeMVar count; putMVar count (v+1); return v }
-- next two from http://www.haskell.org/ghc/docs/7.6.2/html/libraries/base/Control-Concurrent.html
waitForChildren :: MVar [MVar a] -> IO ()
waitForChildren children = do
cs <- takeMVar children
case cs of
[] -> return ()
m:ms -> do
putMVar children ms
takeMVar m
waitForChildren children
forkChild :: MVar [MVar ()] -> IO a -> IO ThreadId
forkChild children io = do
mvar <- newEmptyMVar
childs <- takeMVar children
putMVar children (mvar:childs)
forkFinally io (\_ -> putMVar mvar ())
------------------------------------------------------------------------------
runTests :: IO Counts
runTests =
T.runTestTT $ TestList $ tr0 ++ tr1 ++ tr2 ++ tr ++ trs ++
tfp0 ++ tfp1
main :: IO a
main = do
[n] <- getArgs
t0 <- getCurrentTime
case n of
"1" -> let result = testSequential in ptsr t0 (show result)
"2" -> do { result <- testParallelRange ; ptsr t0 (show result) }
"3" -> do { result <- testFork0 ; ptsr t0 (show result) }
"4" -> do { result <- testFork4 ; ptsr t0 (show result) }
"5" -> do { result <- runTests ; ptsr t0 (show result) }
_ -> error "unknown"
printTimeSince t0
ptsr :: UTCTime -> String -> IO ()
ptsr t0 r = do
printTimeSince t0
putStrLn r
printTimeSince :: UTCTime -> IO b
printTimeSince t0 = do
t1 <- getCurrentTime
printf "time: %.2fs\n" (realToFrac (diffUTCTime t1 t0) :: Double)
-- End of file.
| haroldcarr/learn-haskell-coq-ml-etc | haskell/playpen/art-of-multiprocessor-programming-herlihy.hs | unlicense | 6,416 | 0 | 14 | 1,630 | 1,916 | 942 | 974 | 137 | 6 |
----
-- Copyright (c) 2013 Andrea Bernardini.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
----
module Handler.Genpdf where
import Import
import Data.Aeson
import qualified System.IO.Streams as S
import Network.Http.Client
import Network.HTTP.Types.URI (urlDecode)
import Network.HTTP.Types.Status
import GHC.Generics
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Text.Encoding
import Data.Text
import Data.Time
import Handler.Genepub hiding (submitItems)
import Control.Exception (SomeException)
import Control.Exception.Lifted (catch)
postGenpdfR :: Handler ()
postGenpdfR = do itemType <- runInputPost $ ireq hiddenField "type"
items <- catch (do runInputPost $ ireq selectionField itemType)
(\(e :: SomeException) -> redirect SessionR)
dates <- case itemType of
"link" -> return []
"feed" -> runInputPost $ ireq selectionField "feed_date"
let path = case itemType of
"link" -> "/page"
"feed" -> "/rss"
filename <- lift $ withConnection (openConnection "127.0.0.1" 8080)
(submitItems items dates path)
case filename of
Just f -> do _ <- case itemType of
"feed" -> updateFeedTime items
_ -> return ()
addHeader "Location" $ append "http://localhost:8080/pdf/" f
sendResponseStatus status303 ("" :: Text)
Nothing -> redirect SessionR
_ -> redirect HomeR
submitItems :: [Text] -> [Text] -> B.ByteString -> Connection -> IO (Maybe Text)
submitItems items dates path conn =
do laBS <- case dates of
(x:xs) -> return (encode (LinkArray {links = [Link url lread | url <- items, lread <- dates]}))
[] -> return (encode (LinkArray {links = [Link url "" | url <- items]}))
is <- S.fromLazyByteString laBS
len <- return $ BL.length laBS
q <- buildRequest $ do
http POST $ B.append path "/pdf"
setContentType "application/json"
setContentLength len
sendRequest conn q (inputStreamBody is)
receiveResponse conn (\p i -> do
stream <- S.read i
case stream of
Just bytes -> return $ Just $ decodeUtf8 bytes
Nothing -> return Nothing)
| andrebask/newsprint | src/UserInterface/NewsPrint/Handler/Genpdf.hs | apache-2.0 | 3,223 | 0 | 19 | 1,110 | 713 | 368 | 345 | -1 | -1 |
import SokoDash.NCurses.Render
import SokoDash.NCurses.Input
import SokoDash.World
import SokoDash.Simulator
import SokoDash.NCurses.Elerea
import SokoDash.NCurses.Utils
import FRP.Elerea.Simple
import Data.Function
import Data.Char
import UI.NCurses
import Control.Applicative
import System.IO
import Control.Monad.Trans
import System.Environment
main :: IO ()
main = do
[infile] <- getArgs
s0 <- parse . unlines . takeWhile (not . null) . lines <$> readFile infile
clock <- mkClock 0.5
(input, pushInput) <- external Nothing
runCurses $ do
setEcho False
setCursorMode CursorInvisible
w <- defaultWindow
let runUpdate u = do
x <- updateWindow w u
render
return x
let inp = sampleInput w $ \mev -> do
case decodeEvent =<< mev of
Nothing -> pushInput Nothing >> return False
Just CmdExit -> return True
Just (CmdInput inp) -> pushInput (Just inp) >> return False
game <- liftIO . start $ network s0 input clock
driveNetwork (runUpdate . renderRunState <$> game) inp
where
renderRunState (Running s) = renderState s >> return False
renderRunState _ = return True
| gergoerdi/soko-dash | src/SokoDash/NCurses/Main.hs | bsd-3-clause | 1,282 | 0 | 23 | 374 | 393 | 190 | 203 | 37 | 4 |
{-# OPTIONS_GHC -Wall -fno-warn-orphans #-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeFamilies #-}
{-# LANGUAGE Safe #-}
{- |
Module : Physics.Learn.StateSpace
Copyright : (c) Scott N. Walck 2014-2019
License : BSD3 (see LICENSE)
Maintainer : Scott N. Walck <walck@lvc.edu>
Stability : experimental
A 'StateSpace' is an affine space where the associated vector space
has scalars that are instances of 'Fractional'.
If p is an instance of 'StateSpace', then the associated vectorspace
'Diff' p is intended to represent the space of (time) derivatives
of paths in p.
'StateSpace' is very similar to Conal Elliott's 'AffineSpace'.
-}
module Physics.Learn.StateSpace
( StateSpace(..)
, (.-^)
, Time
, DifferentialEquation
, InitialValueProblem
, EvolutionMethod
, SolutionMethod
, stepSolution
, eulerMethod
)
where
import Data.AdditiveGroup
( AdditiveGroup(..)
)
import Data.VectorSpace
( VectorSpace(..)
)
import Physics.Learn.Position
( Position
, shiftPosition
, displacement
)
import Physics.Learn.CarrotVec
( Vec
, (^*)
, (^-^)
)
infixl 6 .+^, .-^
infix 6 .-.
-- | An instance of 'StateSpace' is a data type that can serve as the state
-- of some system. Alternatively, a 'StateSpace' is a collection of dependent
-- variables for a differential equation.
-- A 'StateSpace' has an associated vector space for the (time) derivatives
-- of the state. The associated vector space is a linearized version of
-- the 'StateSpace'.
class (VectorSpace (Diff p), Fractional (Scalar (Diff p))) => StateSpace p where
-- | Associated vector space
type Diff p
-- | Subtract points
(.-.) :: p -> p -> Diff p
-- | Point plus vector
(.+^) :: p -> Diff p -> p
-- | The scalars of the associated vector space can be thought of as time intervals.
type Time p = Scalar (Diff p)
-- | Point minus vector
(.-^) :: StateSpace p => p -> Diff p -> p
p .-^ v = p .+^ negateV v
instance StateSpace Double where
type Diff Double = Double
(.-.) = (-)
(.+^) = (+)
instance StateSpace Vec where
type Diff Vec = Vec
(.-.) = (^-^)
(.+^) = (^+^)
-- | Position is not a vector, but displacement (difference in position) is a vector.
instance StateSpace Position where
type Diff Position = Vec
(.-.) = flip displacement
(.+^) = flip shiftPosition
instance (StateSpace p, StateSpace q, Time p ~ Time q) => StateSpace (p,q) where
type Diff (p,q) = (Diff p, Diff q)
(p,q) .-. (p',q') = (p .-. p', q .-. q')
(p,q) .+^ (u,v) = (p .+^ u, q .+^ v)
instance (StateSpace p, StateSpace q, StateSpace r, Time p ~ Time q
,Time q ~ Time r) => StateSpace (p,q,r) where
type Diff (p,q,r) = (Diff p, Diff q, Diff r)
(p,q,r) .-. (p',q',r') = (p .-. p', q .-. q', r .-. r')
(p,q,r) .+^ (u,v,w) = (p .+^ u, q .+^ v, r .+^ w)
inf :: a -> [a]
inf x = x : inf x
instance AdditiveGroup v => AdditiveGroup [v] where
zeroV = inf zeroV
(^+^) = zipWith (^+^)
negateV = map negateV
instance VectorSpace v => VectorSpace [v] where
type Scalar [v] = Scalar v
c *^ xs = [c *^ x | x <- xs]
instance StateSpace p => StateSpace [p] where
type Diff [p] = [Diff p]
(.-.) = zipWith (.-.)
(.+^) = zipWith (.+^)
-- | A differential equation expresses how the dependent variables (state)
-- change with the independent variable (time).
-- A differential equation is specified by giving the (time) derivative
-- of the state as a function of the state.
-- The (time) derivative of a state is an element of the associated vector space.
type DifferentialEquation state = state -> Diff state
-- | An initial value problem is a differential equation along with an initial state.
type InitialValueProblem state = (DifferentialEquation state, state)
-- | A (numerical) solution method is a way of converting
-- an initial value problem into a list of states (a solution).
-- The list of states need not be equally spaced in time.
type SolutionMethod state = InitialValueProblem state -> [state]
-- | An evolution method is a way of approximating the state
-- after advancing a finite interval in the independent
-- variable (time) from a given state.
type EvolutionMethod state
= DifferentialEquation state -- ^ differential equation
-> Time state -- ^ time interval
-> state -- ^ initial state
-> state -- ^ evolved state
-- | Given an evolution method and a time step, return the solution method
-- which applies the evolution method repeatedly with with given time step.
-- The solution method returned will produce an infinite list of states.
stepSolution :: EvolutionMethod state -> Time state -> SolutionMethod state
stepSolution ev dt (de, ic) = iterate (ev de dt) ic
-- | The Euler method is the simplest evolution method.
-- It increments the state by the derivative times the time step.
eulerMethod :: StateSpace state => EvolutionMethod state
eulerMethod de dt st = st .+^ de st ^* dt
| walck/learn-physics | src/Physics/Learn/StateSpace.hs | bsd-3-clause | 5,091 | 0 | 10 | 1,190 | 1,107 | 638 | 469 | 80 | 1 |
module Network.LambdaBridge.Timeout where
import Control.Concurrent.MVar
import Control.Exception
import Data.Time.Clock
import qualified System.Timeout as T
-- | 'Limit' is a generic way of having adaptive timeouts, in (fractions of) seconds.
data Limit = Limit
{ waitFor :: Float -- ^ how long to wait, in seconds
, newLimit :: Float -> Maybe Float -> Float
-- ^ given an old timeout time,
-- and the actual time taken (or timeout)
-- how long should we wait?
}
-- | 'boundLimit' creates a Limit with a specific upper bound.
-- It has the following characteristics.
--
-- * the limit starts at 1/10th the given maximum
--
-- * If a timeout happens, we double the expected response time (upto the given maximum)
--
-- * If a response happens, we make the timeout the average between
-- 4 times the response latency, and the previous timeout time.
--
-- This seems to work well in practice.
--
boundLimit :: Float -> Limit
boundLimit n = Limit (n / 10) $ \ t o ->
case o of
Nothing -> min (t * 2) n
Just a -> (a * 4 + t) / 2
-- | 'timeout' uses these Limits to create adaptive timeouts.
timeout :: Limit -> IO (IO a -> IO (Maybe a))
timeout (Limit first fn) = do
timeVar <- newMVar first
return $ \ comp -> do
waitFor <- takeMVar timeVar
(do tm0 <- getCurrentTime
res <- T.timeout (floor (waitFor * 1000 * 1000)) comp
case res of
Nothing -> do putMVar timeVar $ fn waitFor Nothing
return Nothing
Just v -> do tm1 <- getCurrentTime
putMVar timeVar $ fn waitFor (Just (realToFrac $ tm1 `diffUTCTime` tm0))
return (Just v))
`onException`
(putMVar timeVar $ fn waitFor Nothing)
| andygill/lambda-bridge | Network/LambdaBridge/Timeout.hs | bsd-3-clause | 1,675 | 18 | 22 | 391 | 413 | 221 | 192 | 28 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.Parsec.Combinator
-- Copyright : (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : derek.a.elkins@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Commonly used generic combinators
--
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Text.Parsec.Combinator
( choice
, count
, between
, option, optionMaybe, optional
, skipMany1
, many1
, sepBy, sepBy1
, endBy, endBy1
, sepEndBy, sepEndBy1
, chainl, chainl1
, chainr, chainr1
, eof, notFollowedBy
-- tricky combinators
, manyTill, lookAhead, anyToken
) where
import Control.Monad
import Text.Parsec.Prim
-- | @choice ps@ tries to apply the parsers in the list @ps@ in order,
-- until one of them succeeds. Returns the value of the succeeding
-- parser.
choice :: (Stream s m t) => [ParsecT s u m a] -> ParsecT s u m a
choice ps = foldr (<|>) mzero ps
-- | @option x p@ tries to apply parser @p@. If @p@ fails without
-- consuming input, it returns the value @x@, otherwise the value
-- returned by @p@.
--
-- > priority = option 0 (do{ d <- digit
-- > ; return (digitToInt d)
-- > })
option :: (Stream s m t) => a -> ParsecT s u m a -> ParsecT s u m a
option x p = p <|> return x
-- | @option p@ tries to apply parser @p@. If @p@ fails without
-- consuming input, it return 'Nothing', otherwise it returns
-- 'Just' the value returned by @p@.
optionMaybe :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (Maybe a)
optionMaybe p = option Nothing (liftM Just p)
-- | @optional p@ tries to apply parser @p@. It will parse @p@ or nothing.
-- It only fails if @p@ fails after consuming input. It discards the result
-- of @p@.
optional :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m ()
optional p = do{ p; return ()} <|> return ()
-- | @between open close p@ parses @open@, followed by @p@ and @close@.
-- Returns the value returned by @p@.
--
-- > braces = between (symbol "{") (symbol "}")
between :: (Stream s m t) => ParsecT s u m open -> ParsecT s u m close
-> ParsecT s u m a -> ParsecT s u m a
between open close p
= do{ open; x <- p; close; return x }
-- | @skipMany1 p@ applies the parser @p@ /one/ or more times, skipping
-- its result.
skipMany1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m ()
skipMany1 p = do{ p; skipMany p }
{-
skipMany p = scan
where
scan = do{ p; scan } <|> return ()
-}
-- | @many p@ applies the parser @p@ /one/ or more times. Returns a
-- list of the returned values of @p@.
--
-- > word = many1 letter
many1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m [a]
many1 p = do{ x <- p; xs <- many p; return (x:xs) }
{-
many p = scan id
where
scan f = do{ x <- p
; scan (\tail -> f (x:tail))
}
<|> return (f [])
-}
-- | @sepBy p sep@ parses /zero/ or more occurrences of @p@, separated
-- by @sep@. Returns a list of values returned by @p@.
--
-- > commaSep p = p `sepBy` (symbol ",")
sepBy :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
sepBy p sep = sepBy1 p sep <|> return []
-- | @sepBy1 p sep@ parses /one/ or more occurrences of @p@, separated
-- by @sep@. Returns a list of values returned by @p@.
sepBy1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
sepBy1 p sep = do{ x <- p
; xs <- many (sep >> p)
; return (x:xs)
}
-- | @sepEndBy1 p sep@ parses /one/ or more occurrences of @p@,
-- separated and optionally ended by @sep@. Returns a list of values
-- returned by @p@.
sepEndBy1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
sepEndBy1 p sep = do{ x <- p
; do{ sep
; xs <- sepEndBy p sep
; return (x:xs)
}
<|> return [x]
}
-- | @sepEndBy p sep@ parses /zero/ or more occurrences of @p@,
-- separated and optionally ended by @sep@, ie. haskell style
-- statements. Returns a list of values returned by @p@.
--
-- > haskellStatements = haskellStatement `sepEndBy` semi
sepEndBy :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
sepEndBy p sep = sepEndBy1 p sep <|> return []
-- | @endBy1 p sep@ parses /one/ or more occurrences of @p@, seperated
-- and ended by @sep@. Returns a list of values returned by @p@.
endBy1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
endBy1 p sep = many1 (do{ x <- p; sep; return x })
-- | @endBy p sep@ parses /zero/ or more occurrences of @p@, seperated
-- and ended by @sep@. Returns a list of values returned by @p@.
--
-- > cStatements = cStatement `endBy` semi
endBy :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
endBy p sep = many (do{ x <- p; sep; return x })
-- | @count n p@ parses @n@ occurrences of @p@. If @n@ is smaller or
-- equal to zero, the parser equals to @return []@. Returns a list of
-- @n@ values returned by @p@.
count :: (Stream s m t) => Int -> ParsecT s u m a -> ParsecT s u m [a]
count n p | n <= 0 = return []
| otherwise = sequence (replicate n p)
-- | @chainr p op x@ parser /zero/ or more occurrences of @p@,
-- separated by @op@ Returns a value obtained by a /right/ associative
-- application of all functions returned by @op@ to the values returned
-- by @p@. If there are no occurrences of @p@, the value @x@ is
-- returned.
chainr :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> a -> ParsecT s u m a
chainr p op x = chainr1 p op <|> return x
-- | @chainl p op x@ parser /zero/ or more occurrences of @p@,
-- separated by @op@. Returns a value obtained by a /left/ associative
-- application of all functions returned by @op@ to the values returned
-- by @p@. If there are zero occurrences of @p@, the value @x@ is
-- returned.
chainl :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> a -> ParsecT s u m a
chainl p op x = chainl1 p op <|> return x
-- | @chainl1 p op x@ parser /one/ or more occurrences of @p@,
-- separated by @op@ Returns a value obtained by a /left/ associative
-- application of all functions returned by @op@ to the values returned
-- by @p@. . This parser can for example be used to eliminate left
-- recursion which typically occurs in expression grammars.
--
-- > expr = term `chainl1` addop
-- > term = factor `chainl1` mulop
-- > factor = parens expr <|> integer
-- >
-- > mulop = do{ symbol "*"; return (*) }
-- > <|> do{ symbol "/"; return (div) }
-- >
-- > addop = do{ symbol "+"; return (+) }
-- > <|> do{ symbol "-"; return (-) }
chainl1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> ParsecT s u m a
chainl1 p op = do{ x <- p; rest x }
where
rest x = do{ f <- op
; y <- p
; rest (f x y)
}
<|> return x
-- | @chainr1 p op x@ parser /one/ or more occurrences of |p|,
-- separated by @op@ Returns a value obtained by a /right/ associative
-- application of all functions returned by @op@ to the values returned
-- by @p@.
chainr1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m (a -> a -> a) -> ParsecT s u m a
chainr1 p op = scan
where
scan = do{ x <- p; rest x }
rest x = do{ f <- op
; y <- scan
; return (f x y)
}
<|> return x
-----------------------------------------------------------
-- Tricky combinators
-----------------------------------------------------------
-- | The parser @anyToken@ accepts any kind of token. It is for example
-- used to implement 'eof'. Returns the accepted token.
anyToken :: (Stream s m t, Show t) => ParsecT s u m t
anyToken = tokenPrim show (\pos _tok _toks -> pos) Just
-- | This parser only succeeds at the end of the input. This is not a
-- primitive parser but it is defined using 'notFollowedBy'.
--
-- > eof = notFollowedBy anyToken <?> "end of input"
eof :: (Stream s m t, Show t) => ParsecT s u m ()
eof = notFollowedBy anyToken <?> "end of input"
-- | @notFollowedBy p@ only succeeds when parser @p@ fails. This parser
-- does not consume any input. This parser can be used to implement the
-- \'longest match\' rule. For example, when recognizing keywords (for
-- example @let@), we want to make sure that a keyword is not followed
-- by a legal identifier character, in which case the keyword is
-- actually an identifier (for example @lets@). We can program this
-- behaviour as follows:
--
-- > keywordLet = try (do{ string "let"
-- > ; notFollowedBy alphaNum
-- > })
notFollowedBy :: (Stream s m t, Show a) => ParsecT s u m a -> ParsecT s u m ()
notFollowedBy p = try (do{ c <- try p; unexpected (show c) }
<|> return ()
)
-- | @manyTill p end@ applies parser @p@ /zero/ or more times until
-- parser @end@ succeeds. Returns the list of values returned by @p@.
-- This parser can be used to scan comments:
--
-- > simpleComment = do{ string "<!--"
-- > ; manyTill anyChar (try (string "-->"))
-- > }
--
-- Note the overlapping parsers @anyChar@ and @string \"<!--\"@, and
-- therefore the use of the 'try' combinator.
manyTill :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m end -> ParsecT s u m [a]
manyTill p end = scan
where
scan = do{ end; return [] }
<|>
do{ x <- p; xs <- scan; return (x:xs) }
-- | @lookAhead p@ parses @p@ without consuming any input.
lookAhead :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m a
lookAhead p = do{ state <- getParserState
; x <- p
; setParserState state
; return x
}
| maurer/15-411-Haskell-Base-Code | src/Text/Parsec/Combinator.hs | bsd-3-clause | 10,978 | 0 | 12 | 3,606 | 2,257 | 1,201 | 1,056 | 88 | 1 |
module ConfigParsingTests
( tests
)
where
import Control.Applicative
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test, cases)
import Sklite.Config
import Sklite.Types
tests :: Test
tests =
testGroup "Config parsing" $
[ testGroup "Expected failures" $
mkFailingTestCase <$> failureCases
, testGroup "Expected successes" $
mkPassingTestCase <$> successCases
]
mkFailingTestCase :: (String, String, String) -> Test
mkFailingTestCase (desc, input, errorMessage) =
testCase desc $
case parseLayoutConfig input of
Left e -> assertEqual "Parsing failed as expected but was the wrong failure"
errorMessage e
Right _ -> assertFailure "Parsing should have failed but succeeded instead"
mkPassingTestCase :: (String, String, Layout) -> Test
mkPassingTestCase (desc, input, expected) =
testCase desc $
case parseLayoutConfig input of
Left e -> assertFailure $ "Parsing should have succeeded but failed with: " ++ e
Right actual -> assertEqual "Parsing succeeded as expected but yielded an unexpected layout"
expected actual
failureCases :: [(String, String, String)]
failureCases =
[ ( "Not an XML document"
, ""
, "No root element found"
)
, ( "XML document with invalid root element"
, "<foo></foo>"
, "No root element found"
)
, ( "Root missing bandwidth"
, "<layout></layout>"
, "Required attribute \"bandwidth\" missing from element \"layout\""
)
, ( "Root has invalid bandwidth"
, "<layout bandwidth=\"foo\"></layout>"
, "Value of \"bandwidth\" attribute must be an integer"
)
, ( "Too many args elements"
, "<layout bandwidth=\"70\"><cell name=\"foo\" user=\"u\" program=\"prog\" runtime=\"10000\" period=\"10000\"><args><arg value=\"foo\"></args><args><arg value=\"bar\"></args></layout>"
, "At most one 'args' element permitted in each cell"
)
, ( "Cell missing runtime"
, "<layout bandwidth=\"90\"><cell name=\"foo\" user=\"u\" program=\"prog\" period=\"100000\"/></layout>"
, "Required attribute \"runtime\" missing from element \"cell\""
)
, ( "Cell missing period"
, "<layout bandwidth=\"90\"><cell name=\"foo\" user=\"u\" program=\"prog\" runtime=\"100000\"/></layout>"
, "Required attribute \"period\" missing from element \"cell\""
)
, ( "Cell has invalid runtime"
, "<layout bandwidth=\"90\"><cell name=\"foo\" user=\"u\" program=\"prog\" runtime=\"foo\" period=\"100000\"/></layout>"
, "Value of \"runtime\" attribute must be an integer"
)
, ( "Cell has invalid period"
, "<layout bandwidth=\"90\"><cell name=\"foo\" user=\"u\" program=\"prog\" runtime=\"100000\" period=\"foo\"/></layout>"
, "Value of \"period\" attribute must be an integer"
)
, ( "Segment size invalid"
, "<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <segment name=\"foo\" size=\"foo\" />\n\
\</layout>"
, "Value of \"size\" attribute must be an integer"
)
, ( "Cell entry address invalid"
, "<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <cell name=\"foo\" program=\"prog\" entryAddr=\"bogus\" period=\"1\" runtime=\"1\" user=\"joe\">\n\
\</layout>"
, "Value of \"entryAddr\" attribute must be an integer"
)
, ( "Cell missing binary"
, "<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <cell name=\"foo\" program=\"prog\" entryAddr=\"0x20000\" period=\"1\" runtime=\"1\" user=\"joe\">\n\
\</layout>"
, "Required attribute \"binary\" missing from element \"cell\""
)
, ( "Invalid segment map address"
, "<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <segment name=\"foo\" size=\"4096\" />\n\
\ <cell name=\"cell\" program=\"prog\" user=\"joe\" period=\"10000\" runtime=\"10000\">\n\
\ <use-segment name=\"foo\" alias=\"bar\" privileges=\"ro\" mapto=\"invalid\" />\n\
\ </cell>\n\
\</layout>"
, "Value of \"mapto\" attribute must be an integer"
)
, ( "Invalid segment privileges"
, "<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <segment name=\"foo\" size=\"4096\" />\n\
\ <cell name=\"cell\" program=\"prog\" user=\"joe\" period=\"10000\" runtime=\"10000\">\n\
\ <use-segment name=\"foo\" alias=\"bar\" privileges=\"bogus\" />\n\
\ </cell>\n\
\</layout>"
, "Invalid privilege string: \"bogus\", must be one of [\"ro\",\"rw\",\"wo\"]"
)
-- Configs with layouts
, ( "Unidirectional channel with missing from"
, "<layout bandwidth=\"100\" baseDir=\"foo\">\n\
\ <channel name=\"chan\" slots=\"4\" msgsize=\"1024\" to=\"c\" />\n\
\</layout"
, "Required attribute \"from\" missing from element \"channel\""
)
, ( "Unidirectional channel with missing to"
, "<layout bandwidth=\"100\" baseDir=\"foo\">\n\
\ <channel name=\"chan\" slots=\"4\" msgsize=\"1024\" from=\"c\" />\n\
\</layout"
, "Required attribute \"to\" missing from element \"channel\""
)
, ( "Unidirectional channel with missing msgsize"
, "<layout bandwidth=\"100\" baseDir=\"foo\">\n\
\ <channel name=\"chan\" slots=\"4\" to=\"c\" from=\"c\" />\n\
\</layout"
, "Required attribute \"msgsize\" missing from element \"channel\""
)
, ( "Unidirectional channel with invalid msgsize"
, "<layout bandwidth=\"100\" baseDir=\"foo\">\n\
\ <channel name=\"chan\" slots=\"4\" msgsize=\"invalid\" to=\"c\" from=\"c\" />\n\
\</layout"
, "Value of \"msgsize\" attribute must be an integer"
)
, ( "Unidirectional channel with missing slots"
, "<layout bandwidth=\"100\" baseDir=\"foo\">\n\
\ <channel name=\"chan\" msgsize=\"1024\" to=\"c\" from=\"c\" />\n\
\</layout"
, "Required attribute \"slots\" missing from element \"channel\""
)
, ( "Unidirectional channel with invalid slots"
, "<layout bandwidth=\"100\" baseDir=\"foo\">\n\
\ <channel name=\"chan\" slots=\"invalid\" msgsize=\"1024\" to=\"c\" from=\"c\" />\n\
\</layout"
, "Value of \"slots\" attribute must be an integer"
)
, ( "Unidirectional channel with missing name"
, "<layout bandwidth=\"100\" baseDir=\"foo\">\n\
\ <channel msgsize=\"1024\" slots=\"4\" to=\"c\" from=\"c\" />\n\
\</layout"
, "Required attribute \"name\" missing from element \"channel\""
)
]
successCases :: [(String, String, Layout)]
successCases =
[ ("Valid root", validRootConfig, validRootLayout)
, ("Defined segments", definedSegmentsConfig, definedSegmentsLayout)
, ("Cells", cellsConfig, cellsLayout)
, ("Cells with used segments", cellsSegmentsConfig, cellsSegmentsLayout)
, ("Cell receives arguments", cellWithArgs, cellWithArgsLayout)
, ("Channel", unidirChannel, unidirChannelLayout)
, ("Channel with overwriting (1)", unidirChannelOverwrite "1", unidirChannelOverwriteLayout True)
, ("Channel with overwriting (2)", unidirChannelOverwrite "yes", unidirChannelOverwriteLayout True)
, ("Channel with overwriting (3)", unidirChannelOverwrite "true", unidirChannelOverwriteLayout True)
, ("Channel with overwriting (4)", unidirChannelOverwrite "0", unidirChannelOverwriteLayout False)
, ("Channel with overwriting (5)", unidirChannelOverwrite "no", unidirChannelOverwriteLayout False)
, ("Channel with overwriting (6)", unidirChannelOverwrite "false", unidirChannelOverwriteLayout False)
]
unidirChannel :: String
unidirChannel =
"<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <channel name=\"chan\" from=\"c1\" to=\"c2\" msgsize=\"1024\" slots=\"4\" />\n\
\</layout>"
unidirChannelLayout :: Layout
unidirChannelLayout =
let c = Channel { chanFrom = "c1"
, chanTo = "c2"
, chanName = "chan"
, chanMsgSize = 1024
, chanMsgSlots = 4
, chanOverwrite = False
}
in validRootLayout { layoutChannels = [c]
}
unidirChannelOverwrite :: String -> String
unidirChannelOverwrite oStr =
"<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <channel overwrite=\"" ++ oStr ++ "\" name=\"chan\" from=\"c1\" to=\"c2\" msgsize=\"1024\" slots=\"4\" />\n\
\</layout>"
unidirChannelOverwriteLayout :: Bool -> Layout
unidirChannelOverwriteLayout overwrite =
let c = Channel { chanFrom = "c1"
, chanTo = "c2"
, chanName = "chan"
, chanMsgSize = 1024
, chanMsgSlots = 4
, chanOverwrite = overwrite
}
in validRootLayout { layoutChannels = [c]
}
validRootConfig :: String
validRootConfig =
"<layout bandwidth=\"70\" baseDir=\"foo\"></layout>"
validRootLayout :: Layout
validRootLayout =
Layout [] [] 70 []
cellWithArgs :: String
cellWithArgs =
"<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <cell name=\"cell\" user=\"u\" program=\"prog\" runtime=\"70000\" period=\"100000\">\n\
\ <args>\n\
\ <arg value=\"one\"/>\n\
\ <arg value=\"two\"/>\n\
\ <arg value=\"three\"/>\n\
\ </args>\n\
\ </cell>\n\
\</layout>"
cellWithArgsLayout :: Layout
cellWithArgsLayout =
let cs = [c1]
c1 = Cell "cell" "u" "prog" CellMain 70000 100000 [] ["one", "two", "three"] []
in Layout cs [] 70 []
definedSegmentsConfig :: String
definedSegmentsConfig =
"<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <segment name=\"foo\" size=\"4096\" />\n\
\</layout>"
definedSegmentsLayout :: Layout
definedSegmentsLayout =
let r = SharedMemoryRegion 4096 "foo"
in validRootLayout { sharedMemoryRegions = [r] }
cellsConfig :: String
cellsConfig =
"<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <segment name=\"foo\" size=\"4096\" />\n\
\ <cell name=\"cell1\" program=\"prog1\" user=\"joe\" runtime=\"50000\" period=\"100000\" />\n\
\ <cell name=\"cell2\" program=\"prog2\" user=\"joe\" runtime=\"30000\" period=\"100000\" />\n\
\ <cell name=\"cell3\" program=\"prog3\" user=\"joe\" binary=\"prog.bin\" runtime=\"10000\" period=\"100000\" entryAddr=\"0x10000\" size=\"0x20000\"/>\n\
\ </cell>\n\
\</layout>"
cellsLayout :: Layout
cellsLayout =
let c1 = Cell "cell1" "joe" "prog1" CellMain 50000 100000 [] [] []
c2 = Cell "cell2" "joe" "prog2" CellMain 30000 100000 [] [] []
c3 = Cell "cell3" "joe" "prog3" (RawBinary 0x10000 "prog.bin" 0x20000) 10000 100000 [] [] []
in definedSegmentsLayout { layoutCells = [c1, c2, c3] }
cellsSegmentsConfig :: String
cellsSegmentsConfig =
"<layout bandwidth=\"70\" baseDir=\"foo\">\n\
\ <segment name=\"foo\" size=\"4096\" />\n\
\ <cell name=\"cell\" program=\"prog\" user=\"joe\" runtime=\"50000\" period=\"100000\">\n\
\ <use-segment name=\"foo\" alias=\"bar1\" privileges=\"ro\" />\n\
\ <use-segment name=\"foo\" alias=\"bar2\" privileges=\"rw\" mapto=\"0xdeadbeef\" />\n\
\ <use-segment name=\"foo\" alias=\"bar3\" privileges=\"wo\" />\n\
\ </cell>\n\
\ </cell>\n\
\</layout>"
cellsSegmentsLayout :: Layout
cellsSegmentsLayout =
let c = Cell "cell" "joe" "prog" CellMain 50000 100000 [a1, a2, a3] [] []
a1 = SharedMemoryAccess MemReadOnly "foo" "bar1" Nothing
a2 = SharedMemoryAccess MemReadWrite "foo" "bar2" (Just 0xdeadbeef)
a3 = SharedMemoryAccess MemWriteOnly "foo" "bar3" Nothing
in definedSegmentsLayout { layoutCells = [c] }
| GaloisInc/sk-dev-platform | user/sklite/tests/ConfigParsingTests.hs | bsd-3-clause | 11,969 | 0 | 11 | 2,870 | 1,344 | 779 | 565 | 173 | 2 |
module RealWorld.Api.User where
import RealWorld.Api.Prelude
type Api =
Get '[JSON] ()
server :: ServerT Api RealWorld
server =
pure ()
| zudov/servant-realworld-example-app | src/RealWorld/Api/User.hs | bsd-3-clause | 143 | 0 | 7 | 27 | 51 | 29 | 22 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module OnPing.DataServer.Language (
-- * Values
Value (..)
, ToValue (..), FromValue (..)
, Error (..)
-- * Expressions
, Ident (..)
, Exp (..)
-- * Evaluation
, Context (..)
, Eval
, runEval
, evalExp
-- * Actions
, Action (..)
, LabeledAction (..)
-- * Control
, Control (..)
-- * Commands
, Command (..)
-- * Script
, Script
, runScript
-- * Prelude
, prelude
) where
import Data.Text (Text, unpack, pack)
import OnPing.DataServer.Client hiding (KeyInfo)
import OnPing.DataServer.Client.Key (Key (..))
import Control.Monad.Trans.Except
import Control.Monad.Trans.State
import Data.Map (Map)
import qualified Data.Map as M
import Numeric.Natural
import Numeric (showFFloat)
import Data.Monoid ((<>))
import Control.Applicative ((<|>))
import Control.Monad (unless, when)
import Control.Exception (try, displayException, SomeException)
import Data.Bifunctor (bimap)
import Data.String (IsString (..))
import Data.Vector.Mutable (IOVector)
import qualified Data.Vector.Mutable as V
import qualified Data.Vector as FV
import System.Microtimer (time, formatSeconds)
import Data.Word (Word8)
import qualified Graphics.Gnuplot.Simple as Plot
import Onping.Types.TagInfo (PID (..))
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Errors
data Error =
RawError String
| Undefined Ident
| TypeError
| NonFunctionApp
| ClientError String
| Void
| ExitCall
| AssertionFailed
| OutOfBounds Int Int
| KeyNotFound Key
displayError :: Error -> String
displayError (RawError err) = err
displayError (Undefined (Ident v)) = "Undefined variable `" ++ v ++ "`"
displayError TypeError = "Type error"
displayError NonFunctionApp = "Non-function application"
displayError (ClientError err) = "Client error: " ++ err
displayError Void = "Void"
displayError ExitCall = "Exit call"
displayError AssertionFailed = "Assertion failed"
displayError (OutOfBounds i n) = "Out of bounds: " ++ show i ++ " in " ++ show (0 :: Int, n)
displayError (KeyNotFound k) = "Not found: " ++ show k
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Values
data Value =
VError Error
| VBool Bool
| VInt Int
| VDouble Double
| VText Text
| VKey Key
| VPID PID
| VFun (Value -> Value)
displayValue :: Value -> String
displayValue (VError err) = displayError err
displayValue (VBool b) = show b
displayValue (VInt n) = show n
displayValue (VDouble x) = show $ showFFloat (Just 5) x []
displayValue (VText t) = unpack t
displayValue (VKey k) = show k
displayValue (VPID pid) = show pid
displayValue (VFun _) = "<function>"
applyValue :: Value -> Value -> Value
applyValue (VFun f) v = f v
applyValue _ _ = VError NonFunctionApp
class ToValue t where
toValue :: t -> Value
class FromValue t where
fromValue :: Value -> Maybe t
instance ToValue Value where
toValue = id
instance FromValue Value where
fromValue = Just
instance ToValue Error where
toValue = VError
instance FromValue Error where
fromValue (VError err) = Just err
fromValue _ = Nothing
instance ToValue Bool where
toValue = VBool
instance FromValue Bool where
fromValue (VBool b) = Just b
fromValue _ = Nothing
instance ToValue Int where
toValue = VInt
instance FromValue Int where
fromValue (VInt n) = Just n
fromValue _ = Nothing
instance ToValue Double where
toValue = VDouble
instance FromValue Double where
fromValue (VDouble x) = Just x
fromValue _ = Nothing
instance ToValue Text where
toValue = VText
instance FromValue Text where
fromValue (VText t) = Just t
fromValue _ = Nothing
instance ToValue Key where
toValue = VKey
instance FromValue Key where
fromValue (VKey k) = Just k
fromValue _ = Nothing
instance ToValue PID where
toValue = VPID
instance FromValue PID where
fromValue (VPID pid) = Just pid
fromValue _ = Nothing
instance (FromValue a, ToValue b) => ToValue (a -> b) where
toValue f = VFun $ \v ->
case fromValue v of
Just x -> toValue $ f x
_ -> VError TypeError
instance (ToValue a, ToValue b) => ToValue (Either a b) where
toValue (Left a) = toValue a
toValue (Right b) = toValue b
instance (FromValue a, FromValue b) => FromValue (Either a b) where
fromValue v = (Left <$> fromValue v) <|> (Right <$> fromValue v)
instance ToValue Word8 where
toValue = toValue . (fromIntegral :: Exponent -> Int)
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Expressions
newtype Ident = Ident String deriving (Eq, Ord, Show)
instance IsString Ident where
fromString = Ident
data Exp a =
EVar Ident
| EArr Ident (Exp Int)
| EInt Int
| EDouble Double
| EText Text
| EApp (Exp Value) (Exp Value)
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Evaluation
type Array = IOVector Value
data Context = Context
{ namespace :: Map Ident Value
, arrays :: Map Ident Array
, actionNumber :: !Natural
, currentLine :: !Int
}
type Eval = ExceptT Error (StateT Context IO)
runEval :: Eval a -> IO ()
runEval e = do
(t,(r,ct)) <- time $ runStateT (runExceptT e) $ Context
{ namespace = M.empty
, arrays = M.empty
, actionNumber = 0
, currentLine = 0
}
case r of
Left err -> putStrLn $ "ERROR: Line " ++ show (currentLine ct) ++ ": " ++ displayError err
_ -> putStrLn $ "Finished. Actions executed: " ++ show (actionNumber ct)
++ ". Time spent: " ++ formatSeconds t ++ "."
castValue :: (ToValue a, FromValue b) => a -> Eval b
castValue x =
let v = toValue x
in case fromValue v of
Just y -> return y
_ ->
case v of
VError err -> throwE err
_ -> throwE TypeError
valueOf :: FromValue a => Ident -> Eval a
valueOf v = do
ct <- lift get
case M.lookup v $ namespace ct of
Just x -> castValue x
_ -> throwE $ Undefined v
evalExp :: FromValue a => Exp a -> Eval a
evalExp (EVar v) = valueOf v
evalExp (EArr arr e) = do
v <- arrayIn arr
i <- evalExp e
let n = V.length v
unless (0 <= i && i < n) $ throwE $ OutOfBounds i n
liftIO (V.unsafeRead v i) >>= castValue
evalExp (EInt n) = castValue n
evalExp (EDouble x) = castValue x
evalExp (EText t) = castValue t
evalExp (EApp e1 e2) = (applyValue <$> evalExp e1 <*> evalExp e2) >>= castValue
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Arrays
arrayIn :: Ident -> Eval Array
arrayIn v = do
vs <- arrays <$> lift get
case M.lookup v vs of
Just arr -> return arr
_ -> throwE $ Undefined v
listArray :: ToValue a => Ident -> [a] -> Eval ()
listArray v xs = do
arr <- liftIO $ FV.unsafeThaw $ FV.fromList $ fmap toValue xs
lift $ modify $ \ct -> ct { arrays = M.insert v arr $ arrays ct }
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Actions
data Action =
Assignment Ident (Exp Value)
| ActCommand Command
| ActControl Control
assign :: ToValue a => Ident -> a -> Eval ()
assign v x = lift $ modify $ \ct -> ct { namespace = M.insert v (toValue x) $ namespace ct }
increaseActionNumber :: Eval ()
increaseActionNumber = lift $ modify' $ \ct -> ct { actionNumber = actionNumber ct + 1 }
runAction :: Action -> Eval ()
runAction (Assignment v e) = (evalExp e :: Eval Value) >>= assign v >> increaseActionNumber
runAction (ActCommand comm) = runCommand comm >> increaseActionNumber
runAction (ActControl ctrl) = runControl ctrl
data LabeledAction = LAction
{ actionLine :: Int
, theAction :: Action
}
runLAction :: LabeledAction -> Eval ()
runLAction lact = do
lift $ modify' $ \ct -> ct { currentLine = actionLine lact }
runAction $ theAction lact
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Control
data Control =
While (Exp Bool) Script
| ForEach Ident Ident Script
| Isolate Script
| When (Exp Bool) Script
runControl :: Control -> Eval ()
runControl (While e scr) = do
b <- evalExp e
when b $ runScript scr >> runControl (While e scr)
runControl (ForEach arrv v scr) = do
arr <- arrayIn arrv
let n = V.length arr
go i = when (i < n) $ do
x <- liftIO $ V.unsafeRead arr i
assign v x
runScript scr
go $ i + 1
go 0
runControl (Isolate scr) = do
ct <- lift get
arraysCopy <- mapM V.clone $ arrays ct
let io = runStateT (runExceptT $ runScript scr) $ ct { arrays = arraysCopy }
er <- liftIO $ try io
case er of
Left e -> liftIO $ putStrLn $ "EXCEPTION (ISOLATED): " ++ displayException (e :: SomeException)
Right (r,isoct) -> do
case r of
Left err -> liftIO $ putStrLn $ "ERROR (ISOLATED): Line " ++ show (currentLine isoct) ++ ": " ++ displayError err
_ -> return ()
lift $ put $ ct { actionNumber = actionNumber isoct }
runControl (When e scr) = do
b <- evalExp e
when b $ runScript scr
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Commands
data Command =
Print (Exp Value)
| Exit
| Assert (Exp Bool)
| NewArray Ident (Exp Int)
| SetArray Ident (Exp Int) (Exp Value)
| GetAllKeys Ident
| RemoveKey (Exp Key)
| GetTimeBounds Ident Ident
| SetTimeBounds (Exp Int) (Exp Int)
| Sync
| MemoryUsage Ident
| Truncate (Exp Key) (Exp Int)
| KeyInfo (Exp Key) Ident Ident Ident -- ^ Returns t0, size, and pointers
| DensityGraph (Exp Text) (Exp Key)
runCommand :: Command -> Eval ()
runCommand (Print e) = evalExp e >>= liftIO . putStrLn . displayValue
runCommand Exit = throwE ExitCall
runCommand (Assert e) = do
b <- evalExp e
unless b $ throwE AssertionFailed
runCommand (NewArray v en) = do
n <- evalExp en
arr <- liftIO $ V.replicate n $ VError Void
lift $ modify $ \ct -> ct { arrays = M.insert v arr $ arrays ct }
runCommand (SetArray v ei ex) = do
arr <- arrayIn v
i <- evalExp ei
let n = V.length arr
unless (0 <= i && i < n) $ throwE $ OutOfBounds i n
x <- evalExp ex
liftIO $ V.unsafeWrite arr i x
runCommand (GetAllKeys arr) = (clientActionE clientAllKeys :: Eval [Key]) >>= listArray arr
runCommand (RemoveKey k) = evalExp k >>= clientActionM . clientRemove
runCommand (GetTimeBounds lbv ubv) = do
(lb,ub) <- clientActionE clientGetTimeBounds
assign lbv lb
assign ubv ub
runCommand (SetTimeBounds lbe ube) = do
lb <- evalExp lbe
ub <- evalExp ube
clientActionM $ clientSetTimeBounds (lb,ub)
runCommand Sync = clientActionM clientSync
runCommand (MemoryUsage v) = clientActionE clientMemoryUsage >>= assign v
runCommand (Truncate ke te) = do
k <- evalExp ke
t <- evalExp te
clientActionM $ clientTruncate k t
runCommand (KeyInfo ke t0v sv ptrsv) = do
k <- evalExp ke
mkinfo <- clientActionE $ clientInfo k
case mkinfo of
Just kinfo -> do
assign t0v $ kinfo_Time kinfo
assign sv $ kinfo_Size kinfo
assign ptrsv $ kinfo_Pointers kinfo
_ -> throwE $ KeyNotFound k
runCommand (DensityGraph fpe ke) = do
fp <- evalExp fpe
k <- evalExp ke
xs <- clientActionE $ clientDensity k
liftIO $ Plot.plotList
[ Plot.PNG $ unpack fp
, Plot.XLabel "Chunk Index"
, Plot.YLabel "Density"
, Plot.Title "Density Function"
] xs
clientAction :: Client Key IO a -> Eval a
clientAction c = do
server <- valueOf "server"
port <- valueOf "port"
liftIO $ runClient (AwayServer OnPingData (unpack server) port) c
clientActionM :: Client Key IO (Maybe String) -> Eval ()
clientActionM c = do
merr <- clientAction c
case merr of
Just err -> throwE $ ClientError err
_ -> return ()
clientActionE :: Client Key IO (Either String a) -> Eval a
clientActionE c = do
ex <- clientAction c
case ex of
Left err -> throwE $ ClientError err
Right x -> return x
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Script
type Script = [LabeledAction]
runScript :: Script -> Eval ()
runScript = mapM_ runLAction
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Prelude
prelude :: Eval ()
prelude = do
-- Numerical operations
assign "+" (bimap (+) (+) :: Either Int Double -> Either (Int -> Int) (Double -> Double))
assign "-" (bimap (-) (-) :: Either Int Double -> Either (Int -> Int) (Double -> Double))
assign "*" (bimap (*) (*) :: Either Int Double -> Either (Int -> Int) (Double -> Double))
assign "/" (bimap div (/) :: Either Int Double -> Either (Int -> Int) (Double -> Double))
assign "=" ((==) :: Int -> Int -> Bool)
assign "/=" ((/=) :: Int -> Int -> Bool)
assign "<=" (bimap (<=) (<=) :: Either Int Double -> Either (Int -> Bool) (Double -> Bool))
assign ">=" (bimap (>=) (>=) :: Either Int Double -> Either (Int -> Bool) (Double -> Bool))
assign ">" (bimap (>) (>) :: Either Int Double -> Either (Int -> Bool) (Double -> Bool))
assign "<" (bimap (<) (<) :: Either Int Double -> Either (Int -> Bool) (Double -> Bool))
-- Arrays
-- assign "length" (length :: [Value] -> Int)
-- Booleans
assign "true" True
assign "false" False
assign "not" not
assign "|" (||)
assign "&" (&&)
-- Text
assign "++" ((<>) :: Text -> Text -> Text)
assign "display" (pack . displayValue :: Value -> Text)
-- Keys
assign "Key" Key
assign "keypid" keyPID
-- Server default info
assign "server" ("127.0.0.1" :: Text)
assign "port" (5000 :: Int)
| plow-technologies/onping-data-language | OnPing/DataServer/Language.hs | bsd-3-clause | 14,250 | 0 | 20 | 2,967 | 5,000 | 2,542 | 2,458 | 369 | 3 |
module Exercises125 where
import qualified Data.Maybe
-- Determine the Kinds
-- 1. id :: a -> a a has kind *
-- 2. r :: a -> f a a has kind *, f a has kind * -> *
-- String Processing
-- 1.
-- example GHCi session above the functions
-- >>> notThe "the"
-- Nothing
-- >>> notThe "blahtheblah"
-- Just "blahtheblah"
-- >>> notThe "woot"
-- Just "woot"
notThe :: String -> Maybe String
notThe "the" = Nothing
notThe x = Just x
theToA :: Maybe String -> String
theToA Nothing = "a"
theToA (Just x) = x
-- >>> replaceThe "the cow loves us" -- "a cow loves us"
replaceThe :: String -> String
replaceThe x = unwords $ map (theToA . notThe) $ words x
-- 2.
vowelInitial :: String -> Maybe String
vowelInitial x
| head x `elem` "aeiou" = Nothing
| otherwise = Just x
countTheBeforeVowel :: String -> Integer
countTheBeforeVowel = undefined
-- 3.
isVowel :: Char -> Maybe Char
isVowel x
| x `elem` "aeiou" = Just x
| otherwise = Nothing
countVowels :: String -> Integer
countVowels = toInteger . length . Data.Maybe.mapMaybe isVowel
-- Validate the word
newtype Word' =
Word' String
deriving (Eq, Show)
mkWord :: String -> Maybe Word'
mkWord x
| numVowels > numConsonants = Nothing
| otherwise = Just (Word' x)
where
numVowels = countVowels x
numConsonants = toInteger (length x) - numVowels
-- It's only Natural
data Nat =
Zero
| Succ Nat
deriving (Eq, Show)
natToInteger :: Nat -> Integer
natToInteger Zero = 0
natToInteger (Succ n) = 1 + natToInteger n
integerToNat :: Integer -> Maybe Nat
integerToNat x
| x < 0 = Nothing
| otherwise = Just (f x)
where f x
| x == 0 = Zero
| otherwise = Succ (f (x - 1))
-- Small library for Maybe
-- 1.
isJust :: Maybe a -> Bool
isJust (Just _) = True
isJust Nothing = False
isNothing :: Maybe a -> Bool
isNothing = not . isJust
-- 2.
mayybee :: b -> (a -> b) -> Maybe a -> b
maybee b _ Nothing = b
mayybee _ f (Just a) = f a
-- 3.
fromMaybe :: a -> Maybe a -> a
fromMaybe a Nothing = a
fromMaybe _ (Just a) = a
-- 4.
listToMaybe :: [a] -> Maybe a
listToMaybe (a:_) = Just a
listToMaybe _ = Nothing
maybeToList :: Maybe a -> [a]
maybeToList (Just a) = [a]
maybeToList _ = []
-- 5.
catMaybes :: [Maybe a] -> [a]
catMaybes maybeAs = [x | Just x <- maybeAs]
-- 6.
flipMaybe :: [Maybe a] -> Maybe [a]
flipMaybe [] = Just []
flipMaybe xs = foldr f (Just []) xs
where f (Just a) (Just b) = Just (a:b)
f _ _ = Nothing
-- Small library for Either
-- 1.
lefts' :: [Either a b] -> [a]
lefts' = foldr f []
where f (Left a) xs = a : xs
f _ xs = xs
-- 2.
rights' :: [Either a b] -> [b]
rights' = foldr f []
where f (Right b) xs = b : xs
f _ xs = xs
-- 3.
partitionEithers' :: [Either a b] -> ([a], [b])
partitionEithers' = foldr f ([], [])
where f (Left a) (xs, ys) = (a:xs, ys)
f (Right b) (xs, ys) = (xs, b:ys)
-- 4.
-- eitherMaybe' even (Right 2)
-- eitherMaybe' even (Left 2)
eitherMaybe' :: (b -> c) -> Either a b -> Maybe c
eitherMaybe' f (Right x) = Just (f x)
eitherMaybe' _ (Left _) = Nothing
-- 5.
either' :: (a -> c) -> (b -> c) -> Either a b -> c
either' _ g (Right x) = g x
either' f _ (Left x) = f x
-- 6.
eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c
eitherMaybe'' _ (Left _) = Nothing
eitherMaybe'' f e = Just (either' undefined f e)
-- Write your own iterate and unfoldr
-- 1.
-- take 10 $ iterate (+1) 0
myIterate :: (a -> a) -> a -> [a]
myIterate f x = x : myIterate f (f x)
-- 2.
-- take 10 $ unfoldr (\b -> Just (b, b+1)) 0
myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a]
myUnfoldr f x = case f x of
Nothing -> []
Just (x, y) -> x : myUnfoldr f y
-- 3.
betterIterate :: (a -> a) -> a -> [a]
betterIterate f = myUnfoldr (\b -> Just(b, f b))
-- Finally something other than a list
data BinaryTree a =
Leaf
| Node (BinaryTree a) a (BinaryTree a)
deriving (Eq, Ord, Show)
-- 1.
unfold :: (a -> Maybe (a,b,a)) -> a -> BinaryTree b
unfold f b = case f b of
Nothing -> Leaf
Just (x, y, z) -> Node (unfold f x) y (unfold f z)
-- 2.
treeBuild :: Integer -> BinaryTree Integer
treeBuild n = unfold f 0
where f m
| m == n = Nothing
| otherwise = Just (m + 1, m, m + 1)
| pdmurray/haskell-book-ex | src/ch12/Exercises12.5.hs | bsd-3-clause | 4,329 | 0 | 12 | 1,193 | 1,777 | 926 | 851 | 111 | 2 |
import Network.JsonRpc (server, proxy, toMethod)
-- method exposed through rpc
add :: Int -> Int -> IO Int
add a b = return $ a + b
-- a server handler. ByteString -> IO ByteString
serv = server [("add", toMethod add)]
-- a proxy which call serv directly.
directProxy = proxy serv
-- client proxy of add method
add' :: Int -> Int -> IO Int
add' = directProxy "add"
main = add' 1 2 >>= print
| yihuang/haskell-json-rpc | examples/test_direct.hs | bsd-3-clause | 396 | 0 | 8 | 82 | 125 | 66 | 59 | 8 | 1 |
module Rules.Sigma where
import Derivation
import Goal
import Rules.Utils
import Tactic
import Term
-- H >> Sig x : A. B = Sig x : A'. B' in U(i)
-- H >> A = A' in U(i)
-- H, x : A >> B = B' in U(i)
-- Uses: SIG_EQ
sigmaEQ :: PrlTactic
sigmaEQ (Goal ctx t) =
case t of
Eq (Sigma a b) (Sigma a' b') (Uni i) -> return $ Result
{ resultGoals = [ Goal ctx (Eq a a' (Uni i))
, Goal (a <:> ctx) (Eq b b' (Uni i))
]
, resultEvidence = \d -> case d of
[d1, d2] -> SIG_EQ d1 d2
_ -> error "Sigma.EQ: Invalid evidence!"
}
_ -> fail "Sigma.EQ does not apply."
-- H >> Sig x : A. B
-- H >> a = a in A
-- H >> [a/x]B
-- H, a : A >> B = B in U(i)
-- Uses: SIG_INTRO
sigmaINTRO :: Universe -> Term -> PrlTactic
sigmaINTRO i w (Goal ctx t) =
case t of
Sigma a b -> return $ Result
{ resultGoals = [ Goal ctx (Eq w w a)
, Goal ctx (subst w 0 b)
, Goal (a <:> ctx) (Eq b b (Uni i))
]
, resultEvidence = \d -> case d of
[d1, d2, d3] -> SIG_INTRO i w d1 d2 d3
_ -> error "Sigma.INTRO: Invalid evidence!"
}
_ -> fail "Sigma.INTRO does not apply."
-- H >> C
-- H(i) = Sig x : A. B
-- H, x : A, y : B >> C
-- Uses: SIG_ELIM
sigmaELIM :: Target -> PrlTactic
sigmaELIM target (Goal ctx t) =
case nth (irrelevant t) target ctx of
Just (Sigma a b) -> return $ Result
{ resultGoals = [ Goal (b <:> (a <:> ctx)) t]
, resultEvidence = \d -> case d of
[d] -> SIG_ELIM target d
_ -> error "Sigma.ELIM: Invalid evidence!"
}
_ -> fail "Sigma.ELIM does not apply."
-- H >> pair(a; b) = pair(a'; b') in Sig x : A. B
-- H >> a = a' in A
-- H >> b = b' in [a/x]B
-- H, x : A >> B = B in U(i)
-- Uses: PAIR_EQ
sigmaPAIREQ :: Universe -> PrlTactic
sigmaPAIREQ i (Goal ctx t) =
case t of
Eq (Pair m1 n1) (Pair m2 n2) (Sigma a b) -> return $ Result
{ resultGoals = [ Goal ctx (Eq m1 m2 a)
, Goal ctx (Eq n1 n2 (subst m1 0 b))
, Goal (a <:> ctx) (Eq b b (Uni i))
]
, resultEvidence = \d -> case d of
[d1, d2, d3] -> PAIR_EQ i d1 d2 d3
_ -> error "Sigma.PAIREQ: Invalid evidence!"
}
_ -> fail "Sigma.PAIREQ does not apply."
-- H >> fst(a) = fst(a') in A
-- H >> a = a' in Sig x : A. B
-- Uses: FST_EQ
-- Note that the supplied term should be Sig x : A . B
sigmaFSTEQ :: Term -> PrlTactic
sigmaFSTEQ w (Goal ctx t) =
case (w, t) of
(Sigma a b, Eq (Fst m1) (Fst m2) a') | a == a' -> return $ Result
{ resultGoals = [ Goal ctx (Eq m1 m2 w)
]
, resultEvidence = \d -> case d of
[d] -> FST_EQ w d
_ -> error "Sigma.FSTEQ: Invalid evidence!"
}
_ -> fail "Sigma.FSTEQ does not apply."
-- H >> snd(a) = snd(a') in B'
-- H >> a = a' in Sig x : A. B
-- H >> [fst(a)/x]B = B' in U(i)
-- Uses: SND_EQ
-- Note that the supplied term should be Sig x : A . B
sigmaSNDEQ :: Universe -> Term -> PrlTactic
sigmaSNDEQ i w (Goal ctx t) =
case (w, t) of
(Sigma a b, Eq (Snd m1) (Snd m2) b') -> return $ Result
{ resultGoals = [ Goal ctx (Eq m1 m2 w)
, Goal ctx (Eq (subst (Fst m1) 0 b) b' (Uni i))
]
, resultEvidence = \d -> case d of
_ -> error "Sigma.SNDENV: Invalid evidence!"
}
_ -> fail "Sigma.SNDEQ does not apply."
| thsutton/cha | lib/Rules/Sigma.hs | bsd-3-clause | 3,775 | 0 | 18 | 1,512 | 1,111 | 588 | 523 | 65 | 3 |
{-# LANGUAGE QuasiQuotes #-}
module Main
where
import Codec.Binary.UTF8.String
import Control.Applicative
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe
import Data.Maybe
import qualified Data.ByteString.Char8 as BC
import qualified Filesystem as FS
import Filesystem.Path
import qualified Filesystem.Path.CurrentOS as F
import Network.CGI
import Prelude hiding (FilePath)
import Safe
import System.Argv0
import System.IO hiding (FilePath)
import Text.CSV
import Text.Parsec hiding (getInput, (<|>))
import Str
dataFile :: IO FilePath
dataFile = do
argv0 <- getArgv0
return $ directory argv0 </> F.decodeString "data.csv"
contents :: String -> String
contents body = header ++ body ++ footer
where
header = [str|<html>
<head>
<title>CSV View</title>
</head>
<body>
<h1>CSV View</h1>
<h2>List</h2>
|]
footer = [str|</body>
</html>
|]
makeform :: Record -> Int -> String
makeform header num = [str|<form method="POST" action=".">
<h2>Register</h2>
<table border=1>
|] ++ (h $ tail header) ++ tr (f 1 num) ++ [str|</table>
<br/>
<input type="submit" value="Register">
<input type="reset" value="Clear">
</form>
|]
where
input n = "<input type=\"text\" name=\"f" ++ show n ++ "\">"
f n m
| n <= m = td (input n) ++ f (n+1) m
| otherwise = ""
showTable :: Record -> CSV -> String
showTable header dat = table $ foldl (++) (h header) (map g dat)
where
g [] = ""
g (r:rs) = tr $ foldl (++) "" (map td $ radio r:rs)
table e = [str|<form method="POST" action=".">
<table border=1>
|] ++ e ++ [str|</table>
<input type="hidden" name="delete" value="true">
<input type="submit" value="Delete">
</form>
|]
radio v = "<input type=\"radio\" name=\"id\" value=\"" ++ v ++ "\">"
tr :: String -> String
tr e = "<tr>" ++ e ++ "</tr>\n"
td :: String -> String
td e = "<td>" ++ e ++ "</td>"
th :: String -> String
th e = "<th>" ++ e ++ "</th>"
h :: Record -> String
h [] = ""
h rs = tr $ foldl (++) "" (map th rs)
loadCSV :: IO (Record, CSV, Int)
loadCSV = do
path <- dataFile
FS.withFile path ReadMode $ \file -> do
hline <- hGetLine file
let hres = parse csv "header" $ encodeString hline
header <- either (fail . show) (return . head) hres
other <- hGetContents file
let result = parse csv "csv parse" $ other
csvret <- either (fail . show) (return . initIf (==[""])) result
nid <- maybe (fail "newId Error") return $ newId csvret
return (header, csvret, nid)
where
initIf :: (a -> Bool) -> [a] -> [a]
initIf _ [] = []
initIf f [x]
| f x = []
| otherwise = [x]
initIf f (x:xs) = x:initIf f xs
newId :: CSV -> Maybe Int
newId = newId' 0
where
newId' l [] = Just l
newId' l (f:fs) = headMay f >>= readMay >>= \val ->
if l >= val
then newId' l fs
else newId' val fs
getInput' :: MonadCGI m => String -> MaybeT m String
getInput' query = do
val <- lift $ getInput query
maybe (fail "query not found") return val
getNewRecord :: MonadCGI m => Int -> Int -> MaybeT m Record
getNewRecord newId num = do
record <- getRecord num []
return $ show newId:record
where
getRecord :: MonadCGI m => Int -> [Field] -> MaybeT m Record
getRecord 0 ret = return ret
getRecord n ret = do
field <- getField n
getRecord (n-1) (field:ret)
getField :: MonadCGI m => Int -> MaybeT m Field
getField n = getInput' $ "f" ++ show n
addRecord :: MonadCGI m => Int -> Int -> CSV -> MaybeT m CSV
addRecord num newId records = do
new <- getNewRecord newId num
return $ records ++ [new]
deleteRecord :: MonadCGI m => CSV -> MaybeT m CSV
deleteRecord records = do
getInput' "delete"
delId <- getInput' "id"
maybe (fail "delete id not found") return $ delete records delId
where
delete :: CSV -> String -> Maybe CSV
delete [] _ = Nothing
delete (s:ss) delseq = do
sseq <- headMay s
if sseq == delseq
then Just ss
else (s:) <$> delete ss delseq
update :: Record -> CSV -> IO CSV
update header new = do
let newData = header:new
dataFile >>= (flip FS.writeFile $ BC.pack $ printCSV newData)
return new
main :: IO ()
main = runCGI $ handleCGI (output . contents . show) $ do
(header, dat, lastId) <- liftIO loadCSV
let len = (length header) - 1
ret <- runMaybeT $ addRecord len (lastId + 1) dat <|> deleteRecord dat
dat2 <- maybe (return dat) (liftIO . update header) ret
setHeader "Content-type" "text/html; charset=UTF-8"
output $ contents $ showTable header dat2 ++ makeform header len
where
handleCGI = flip catchCGI
| yunomu/csvedit | src/Main.hs | bsd-3-clause | 4,740 | 11 | 17 | 1,217 | 1,758 | 903 | 855 | 120 | 5 |
module App.Controllers.Home where
import Turbinado.Controller
index :: Controller ()
index = return ()
performance :: Controller ()
performance = return ()
install :: Controller ()
install = return ()
architecture :: Controller ()
architecture= return ()
hello :: Controller ()
hello = clearLayout
-- SPLIT HERE
| abuiles/turbinado-blog | tmp/compiled/App/Controllers/Home.hs | bsd-3-clause | 324 | 0 | 6 | 58 | 108 | 57 | 51 | 12 | 1 |
module Server.Game where
import Haste.App (SessionID)
import Control.Concurrent (modifyMVar_, readMVar, newChan, dupChan, writeChan)
import Data.UUID (toString)
import System.Random
import Data.ByteString.Char8 (ByteString, empty, pack, unpack)
import Crypto.PasswordStore (makePassword, verifyPassword)
import Control.Monad (when)
import qualified Database.Esqueleto as Esql
import Hastings.Utils
import Hastings.ServerUtils
import LobbyTypes
import qualified Hastings.Database.Game as GameDB
import qualified Hastings.Database.Player as PlayerDB
import qualified Hastings.Database.Fields as Fields
-- |Removes a player from it's game
leaveGame :: ConcurrentClientList -> SessionID -> IO ()
leaveGame mVarClients sid = do
clientList <- readMVar mVarClients
dbGame <- GameDB.retrieveGameBySid sid
case dbGame of
Just (Esql.Entity gameKey game) -> do
GameDB.removePlayerFromGame sid gameKey
sessionIds <- GameDB.retrieveSessionIdsInGame gameKey
when (sid == Fields.gameOwner game && (not . null) sessionIds) $
GameDB.setGameOwner gameKey $ head sessionIds
messageClientsWithSid KickedFromGame clientList [sid]
messageClientsWithSid PlayerLeftGame clientList sessionIds
_ -> return ()
createGame :: ConcurrentClientList -> SessionID -> Int -> IO (Maybe String)
createGame mVarClients sid maxPlayers = do
clientList <- readMVar mVarClients
gen <- newStdGen
let (uuid, g) = random gen
let uuidStr = Data.UUID.toString uuid
existingGame <- GameDB.retrieveGameByUUID uuidStr
case existingGame of
Just _ -> return Nothing
Nothing -> do
gameKey <- GameDB.saveGame uuidStr "Game Name" maxPlayers sid $ pack ""
GameDB.addPlayerToGame sid gameKey
messageClients GameAdded clientList
return $ Just uuidStr
-- |Lets a player join a game
playerJoinGame :: ConcurrentClientList -- ^The list of all players connected
-> SessionID -- ^The SessionID of the player
-> String -- ^The UUID of the game to join
-> String -- ^The password of the game, if no password this can be ""
-> IO Bool -- ^Returns if able to join or not
playerJoinGame mVarClients sid gameID passwordString = do
clientList <- readMVar mVarClients
dbGame <- GameDB.retrieveGameByUUID gameID
case dbGame of
Just (Esql.Entity gameKey game) -> do
let passwordOfGame = Fields.gamePassword game
numberOfPlayersInGame <- GameDB.retrieveNumberOfPlayersInGame gameID
if passwordOfGame == empty || verifyPassword (pack passwordString) passwordOfGame
then if Fields.gameMaxAmountOfPlayers game > numberOfPlayersInGame
then do
GameDB.addPlayerToGame sid gameKey
sessionIds <- GameDB.retrieveSessionIdsInGame gameKey
when (length sessionIds == 1) $
GameDB.setGameOwner gameKey sid
messageClientsWithSid PlayerJoinedGame clientList sessionIds
return True
else do
messageClientsWithSid (LobbyError "Game is full") clientList [sid]
return False
else do
messageClientsWithSid (LobbyError "Wrong password") clientList [sid]
return False
_ -> return False
-- |Finds the name of a game given it's identifier
findGameNameWithID :: String -> IO String
findGameNameWithID gameID = do
dbGame <- GameDB.retrieveGameByUUID gameID
case dbGame of
Just (Esql.Entity _ game) -> return $ Fields.gameName game
_ -> return ""
-- |Finds the name of the game the client is currently in
findGameNameWithSid :: SessionID -> IO String
findGameNameWithSid sid = do
dbGame <- GameDB.retrieveGameBySid sid
case dbGame of
Just (Esql.Entity _ game) -> return $ Fields.gameName game
Nothing -> return ""
-- |Finds the name of the players of the game the current client is in
playerNamesInGameWithSid :: SessionID -> IO [String]
playerNamesInGameWithSid sid = do
dbGame <- GameDB.retrieveGameBySid sid
case dbGame of
Just (Esql.Entity gameKey _) -> do
playersInGame <- GameDB.retrievePlayersInGame gameKey
return $ map (Fields.playerUserName . Esql.entityVal) playersInGame
Nothing -> return []
-- |Kicks the player with index 'Int' from the list of players in
-- the game that the current client is in.
kickPlayerWithSid :: ConcurrentClientList -> SessionID -> Name -> IO ()
kickPlayerWithSid mVarClients sid name = do
clientList <- readMVar mVarClients
dbGame <- GameDB.retrieveGameBySid sid
case dbGame of
Nothing -> return ()
Just (Esql.Entity gameKey game) -> do
kickSessionId <- PlayerDB.retrievePlayerSessionId name
case kickSessionId of
Just sessionId -> do
GameDB.removePlayerFromGame sessionId gameKey
sessionIdsInGame <- GameDB.retrieveSessionIdsInGame gameKey
messageClientsWithSid KickedFromGame clientList [sessionId]
messageClientsWithSid PlayerLeftGame clientList sessionIdsInGame
_ -> return ()
-- |Change the name of a 'LobbyGame' that the connected client is in
changeGameNameWithSid :: ConcurrentClientList -> SessionID -> Name -> IO ()
changeGameNameWithSid mVarClients sid newName = do
clientList <- readMVar mVarClients
dbGame <- GameDB.retrieveGameBySid sid
case dbGame of
Nothing -> return ()
Just (Esql.Entity _ game) -> do
GameDB.setNameOnGame (Fields.gameUuid game) newName
messageClients GameNameChange clientList
-- |Changes the maximum number of players for a game
-- Requires that the player is the last in the player list (i.e. the owner)
changeMaxNumberOfPlayers :: SessionID -> Int -> IO ()
changeMaxNumberOfPlayers sid newMax = do
dbGame <- GameDB.retrieveGameBySid sid
case dbGame of
Nothing -> return ()
Just (Esql.Entity _ game) ->
when (sid == Fields.gameOwner game) $
GameDB.setNumberOfPlayersInGame (Fields.gameUuid game) newMax
-- |Sets the password (as a 'ByteString') of the game the client is in.
-- |Only possible if the client is the owner of the game.
setPasswordToGame :: ConcurrentClientList -> SessionID -> String -> IO ()
setPasswordToGame mVarClients sid passwordString = do
let password = pack passwordString
hashedPassword <- makePassword password 17
clientList <- readMVar mVarClients
ownerOfGame <- isOwnerOfGame sid
dbGame <- GameDB.retrieveGameBySid sid
case (dbGame, ownerOfGame) of
(_, False) ->
messageClientsWithSid (LobbyError "Not owner of the game") clientList [sid]
(Just (Esql.Entity _ game), True) ->
GameDB.setPasswordOnGame (Fields.gameUuid game) hashedPassword
-- |Returns True if game is password protected, False otherwise. 'String' is the UUID of the game
isGamePasswordProtected :: String -> IO Bool
isGamePasswordProtected guuid = do
dbGame <- GameDB.retrieveGameByUUID guuid
case dbGame of
Nothing -> return False
Just (Esql.Entity _ game) -> return $ Fields.gamePassword game /= pack ""
startGame :: ConcurrentClientList -> SessionID -> IO ()
startGame mVarClientList sid = do
dbGame <- GameDB.retrieveGameBySid sid
case dbGame of
Nothing -> return ()
Just (Esql.Entity gameKey game) -> do
sids <- GameDB.retrieveSessionIdsInGame gameKey
gameChan <- newChan
modifyMVar_ mVarClientList $ \clientList -> do
mapM
(\c -> do
writeChan (lobbyChannel c) StartGame
duplicateChan <- dupChan gameChan
return c{gameChannel = duplicateChan}
)
clientList
| DATx02-16-14/Hastings | src/Server/Game.hs | bsd-3-clause | 7,813 | 0 | 23 | 1,889 | 1,889 | 903 | 986 | 155 | 4 |
{-
pong - a very simple FunGEn example.
http://www.cin.ufpe.br/~haskell/fungen
Copyright (C) 2001 Andre Furtado <awbf@cin.ufpe.br>
This code 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.
-}
module Main where
import Graphics.UI.Fungen
import Graphics.Rendering.OpenGL (GLdouble)
import Paths_FunGEn (getDataFileName)
data GameAttribute = Score Int
width = 400
height = 400
w = fromIntegral width :: GLdouble
h = fromIntegral height :: GLdouble
main :: IO ()
main = do
texbmp <- getDataFileName "examples/pong/tex.bmp"
let winConfig = WindowConfig { wcPosition = (Point2D 100 80)
, wcSize = (Point2D width height)
, wcName = "A brief example!"
}
bmpList = [(texbmp, Nothing)]
gameMap = textureMap 0 30 30 w h
bar = objectGroup "barGroup" [createBar]
ball = objectGroup "ballGroup" [createBall]
initScore = Score 0
input = [
(SpecialKey KeyRight, StillDown, moveBarToRight)
,(SpecialKey KeyLeft, StillDown, moveBarToLeft)
,(Char 'q', Press, \_ _ -> funExit)
]
funInit winConfig gameMap [bar,ball] () initScore input gameCycle (Timer 30) bmpList
createBall :: GameObject ()
createBall =
let ballPic = Basic (Circle 6.0 0.0 1.0 0.0 Filled)
in object "ball" ballPic False (Point2D (w/2) (h/2)) (Point2D (-8) 8) ()
createBar :: GameObject ()
createBar =
let barBound = map (uncurry Point2D) [(-25,-6),(25,-6),(25,6),(-25,6)]
barPic = Basic (Polyg barBound 1.0 1.0 1.0 Filled)
in object "bar" barPic False (Point2D (w/2) 30) (Point2D 0 0) ()
moveBarToRight :: Modifiers -> Position -> IOGame GameAttribute () () () ()
moveBarToRight _ _ = do
obj <- findObject "bar" "barGroup"
(Point2D pX pY) <- getObjectPosition obj
(Point2D sX _) <- getObjectSize obj
if (pX + (sX/2) + 5 <= w)
then (setObjectPosition (Point2D (pX + 5) pY) obj)
else (setObjectPosition (Point2D (w - (sX/2)) pY) obj)
moveBarToLeft :: Modifiers -> Position -> IOGame GameAttribute () () () ()
moveBarToLeft _ _ = do
obj <- findObject "bar" "barGroup"
(Point2D pX pY) <- getObjectPosition obj
(Point2D sX _) <- getObjectSize obj
if (pX - (sX/2) - 5 >= 0)
then (setObjectPosition (Point2D (pX - 5) pY) obj)
else (setObjectPosition (Point2D (sX/2) pY) obj)
gameCycle :: IOGame GameAttribute () () () ()
gameCycle = do
(Score n) <- getGameAttribute
printOnScreen (show n) TimesRoman24 origin 1.0 1.0 1.0
ball <- findObject "ball" "ballGroup"
col1 <- objectLeftMapCollision ball
col2 <- objectRightMapCollision ball
when (col1 || col2) (reverseXSpeed ball)
col3 <- objectTopMapCollision ball
when col3 (reverseYSpeed ball)
col4 <- objectBottomMapCollision ball
when col4 $ do
-- funExit
setGameAttribute (Score 0)
reverseYSpeed ball
bar <- findObject "bar" "barGroup"
col5 <- objectsCollision ball bar
let (Point2D _ vy) = getGameObjectSpeed ball
when (and [col5, vy < 0]) (do reverseYSpeed ball
setGameAttribute (Score (n + 10)))
showFPS TimesRoman24 (Point2D (w-40) 0) 1.0 0.0 0.0
| jordanemedlock/fungen | examples/pong/pong.hs | bsd-3-clause | 3,390 | 0 | 15 | 880 | 1,183 | 600 | 583 | 70 | 2 |
{-# OPTIONS -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Word
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Unsigned integer types.
--
-----------------------------------------------------------------------------
module Data.Word
(
-- * Unsigned integral types
Word,
Word8, Word16, Word32, Word64,
-- * Notes
-- $notes
) where
import Hugs.Word
{- $notes
* All arithmetic is performed modulo 2^n, where n is the number of
bits in the type. One non-obvious consequence of this is that 'negate'
should /not/ raise an error on negative arguments.
* For coercing between any two integer types, use
'fromIntegral', which is specialized for all the
common cases so should be fast enough. Coercing word types to and
from integer types preserves representation, not sign.
* It would be very natural to add a type 'Natural' providing an unbounded
size unsigned integer, just as 'Integer' provides unbounded
size signed integers. We do not do that yet since there is no demand
for it.
* The rules that hold for 'Enum' instances over a bounded type
such as 'Int' (see the section of the Haskell report dealing
with arithmetic sequences) also hold for the 'Enum' instances
over the various 'Word' types defined here.
* Right and left shifts by amounts greater than or equal to the width
of the type result in a zero result. This is contrary to the
behaviour in C, which is undefined; a common interpretation is to
truncate the shift count to the width of the type, for example @1 \<\<
32 == 1@ in some C implementations.
-}
| OS2World/DEV-UTIL-HUGS | libraries/Data/Word.hs | bsd-3-clause | 1,843 | 6 | 4 | 362 | 53 | 40 | 13 | 6 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Berp.Base.StdTypes.Complex
-- Copyright : (c) 2010 Bernie Pope
-- License : BSD-style
-- Maintainer : florbitous@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- The standard floating point type.
--
-----------------------------------------------------------------------------
module Berp.Base.StdTypes.Complex (complex, complexClass) where
import Data.Complex (Complex (..), realPart, imagPart)
import Berp.Base.Monad (constantIO)
import Berp.Base.Prims (primitive, raise)
import Berp.Base.SemanticTypes (Object (..), Eval)
import Berp.Base.Identity (newIdentity)
import Berp.Base.Attributes (mkAttributesList)
import Berp.Base.StdNames
import Berp.Base.Builtins (notImplementedError)
import Berp.Base.Operators
( addComplexComplexComplex
, addComplexIntComplex
, addComplexFloatComplex
, subComplexComplexComplex
, subComplexIntComplex
, subComplexFloatComplex
, mulComplexComplexComplex
, mulComplexIntComplex
, mulComplexFloatComplex
, divComplexComplexComplex
, divComplexIntComplex
, divComplexFloatComplex
, eqComplexComplexBool
, eqComplexIntBool
, eqComplexFloatBool )
import {-# SOURCE #-} Berp.Base.StdTypes.Type (newType)
import Berp.Base.StdTypes.ObjectBase (objectBase)
import Berp.Base.StdTypes.String (string)
{-# NOINLINE complex #-}
complex :: Complex Double -> Object
complex c = constantIO $ do
identity <- newIdentity
return $ Complex { object_identity = identity, object_complex = c }
{-# NOINLINE complexClass #-}
complexClass :: Object
complexClass = constantIO $ do
dict <- attributes
newType [string "complex", objectBase, dict]
attributes :: IO Object
attributes = mkAttributesList
[ (specialAddName, add)
, (specialSubName, sub)
, (specialMulName, mul)
, (specialDivName, divide)
, (specialEqName, eq)
, (specialStrName, str)
]
mkOp :: (Object -> Object -> Eval Object) ->
(Object -> Object -> Eval Object) ->
(Object -> Object -> Eval Object) ->
Object
mkOp opComplex opFloat opInt = primitive 2 fun
where
fun (x:y:_) =
case y of
Complex {} -> opComplex x y
Float {} -> opFloat x y
Integer {} -> opInt x y
_other -> raise notImplementedError
fun _other = error "operator on Complex applied to wrong number of arguments"
add :: Object
add = mkOp addComplexComplexComplex addComplexFloatComplex addComplexIntComplex
sub :: Object
sub = mkOp subComplexComplexComplex subComplexFloatComplex subComplexIntComplex
mul :: Object
mul = mkOp mulComplexComplexComplex mulComplexFloatComplex mulComplexIntComplex
divide :: Object
divide = mkOp divComplexComplexComplex divComplexFloatComplex divComplexIntComplex
eq :: Object
eq = mkOp eqComplexComplexBool eqComplexFloatBool eqComplexIntBool
str :: Object
str = primitive 1 fun
where
fun (x:_) = return $ string $ showComplex x
fun _other = error "str method on Complex applied to wrong number of arguments"
showComplex :: Object -> String
showComplex obj
| r == 0 = if i < 0 then "-" ++ showImg else showImg
| i < 0 = "(" ++ showR ++ "-" ++ showImg ++ ")"
| otherwise = "(" ++ showR ++ "+" ++ showImg ++ ")"
where
showImg = showI ++ "j"
showI = showNum $ abs i
showR = showNum r
c = object_complex obj
i = imagPart c
r = realPart c
showNum :: Double -> String
showNum n
| fracPart == 0 = show intPart
| otherwise = show n
where
(intPart, fracPart) = properFraction n :: (Integer, Double)
| bjpop/berp | libs/src/Berp/Base/StdTypes/Complex.hs | bsd-3-clause | 3,618 | 0 | 11 | 698 | 908 | 505 | 403 | 88 | 5 |
module Main where
import Control.Arrow ((&&&))
import Control.Applicative ((<$>))
import Data.List (sortBy)
import Data.Ord (comparing)
main :: IO ()
main = do n <- read <$> getLine :: IO Int
input <- map ((\[x,y]->(x,y)). map read . words) . take n . lines <$> getContents ::IO [(Int,Int)]
let l = length input
(hd,lt)= maximum &&& minimum $ map fst input
modus = snd $ sortBy (comparing snd) input !! (l `div` 2)
diffs = map (\x -> abs $ snd x - modus) input
a = abs (hd-lt) + sum diffs
print a
| epsilonhalbe/Sammelsurium | Codingame/NetworkCables/NetworkCables.hs | bsd-3-clause | 597 | 0 | 17 | 193 | 281 | 151 | 130 | 14 | 1 |
/*Owner & Copyrights: Vance King Saxbe. A.*//* Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/{-# Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting, GoldSax Money, GoldSax Treasury, GoldSax Finance, GoldSax Banking and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. This Engagement sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager. LANGUAGE FlexibleContexts, DeriveGeneric #-}
module GoldSaxMachineModule9.Types where
import Control.Monad.Error
import Data.Binary
import GHC.Generics
data Client i = GovOrg { clientId :: i, clientName :: String }
| Company { clientId :: i, clientName :: String
, person :: Person, duty :: String }
| Individual { clientId :: i, person :: Person }
deriving Show
data Person = Person { firstName :: String, lastName :: String }
deriving (Show, Read, Generic)
instance Binary Person
data CompanyNameError = GovOrgArgument | IndividualArgument
companyName :: MonadError CompanyNameError m => Client i -> m String
companyName Company { clientName = n } = return n
companyName GovOrg { } = throwError GovOrgArgument
companyName Individual { } = throwError IndividualArgument
companyNameDef :: MonadError CompanyNameError m => Client i -> m String
companyNameDef c = companyName c `catchError` (\_ -> return "")
/*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/ | VanceKingSaxbeA/GoldSaxMachineStore | GoldSaxMachineModule9/src/Chapter9/Types.hs | mit | 2,109 | 23 | 16 | 396 | 516 | 273 | 243 | -1 | -1 |
z = let f x = do
print "hello"
in f 0
| itchyny/vim-haskell-indent | test/do/let_do.in.hs | mit | 38 | 1 | 10 | 12 | 31 | 12 | 19 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import BackslashPatternTests
import MatchingTests
import ParseTests
import SubpatternTests
import Test.Tasty
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests =
testGroup
""
[ testGroup "Parse" parseTests,
testGroup "Subpatterns" subpatternTests,
testGroup "Backslash patterns" backslashPatterns,
testGroup "Matching" matchingTests
]
| lorcanmcdonald/regexicon | src/Tests/Main.hs | mit | 436 | 0 | 7 | 83 | 87 | 48 | 39 | 17 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : ./MMT/Tools.hs
Description : parse tree produced by MMT
Copyright :
License :
Maintainer : a.jakubauskas@jacobs-university.de
Stability : experimental
Portability :
-}
module MMT.Tools where
import Data.Typeable
-- | identifier is just a string
type Id = String
{- |
tree:
variables
func. application
Maybe( patternName, instanceName)
name
arguments
OR
symbol (0 args)
binding
typed binding
-}
data Tree = Variable Id |
Application Id (Maybe (Id, Id)) [Tree] |
Bind Id Id Tree |
Tbind Id Id Tree Tree deriving (Show, Typeable)
-- declaration - represents instance of pattern
data Decl = Decl Id Id [Tree] deriving (Show, Typeable)
-- signature
data Sign = Sign [Decl] deriving (Show, Typeable)
-- theory
data Theo = Theo {sign :: Sign, axioms :: [Tree]} deriving (Show, Typeable)
| spechub/Hets | MMT/Tools.hs | gpl-2.0 | 892 | 0 | 9 | 194 | 173 | 103 | 70 | 11 | 0 |
<?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="id-ID">
<title>Plug-n-Hack | ZAP Ekstensi</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Isi</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Indeks</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Telusuri</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorit</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_id_ID/helpset_id_ID.hs | apache-2.0 | 968 | 92 | 29 | 159 | 403 | 216 | 187 | -1 | -1 |
{-# LANGUAGE NamedFieldPuns,RecordWildCards #-}
module Example.Regression where
import Text.PrettyPrint.Mainland as PP
import Language.Pads.Syntax
import qualified Language.Pads.Parser as P
import Language.Pads.RegExp
import Text.Parsec.Error
import Language.Pads.Pretty
testParsePadsDecls :: String -> Either ParseError [PadsDecl]
testParsePadsDecls input = P.parsePadsDecls "test" 0 0 input
ppDeclList decls = stack (map ppr decls)
results
= [result1, result2, result3, result4, result5, result6, result7,
result8, result9, result10, result11, result12, result13, result14,
result15, result16, result17, result18, result19, result20, result21,
result22, result23, result24, result25, result26, result27, result28,
result29, result30, result31, result32, result33, result34, result35,
result36, result37, result38, result39, result40, result41, result42,
result43, result44, result45, result46, result47, result48, result49,
result50, result51, result52, result53
]
result = and results
failures = [n | (r,n) <- zip results [1..], not r]
---------------------
t1 = "type MyChar = Char"
pt1 = testParsePadsDecls t1
ppt1 = case pt1 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result1 = t1 == ppt1
t2 = "type IntPair = (Int, '|', Int)"
pt2 = testParsePadsDecls t2
ppt2 = case pt2 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result2 = t2 == ppt2
t3 = "type Bar = (Int, ',', IntPair, ';', Int)"
pt3 = testParsePadsDecls t3
ppt3 = case pt3 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result3 = t3 == ppt3
t4 = "type Bar2 = (Int, ',', (Int, ':', Int), ';', Int)"
pt4 = testParsePadsDecls t4
ppt4 = case pt4 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result4 = t4 == ppt4
t5 = "type BazR = Line (Int, ',', Int)"
pt5 = testParsePadsDecls t5
ppt5 = case pt5 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result5 = t5 == ppt5
t6 = "type StrTy = StringFW <|testStrLen + computeLen 4|>"
pt6 = testParsePadsDecls t6
ppt6 = case pt6 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result6 = t6 == ppt6
t7 = "type StrTy1 = StringC 'o'"
pt7 = testParsePadsDecls t7
ppt7 = case pt7 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result7 = t7 == ppt7
t8 = "type Baz = (StringFW 3, ',', Int)"
pt8 = testParsePadsDecls t8
ppt8 = case pt8 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result8 = t8 == ppt8
t9 = "type StrME = StringME \"a+\""
pt9 = testParsePadsDecls t9
ppt9 = case pt9 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result9 = t9 == ppt9
t10 = "type StrP1 (x :: Int) = StringFW <|x - 1|>"
pt10 = testParsePadsDecls t10
ppt10 = case pt10 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result10 = t10 == ppt10
t11 = "newtype IntRange = IntRange (constrain x :: Int where <|(0 <= x) && (x <= 256)|>)"
pt11 = testParsePadsDecls t11
ppt11 = case pt11 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result11 = t11 == ppt11
t12 = "type IntRangeP (low :: Int, high :: Int) = constrain x :: Int where <|(low <= x) && ((x <= high) && (numErrors x_md == 0))|>"
pt12 = testParsePadsDecls t12
ppt12 = case pt12 of Left e -> show e ; Right r -> pretty 80 (ppDeclList r)
result12 = t12 == ppt12
t13 = "data Record (bound :: Int) = Rec {i1 :: Int, ',', i2 :: Int} where <|(i1 + i2) <= bound|>"
pt13 = testParsePadsDecls t13
ppt13 = case pt13 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result13 = t13 == ppt13
t14 = "data Record2 (bound :: Int) = Rec2 {i1 :: Int, ',', i2 :: Int where <|(i1 + i2) <= bound|>}"
pt14 = testParsePadsDecls t14
ppt14 = case pt14 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result14 = t14 == ppt14
t15 = "data Id = Numeric Int | Alpha (StringC ',')"
pt15 = testParsePadsDecls t15
ppt15 = case pt15 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result15 = t15 == ppt15
t16 = "data Id3 = Numeric3 (IntRangeP <|(1, 10)|>) | Numeric3a Int | Lit3 ','"
pt16 = testParsePadsDecls t16
ppt16 = case pt16 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result16 = t16 == ppt16
t17 = "data Ab_or_a = AB \"ab\" | A \"a\""
pt17 = testParsePadsDecls t17
ppt17 = case pt17 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result17 = t17 == ppt17
t18 = "data AB_test = AB_test {field_AB :: Ab_or_a, 'b'}"
pt18 = testParsePadsDecls t18
ppt18 = case pt18 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result18 = t18 == ppt18
t19 = "data Method = GET | PUT | LINK | UNLINK | POST"
pt19 = testParsePadsDecls t19
ppt19 = case pt19 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result19 = t19 == ppt19
t20 = "data Version = Version {\"HTTP/\", major :: Int, '.', minor :: Int}"
pt20 = testParsePadsDecls t20
ppt20 = case pt20 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result20 = t20 == ppt20
t21 = "data Request = Request {'\"', method :: Method, ' ', url :: StringC ' ', ' ', version :: Version where <|checkVersion method version|>, '\"'}"
pt21 = testParsePadsDecls t21
ppt21 = case pt21 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result21 = t21 == ppt21
t22 = "type Eor_Test = (Int, Eor, Int)"
pt22 = testParsePadsDecls t22
ppt22 = case pt22 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result22 = t22 == ppt22
t23 = "type Eof_Test = (Int, Eor, Int, Eof)"
pt23 = testParsePadsDecls t23
ppt23 = case pt23 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result23 = t23 == ppt23
t24 = "type Opt_test = (Int, '|', Maybe Int, '|', Int)"
pt24 = testParsePadsDecls t24
ppt24 = case pt24 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result24 = t24 == ppt24
t25 = "type Entries_nosep_noterm = [StringFW 3]"
pt25 = testParsePadsDecls t25
ppt25 = case pt25 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result25 = t25 == ppt25
t26 = "type Entries_nosep_noterm2 = [Char]"
pt26 = testParsePadsDecls t26
ppt26 = case pt26 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result26 = t26 == ppt26
t27 = "type EvenInt = constrain x :: Digit where <|(x `mod` 2) == 0|>"
pt27 = testParsePadsDecls t27
ppt27 = case pt27 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result27 = t27 == ppt27
t28 = "type DigitList = [Digit | ',']"
pt28 = testParsePadsDecls t28
ppt28 = case pt28 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result28 = t28 == ppt28
t29 = "type DigitListLen (x :: Int) = [Digit] length <|x + 1|>"
pt29 = testParsePadsDecls t29
ppt29 = case pt29 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result29 = t29 == ppt29
t30 = "type DigitListLenSep (x :: Int) = [Digit | \"ab\"] length <|x + 1|>"
pt30 = testParsePadsDecls t30
ppt30 = case pt30 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result30 = t30 == ppt30
t31 = "type DigitListTerm = [Digit] terminator Eor"
pt31 = testParsePadsDecls t31
ppt31 = case pt31 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result31 = t31 == ppt31
t32 = "type DigitListTermSep = [Digit | '|'] terminator ';'"
pt32 = testParsePadsDecls t32
ppt32 = case pt32 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result32 = t32 == ppt32
t33 = "type TryTest = (Try Char, StringFW 3)"
pt33 = testParsePadsDecls t33
ppt33 = case pt33 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result33 = t33 == ppt33
t34 = "type ListWithTry = ([Char] terminator Try Digit, Digit)"
pt34 = testParsePadsDecls t34
ppt34 = case pt34 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result34 = t34 == ppt34
t35 = "type WithVoid = (Char, ',', Void, '|')"
pt35 = testParsePadsDecls t35
ppt35 = case pt35 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result35 = t35 == ppt35
t36 = "data VoidOpt = PDigit Digit | Pcolor \"red\" | Pnothing Void"
pt36 = testParsePadsDecls t36
ppt36 = case pt36 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result36 = t36 == ppt36
t37 = "type VoidEntry = (VoidOpt, StringFW 3)"
pt37 = testParsePadsDecls t37
ppt37 = case pt37 of Left e -> show e ; Right r -> pretty 100 (ppDeclList r)
result37 = t37 == ppt37
t38 = "data Switch (which :: Int) = case which of 0 -> Even Int where <|(even `mod` 2) == 0|> | 1 -> Comma ',' | otherwise -> Missing Void"
pt38 = testParsePadsDecls t38
ppt38 = case pt38 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result38 = t38 == ppt38
t39 = "data MyBody (which :: Int) = case which of 0 -> First Int | 1 -> Second (StringC ',') | otherwise -> Other Void"
pt39 = testParsePadsDecls t39
ppt39 = case pt39 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result39 = t39 == ppt39
t40 = "data MyEntry = MyEntry {header :: Int, ',', body :: MyBody header, ',', trailer :: Char}"
pt40 = testParsePadsDecls t40
ppt40 = case pt40 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result40 = t40 == ppt40
t41 = "type MyData = [Line MyEntry] terminator Eof"
pt41 = testParsePadsDecls t41
ppt41 = case pt41 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result41 = t41 == ppt41
t42 = "data HP = HP {student_num :: Int, ',', student_name :: StringFW <|pintToInt student_num|>}"
pt42 = testParsePadsDecls t42
ppt42 = case pt42 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result42 = t42 == ppt42
t43 = "type HP_data = [Line HP]"
pt43 = testParsePadsDecls t43
ppt43 = case pt43 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result43 = t43 == ppt43
acomma = ','
t44 = "data LitRec = LitRec {fstField :: Int, acomma, sndField :: Int}"
-- "data LitRec = LitRec {fstField :: Int, acomma :: Int, sndField :: Int}"
pt44 = testParsePadsDecls t44
-- Urgh. Parses as multiple Int fields.
ppt44 = case pt44 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result44 = t44 == ppt44
t45 = "type WhiteSpace = (Int, '[ \\t]+', Int)"
pt45 = testParsePadsDecls t45
ppt45 = case pt45 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result45 = t45 == ppt45
ws = RE "[ \t]+"
t46 = "type WhiteSpace2 = (Int, ws, Int)"
pt46 = testParsePadsDecls t46
ppt46 = case pt46 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result46 = t46 == ppt46
t47 = "type RE_ty = (Pre \"[tod]\", ws, Pre \"a+\")"
pt47 = testParsePadsDecls t47
ppt47 = case pt47 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result47 = t47 == ppt47
t48 = "type Pstringln = Line (constrain x :: PstringSE \"$\" where True)"
pt48 = testParsePadsDecls t48
ppt48 = case pt48 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result48 = t48 == ppt48
t49 = "type Phex32FW (size :: Int) = transform StringFW size => Int using <|(hexStr2Int, int2HexStr size)|>"
pt49 = testParsePadsDecls t49
ppt49 = case pt49 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result49 = t49 == ppt49
t50 = "type Int = transform StringME \"[0..9]+\" => Int using <|(s2i, i2s)|>"
pt50 = testParsePadsDecls t50
ppt50 = case pt50 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result50 = t50 == ppt50
t51 = "type Char = transform StringFW 1 => Char using <|(head, \\x -> [x])|>"
pt51 = testParsePadsDecls t51
ppt51 = case pt51 of Left e -> show e ; Right r -> pretty 151 (ppDeclList r)
result51 = t51 == ppt51
t52 = "type Fun a b = transform b => (a -> b) using <|(const, \\f -> f def)|>"
t52' = "type Fun a b = transform b => (->) a b using <|(const, \\f -> f def)|>"
pt52 = testParsePadsDecls t52
ppt52 = case pt52 of Left e -> show e ; Right r -> pretty 152 (ppDeclList r)
result52 = t52' == ppt52
t53 = "type StrTy = PstringFW <|testStrLen + computeLen 4|>"
pt53 = testParsePadsDecls t53
ppt53 = case pt53 of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result53 = t53 == ppt53
t54 = "data HP = HP {student_num :: Pint, ',', student_name :: PstringFW <|pintToInt student_num|>}\ntype HP_data = [Line HP]"
pt54 = testParsePadsDecls t54
ppt54 = case pt54 of Left e -> show e ; Right r -> pretty 250 (ppDeclList r)
result54 = t54 == ppt54
(t55,pt55,ppt55,result55) = (t,pt,ppt,result)
where
t = "newtype Void = Void ()"
pt = testParsePadsDecls t
ppt = case pt of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result = t == ppt
(t56,pt56,ppt56,result56) = (t,pt,ppt,result)
where
t = "type Foo = Baz '[a-z+]'"
pt = testParsePadsDecls t
ppt = case pt of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result = t == ppt
(t57,pt57,ppt57,result57) = (t,pt,ppt,result)
where
t = "type BazR = Line (Pint, ',', Pint)"
pt = testParsePadsDecls t
ppt = case pt of Left e -> show e ; Right r -> pretty 150 (ppDeclList r)
result = t == ppt
| GaloisInc/pads-haskell | Examples/Regression.hs | bsd-3-clause | 12,719 | 0 | 12 | 2,662 | 4,077 | 2,091 | 1,986 | 256 | 2 |
{-# LANGUAGE CPP, DeriveGeneric, FlexibleInstances, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Representation of dice for parameters scaled with current level depth.
module Game.LambdaHack.Common.Dice
( -- * Frequency distribution for casting dice scaled with level depth
Dice, diceConst, diceLevel, diceMult, (|*|)
, d, ds, dl, intToDice
, maxDice, minDice, meanDice, reduceDice
-- * Dice for rolling a pair of integer parameters representing coordinates.
, DiceXY(..), maxDiceXY, minDiceXY, meanDiceXY
#ifdef EXPOSE_INTERNAL
-- * Internal operations
, SimpleDice
#endif
) where
import Control.Applicative
import Control.DeepSeq
import Data.Binary
import qualified Data.Char as Char
import Data.Hashable (Hashable)
import qualified Data.IntMap.Strict as IM
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Data.Tuple
import GHC.Generics (Generic)
import Game.LambdaHack.Common.Frequency
import Game.LambdaHack.Common.Msg
type SimpleDice = Frequency Int
normalizeSimple :: SimpleDice -> SimpleDice
normalizeSimple fr = toFreq (nameFrequency fr)
$ map swap $ IM.toAscList $ IM.fromListWith (+)
$ map swap $ runFrequency fr
-- Normalized mainly as an optimization, but it also makes many expected
-- algebraic laws hold (wrt @Eq@), except for some laws about
-- multiplication. We use @liftA2@ instead of @liftM2@, because it's probably
-- faster in this case.
instance Num SimpleDice where
fr1 + fr2 = normalizeSimple $ liftA2AdditiveName "+" (+) fr1 fr2
fr1 * fr2 =
let frRes = normalizeSimple $ do
n <- fr1
sum $ replicate n fr2 -- not commutative!
nameRes =
case T.uncons $ nameFrequency fr2 of
_ | nameFrequency fr1 == "0" || nameFrequency fr2 == "0" -> "0"
Just ('d', _) | T.all Char.isDigit $ nameFrequency fr1 ->
nameFrequency fr1 <> nameFrequency fr2
_ -> nameFrequency fr1 <+> "*" <+> nameFrequency fr2
in renameFreq nameRes frRes
fr1 - fr2 = normalizeSimple $ liftA2AdditiveName "-" (-) fr1 fr2
negate = liftAName "-" negate
abs = normalizeSimple . liftAName "abs" abs
signum = normalizeSimple . liftAName "signum" signum
fromInteger n = renameFreq (tshow n) $ pure $ fromInteger n
liftAName :: Text -> (Int -> Int) -> SimpleDice -> SimpleDice
liftAName name f fr =
let frRes = liftA f fr
nameRes = name <> " (" <> nameFrequency fr <> ")"
in renameFreq nameRes frRes
liftA2AdditiveName :: Text
-> (Int -> Int -> Int)
-> SimpleDice -> SimpleDice -> SimpleDice
liftA2AdditiveName name f fra frb =
let frRes = liftA2 f fra frb
nameRes
| nameFrequency fra == "0" =
(if name == "+" then "" else name) <+> nameFrequency frb
| nameFrequency frb == "0" = nameFrequency fra
| otherwise = nameFrequency fra <+> name <+> nameFrequency frb
in renameFreq nameRes frRes
dieSimple :: Int -> SimpleDice
dieSimple n = uniformFreq ("d" <> tshow n) [1..n]
zdieSimple :: Int -> SimpleDice
zdieSimple n = uniformFreq ("z" <> tshow n) [0..n-1]
dieLevelSimple :: Int -> SimpleDice
dieLevelSimple n = uniformFreq ("ds" <> tshow n) [1..n]
zdieLevelSimple :: Int -> SimpleDice
zdieLevelSimple n = uniformFreq ("zl" <> tshow n) [0..n-1]
-- | Dice for parameters scaled with current level depth.
-- To the result of rolling the first set of dice we add the second,
-- scaled in proportion to current depth divided by maximal dungeon depth.
-- The result if then multiplied by the scale --- to be used to ensure
-- that dice results are multiples of, e.g., 10. The scale is set with @|*|@.
data Dice = Dice
{ diceConst :: SimpleDice
, diceLevel :: SimpleDice
, diceMult :: Int
}
deriving (Read, Eq, Ord, Generic)
-- Read and Show should be inverses in this case.
instance Show Dice where
show Dice{..} = T.unpack $
let rawMult = nameFrequency diceLevel
scaled = if rawMult == "0" then "" else rawMult
signAndMult = case T.uncons scaled of
Just ('-', _) -> scaled
_ -> "+" <+> scaled
in (if nameFrequency diceLevel == "0" then nameFrequency diceConst
else if nameFrequency diceConst == "0" then scaled
else nameFrequency diceConst <+> signAndMult)
<+> if diceMult == 1 then "" else "|*|" <+> tshow diceMult
instance Hashable Dice
instance Binary Dice
instance NFData Dice
instance Num Dice where
(Dice dc1 dl1 ds1) + (Dice dc2 dl2 ds2) =
Dice (scaleFreq ds1 dc1 + scaleFreq ds2 dc2)
(scaleFreq ds1 dl1 + scaleFreq ds2 dl2)
1
(Dice dc1 dl1 ds1) * (Dice dc2 dl2 ds2) =
-- Hacky, but necessary (unless we forgo general multiplication and
-- stick to multiplications by a scalar from the left and from the right).
-- The pseudo-reasoning goes (remember the multiplication
-- is not commutative, so we take all kinds of liberties):
-- (dc1 + dl1 * l) * (dc2 + dl2 * l)
-- = dc1 * dc2 + dc1 * dl2 * l + dl1 * l * dc2 + dl1 * l * dl2 * l
-- = dc1 * dc2 + (dc1 * dl2) * l + (dl1 * dc2) * l + (dl1 * dl2) * l * l
-- Now, we don't have a slot to put the coefficient of l * l into
-- (and we don't know l yet, so we can't eliminate it by division),
-- so we happily ignore it. Done. It works well in the cases that interest
-- us, that is, multiplication by a scalar (a one-element frequency
-- distribution) from any side, unscaled and scaled by level depth
-- (but when we multiply two scaled scalars, we get 0).
Dice (scaleFreq ds1 dc1 * scaleFreq ds2 dc2)
(scaleFreq ds1 dc1 * scaleFreq ds2 dl2
+ scaleFreq ds1 dl1 * scaleFreq ds2 dc2)
1
(Dice dc1 dl1 ds1) - (Dice dc2 dl2 ds2) =
Dice (scaleFreq ds1 dc1 - scaleFreq ds2 dc2)
(scaleFreq ds1 dl1 - scaleFreq ds2 dl2)
1
negate = affectBothDice negate
abs = affectBothDice abs
signum = affectBothDice signum
fromInteger n = Dice (fromInteger n) 0 1
affectBothDice :: (SimpleDice -> SimpleDice) -> Dice -> Dice
affectBothDice f (Dice dc1 dl1 ds1) = Dice (f dc1) (f dl1) ds1
-- | A single simple dice.
d :: Int -> Dice
d n = Dice (dieSimple n) 0 1
-- | Dice scaled with level.
ds :: Int -> Dice
ds n = Dice 0 (dieLevelSimple n) 1
dl :: Int -> Dice
dl = ds
-- Not exposed to save on documentation.
_z :: Int -> Dice
_z n = Dice (zdieSimple n) 0 1
_zl :: Int -> Dice
_zl n = Dice 0 (zdieLevelSimple n) 1
intToDice :: Int -> Dice
intToDice = fromInteger . fromIntegral
infixl 5 |*|
-- | Multiplying the dice, after all randomness is resolved, by a constant.
-- Infix declaration ensures that @1 + 2 |*| 3@ parses as @(1 + 2) |*| 3@.
(|*|) :: Dice -> Int -> Dice
Dice dc1 dl1 ds1 |*| s2 = Dice dc1 dl1 (ds1 * s2)
-- | Maximal value of dice. The scaled part taken assuming maximum level.
maxDice :: Dice -> Int
maxDice Dice{..} = (fromMaybe 0 (maxFreq diceConst)
+ fromMaybe 0 (maxFreq diceLevel))
* diceMult
-- | Minimal value of dice. The scaled part ignored.
minDice :: Dice -> Int
minDice Dice{..} = fromMaybe 0 (minFreq diceConst) * diceMult
-- | Mean value of dice. The level-dependent part is taken assuming
-- the highest level, because that's where the game is the hardest.
-- Assumes the frequencies are not null.
meanDice :: Dice -> Int
meanDice Dice{..} = (meanFreq diceConst + meanFreq diceLevel) * diceMult
reduceDice :: Dice -> Maybe Int
reduceDice de =
let minD = minDice de
in if minD == maxDice de then Just minD else Nothing
-- | Dice for rolling a pair of integer parameters pertaining to,
-- respectively, the X and Y cartesian 2D coordinates.
data DiceXY = DiceXY !Dice !Dice
deriving (Show, Eq, Ord, Generic)
instance Hashable DiceXY
instance Binary DiceXY
-- | Maximal value of DiceXY.
maxDiceXY :: DiceXY -> (Int, Int)
maxDiceXY (DiceXY x y) = (maxDice x, maxDice y)
-- | Minimal value of DiceXY.
minDiceXY :: DiceXY -> (Int, Int)
minDiceXY (DiceXY x y) = (minDice x, minDice y)
-- | Mean value of DiceXY.
meanDiceXY :: DiceXY -> (Int, Int)
meanDiceXY (DiceXY x y) = (meanDice x, meanDice y)
| Concomitant/LambdaHack | Game/LambdaHack/Common/Dice.hs | bsd-3-clause | 8,157 | 0 | 19 | 1,912 | 2,099 | 1,092 | 1,007 | -1 | -1 |
module Data.MExtraChan where
import Control.Applicative
import Control.Concurrent.MVar
import Control.Concurrent.Chan
data ExtraChan a = ExtraChan { chan :: Chan a
, minEver :: MVar a
, maxEver :: MVar a
, lLength :: MVar Int
}
newExtraChan :: (Bounded a) => IO (ExtraChan a)
newExtraChan = ExtraChan
<$> newChan
<*> newMVar maxBound
<*> newMVar minBound
<*> newMVar 0
writeExtraChan :: (Ord a) => ExtraChan a -> a -> IO ()
writeExtraChan c a = do
oldMin <- takeMVar (minEver c)
oldMax <- takeMVar (maxEver c)
oldLen <- takeMVar (lLength c)
writeChan (chan c) a
putMVar (lLength c) (succ oldLen)
putMVar (maxEver c) (max oldMax a)
putMVar (minEver c) (min oldMin a)
readExtraChan :: (Ord a) => ExtraChan a -> IO a
readExtraChan c = do
len <- takeMVar (lLength c)
a <- readChan $ chan c
putMVar (lLength c) (len - 1)
return a
readExtraChan' :: (Ord a) => ExtraChan a -> IO a
readExtraChan' c = do
a <- readChan $ chan c
l <- takeMVar (lLength c)
putMVar (lLength c) (l - 1)
return a
extraChanLength :: ExtraChan a -> IO Int
extraChanLength c = readMVar (lLength c)
chanInfo :: (Show a) => ExtraChan a -> IO String
chanInfo c = do
xs <- getChanContents (chan c)
min' <- readMVar (minEver c)
max' <- readMVar (maxEver c)
len' <- readMVar (lLength c)
return $ unwords ["Vals:", show xs
,"Min:", show min'
,"Max:", show max'
,"Len:", show len'
] | imalsogreg/stm-demo | Data/MExtraChan.hs | bsd-3-clause | 1,650 | 0 | 10 | 548 | 640 | 308 | 332 | 47 | 1 |
-- |
-- Module : Data.Hourglass.Time
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
-- generic time representation interface to allow
-- arbitrary conversion between different time representation
--
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.Hourglass.Time
(
-- * Generic time classes
Time(..)
, Timeable(..)
-- * Elapsed time
, Elapsed(..)
, ElapsedP(..)
-- * Generic conversion
, timeConvert
-- * Date and Time
, timeGetDate
, timeGetDateTimeOfDay
, timeGetTimeOfDay
-- * Arithmetic
, Duration(..)
, Period(..)
, TimeInterval(..)
, timeAdd
, timeDiff
, timeDiffP
, dateAddPeriod
) where
import Data.Data ()
import Data.Hourglass.Types
import Data.Hourglass.Calendar
import Data.Hourglass.Diff
import Foreign.C.Types (CTime(..))
-- | Timeable represent every type that can be made to look like time types.
--
-- * can be converted to ElapsedP and Elapsed
--
-- * optionally have a timezone associated
--
-- * have nanoseconds accessor (which can return 0 when the type is not more precise than seconds)
--
class Timeable t where
-- | convert a time representation to the number of elapsed seconds and nanoseconds to a specific epoch
timeGetElapsedP :: t -> ElapsedP
-- | convert a time representation to the number of elapsed seconds to a specific epoch.
--
-- defaults to timeGetElapsedP unless defined explicitely by an instance
timeGetElapsed :: t -> Elapsed
timeGetElapsed t = e where ElapsedP e _ = timeGetElapsedP t
-- | return the number of optional nanoseconds.
--
-- If the underlaying type is not precise enough to record nanoseconds
-- (or any variant between seconds and nanoseconds), 0 should be returned
--
-- defaults to 'timeGetElapsedP' unless defined explicitely by an instance,
-- for efficiency reason, it's a good idea to override this methods if
-- you know the type is not more precise than Seconds.
timeGetNanoSeconds :: t -> NanoSeconds
timeGetNanoSeconds t = ns where ElapsedP _ ns = timeGetElapsedP t
-- | Represent time types that can be created from other time types.
--
-- Every conversion happens throught ElapsedP or Elapsed types.
class Timeable t => Time t where
-- | convert from a number of elapsed seconds and nanoseconds to another time representation
timeFromElapsedP :: ElapsedP -> t
-- | convert from a number of elapsed seconds and nanoseconds to another time representation
--
-- defaults to timeFromElapsedP unless defined explicitely by an instance.
timeFromElapsed :: Elapsed -> t
timeFromElapsed e = timeFromElapsedP (ElapsedP e 0)
#if (MIN_VERSION_base(4,5,0))
instance Timeable CTime where
timeGetElapsedP c = ElapsedP (timeGetElapsed c) 0
timeGetElapsed (CTime c) = Elapsed (Seconds $ fromIntegral c)
timeGetNanoSeconds _ = 0
instance Time CTime where
timeFromElapsedP (ElapsedP e _) = timeFromElapsed e
timeFromElapsed (Elapsed (Seconds c)) = CTime (fromIntegral c)
#endif
instance Timeable Elapsed where
timeGetElapsedP e = ElapsedP e 0
timeGetElapsed e = e
timeGetNanoSeconds _ = 0
instance Time Elapsed where
timeFromElapsedP (ElapsedP e _) = e
timeFromElapsed e = e
instance Timeable ElapsedP where
timeGetElapsedP e = e
timeGetNanoSeconds (ElapsedP _ ns) = ns
instance Time ElapsedP where
timeFromElapsedP e = e
instance Timeable Date where
timeGetElapsedP d = timeGetElapsedP (DateTime d (TimeOfDay 0 0 0 0))
instance Time Date where
timeFromElapsedP (ElapsedP elapsed _) = d
where (DateTime d _) = dateTimeFromUnixEpoch elapsed
instance Timeable DateTime where
timeGetElapsedP d = ElapsedP (dateTimeToUnixEpoch d) (timeGetNanoSeconds d)
timeGetElapsed d = dateTimeToUnixEpoch d
timeGetNanoSeconds (DateTime _ (TimeOfDay _ _ _ ns)) = ns
instance Time DateTime where
timeFromElapsedP elapsed = dateTimeFromUnixEpochP elapsed
-- | Convert one time representation into another one
--
-- The return type need to be infer by the context.
--
-- If the context cannot be infer through this, some specialized functions
-- are available for built-in types:
--
-- * 'timeGetDate'
--
-- * 'timeGetDateTimeOfDay'
--
-- * 'timeGetElapsed', 'timeGetElapsedP'
timeConvert :: (Timeable t1, Time t2) => t1 -> t2
timeConvert t1 = timeFromElapsedP (timeGetElapsedP t1)
{-# INLINE[2] timeConvert #-}
{-# RULES "timeConvert/ID" timeConvert = id #-}
{-# RULES "timeConvert/ElapsedP" timeConvert = timeGetElapsedP #-}
{-# RULES "timeConvert/Elapsed" timeConvert = timeGetElapsed #-}
-- | Get the calendar Date (year-month-day) from a time representation
--
-- specialization of 'timeConvert'
timeGetDate :: Timeable t => t -> Date
timeGetDate t = d where (DateTime d _) = timeGetDateTimeOfDay t
{-# INLINE[2] timeGetDate #-}
{-# RULES "timeGetDate/ID" timeGetDate = id #-}
{-# RULES "timeGetDate/DateTime" timeGetDate = dtDate #-}
-- | Get the day time (hours:minutes:seconds) from a time representation
--
-- specialization of 'timeConvert'
timeGetTimeOfDay :: Timeable t => t -> TimeOfDay
timeGetTimeOfDay t = tod where (DateTime _ tod) = timeGetDateTimeOfDay t
{-# INLINE[2] timeGetTimeOfDay #-}
{-# RULES "timeGetTimeOfDay/Date" timeGetTimeOfDay = const (TimeOfDay 0 0 0 0) #-}
{-# RULES "timeGetTimeOfDay/DateTime" timeGetTimeOfDay = dtTime #-}
-- | Get the date and time of day from a time representation
--
-- specialization of 'timeConvert'
timeGetDateTimeOfDay :: Timeable t => t -> DateTime
timeGetDateTimeOfDay t = dateTimeFromUnixEpochP $ timeGetElapsedP t
{-# INLINE[2] timeGetDateTimeOfDay #-}
{-# RULES "timeGetDateTimeOfDay/ID" timeGetDateTimeOfDay = id #-}
{-# RULES "timeGetDateTimeOfDay/Date" timeGetDateTimeOfDay = flip DateTime (TimeOfDay 0 0 0 0) #-}
-- | add some time interval to a time representation and returns this new time representation
--
-- example:
--
-- > t1 `timeAdd` mempty { durationHours = 12 }
timeAdd :: (Time t, TimeInterval ti) => t -> ti -> t
timeAdd t ti = timeFromElapsedP $ elapsedTimeAddSecondsP (timeGetElapsedP t) (toSeconds ti)
-- | Get the difference in seconds between two time representation
--
-- effectively:
--
-- > t2 `timeDiff` t1 = t2 - t1
timeDiff :: (Timeable t1, Timeable t2) => t1 -> t2 -> Seconds
timeDiff t1 t2 = sec where (Elapsed sec) = timeGetElapsed t1 - timeGetElapsed t2
-- | Get the difference in seconds and nanoseconds between two time representation
--
-- effectively:
--
-- > @t2 `timeDiffP` t1 = t2 - t1
timeDiffP :: (Timeable t1, Timeable t2) => t1 -> t2 -> (Seconds, NanoSeconds)
timeDiffP t1 t2 = (sec, ns)
where (ElapsedP (Elapsed sec) ns) = timeGetElapsedP t1 - timeGetElapsedP t2
| ppelleti/hs-hourglass | Data/Hourglass/Time.hs | bsd-3-clause | 6,955 | 0 | 10 | 1,367 | 1,126 | 629 | 497 | 87 | 1 |
{-# LANGUAGE CPP, GADTs, RankNTypes #-}
-----------------------------------------------------------------------------
--
-- Cmm utilities.
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module CmmUtils(
-- CmmType
primRepCmmType, slotCmmType, slotForeignHint,
typeCmmType, typeForeignHint,
-- CmmLit
zeroCLit, mkIntCLit,
mkWordCLit, packHalfWordsCLit,
mkByteStringCLit,
mkDataLits, mkRODataLits,
mkStgWordCLit,
-- CmmExpr
mkIntExpr, zeroExpr,
mkLblExpr,
cmmRegOff, cmmOffset, cmmLabelOff, cmmOffsetLit, cmmOffsetExpr,
cmmRegOffB, cmmOffsetB, cmmLabelOffB, cmmOffsetLitB, cmmOffsetExprB,
cmmRegOffW, cmmOffsetW, cmmLabelOffW, cmmOffsetLitW, cmmOffsetExprW,
cmmIndex, cmmIndexExpr, cmmLoadIndex, cmmLoadIndexW,
cmmNegate,
cmmULtWord, cmmUGeWord, cmmUGtWord, cmmUShrWord,
cmmSLtWord,
cmmNeWord, cmmEqWord,
cmmOrWord, cmmAndWord,
cmmSubWord, cmmAddWord, cmmMulWord, cmmQuotWord,
cmmToWord,
isTrivialCmmExpr, hasNoGlobalRegs,
-- Statics
blankWord,
-- Tagging
cmmTagMask, cmmPointerMask, cmmUntag, cmmIsTagged,
cmmConstrTag1,
-- Overlap and usage
regsOverlap, regUsedIn,
-- Liveness and bitmaps
mkLiveness,
-- * Operations that probably don't belong here
modifyGraph,
ofBlockMap, toBlockMap, insertBlock,
ofBlockList, toBlockList, bodyToBlockList,
toBlockListEntryFirst, toBlockListEntryFirstFalseFallthrough,
foldGraphBlocks, mapGraphNodes, postorderDfs, mapGraphNodes1,
analFwd, analBwd, analRewFwd, analRewBwd,
dataflowPassFwd, dataflowPassBwd, dataflowAnalFwd, dataflowAnalBwd,
dataflowAnalFwdBlocks,
-- * Ticks
blockTicks
) where
#include "HsVersions.h"
import TyCon ( PrimRep(..), PrimElemRep(..) )
import RepType ( UnaryType, SlotTy (..), typePrimRep )
import SMRep
import Cmm
import BlockId
import CLabel
import Outputable
import Unique
import UniqSupply
import DynFlags
import Util
import CodeGen.Platform
import Data.Word
import Data.Maybe
import Data.Bits
import Hoopl
---------------------------------------------------
--
-- CmmTypes
--
---------------------------------------------------
primRepCmmType :: DynFlags -> PrimRep -> CmmType
primRepCmmType _ VoidRep = panic "primRepCmmType:VoidRep"
primRepCmmType dflags PtrRep = gcWord dflags
primRepCmmType dflags IntRep = bWord dflags
primRepCmmType dflags WordRep = bWord dflags
primRepCmmType _ Int64Rep = b64
primRepCmmType _ Word64Rep = b64
primRepCmmType dflags AddrRep = bWord dflags
primRepCmmType _ FloatRep = f32
primRepCmmType _ DoubleRep = f64
primRepCmmType _ (VecRep len rep) = vec len (primElemRepCmmType rep)
slotCmmType :: DynFlags -> SlotTy -> CmmType
slotCmmType dflags PtrSlot = gcWord dflags
slotCmmType dflags WordSlot = bWord dflags
slotCmmType _ Word64Slot = b64
slotCmmType _ FloatSlot = f32
slotCmmType _ DoubleSlot = f64
primElemRepCmmType :: PrimElemRep -> CmmType
primElemRepCmmType Int8ElemRep = b8
primElemRepCmmType Int16ElemRep = b16
primElemRepCmmType Int32ElemRep = b32
primElemRepCmmType Int64ElemRep = b64
primElemRepCmmType Word8ElemRep = b8
primElemRepCmmType Word16ElemRep = b16
primElemRepCmmType Word32ElemRep = b32
primElemRepCmmType Word64ElemRep = b64
primElemRepCmmType FloatElemRep = f32
primElemRepCmmType DoubleElemRep = f64
typeCmmType :: DynFlags -> UnaryType -> CmmType
typeCmmType dflags ty = primRepCmmType dflags (typePrimRep ty)
primRepForeignHint :: PrimRep -> ForeignHint
primRepForeignHint VoidRep = panic "primRepForeignHint:VoidRep"
primRepForeignHint PtrRep = AddrHint
primRepForeignHint IntRep = SignedHint
primRepForeignHint WordRep = NoHint
primRepForeignHint Int64Rep = SignedHint
primRepForeignHint Word64Rep = NoHint
primRepForeignHint AddrRep = AddrHint -- NB! AddrHint, but NonPtrArg
primRepForeignHint FloatRep = NoHint
primRepForeignHint DoubleRep = NoHint
primRepForeignHint (VecRep {}) = NoHint
slotForeignHint :: SlotTy -> ForeignHint
slotForeignHint PtrSlot = AddrHint
slotForeignHint WordSlot = NoHint
slotForeignHint Word64Slot = NoHint
slotForeignHint FloatSlot = NoHint
slotForeignHint DoubleSlot = NoHint
typeForeignHint :: UnaryType -> ForeignHint
typeForeignHint = primRepForeignHint . typePrimRep
---------------------------------------------------
--
-- CmmLit
--
---------------------------------------------------
-- XXX: should really be Integer, since Int doesn't necessarily cover
-- the full range of target Ints.
mkIntCLit :: DynFlags -> Int -> CmmLit
mkIntCLit dflags i = CmmInt (toInteger i) (wordWidth dflags)
mkIntExpr :: DynFlags -> Int -> CmmExpr
mkIntExpr dflags i = CmmLit $! mkIntCLit dflags i
zeroCLit :: DynFlags -> CmmLit
zeroCLit dflags = CmmInt 0 (wordWidth dflags)
zeroExpr :: DynFlags -> CmmExpr
zeroExpr dflags = CmmLit (zeroCLit dflags)
mkWordCLit :: DynFlags -> Integer -> CmmLit
mkWordCLit dflags wd = CmmInt wd (wordWidth dflags)
mkByteStringCLit :: Unique -> [Word8] -> (CmmLit, GenCmmDecl CmmStatics info stmt)
-- We have to make a top-level decl for the string,
-- and return a literal pointing to it
mkByteStringCLit uniq bytes
= (CmmLabel lbl, CmmData sec $ Statics lbl [CmmString bytes])
where
lbl = mkStringLitLabel uniq
sec = Section ReadOnlyData lbl
mkDataLits :: Section -> CLabel -> [CmmLit] -> GenCmmDecl CmmStatics info stmt
-- Build a data-segment data block
mkDataLits section lbl lits
= CmmData section (Statics lbl $ map CmmStaticLit lits)
mkRODataLits :: CLabel -> [CmmLit] -> GenCmmDecl CmmStatics info stmt
-- Build a read-only data block
mkRODataLits lbl lits
= mkDataLits section lbl lits
where
section | any needsRelocation lits = Section RelocatableReadOnlyData lbl
| otherwise = Section ReadOnlyData lbl
needsRelocation (CmmLabel _) = True
needsRelocation (CmmLabelOff _ _) = True
needsRelocation _ = False
mkStgWordCLit :: DynFlags -> StgWord -> CmmLit
mkStgWordCLit dflags wd = CmmInt (fromStgWord wd) (wordWidth dflags)
packHalfWordsCLit :: DynFlags -> StgHalfWord -> StgHalfWord -> CmmLit
-- Make a single word literal in which the lower_half_word is
-- at the lower address, and the upper_half_word is at the
-- higher address
-- ToDo: consider using half-word lits instead
-- but be careful: that's vulnerable when reversed
packHalfWordsCLit dflags lower_half_word upper_half_word
= if wORDS_BIGENDIAN dflags
then mkWordCLit dflags ((l `shiftL` hALF_WORD_SIZE_IN_BITS dflags) .|. u)
else mkWordCLit dflags (l .|. (u `shiftL` hALF_WORD_SIZE_IN_BITS dflags))
where l = fromStgHalfWord lower_half_word
u = fromStgHalfWord upper_half_word
---------------------------------------------------
--
-- CmmExpr
--
---------------------------------------------------
mkLblExpr :: CLabel -> CmmExpr
mkLblExpr lbl = CmmLit (CmmLabel lbl)
cmmOffsetExpr :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr
-- assumes base and offset have the same CmmType
cmmOffsetExpr dflags e (CmmLit (CmmInt n _)) = cmmOffset dflags e (fromInteger n)
cmmOffsetExpr dflags e byte_off = CmmMachOp (MO_Add (cmmExprWidth dflags e)) [e, byte_off]
cmmOffset :: DynFlags -> CmmExpr -> Int -> CmmExpr
cmmOffset _ e 0 = e
cmmOffset _ (CmmReg reg) byte_off = cmmRegOff reg byte_off
cmmOffset _ (CmmRegOff reg m) byte_off = cmmRegOff reg (m+byte_off)
cmmOffset _ (CmmLit lit) byte_off = CmmLit (cmmOffsetLit lit byte_off)
cmmOffset _ (CmmStackSlot area off) byte_off
= CmmStackSlot area (off - byte_off)
-- note stack area offsets increase towards lower addresses
cmmOffset _ (CmmMachOp (MO_Add rep) [expr, CmmLit (CmmInt byte_off1 _rep)]) byte_off2
= CmmMachOp (MO_Add rep)
[expr, CmmLit (CmmInt (byte_off1 + toInteger byte_off2) rep)]
cmmOffset dflags expr byte_off
= CmmMachOp (MO_Add width) [expr, CmmLit (CmmInt (toInteger byte_off) width)]
where
width = cmmExprWidth dflags expr
-- Smart constructor for CmmRegOff. Same caveats as cmmOffset above.
cmmRegOff :: CmmReg -> Int -> CmmExpr
cmmRegOff reg 0 = CmmReg reg
cmmRegOff reg byte_off = CmmRegOff reg byte_off
cmmOffsetLit :: CmmLit -> Int -> CmmLit
cmmOffsetLit (CmmLabel l) byte_off = cmmLabelOff l byte_off
cmmOffsetLit (CmmLabelOff l m) byte_off = cmmLabelOff l (m+byte_off)
cmmOffsetLit (CmmLabelDiffOff l1 l2 m) byte_off
= CmmLabelDiffOff l1 l2 (m+byte_off)
cmmOffsetLit (CmmInt m rep) byte_off = CmmInt (m + fromIntegral byte_off) rep
cmmOffsetLit _ byte_off = pprPanic "cmmOffsetLit" (ppr byte_off)
cmmLabelOff :: CLabel -> Int -> CmmLit
-- Smart constructor for CmmLabelOff
cmmLabelOff lbl 0 = CmmLabel lbl
cmmLabelOff lbl byte_off = CmmLabelOff lbl byte_off
-- | Useful for creating an index into an array, with a statically known offset.
-- The type is the element type; used for making the multiplier
cmmIndex :: DynFlags
-> Width -- Width w
-> CmmExpr -- Address of vector of items of width w
-> Int -- Which element of the vector (0 based)
-> CmmExpr -- Address of i'th element
cmmIndex dflags width base idx = cmmOffset dflags base (idx * widthInBytes width)
-- | Useful for creating an index into an array, with an unknown offset.
cmmIndexExpr :: DynFlags
-> Width -- Width w
-> CmmExpr -- Address of vector of items of width w
-> CmmExpr -- Which element of the vector (0 based)
-> CmmExpr -- Address of i'th element
cmmIndexExpr dflags width base (CmmLit (CmmInt n _)) = cmmIndex dflags width base (fromInteger n)
cmmIndexExpr dflags width base idx =
cmmOffsetExpr dflags base byte_off
where
idx_w = cmmExprWidth dflags idx
byte_off = CmmMachOp (MO_Shl idx_w) [idx, mkIntExpr dflags (widthInLog width)]
cmmLoadIndex :: DynFlags -> CmmType -> CmmExpr -> Int -> CmmExpr
cmmLoadIndex dflags ty expr ix = CmmLoad (cmmIndex dflags (typeWidth ty) expr ix) ty
-- The "B" variants take byte offsets
cmmRegOffB :: CmmReg -> ByteOff -> CmmExpr
cmmRegOffB = cmmRegOff
cmmOffsetB :: DynFlags -> CmmExpr -> ByteOff -> CmmExpr
cmmOffsetB = cmmOffset
cmmOffsetExprB :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr
cmmOffsetExprB = cmmOffsetExpr
cmmLabelOffB :: CLabel -> ByteOff -> CmmLit
cmmLabelOffB = cmmLabelOff
cmmOffsetLitB :: CmmLit -> ByteOff -> CmmLit
cmmOffsetLitB = cmmOffsetLit
-----------------------
-- The "W" variants take word offsets
cmmOffsetExprW :: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr
-- The second arg is a *word* offset; need to change it to bytes
cmmOffsetExprW dflags e (CmmLit (CmmInt n _)) = cmmOffsetW dflags e (fromInteger n)
cmmOffsetExprW dflags e wd_off = cmmIndexExpr dflags (wordWidth dflags) e wd_off
cmmOffsetW :: DynFlags -> CmmExpr -> WordOff -> CmmExpr
cmmOffsetW dflags e n = cmmOffsetB dflags e (wordsToBytes dflags n)
cmmRegOffW :: DynFlags -> CmmReg -> WordOff -> CmmExpr
cmmRegOffW dflags reg wd_off = cmmRegOffB reg (wordsToBytes dflags wd_off)
cmmOffsetLitW :: DynFlags -> CmmLit -> WordOff -> CmmLit
cmmOffsetLitW dflags lit wd_off = cmmOffsetLitB lit (wordsToBytes dflags wd_off)
cmmLabelOffW :: DynFlags -> CLabel -> WordOff -> CmmLit
cmmLabelOffW dflags lbl wd_off = cmmLabelOffB lbl (wordsToBytes dflags wd_off)
cmmLoadIndexW :: DynFlags -> CmmExpr -> Int -> CmmType -> CmmExpr
cmmLoadIndexW dflags base off ty = CmmLoad (cmmOffsetW dflags base off) ty
-----------------------
cmmULtWord, cmmUGeWord, cmmUGtWord, cmmUShrWord,
cmmSLtWord,
cmmNeWord, cmmEqWord,
cmmOrWord, cmmAndWord,
cmmSubWord, cmmAddWord, cmmMulWord, cmmQuotWord
:: DynFlags -> CmmExpr -> CmmExpr -> CmmExpr
cmmOrWord dflags e1 e2 = CmmMachOp (mo_wordOr dflags) [e1, e2]
cmmAndWord dflags e1 e2 = CmmMachOp (mo_wordAnd dflags) [e1, e2]
cmmNeWord dflags e1 e2 = CmmMachOp (mo_wordNe dflags) [e1, e2]
cmmEqWord dflags e1 e2 = CmmMachOp (mo_wordEq dflags) [e1, e2]
cmmULtWord dflags e1 e2 = CmmMachOp (mo_wordULt dflags) [e1, e2]
cmmUGeWord dflags e1 e2 = CmmMachOp (mo_wordUGe dflags) [e1, e2]
cmmUGtWord dflags e1 e2 = CmmMachOp (mo_wordUGt dflags) [e1, e2]
--cmmShlWord dflags e1 e2 = CmmMachOp (mo_wordShl dflags) [e1, e2]
cmmSLtWord dflags e1 e2 = CmmMachOp (mo_wordSLt dflags) [e1, e2]
cmmUShrWord dflags e1 e2 = CmmMachOp (mo_wordUShr dflags) [e1, e2]
cmmAddWord dflags e1 e2 = CmmMachOp (mo_wordAdd dflags) [e1, e2]
cmmSubWord dflags e1 e2 = CmmMachOp (mo_wordSub dflags) [e1, e2]
cmmMulWord dflags e1 e2 = CmmMachOp (mo_wordMul dflags) [e1, e2]
cmmQuotWord dflags e1 e2 = CmmMachOp (mo_wordUQuot dflags) [e1, e2]
cmmNegate :: DynFlags -> CmmExpr -> CmmExpr
cmmNegate _ (CmmLit (CmmInt n rep)) = CmmLit (CmmInt (-n) rep)
cmmNegate dflags e = CmmMachOp (MO_S_Neg (cmmExprWidth dflags e)) [e]
blankWord :: DynFlags -> CmmStatic
blankWord dflags = CmmUninitialised (wORD_SIZE dflags)
cmmToWord :: DynFlags -> CmmExpr -> CmmExpr
cmmToWord dflags e
| w == word = e
| otherwise = CmmMachOp (MO_UU_Conv w word) [e]
where
w = cmmExprWidth dflags e
word = wordWidth dflags
---------------------------------------------------
--
-- CmmExpr predicates
--
---------------------------------------------------
isTrivialCmmExpr :: CmmExpr -> Bool
isTrivialCmmExpr (CmmLoad _ _) = False
isTrivialCmmExpr (CmmMachOp _ _) = False
isTrivialCmmExpr (CmmLit _) = True
isTrivialCmmExpr (CmmReg _) = True
isTrivialCmmExpr (CmmRegOff _ _) = True
isTrivialCmmExpr (CmmStackSlot _ _) = panic "isTrivialCmmExpr CmmStackSlot"
hasNoGlobalRegs :: CmmExpr -> Bool
hasNoGlobalRegs (CmmLoad e _) = hasNoGlobalRegs e
hasNoGlobalRegs (CmmMachOp _ es) = all hasNoGlobalRegs es
hasNoGlobalRegs (CmmLit _) = True
hasNoGlobalRegs (CmmReg (CmmLocal _)) = True
hasNoGlobalRegs (CmmRegOff (CmmLocal _) _) = True
hasNoGlobalRegs _ = False
---------------------------------------------------
--
-- Tagging
--
---------------------------------------------------
-- Tag bits mask
--cmmTagBits = CmmLit (mkIntCLit tAG_BITS)
cmmTagMask, cmmPointerMask :: DynFlags -> CmmExpr
cmmTagMask dflags = mkIntExpr dflags (tAG_MASK dflags)
cmmPointerMask dflags = mkIntExpr dflags (complement (tAG_MASK dflags))
-- Used to untag a possibly tagged pointer
-- A static label need not be untagged
cmmUntag :: DynFlags -> CmmExpr -> CmmExpr
cmmUntag _ e@(CmmLit (CmmLabel _)) = e
-- Default case
cmmUntag dflags e = cmmAndWord dflags e (cmmPointerMask dflags)
-- Test if a closure pointer is untagged
cmmIsTagged :: DynFlags -> CmmExpr -> CmmExpr
cmmIsTagged dflags e = cmmNeWord dflags (cmmAndWord dflags e (cmmTagMask dflags)) (zeroExpr dflags)
cmmConstrTag1 :: DynFlags -> CmmExpr -> CmmExpr
-- Get constructor tag, but one based.
cmmConstrTag1 dflags e = cmmAndWord dflags e (cmmTagMask dflags)
-----------------------------------------------------------------------------
-- Overlap and usage
-- | Returns True if the two STG registers overlap on the specified
-- platform, in the sense that writing to one will clobber the
-- other. This includes the case that the two registers are the same
-- STG register. See Note [Overlapping global registers] for details.
regsOverlap :: DynFlags -> CmmReg -> CmmReg -> Bool
regsOverlap dflags (CmmGlobal g) (CmmGlobal g')
| Just real <- globalRegMaybe (targetPlatform dflags) g,
Just real' <- globalRegMaybe (targetPlatform dflags) g',
real == real'
= True
regsOverlap _ reg reg' = reg == reg'
-- | Returns True if the STG register is used by the expression, in
-- the sense that a store to the register might affect the value of
-- the expression.
--
-- We must check for overlapping registers and not just equal
-- registers here, otherwise CmmSink may incorrectly reorder
-- assignments that conflict due to overlap. See Trac #10521 and Note
-- [Overlapping global registers].
regUsedIn :: DynFlags -> CmmReg -> CmmExpr -> Bool
regUsedIn dflags = regUsedIn_ where
_ `regUsedIn_` CmmLit _ = False
reg `regUsedIn_` CmmLoad e _ = reg `regUsedIn_` e
reg `regUsedIn_` CmmReg reg' = regsOverlap dflags reg reg'
reg `regUsedIn_` CmmRegOff reg' _ = regsOverlap dflags reg reg'
reg `regUsedIn_` CmmMachOp _ es = any (reg `regUsedIn_`) es
_ `regUsedIn_` CmmStackSlot _ _ = False
--------------------------------------------
--
-- mkLiveness
--
---------------------------------------------
mkLiveness :: DynFlags -> [Maybe LocalReg] -> Liveness
mkLiveness _ [] = []
mkLiveness dflags (reg:regs)
= take sizeW bits ++ mkLiveness dflags regs
where
sizeW = case reg of
Nothing -> 1
Just r -> (widthInBytes (typeWidth (localRegType r)) + wORD_SIZE dflags - 1)
`quot` wORD_SIZE dflags
-- number of words, rounded up
bits = repeat $ is_non_ptr reg -- True <=> Non Ptr
is_non_ptr Nothing = True
is_non_ptr (Just reg) = not $ isGcPtrType (localRegType reg)
-- ============================================== -
-- ============================================== -
-- ============================================== -
---------------------------------------------------
--
-- Manipulating CmmGraphs
--
---------------------------------------------------
modifyGraph :: (Graph n C C -> Graph n' C C) -> GenCmmGraph n -> GenCmmGraph n'
modifyGraph f g = CmmGraph {g_entry=g_entry g, g_graph=f (g_graph g)}
toBlockMap :: CmmGraph -> BlockEnv CmmBlock
toBlockMap (CmmGraph {g_graph=GMany NothingO body NothingO}) = body
ofBlockMap :: BlockId -> BlockEnv CmmBlock -> CmmGraph
ofBlockMap entry bodyMap = CmmGraph {g_entry=entry, g_graph=GMany NothingO bodyMap NothingO}
insertBlock :: CmmBlock -> BlockEnv CmmBlock -> BlockEnv CmmBlock
insertBlock block map =
ASSERT(isNothing $ mapLookup id map)
mapInsert id block map
where id = entryLabel block
toBlockList :: CmmGraph -> [CmmBlock]
toBlockList g = mapElems $ toBlockMap g
-- | like 'toBlockList', but the entry block always comes first
toBlockListEntryFirst :: CmmGraph -> [CmmBlock]
toBlockListEntryFirst g
| mapNull m = []
| otherwise = entry_block : others
where
m = toBlockMap g
entry_id = g_entry g
Just entry_block = mapLookup entry_id m
others = filter ((/= entry_id) . entryLabel) (mapElems m)
-- | Like 'toBlockListEntryFirst', but we strive to ensure that we order blocks
-- so that the false case of a conditional jumps to the next block in the output
-- list of blocks. This matches the way OldCmm blocks were output since in
-- OldCmm the false case was a fallthrough, whereas in Cmm conditional branches
-- have both true and false successors. Block ordering can make a big difference
-- in performance in the LLVM backend. Note that we rely crucially on the order
-- of successors returned for CmmCondBranch by the NonLocal instance for CmmNode
-- defind in cmm/CmmNode.hs. -GBM
toBlockListEntryFirstFalseFallthrough :: CmmGraph -> [CmmBlock]
toBlockListEntryFirstFalseFallthrough g
| mapNull m = []
| otherwise = dfs setEmpty [entry_block]
where
m = toBlockMap g
entry_id = g_entry g
Just entry_block = mapLookup entry_id m
dfs :: LabelSet -> [CmmBlock] -> [CmmBlock]
dfs _ [] = []
dfs visited (block:bs)
| id `setMember` visited = dfs visited bs
| otherwise = block : dfs (setInsert id visited) bs'
where id = entryLabel block
bs' = foldr add_id bs (successors block)
add_id id bs = case mapLookup id m of
Just b -> b : bs
Nothing -> bs
ofBlockList :: BlockId -> [CmmBlock] -> CmmGraph
ofBlockList entry blocks = CmmGraph { g_entry = entry
, g_graph = GMany NothingO body NothingO }
where body = foldr addBlock emptyBody blocks
bodyToBlockList :: Body CmmNode -> [CmmBlock]
bodyToBlockList body = mapElems body
mapGraphNodes :: ( CmmNode C O -> CmmNode C O
, CmmNode O O -> CmmNode O O
, CmmNode O C -> CmmNode O C)
-> CmmGraph -> CmmGraph
mapGraphNodes funs@(mf,_,_) g =
ofBlockMap (entryLabel $ mf $ CmmEntry (g_entry g) GlobalScope) $
mapMap (mapBlock3' funs) $ toBlockMap g
mapGraphNodes1 :: (forall e x. CmmNode e x -> CmmNode e x) -> CmmGraph -> CmmGraph
mapGraphNodes1 f = modifyGraph (mapGraph f)
foldGraphBlocks :: (CmmBlock -> a -> a) -> a -> CmmGraph -> a
foldGraphBlocks k z g = mapFold k z $ toBlockMap g
postorderDfs :: CmmGraph -> [CmmBlock]
postorderDfs g = {-# SCC "postorderDfs" #-} postorder_dfs_from (toBlockMap g) (g_entry g)
-------------------------------------------------
-- Running dataflow analysis and/or rewrites
-- Constructing forward and backward analysis-only pass
analFwd :: DataflowLattice f -> FwdTransfer n f -> FwdPass UniqSM n f
analBwd :: DataflowLattice f -> BwdTransfer n f -> BwdPass UniqSM n f
analFwd lat xfer = analRewFwd lat xfer noFwdRewrite
analBwd lat xfer = analRewBwd lat xfer noBwdRewrite
-- Constructing forward and backward analysis + rewrite pass
analRewFwd :: DataflowLattice f -> FwdTransfer n f
-> FwdRewrite UniqSM n f
-> FwdPass UniqSM n f
analRewBwd :: DataflowLattice f
-> BwdTransfer n f
-> BwdRewrite UniqSM n f
-> BwdPass UniqSM n f
analRewFwd lat xfer rew = FwdPass {fp_lattice = lat, fp_transfer = xfer, fp_rewrite = rew}
analRewBwd lat xfer rew = BwdPass {bp_lattice = lat, bp_transfer = xfer, bp_rewrite = rew}
-- Running forward and backward dataflow analysis + optional rewrite
dataflowPassFwd :: NonLocal n =>
GenCmmGraph n -> [(BlockId, f)]
-> FwdPass UniqSM n f
-> UniqSM (GenCmmGraph n, BlockEnv f)
dataflowPassFwd (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = do
(graph, facts, NothingO) <- analyzeAndRewriteFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts)
return (CmmGraph {g_entry=entry, g_graph=graph}, facts)
dataflowAnalFwd :: NonLocal n =>
GenCmmGraph n -> [(BlockId, f)]
-> FwdPass UniqSM n f
-> BlockEnv f
dataflowAnalFwd (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd =
analyzeFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts)
dataflowAnalFwdBlocks :: NonLocal n =>
GenCmmGraph n -> [(BlockId, f)]
-> FwdPass UniqSM n f
-> UniqSM (BlockEnv f)
dataflowAnalFwdBlocks (CmmGraph {g_entry=entry, g_graph=graph}) facts fwd = do
-- (graph, facts, NothingO) <- analyzeAndRewriteFwd fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts)
-- return facts
return (analyzeFwdBlocks fwd (JustC [entry]) graph (mkFactBase (fp_lattice fwd) facts))
dataflowAnalBwd :: NonLocal n =>
GenCmmGraph n -> [(BlockId, f)]
-> BwdPass UniqSM n f
-> BlockEnv f
dataflowAnalBwd (CmmGraph {g_entry=entry, g_graph=graph}) facts bwd =
analyzeBwd bwd (JustC [entry]) graph (mkFactBase (bp_lattice bwd) facts)
dataflowPassBwd :: NonLocal n =>
GenCmmGraph n -> [(BlockId, f)]
-> BwdPass UniqSM n f
-> UniqSM (GenCmmGraph n, BlockEnv f)
dataflowPassBwd (CmmGraph {g_entry=entry, g_graph=graph}) facts bwd = do
(graph, facts, NothingO) <- analyzeAndRewriteBwd bwd (JustC [entry]) graph (mkFactBase (bp_lattice bwd) facts)
return (CmmGraph {g_entry=entry, g_graph=graph}, facts)
-------------------------------------------------
-- Tick utilities
-- | Extract all tick annotations from the given block
blockTicks :: Block CmmNode C C -> [CmmTickish]
blockTicks b = reverse $ foldBlockNodesF goStmt b []
where goStmt :: CmmNode e x -> [CmmTickish] -> [CmmTickish]
goStmt (CmmTick t) ts = t:ts
goStmt _other ts = ts
| snoyberg/ghc | compiler/cmm/CmmUtils.hs | bsd-3-clause | 24,392 | 0 | 18 | 5,177 | 6,246 | 3,285 | 2,961 | 396 | 6 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, ScopedTypeVariables #-}
-- | Types definitions
module Instagram.Types (
Credentials(..)
,clientIDBS
,clientSecretBS
,OAuthToken(..)
,AccessToken(..)
,UserID
,User(..)
,UserCounts(..)
,Scope(..)
,IGException(..)
,Envelope(..)
,ErrEnvelope(..)
,IGError
,Pagination(..)
,MediaID
,Media(..)
,Position(..)
,UserPosition(..)
,LocationID
,Location(..)
,ImageData(..)
,Images(..)
,CommentID
,Comment(..)
,Collection(..)
,Aspect(..)
,media
,CallbackUrl
,Subscription(..)
,Update(..)
,TagName
,Tag(..)
,OutgoingStatus(..)
,IncomingStatus(..)
,Relationship(..)
,NoResult
,GeographyID
)where
import Control.Applicative
import Data.Text
import Data.Typeable (Typeable)
import Data.ByteString (ByteString)
import Data.Aeson
import qualified Data.Text.Encoding as TE
import Control.Exception.Base (Exception)
import Data.Time.Clock.POSIX (POSIXTime)
import qualified Data.Text as T (pack)
import Data.Aeson.Types (Parser)
import qualified Data.HashMap.Strict as HM (lookup)
-- | the app credentials
data Credentials = Credentials {
cClientID :: Text -- ^ client id
,cClientSecret :: Text -- ^ client secret
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | get client id in ByteString form
clientIDBS :: Credentials -> ByteString
clientIDBS=TE.encodeUtf8 . cClientID
-- | get client secret in ByteString form
clientSecretBS :: Credentials -> ByteString
clientSecretBS=TE.encodeUtf8 . cClientSecret
-- | the oauth token returned after authentication
data OAuthToken = OAuthToken {
oaAccessToken :: AccessToken -- ^ the access token
,oaUser :: User -- ^ the user structure returned
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON OAuthToken where
toJSON oa=object ["access_token" .= oaAccessToken oa, "user" .= oaUser oa]
-- | from json as per Instagram format
instance FromJSON OAuthToken where
parseJSON (Object v) =OAuthToken <$>
v .: "access_token" <*>
v .: "user"
parseJSON _= fail "OAuthToken"
-- | the access token is simply a Text
newtype AccessToken=AccessToken Text
deriving (Eq, Ord, Read, Show, Typeable)
-- | simple string
instance ToJSON AccessToken where
toJSON (AccessToken at)=String at
-- | simple string
instance FromJSON AccessToken where
parseJSON (String s)=pure $ AccessToken s
parseJSON _= fail "AccessToken"
-- | User ID
type UserID = Text
-- | the User partial profile returned by the authentication
data User = User {
uID :: UserID,
uUsername :: Text,
uFullName :: Text,
uProfilePicture :: Maybe Text,
uWebsite :: Maybe Text,
uBio :: Maybe Text,
uCounts :: Maybe UserCounts
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON User where
toJSON u = object
[ "id" .= uID u
, "username" .= uUsername u
, "full_name" .= uFullName u
, "profile_picture" .= uProfilePicture u
, "website" .= uWebsite u
, "bio" .= uBio u
]
-- | from json as per Instagram format
instance FromJSON User where
parseJSON (Object v) =User <$>
v .: "id" <*>
v .: "username" <*>
v .: "full_name" <*>
v .:? "profile_picture" <*>
v .:? "website" <*>
v .:? "bio" <*>
v .:? "counts"
parseJSON _= fail "User"
-- | the User counts info returned by some endpoints
data UserCounts = UserCounts
{ ucMedia :: Int
, ucFollows :: Int
, ucFollowedBy :: Int
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | from json as per Instagram format
instance FromJSON UserCounts where
parseJSON (Object v) = UserCounts <$>
v .: "media" <*>
v .: "follows" <*>
v .: "followed_by"
parseJSON _= fail "UserCounts"
-- | to json as per Instagram format
instance ToJSON UserCounts where
toJSON uc = object
[ "media" .= ucMedia uc
, "follows" .= ucFollows uc
, "followed_by" .= ucFollowedBy uc
]
-- | the scopes of the authentication
data Scope=Basic | Comments | Relationships | Likes
deriving (Show,Read,Eq,Ord,Enum,Bounded,Typeable)
-- | an error returned to us by Instagram
data IGError = IGError {
igeCode :: Int
,igeType :: Maybe Text
,igeMessage :: Maybe Text
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON IGError where
toJSON e=object ["code" .= igeCode e, "error_type" .= igeType e , "error_message" .= igeMessage e]
-- | from json as per Instagram format
instance FromJSON IGError where
parseJSON (Object v) =IGError <$>
v .: "code" <*>
v .:? "error_type" <*>
v .:? "error_message"
parseJSON _= fail "IGError"
-- | an exception that a call to instagram may throw
data IGException = JSONException String -- ^ JSON parsingError
| IGAppException IGError -- ^ application exception
deriving (Show,Typeable)
-- | make our exception type a normal exception
instance Exception IGException
-- | envelope for Instagram OK response
data Envelope d=Envelope{
eMeta :: IGError -- ^ this should only say 200, no error, but put here for completeness
,eData :: d -- ^ data, garanteed to be present (otherwise we get an ErrEnvelope)
,ePagination :: Maybe Pagination
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance (ToJSON d)=>ToJSON (Envelope d) where
toJSON e=object ["meta" .= eMeta e, "data" .= eData e, "pagination" .= ePagination e]
-- | from json as per Instagram format
instance (FromJSON d)=>FromJSON (Envelope d) where
parseJSON (Object v) =Envelope <$>
v .: "meta" <*>
v .: "data" <*>
v .:? "pagination"
parseJSON _= fail "Envelope"
-- | error envelope for Instagram error response
data ErrEnvelope=ErrEnvelope{
eeMeta :: IGError
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON ErrEnvelope where
toJSON e=object ["meta" .= eeMeta e]
-- | from json as per Instagram format
instance FromJSON ErrEnvelope where
parseJSON (Object v) =ErrEnvelope <$>
v .: "meta"
parseJSON _= fail "ErrEnvelope"
-- | pagination info for responses that can return a lot of data
data Pagination = Pagination {
pNextUrl :: Maybe Text
,pNextMaxID :: Maybe Text
,pNextMinID :: Maybe Text
,pNextMaxTagID :: Maybe Text
,pMinTagID :: Maybe Text
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON Pagination where
toJSON p=object ["next_url" .= pNextUrl p, "next_max_id" .= pNextMaxID p, "next_min_id" .= pNextMinID p, "next_max_tag_id" .= pNextMaxTagID p,"min_tag_id" .= pMinTagID p]
-- | from json as per Instagram format
instance FromJSON Pagination where
parseJSON (Object v) =Pagination <$>
v .:? "next_url" <*>
v .:? "next_max_id" <*>
v .:? "next_min_id" <*>
v .:? "next_max_tag_id" <*>
v .:? "min_tag_id"
parseJSON _= fail "Pagination"
-- | Media ID
type MediaID=Text
-- | instagram media object
data Media = Media {
mID :: MediaID
,mCaption :: Maybe Comment
,mLink :: Text
,mUser :: User
,mCreated :: POSIXTime
,mImages :: Images
,mType :: Text
,mUsersInPhoto :: [UserPosition]
,mFilter :: Maybe Text
,mTags :: [Text]
,mLocation :: Maybe Location
,mComments :: Collection Comment
,mLikes :: Collection User
,mUserHasLiked :: Bool
,mAttribution :: Maybe Object -- ^ seems to be open format https://groups.google.com/forum/?fromgroups#!topic/instagram-api-developers/KvGH1cnjljQ
}
deriving (Show,Eq,Typeable)
-- | to json as per Instagram format
instance ToJSON Media where
toJSON m=object ["id" .= mID m,"caption" .= mCaption m,"user".= mUser m,"link" .= mLink m, "created_time" .= toJSON (show ((round $ mCreated m) :: Integer))
,"images" .= mImages m,"type" .= mType m,"users_in_photo" .= mUsersInPhoto m, "filter" .= mFilter m,"tags" .= mTags m
,"location" .= mLocation m,"comments" .= mComments m,"likes" .= mLikes m,"user_has_liked" .= mUserHasLiked m,"attribution" .= mAttribution m]
-- | from json as per Instagram format
instance FromJSON Media where
parseJSON (Object v) =do
ct::String<-v .: "created_time"
Media <$>
v .: "id" <*>
v .:? "caption" <*>
v .: "link" <*>
v .: "user" <*>
pure (fromIntegral (read ct::Integer)) <*>
v .: "images" <*>
v .: "type" <*>
v .: "users_in_photo" <*>
v .:? "filter" <*>
v .: "tags" <*>
v .:? "location" <*>
v .:? "comments" .!= Collection 0 [] <*>
v .:? "likes" .!= Collection 0 [] <*>
v .:? "user_has_liked" .!= False <*>
v .:? "attribution"
parseJSON _= fail "Media"
-- | position in picture
data Position = Position {
pX ::Double
,pY :: Double
} deriving (Show,Eq,Typeable)
-- | to json as per Instagram format
instance ToJSON Position where
toJSON p=object ["x" .= pX p,"y" .= pY p]
-- | from json as per Instagram format
instance FromJSON Position where
parseJSON (Object v) = Position <$>
v .: "x" <*>
v .: "y"
parseJSON _=fail "Position"
-- | position of a user
data UserPosition = UserPosition {
upPosition :: Position
,upUser :: User
} deriving (Show,Eq,Typeable)
-- | to json as per Instagram format
instance ToJSON UserPosition where
toJSON p=object ["position" .= upPosition p,"user" .= upUser p]
-- | from json as per Instagram format
instance FromJSON UserPosition where
parseJSON (Object v) = UserPosition <$>
v .: "position" <*>
v .: "user"
parseJSON _=fail "UserPosition"
-- | location ID
type LocationID = Text
-- | geographical location info
data Location = Location {
lID :: Maybe LocationID
,lLatitude :: Maybe Double
,lLongitude :: Maybe Double
,lStreetAddress :: Maybe Text
,lName :: Maybe Text
}
deriving (Show,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON Location where
toJSON l=object ["id" .= lID l,"latitude" .= lLatitude l,"longitude" .= lLongitude l, "street_address" .= lStreetAddress l,"name" .= lName l]
-- | from json as per Instagram format
instance FromJSON Location where
parseJSON (Object v) =
Location <$>
parseID v <*>
v .:? "latitude" <*>
v .:? "longitude" <*>
v .:? "street_address" <*>
v .:? "name"
where
-- | the Instagram API hasn't made its mind up, sometimes location id is an int, sometimes a string
parseID :: Object -> Parser (Maybe LocationID)
parseID obj=case HM.lookup "id" obj of
Just (String s)->pure $ Just s
Just (Number n)->pure $ Just $ T.pack $ show n
Nothing->pure Nothing
_->fail "LocationID"
parseJSON _= fail "Location"
-- | data for a single image
data ImageData = ImageData {
idURL :: Text,
idWidth :: Integer,
idHeight :: Integer
}
deriving (Show,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON ImageData where
toJSON i=object ["url" .= idURL i,"width" .= idWidth i,"height" .= idHeight i]
-- | from json as per Instagram format
instance FromJSON ImageData where
parseJSON (Object v) = ImageData <$>
v .: "url" <*>
v .: "width" <*>
v .: "height"
parseJSON _= fail "ImageData"
-- | different images for the same media
data Images = Images {
iLowRes :: ImageData
,iThumbnail :: ImageData
,iStandardRes :: ImageData
}
deriving (Show,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON Images where
toJSON i=object ["low_resolution" .= iLowRes i,"thumbnail" .= iThumbnail i,"standard_resolution" .= iStandardRes i]
-- | from json as per Instagram format
instance FromJSON Images where
parseJSON (Object v) = Images <$>
v .: "low_resolution" <*>
v .: "thumbnail" <*>
v .: "standard_resolution"
parseJSON _= fail "Images"
-- | comment id
type CommentID = Text
-- | Commenton on a medium
data Comment = Comment {
cID :: CommentID
,cCreated :: POSIXTime
,cText :: Text
,cFrom :: User
}
deriving (Show,Eq,Ord,Typeable)
-- | to json asCommentstagram format
instance ToJSON Comment where
toJSON c=object ["id" .= cID c,"created_time" .= toJSON (show ((round $ cCreated c) :: Integer))
,"text" .= cText c,"from" .= cFrom c]
-- | from json asCommentstagram format
instance FromJSON Comment where
parseJSON (Object v) =do
ct::String<-v .: "created_time"
Comment <$>
v .: "id" <*>
pure (fromIntegral (read ct::Integer)) <*>
v .: "text" <*>
v .: "from"
parseJSON _= fail "Caption"
-- | a collection of items (count + data)
-- data can only be a subset
data Collection a= Collection {
cCount :: Integer
,cData :: [a]
}
deriving (Show,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance (ToJSON a)=>ToJSON (Collection a) where
toJSON igc=object ["count" .= cCount igc,"data" .= cData igc]
-- | from json as per Instagram format
instance (FromJSON a)=>FromJSON (Collection a) where
parseJSON (Object v) = Collection <$>
v .: "count" <*>
v .: "data"
parseJSON _= fail "Collection"
-- | the URL to receive notifications to
type CallbackUrl = Text
-- | notification aspect
data Aspect = Aspect Text
deriving (Show, Read, Eq, Ord, Typeable)
-- | to json as per Instagram format
instance ToJSON Aspect where
toJSON (Aspect t)=String t
-- | from json as per Instagram format
instance FromJSON Aspect where
parseJSON (String t) = pure $ Aspect t
parseJSON _= fail "Aspect"
-- | the media Aspect, the only one supported for now
media :: Aspect
media = Aspect "media"
-- | a subscription to a real time notification
data Subscription= Subscription {
sID :: Text
,sType :: Text
,sObject :: Text
,sObjectID :: Maybe Text
,sAspect :: Aspect
,sCallbackUrl :: CallbackUrl
,sLatitude :: Maybe Double
,sLongitude :: Maybe Double
,sRadius :: Maybe Integer
}
deriving (Show,Eq,Typeable)
-- | to json as per Instagram format
instance ToJSON Subscription where
toJSON s=object ["id" .= sID s,"type" .= sType s,"object" .= sObject s,"object_id" .= sObjectID s,"aspect" .= sAspect s
,"callback_url".=sCallbackUrl s,"lat".= sLatitude s,"lng".=sLongitude s,"radius".=sRadius s]
-- | from json as per Instagram format
instance FromJSON Subscription where
parseJSON (Object v) = Subscription <$>
v .: "id" <*>
v .: "type" <*>
v .: "object" <*>
v .:? "object_id" <*>
v .: "aspect" <*>
v .: "callback_url" <*>
v .:? "lat" <*>
v .:? "lng" <*>
v .:? "radius"
parseJSON _= fail "Subscription"
-- | an update from a subscription
data Update = Update {
uSubscriptionID :: Integer
,uObject :: Text
,uObjectID :: Text
,uChangedAspect :: Aspect
,uTime :: POSIXTime
}
deriving (Show,Eq,Typeable)
-- | to json as per Instagram format
instance ToJSON Update where
toJSON u=object ["subscription_id" .= uSubscriptionID u ,"object" .= uObject u,"object_id" .= uObjectID u
,"changed_aspect" .= uChangedAspect u,"time" .= toJSON ((round $ uTime u) :: Integer)]
-- | from json as per Instagram format
instance FromJSON Update where
parseJSON (Object v) =do
ct::Integer<-v .: "time"
Update <$>
v .: "subscription_id" <*>
v .: "object" <*>
v .: "object_id" <*>
v .: "changed_aspect" <*>
pure (fromIntegral ct)
parseJSON _= fail "Update"
-- | Tag Name
type TagName = Text
-- | a Tag
data Tag = Tag {
tName :: TagName,
tMediaCount :: Integer
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON Tag where
toJSON t=object ["name" .= tName t,"media_count" .= tMediaCount t]
-- | from json as per Instagram format
instance FromJSON Tag where
parseJSON (Object v) = Tag <$>
v .: "name" <*>
v .:? "media_count" .!= 0
parseJSON _= fail "Tag"
-- | outgoing relationship status
data OutgoingStatus = Follows | Requested | OutNone
deriving (Show,Read,Eq,Ord,Bounded,Enum,Typeable)
-- | to json as per Instagram format
instance ToJSON OutgoingStatus where
toJSON Follows = String "follows"
toJSON Requested = String "requested"
toJSON OutNone = String "none"
-- | from json as per Instagram format
instance FromJSON OutgoingStatus where
parseJSON (String "follows")=pure Follows
parseJSON (String "requested")=pure Requested
parseJSON (String "none")=pure OutNone
parseJSON _= fail "OutgoingStatus"
-- | incoming relationship status
data IncomingStatus = FollowedBy | RequestedBy | BlockedByYou | InNone
deriving (Show,Read,Eq,Ord,Bounded,Enum,Typeable)
-- | to json as per Instagram format
instance ToJSON IncomingStatus where
toJSON FollowedBy = String "followed_by"
toJSON RequestedBy = String "requested_by"
toJSON BlockedByYou = String "blocked_by_you"
toJSON InNone = String "none"
-- | from json as per Instagram format
instance FromJSON IncomingStatus where
parseJSON (String "followed_by")=pure FollowedBy
parseJSON (String "requested_by")=pure RequestedBy
parseJSON (String "blocked_by_you")=pure BlockedByYou
parseJSON (String "none")=pure InNone
parseJSON _= fail "IncomingStatus"
-- | a relationship between two users
data Relationship = Relationship {
rOutgoing :: OutgoingStatus
,rIncoming :: IncomingStatus
,rTargetUserPrivate :: Bool -- ^ not present in doc
}
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON Relationship where
toJSON r=object ["outgoing_status" .= rOutgoing r,"incoming_status" .= rIncoming r,"target_user_is_private" .= rTargetUserPrivate r]
-- | from json as per Instagram format
instance FromJSON Relationship where
parseJSON (Object v) = Relationship <$>
v .:? "outgoing_status" .!= OutNone <*>
v .:? "incoming_status" .!= InNone <*>
v .:? "target_user_is_private" .!= False
parseJSON _= fail "Relationship"
-- | Instagram returns data:null for nothing, but Aeson considers that () maps to an empty array...
-- so we model the fact that we expect null via NoResult
data NoResult = NoResult
deriving (Show,Read,Eq,Ord,Typeable)
-- | to json as per Instagram format
instance ToJSON NoResult where
toJSON _=Null
-- | from json as per Instagram format
instance FromJSON NoResult where
parseJSON Null = pure NoResult
parseJSON _= fail "NoResult"
-- | geography ID
type GeographyID = Text
| potomak/ig | src/Instagram/Types.hs | bsd-3-clause | 20,024 | 0 | 39 | 5,568 | 5,126 | 2,751 | 2,375 | 436 | 1 |
module Test.FFI where
import FFI.Visualise
import SPL.Top
import Utils
mk s e = st s e $ showType $ uncondLookup s get_types
tests =
[
mk "sum" "num num -> num"
, mk "bind" "IO<??a> (??a -> IO<??b>) -> IO<??b>"
]
| kayuri/HNC | Test/FFI.hs | lgpl-3.0 | 221 | 8 | 7 | 49 | 76 | 40 | 36 | 9 | 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="bs-BA">
<title>Authentication Statistics | 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> | thc202/zap-extensions | addOns/authstats/src/main/javahelp/org/zaproxy/zap/extension/authstats/resources/help_bs_BA/helpset_bs_BA.hs | apache-2.0 | 986 | 87 | 29 | 159 | 396 | 212 | 184 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
module Hadrian.Oracles.Path (
lookupInPath, bashPath, fixAbsolutePathOnWindows, pathOracle
) where
import Control.Monad
import Data.Maybe
import Data.Char
import Data.List.Extra
import Development.Shake
import Development.Shake.Classes
import Development.Shake.FilePath
import System.Directory
import System.Info.Extra
import Hadrian.Utilities
-- | Lookup a specified 'FilePath' in the system @PATH@.
lookupInPath :: FilePath -> Action FilePath
lookupInPath name
| name == takeFileName name = askOracle $ LookupInPath name
| otherwise = return name
-- | Lookup the path to the @bash@ interpreter.
bashPath :: Action FilePath
bashPath = lookupInPath "bash"
-- | Fix an absolute path on Windows:
-- * "/c/" => "C:/"
-- * "/usr/bin/tar.exe" => "C:/msys/usr/bin/tar.exe"
fixAbsolutePathOnWindows :: FilePath -> Action FilePath
fixAbsolutePathOnWindows path =
if isWindows
then do
let (dir, file) = splitFileName path
winDir <- askOracle $ WindowsPath dir
return $ winDir -/- file
else
return path
newtype LookupInPath = LookupInPath String
deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
type instance RuleResult LookupInPath = String
newtype WindowsPath = WindowsPath FilePath
deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
type instance RuleResult WindowsPath = String
-- | Oracles for looking up paths. These are slow and require caching.
pathOracle :: Rules ()
pathOracle = do
void $ addOracleCache $ \(WindowsPath path) -> do
Stdout out <- quietly $ cmd ["cygpath", "-m", path]
let windowsPath = unifyPath $ dropWhileEnd isSpace out
putLoud $ "| Windows path mapping: " ++ path ++ " => " ++ windowsPath
return windowsPath
void $ addOracleCache $ \(LookupInPath name) -> do
let unpack = fromMaybe . error $ "Cannot find executable " ++ quote name
path <- unifyPath . unpack <$> liftIO (findExecutable name)
putLoud $ "| Executable found: " ++ name ++ " => " ++ path
return path
| snowleopard/hadrian | src/Hadrian/Oracles/Path.hs | mit | 2,090 | 0 | 16 | 444 | 516 | 267 | 249 | 45 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, OverlappingInstances
, ScopedTypeVariables
, FlexibleInstances
#-}
{-# OPTIONS_GHC -funbox-strict-fields -fno-warn-warnings-deprecations #-}
-- The -XOverlappingInstances flag allows the user to over-ride
-- the instances for Typeable given here. In particular, we provide an instance
-- instance ... => Typeable (s a)
-- But a user might want to say
-- instance ... => Typeable (MyType a b)
-----------------------------------------------------------------------------
-- |
-- Module : Data.Typeable
-- Copyright : (c) The University of Glasgow, CWI 2001--2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- This module defines the old, kind-monomorphic 'Typeable' class. It is now
-- deprecated; users are recommended to use the kind-polymorphic
-- "Data.Typeable" module instead.
--
-- /Since: 4.7.0.0/
-----------------------------------------------------------------------------
module Data.OldTypeable {-# DEPRECATED "Use Data.Typeable instead" #-} -- deprecated in 7.8
(
-- * The Typeable class
Typeable( typeOf ), -- :: a -> TypeRep
-- * Type-safe cast
cast, -- :: (Typeable a, Typeable b) => a -> Maybe b
gcast, -- a generalisation of cast
-- * Type representations
TypeRep, -- abstract, instance of: Eq, Show, Typeable
showsTypeRep,
TyCon, -- abstract, instance of: Eq, Show, Typeable
tyConString, -- :: TyCon -> String
tyConPackage, -- :: TyCon -> String
tyConModule, -- :: TyCon -> String
tyConName, -- :: TyCon -> String
-- * Construction of type representations
mkTyCon, -- :: String -> TyCon
mkTyCon3, -- :: String -> String -> String -> TyCon
mkTyConApp, -- :: TyCon -> [TypeRep] -> TypeRep
mkAppTy, -- :: TypeRep -> TypeRep -> TypeRep
mkFunTy, -- :: TypeRep -> TypeRep -> TypeRep
-- * Observation of type representations
splitTyConApp, -- :: TypeRep -> (TyCon, [TypeRep])
funResultTy, -- :: TypeRep -> TypeRep -> Maybe TypeRep
typeRepTyCon, -- :: TypeRep -> TyCon
typeRepArgs, -- :: TypeRep -> [TypeRep]
typeRepKey, -- :: TypeRep -> IO TypeRepKey
TypeRepKey, -- abstract, instance of Eq, Ord
-- * The other Typeable classes
-- | /Note:/ The general instances are provided for GHC only.
Typeable1( typeOf1 ), -- :: t a -> TypeRep
Typeable2( typeOf2 ), -- :: t a b -> TypeRep
Typeable3( typeOf3 ), -- :: t a b c -> TypeRep
Typeable4( typeOf4 ), -- :: t a b c d -> TypeRep
Typeable5( typeOf5 ), -- :: t a b c d e -> TypeRep
Typeable6( typeOf6 ), -- :: t a b c d e f -> TypeRep
Typeable7( typeOf7 ), -- :: t a b c d e f g -> TypeRep
gcast1, -- :: ... => c (t a) -> Maybe (c (t' a))
gcast2, -- :: ... => c (t a b) -> Maybe (c (t' a b))
-- * Default instances
-- | /Note:/ These are not needed by GHC, for which these instances
-- are generated by general instance declarations.
typeOfDefault, -- :: (Typeable1 t, Typeable a) => t a -> TypeRep
typeOf1Default, -- :: (Typeable2 t, Typeable a) => t a b -> TypeRep
typeOf2Default, -- :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
typeOf3Default, -- :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
typeOf4Default, -- :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
typeOf5Default, -- :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
typeOf6Default -- :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
) where
import Data.OldTypeable.Internal hiding (mkTyCon)
import Unsafe.Coerce
import Data.Maybe
import GHC.Base
import GHC.Fingerprint.Type
import GHC.Fingerprint
#include "OldTypeable.h"
{-# DEPRECATED typeRepKey "TypeRep itself is now an instance of Ord" #-} -- deprecated in 7.2
-- | (DEPRECATED) Returns a unique key associated with a 'TypeRep'.
-- This function is deprecated because 'TypeRep' itself is now an
-- instance of 'Ord', so mappings can be made directly with 'TypeRep'
-- as the key.
--
typeRepKey :: TypeRep -> IO TypeRepKey
typeRepKey (TypeRep f _ _) = return (TypeRepKey f)
--
-- let fTy = mkTyCon "Foo" in show (mkTyConApp (mkTyCon ",,")
-- [fTy,fTy,fTy])
--
-- returns "(Foo,Foo,Foo)"
--
-- The TypeRep Show instance promises to print tuple types
-- correctly. Tuple type constructors are specified by a
-- sequence of commas, e.g., (mkTyCon ",,,,") returns
-- the 5-tuple tycon.
newtype TypeRepKey = TypeRepKey Fingerprint
deriving (Eq,Ord)
----------------- Construction ---------------------
{-# DEPRECATED mkTyCon "either derive Typeable, or use mkTyCon3 instead" #-} -- deprecated in 7.2
-- | Backwards-compatible API
mkTyCon :: String -- ^ unique string
-> TyCon -- ^ A unique 'TyCon' object
mkTyCon name = TyCon (fingerprintString name) "" "" name
-------------------------------------------------------------
--
-- Type-safe cast
--
-------------------------------------------------------------
-- | The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b
cast x = r
where
r = if typeOf x == typeOf (fromJust r)
then Just $ unsafeCoerce x
else Nothing
-- | A flexible variation parameterised in a type constructor
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
gcast x = r
where
r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> *
gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
gcast1 x = r
where
r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> * -> *
gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))
gcast2 x = r
where
r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
| frantisekfarka/ghc-dsi | libraries/base/Data/OldTypeable.hs | bsd-3-clause | 6,688 | 0 | 13 | 1,919 | 818 | 497 | 321 | 104 | 2 |
{--! run liquid with idirs=../../benchmarks/bytestring-0.9.2.1 idirs=../../include no-termination -}
{-# OPTIONS_GHC -cpp -fglasgow-exts -fno-warn-orphans #-}
-- GET THIS TO WORK WITHOUT THE "base" measure and realated theorem,
-- but with raw pointer arithmetic. I.e. give plusPtr the right signature:
-- (v = base + off)
-- Can do so now, by:
--
-- embed Ptr as int
--
-- but the problem is that then it throws off all qualifier definitions like
--
-- qualif EqPLen(v: ForeignPtr a, x: Ptr a): (fplen v) = (plen x)
-- qualif EqPLen(v: Ptr a, x: ForeignPtr a): (plen v) = (fplen x)
--
-- because there is no such thing as Ptr a by the time we get to Fixpoint. yuck.
-- Meaning we have to rewrite the above to the rather lame:
-- qualif EqPLenPOLY2(v: a, x: b): (plen v) = (fplen x)
module Data.ByteString (
ByteString, -- abstract, instances: Eq, Ord, Show, Read, Data, Typeable, Monoid
foldl -- :: (a -> Word8 -> a) -> a -> ByteString -> a
) where
import Language.Haskell.Liquid.Prelude
import qualified Prelude as P
import Prelude hiding (reverse,head,tail,last,init,null
,length,map,lines,foldl,foldr,unlines
,concat,any,take,drop,splitAt,takeWhile
,dropWhile,span,break,elem,filter,maximum
,minimum,all,concatMap,foldl1,foldr1
,scanl,scanl1,scanr,scanr1
,readFile,writeFile,appendFile,replicate
,getContents,getLine,putStr,putStrLn,interact
,zip,zipWith,unzip,notElem)
import Data.ByteString.Internal
import Data.ByteString.Unsafe
import Data.ByteString.Fusion
import qualified Data.List as List
import Data.Word (Word8)
import Data.Maybe (listToMaybe)
import Data.Array (listArray)
import qualified Data.Array as Array ((!))
-- Control.Exception.bracket not available in yhc or nhc
#ifndef __NHC__
import Control.Exception (bracket, assert)
import qualified Control.Exception as Exception
#else
import IO (bracket)
#endif
import Control.Monad (when)
import Foreign.C.String (CString, CStringLen)
import Foreign.C.Types (CSize)
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc (allocaBytes, mallocBytes, reallocBytes, finalizerFree)
import Foreign.Marshal.Array (allocaArray)
import Foreign.Ptr
import Foreign.Storable (Storable(..))
-- hGetBuf and hPutBuf not available in yhc or nhc
import System.IO (stdin,stdout,hClose,hFileSize
,hGetBuf,hPutBuf,openBinaryFile
,Handle,IOMode(..))
import Data.Monoid (Monoid, mempty, mappend, mconcat)
#if !defined(__GLASGOW_HASKELL__)
import System.IO.Unsafe
import qualified System.Environment
import qualified System.IO (hGetLine)
#endif
#if defined(__GLASGOW_HASKELL__)
import System.IO (hGetBufNonBlocking)
import System.IO.Error (isEOFError)
import GHC.Handle
import GHC.Prim (Word#, (+#), writeWord8OffAddr#)
import GHC.Base (build)
import GHC.Word hiding (Word8)
import GHC.Ptr (Ptr(..))
import GHC.ST (ST(..))
import GHC.IOBase
#endif
-- An alternative to Control.Exception (assert) for nhc98
#ifdef __NHC__
#define assert assertS "__FILE__ : __LINE__"
assertS :: String -> Bool -> a -> a
assertS _ True = id
assertS s False = error ("assertion failed at "++s)
#endif
-- LIQUID
import GHC.IO.Buffer
import Language.Haskell.Liquid.Prelude (intCSize)
import qualified Data.ByteString.Lazy.Internal
import qualified Data.ByteString.Fusion
import qualified Data.ByteString.Internal
import qualified Data.ByteString.Unsafe
import qualified Foreign.C.Types
{-@ memcpy_ptr_baoff :: p:(Ptr a)
-> RawBuffer b
-> Int
-> {v:CSize | (OkPLen v p)} -> IO (Ptr ())
@-}
memcpy_ptr_baoff :: Ptr a -> RawBuffer b -> Int -> CSize -> IO (Ptr ())
memcpy_ptr_baoff = error "LIQUIDCOMPAT"
readCharFromBuffer :: RawBuffer b -> Int -> IO (Char, Int)
readCharFromBuffer x y = error "LIQUIDCOMPAT"
wantReadableHandleLIQUID :: String -> Handle -> (Handle__ -> IO a) -> IO a
wantReadableHandleLIQUID x y f = error $ show $ liquidCanaryFusion 12 -- "LIQUIDCOMPAT"
{-@ qualif Gimme(v:a, n:b, acc:a): (len v) = (n + 1 + (len acc)) @-}
{-@ qualif Zog(v:a, p:a) : (plen p) <= (plen v) @-}
{-@ qualif Zog(v:a) : 0 <= (plen v) @-}
{- type ByteStringNE = {v:ByteString | (bLength v) > 0} @-}
{- type ByteStringSZ B = {v:ByteString | (bLength v) = (bLength B)} @-}
-- -----------------------------------------------------------------------------
--
-- Useful macros, until we have bang patterns
--
#define STRICT1(f) f a | a `seq` False = undefined
#define STRICT2(f) f a b | a `seq` b `seq` False = undefined
#define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined
#define STRICT4(f) f a b c d | a `seq` b `seq` c `seq` d `seq` False = undefined
#define STRICT5(f) f a b c d e | a `seq` b `seq` c `seq` d `seq` e `seq` False = undefined
-- -----------------------------------------------------------------------------
{-@ foldl :: (a -> Word8 -> a) -> a -> ByteString -> a @-}
foldl :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl f v (PS x s l) = inlinePerformIO $ withForeignPtr x $ \ptr ->
lgo v (ptr `plusPtr` s) (ptr `plusPtr` (s+l))
where
STRICT3(lgo)
lgo z p q | eqPtr p q = return z
| otherwise = do c <- peek p
lgo (f z c) (p `plusPtr` 1) q
{-# INLINE foldl #-}
{- liquid_thm_ptr_cmp :: p:PtrV a
-> q:{v:(PtrV a) | ((plen v) <= (plen p) && v != p && (pbase v) = (pbase p))}
-> {v: (PtrV a) | ((v = p) && ((plen q) < (plen p))) }
@-}
liquid_thm_ptr_cmp :: Ptr a -> Ptr a -> Ptr a
liquid_thm_ptr_cmp p q = p
-- | 'foldl\'' is like 'foldl', but strict in the accumulator.
-- Though actually foldl is also strict in the accumulator.
foldl' :: (a -> Word8 -> a) -> a -> ByteString -> a
foldl' = foldl
{-# INLINE foldl' #-}
-- | Perform an operation with a temporary ByteString
withPtr :: ForeignPtr a -> (Ptr a -> IO b) -> b
withPtr fp io = inlinePerformIO (withForeignPtr fp io)
{-# INLINE withPtr #-}
-- Common up near identical calls to `error' to reduce the number
-- constant strings created when compiled:
{-@ errorEmptyList :: {v:String | false} -> a @-}
errorEmptyList :: String -> a
errorEmptyList fun = moduleError fun "empty ByteString"
{-# NOINLINE errorEmptyList #-}
moduleError :: String -> String -> a
moduleError fun msg = error ("Data.ByteString." ++ fun ++ ':':' ':msg)
{-# NOINLINE moduleError #-}
-- LIQUID -- -- Find from the end of the string using predicate
-- LIQUID -- findFromEndUntil :: (Word8 -> Bool) -> ByteString -> Int
-- LIQUID -- STRICT2(findFromEndUntil)
-- LIQUID -- findFromEndUntil f ps@(PS x s l) =
-- LIQUID -- if null ps then 0
-- LIQUID -- else if f (last ps) then l
-- LIQUID -- else findFromEndUntil f (PS x s (l-1))
| mightymoose/liquidhaskell | tests/todo/ptr.hs | bsd-3-clause | 7,332 | 0 | 12 | 1,900 | 1,201 | 728 | 473 | -1 | -1 |
{-# OPTIONS -XRecursiveDo #-}
-- test let bindings, polymorphism is ok provided they are not
-- isolated in a recursive segment
-- NB. this is not what Hugs does!
module Main (main) where
import Control.Monad.Fix
t :: IO (Int, Int)
t = mdo let l [] = 0
l (x:xs) = 1 + l xs
return (l "1", l [1,2,3])
main :: IO ()
main = t >>= print
| siddhanathan/ghc | testsuite/tests/mdo/should_compile/mdo004.hs | bsd-3-clause | 352 | 0 | 13 | 89 | 119 | 66 | 53 | -1 | -1 |
module Barcode where
import Control.Applicative ((<$>))
import Control.Monad (forM_)
import Data.Array (Array(..), (!), bounds, elems, indices, ixmap, listArray)
import Data.Char (digitToInt)
import Data.Ix (Ix(..))
import Data.List (foldl', group, sort, sortBy, tails)
import Data.Maybe (catMaybes, listToMaybe)
import Data.Ratio (Ratio)
import Data.Word (Word8)
import System.Environment (getArgs)
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.Map as M
import Parse
checkDigit :: (Integral a) => [a] -> a
checkDigit ds = 10 - (sum products `mod` 10)
where products = mapEveryOther (*3) (reverse ds)
mapEveryOther :: (a -> a) -> [a] -> [a]
mapEveryOther f = zipWith ($) (cycle [f, id])
leftOddList = [
"0001101", "0011001", "0010011", "0111101", "0100011",
"0110001", "0101111", "0111011", "0110111", "0001011"]
rightList = map complement <$> leftOddList
where
complement '0' = '1'
complement '1' = '0'
leftEvenList = map reverse rightList
parityList = [
"111111", "110100", "110010", "110001", "101100",
"100110", "100011", "101010", "101001", "100101"]
listToArray :: [a] -> Array Int a
listToArray xs = listArray (0, l-1) xs
where l = length xs
leftOddCodes, leftEvenCodes, rightCodes, parityCodes :: Array Int String
leftOddCodes = listToArray leftOddList
leftEvenCodes = listToArray leftEvenList
rightCodes = listToArray rightList
parityCodes = listToArray parityList
foldA :: Ix k => (a -> b -> a) -> a -> Array k b -> a
foldA f s a = go s (indices a)
where
go s (j:js) =
let s' = f s (a ! j)
in s' `seq` go s' js
go s _ = s
foldA1 :: Ix k => (a -> a -> a) -> Array k a -> a
foldA1 f a = foldA f (a ! fst (bounds a)) a
encodeEAN13 :: String -> String
encodeEAN13 = concat . encodeDigits . map digitToInt
encodeDigits :: [Int] -> [String]
encodeDigits s@(first:rest) =
outerGuard : lefties ++ centerGuard : righties ++ [outerGuard]
where
(left, right) = splitAt 5 rest
lefties = zipWith leftEncode (parityCodes ! first) left
righties = map rightEncode (right ++ [checkDigit s])
leftEncode :: Char -> Int -> String
leftEncode '1' = (leftOddCodes !)
leftEncode '0' = (leftEvenCodes !)
rightEncode :: Int -> String
rightEncode = (rightCodes !)
outerGuard = "101"
centerGuard = "01010"
type Pixel = Word8
type RGB = (Pixel, Pixel, Pixel)
type Pixmap = Array (Int, Int) RGB
parseRawPPM :: Parse Pixmap
parseRawPPM =
parseWhileWith w2c (/= '\n') ==> \header -> assert (header == "P6") "invalid raw header" ==>&
skipSpaces ==>&
parseNat ==> \width -> skipSpaces ==>&
parseNat ==> \height -> skipSpaces ==>&
parseNat ==> \maxValue -> assert (maxValue == 255) "max vlue out of spec" ==>&
parseByte ==>&
parseTimes (width * height) parseRGB ==> \pxs ->
identity (listArray ((0, 0), (width-1, height-1)) pxs)
parseRGB :: Parse RGB
parseRGB =
parseByte ==> \r ->
parseByte ==> \g ->
parseByte ==> \b ->
identity (r, g, b)
parseTimes :: Int -> Parse a -> Parse [a]
parseTimes 0 _ = identity []
parseTimes n p = p ==> \x -> (x:) <$> parseTimes (n-1) p
luminance :: (Pixel, Pixel, Pixel) -> Pixel
luminance (r, g, b) = round (r' * 0.30 + g' * 0.59 + b' * 0.11)
where
r' = fromIntegral r
g' = fromIntegral g
b' = fromIntegral b
type Greymap = Array (Int, Int) Pixel
pixmapToGreymap :: Pixmap -> Greymap
pixmapToGreymap = fmap luminance
data Bit = Zero | One deriving (Eq, Show)
threshold :: (Ix k, Integral a) => Double -> Array k a -> Array k Bit
threshold n a = binary <$> a
where
binary i
| i < pivot = Zero
| otherwise = One
pivot = round $ least + (greatest - least) * n
least = fromIntegral $ choose (<) a
greatest = fromIntegral $ choose (>) a
choose f = foldA1 $ \x y -> if f x y then x else y
type Run = Int
type RunLength a = [(Run, a)]
runLength :: Eq a => [a] -> RunLength a
runLength = map rle . group
where rle xs = (length xs, head xs)
runLengths :: Eq a => [a] -> [Run]
runLengths = map fst . runLength
type Score = Ratio Int
scaleToOne :: [Run] -> [Score]
scaleToOne xs = map divide xs
where
divide d = fromIntegral d / divisor
divisor = fromIntegral (sum xs)
type ScoreTable = [[Score]]
asSRL :: [String] -> ScoreTable
asSRL = map (scaleToOne . runLengths)
leftOddSRL = asSRL leftOddList
leftEvenSRL = asSRL leftEvenList
rightSRL = asSRL rightList
paritySRL = asSRL parityList
distance :: [Score] -> [Score] -> Score
distance a b = sum . map abs $ zipWith (-) a b
bestScores :: ScoreTable -> [Run] -> [(Score, Digit)]
bestScores srl ps = take 3 . sort $ scores
where
scores = zip [distance d (scaleToOne ps) | d <- srl] digits
digits = [0..9]
data Parity a = Even a | Odd a | None a deriving (Show)
fromParity :: Parity a -> a
fromParity (Even a) = a
fromParity (Odd a) = a
fromParity (None a) = a
parityMap :: (a -> b) -> Parity a -> Parity b
parityMap f (Even a) = Even (f a)
parityMap f (Odd a) = Odd (f a)
parityMap f (None a) = None (f a)
instance Functor Parity where
fmap = parityMap
on :: (a -> a -> b) -> (c -> a) -> c -> c -> b
on f g x y = g x `f` g y
compareWithoutParity = compare `on` fromParity
type Digit = Word8
bestLeft :: [Run] -> [Parity (Score, Digit)]
bestLeft ps =
sortBy compareWithoutParity
((map Odd (bestScores leftOddSRL ps)) ++
(map Even (bestScores leftEvenSRL ps)))
bestRight :: [Run] -> [Parity (Score, Digit)]
bestRight = map None . bestScores rightSRL
chunkWith :: ([a] -> ([a], [a])) -> [a] -> [[a]]
chunkWith _ [] = []
chunkWith f xs =
let (h, t) = f xs
in h : chunkWith f t
chunksOf :: Int -> [a] -> [[a]]
chunksOf n = chunkWith (splitAt n)
candidateDigits :: RunLength Bit -> [[Parity Digit]]
candidateDigits ((_, One):_) = []
candidateDigits rle | length rle < 59 = []
candidateDigits rle
| any null match = []
| otherwise = map (map (fmap snd)) match
where
match = map bestLeft left ++ map bestRight right
left = chunksOf 4 . take 24 . drop 3 $ runLengths
right = chunksOf 4 . take 24 . drop 32 $ runLengths
runLengths = map fst rle
type Map a = M.Map Digit [a]
type DigitMap = Map Digit
type ParityMap = Map (Parity Digit)
updateMap ::
Parity Digit ->
Digit ->
[Parity Digit] ->
ParityMap ->
ParityMap
updateMap digit key seq =
insertMap key (fromParity digit) (digit:seq)
insertMap :: Digit -> Digit -> [a] -> Map a -> Map a
insertMap key digit val m = val `seq` M.insert key' val m
where key' = (key + digit) `mod` 10
useDigit :: ParityMap -> ParityMap -> Parity Digit -> ParityMap
useDigit old new digit =
new `M.union` M.foldWithKey (updateMap digit) M.empty old
incorporateDigits :: ParityMap -> [Parity Digit] -> ParityMap
incorporateDigits old digits = foldl' (useDigit old) M.empty digits
finalDigits :: [[Parity Digit]] -> ParityMap
finalDigits = foldl' incorporateDigits (M.singleton 0 []) . mapEveryOther (map (fmap (*3)))
firstDigit :: [Parity a] -> Digit
firstDigit =
snd .
head .
bestScores paritySRL .
runLengths .
map parityBit .
take 6
where
parityBit (Even _) = Zero
parityBit (Odd _) = One
addFirstDigit :: ParityMap -> DigitMap
addFirstDigit = M.foldWithKey updateFirst M.empty
updateFirst :: Digit -> [Parity Digit] -> DigitMap -> DigitMap
updateFirst key seq = insertMap key digit (digit:renormalize qes)
where
renormalize = mapEveryOther (`div` 3) . map fromParity
digit = firstDigit qes
qes = reverse seq
buildMap :: [[Parity Digit]] -> DigitMap
buildMap =
M.mapKeys (10 -) .
addFirstDigit .
finalDigits
solve :: [[Parity Digit]] -> [[Digit]]
solve [] = []
solve xs = catMaybes $ map (addCheckDigit m) checkDigits
where
checkDigits = map fromParity (last xs)
m = buildMap (init xs)
addCheckDigit m k = (++[k]) <$> M.lookup k m
withRow :: Int -> Pixmap -> (RunLength Bit -> a) -> a
withRow n greymap f = f . runLength . elems $ posterized
where
posterized = threshold 0.4 . fmap luminance . row n $ greymap
row :: (Ix a, Ix b) => b -> Array (a, b) c -> Array a c
row j a = ixmap (l, u) project a
where
project i = (i, j)
((l, _), (u, _)) = bounds a
findMatch :: [(Run, Bit)] -> Maybe [[Digit]]
findMatch =
listToMaybe
. filter (not . null)
. map (solve . candidateDigits)
. tails
findEAN13 :: Pixmap -> Maybe [Digit]
findEAN13 pixmap = withRow center pixmap (fmap head . findMatch)
where
(_, (maxX, _)) = bounds pixmap
center = (maxX + 1) `div` 2
main :: IO ()
main = do
args <- getArgs
forM_ args $ \arg -> do
e <- parse parseRawPPM <$> L.readFile arg
case e of
Left err ->
print $ "error: " ++ err
Right pixmap ->
print $ findEAN13 pixmap
| pauldoo/scratch | RealWorldHaskell/ch12/Barcode.hs | isc | 9,022 | 0 | 20 | 2,273 | 3,779 | 2,016 | 1,763 | 240 | 2 |
{-# LANGUAGE LambdaCase #-}
module Main (main) where
import Data.Foldable (asum)
import Data.Functor (($>))
import Data.List (nub)
import Data.Void (Void)
import System.IO (hFlush, stdout)
import Text.Megaparsec (Parsec, eof, parse, sepBy1, some, try, (<|>))
import Text.Megaparsec.Char (char, digitChar, space, space1, string)
import Text.Megaparsec.Error (errorBundlePretty)
data Modifier
= Even
| Odd
| EveryOtherEven
| EveryOtherOdd
deriving Show
data Problems
= Single Int
| Range Int Int
| ModifiedRange Int Int Modifier
deriving Show
type Parser = Parsec Void String
int :: Parser Int
int = read <$> some digitChar
modifier :: Parser Modifier
modifier = asum
[ string "even" $> Even
, string "odd" $> Odd
, string "eoe" $> EveryOtherEven
, string "eoo" $> EveryOtherOdd
]
single :: Parser Problems
single = Single <$> int
range :: Parser Problems
range = do
x <- int
_ <- char '-'
y <- int
pure (Range x y)
modifiedRange :: Parser Problems
modifiedRange = do
Range x y <- range
_ <- space1
m <- modifier
pure (ModifiedRange x y m)
problems :: Parser Problems
problems = try modifiedRange <|> try range <|> single
someProblems :: Parser [Problems]
someProblems = problems `sepBy1` (char ',' *> space) <* eof
everyOther :: [a] -> [a]
everyOther [] = []
everyOther [x] = [x]
everyOther (x : _ : xs) = x : everyOther xs
problemsToList :: Problems -> [Int]
problemsToList = \case
Single x -> [x]
Range x y -> [x .. y]
ModifiedRange x y m ->
let
evens = filter even [x .. y]
odds = filter odd [x .. y]
in
case m of
Even -> evens
Odd -> odds
EveryOtherEven -> everyOther evens
EveryOtherOdd -> everyOther odds
countProblems :: [Problems] -> Int
countProblems = length . nub . concatMap problemsToList
problemCounter :: String -> String
problemCounter input =
case parse someProblems "" input of
Left errorBundle -> errorBundlePretty errorBundle
Right ps -> "Problems: " <> show (countProblems ps)
prompt :: String -> IO String
prompt s = do
putStr s
hFlush stdout
getLine
main :: IO ()
main = do
input <- prompt "Enter problems: "
putStrLn (problemCounter input)
| evanrelf/problem-counter | haskell/src/Main.hs | isc | 2,225 | 0 | 13 | 510 | 811 | 425 | 386 | 81 | 6 |
module Exercise where
list35 :: Int -> [Int]
list35 k = [x | x <- [1..k-1], x `mod` 3 == 0 || x `mod` 5 == 0]
add35 :: Int -> Int
add35 k = sum $ list35 k
add :: [Int] -> Int -> Int
add ks n = sum $ filter (\x -> any (\y -> x `mod` y == 0) ks) [0..n-1]
-- alternative
add' :: [Int] -> Int -> Int
add' ks n = sum [n | n <- [0..n-1], any (\k -> n `mod` k == 0) ks]
| tcoenraad/functioneel-programmeren | 2014/opg1a.hs | mit | 367 | 0 | 13 | 97 | 248 | 136 | 112 | 9 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module Web.Hablog.Html where
import Data.String (fromString)
import Data.List (sort)
import qualified Data.Text.Lazy as T
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5.Attributes as A
import Web.Hablog.Config
import qualified Web.Hablog.Post as Post
import qualified Web.Hablog.Page as Page
template :: Config -> Post.Preview -> Bool -> T.Text -> String -> H.Html -> H.Html
template cfg preview highlight title' pageRoute container = do
let
title = T.concat [blogTitle cfg, " - ", title']
H.docTypeHtml $ do
H.head $ do
H.title (H.toHtml title)
H.meta ! A.charset "utf-8"
H.meta ! A.content "width=650" ! A.name "viewport"
addPreview (preview { Post.previewTitle = Just title })
H.link ! A.rel "stylesheet" ! A.type_ "text/css" ! A.href (H.stringValue . bgTheme $ blogTheme cfg)
if highlight
then H.link ! A.rel "stylesheet" ! A.type_ "text/css" ! A.href (H.stringValue . codeTheme $ blogTheme cfg)
else mempty
H.body $ do
H.div ! A.class_ "container" $ do
logo cfg pageRoute
H.div ! A.class_ "maincontainer" $ container
footer
if highlight
then do
H.script ! A.src "/static/highlight/highlight.pack.js" $ ""
H.script "hljs.initHighlightingOnLoad();"
else
mempty
addPreview :: Post.Preview -> H.Html
addPreview Post.Preview{..} = do
mymeta "description" previewTitle
mymeta "author" previewAuthor
mymeta "twitter:card" (Just "summary")
mymeta "twitter:site" previewSite
mymeta "twitter:title" previewTitle
mymeta "twitter:description" previewSummary
mymeta "twitter:image" (T.pack . fst <$> previewImage)
mymeta "twitter:image-alt" (snd <$> previewImage)
where
mymeta name mcontent =
case mcontent of
Nothing -> pure ()
Just content ->
H.meta ! A.name name ! A.content (H.textValue $ T.toStrict content)
mainTemplate :: H.Html -> H.Html
mainTemplate = H.article ! A.class_ "content"
notFoundPage :: Config -> H.Html
notFoundPage cfg =
template cfg Post.noPreview False "Not Found" "notfound" $ mainTemplate $ do
H.h1 "Not found"
H.p "The page you search for is not available."
logo :: Config -> String -> H.Html
logo cfg pageRoute = H.header ! A.class_ "logo" $ H.h1 $ do
H.a ! A.href (H.stringValue $ "/" ++ pageRoute) $ H.toHtml (blogTitle cfg)
"/" >> H.toHtml pageRoute
footer :: H.Html
footer = H.footer ! A.class_ "footer" $ do
H.div $ H.a ! A.href "/blog/rss" $ "RSS feed"
H.span "Powered by "
H.a ! A.href "https://github.com/soupi/hablog" $ "Hablog"
errorPage :: Config -> T.Text -> String -> H.Html
errorPage cfg ttl msg =
template cfg Post.noPreview False ttl "" $ do
H.h2 "Something Went Wrong..."
H.p $ H.toHtml msg
emptyPage :: H.Html
emptyPage = H.span " "
postsListHtml :: [Post.Post] -> H.Html
postsListHtml posts =
H.div ! A.class_ "PostsList" $ do
H.h1 "Posts"
postsList posts
postsList :: [Post.Post] -> H.Html
postsList = H.ul . mconcat . fmap postsListItem
postsListItem :: Post.Post -> H.Html
postsListItem post = H.li $ do
H.span ! A.class_ "postDate" $ H.toHtml $ Post.getDate post
H.span ! A.class_ "seperator" $ " - "
H.a ! A.href (fromString $ T.unpack ("/blog/" `T.append` Post.getPath post)) $ H.toHtml $ Post.postTitle post
postPage :: Config -> Post.Post -> H.Html
postPage cfg post = template cfg (Post.postPreview post) True (Post.postTitle post) "blog" $
H.article ! A.class_ "post" $ do
H.div ! A.class_ "postTitle" $ do
H.a ! A.href (fromString $ T.unpack ("/blog/" `T.append` Post.getPath post)) $ H.h2 ! A.class_ "postHeader" $ H.toHtml (Post.postTitle post)
H.span ! A.class_ "postSubTitle" $ do
H.span ! A.class_ "postAuthor" $ H.toHtml $ authorsList $ Post.postAuthors post
H.span ! A.class_ "seperator" $ " - "
H.span ! A.class_ "postDate" $ H.toHtml $ Post.getDate post
H.span ! A.class_ "seperator" $ " - "
H.span ! A.class_ "postTags" $ tagsList (Post.postTags post)
H.div ! A.class_ "postContent" $ Post.postContent post
pagePage :: Config -> Page.Page -> H.Html
pagePage cfg page =
template
cfg
(Page.pagePreview page)
True
(Page.pageName page)
(Page.pageURL page)
(pageContent page)
pageContent :: Page.Page -> H.Html
pageContent page = do
H.article ! A.class_ "post" $ do
H.div ! A.class_ "postContent" $ Page.pageContent page
pagesList :: [Page.Page] -> H.Html
pagesList = mconcat . fmap pagesListItem . sort
pagesListItem :: Page.Page -> H.Html
pagesListItem page =
H.li
$ H.a ! A.href (fromString ("/" ++ Page.pageURL page))
$ H.toHtml (Page.pageName page)
tagsList :: [T.Text] -> H.Html
tagsList = H.ul . mconcat . fmap tagsListItem . sort
tagsListItem :: T.Text -> H.Html
tagsListItem tag = H.li $ H.a ! A.href (fromString $ T.unpack ("/blog/tags/" `T.append` tag)) $ H.toHtml tag
authorsList :: [T.Text] -> H.Html
authorsList = H.ul . mconcat . fmap authorsListItem . sort
authorsListItem :: T.Text -> H.Html
authorsListItem author = H.li $ H.a ! A.href (fromString $ T.unpack ("/blog/authors/" `T.append` author)) $ H.toHtml author
| soupi/hablog | src/Web/Hablog/Html.hs | mit | 5,320 | 0 | 22 | 1,129 | 2,009 | 985 | 1,024 | 126 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : System.Console.GetFlag
-- Copyright : (c) Troels Henriksen 2010
-- (c) Sven Panne 2002-2005
-- License : MIT-style (see LICENSE)
-- Stability : stable
-- Portability : portable
--
-- This adaptation of "System.Console.GetOpt" provides easy handling
-- of classic Unix/Plan 9-style command line options. This means that
-- single dashes are used to prefix option names, which may be of any
-- length (not just single characters, although such is generally
-- recommended). It is not possible to collapse multiple options in a
-- single parameter, so you will have to write @-a -b@ instead of
-- @-ab@. A single GNU extension is included: the parameter @--@ will
-- cause anything past it to be returned as arguments, not options,
-- even if the parameters have leading dashes.
--
-- The API is almost compatible with "System.Console.GetOpt", the only
-- difference being in 'OptDescr', which no longer permits multiple
-- names per option.
--
-----------------------------------------------------------------------------
module System.Console.GetFlag (
-- * GetFlag
getOpt, getOpt',
usageInfo,
ArgOrder(..),
OptDescr(..),
ArgDescr(..),
-- * Examples
-- |To hopefully illuminate the role of the different data structures,
-- here are the command-line options for a (very simple) compiler,
-- done in two different ways.
-- The difference arises because the type of 'getOpt' is
-- parameterized by the type of values derived from flags.
-- ** Interpreting flags as concrete values
-- $example1
-- ** Interpreting flags as transformations of an options record
-- $example2
) where
import Prelude
-- |What to do with options following non-options
data ArgOrder a
= RequireOrder -- ^ no option processing after first non-option
| Permute -- ^ freely intersperse options and non-options
| ReturnInOrder (String -> a) -- ^ wrap non-options into options
{-|
Each 'OptDescr' describes a single option.
The arguments to 'Option' are:
* the name of the option
* argument descriptor
* explanation of option for user
-}
data OptDescr a = -- description of a single options:
Option String -- option string
(ArgDescr a) -- argument descriptor
String -- explanation of option for user
-- |Describes whether an option takes an argument or not, and if so
-- how the argument is injected into a value of type @a@.
data ArgDescr a
= NoArg a -- ^ no argument expected
| ReqArg (String -> a) String -- ^ option requires argument
| OptArg (Maybe String -> a) String -- ^ optional argument
data OptKind a -- kind of cmd line arg (internal use only):
= Opt a -- an option
| UnreqOpt String -- an un-recognized option
| NonOpt String -- a non-option
| EndOfOpts -- end-of-options marker (i.e. "--")
| OptErr String -- something went wrong...
-- | Return a string describing the usage of a command, derived from
-- the header (first argument) and the options described by the
-- second argument.
usageInfo :: String -- header
-> [OptDescr a] -- option descriptors
-> String -- nicely formatted decription of options
usageInfo header optDescr = unlines (header:table)
where (ss,ds) = (unzip . concatMap fmtOpt) optDescr
table = zipWith paste (sameLen ss) ds
paste x y = " " ++ x ++ " " ++ y
sameLen xs = flushLeft ((maximum . map length) xs) xs
flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]
fmtOpt :: OptDescr a -> [(String,String)]
fmtOpt (Option name ad descr) =
case lines descr of
[] -> [(fmt ad,"")]
(d:ds) -> (fmt ad,d) : [ ("",d') | d' <- ds ]
where fmt (NoArg _ ) = '-' : name
fmt (ReqArg _ ad') = '-' : name ++ " " ++ ad'
fmt (OptArg _ ad') = '-' : name ++ "[" ++ ad' ++ "]"
{-|
Process the command-line, and return the list of values that matched
(and those that didn\'t). The arguments are:
* The order requirements (see 'ArgOrder')
* The option descriptions (see 'OptDescr')
* The actual command line arguments (presumably got from
'System.Environment.getArgs').
'getOpt' returns a triple consisting of the option arguments, a list
of non-options, and a list of error messages.
-}
getOpt :: ArgOrder a -- non-option handling
-> [OptDescr a] -- option descriptors
-> [String] -- the command-line arguments
-> ([a],[String],[String]) -- (options,non-options,error messages)
getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us)
where (os,xs,us,es) = getOpt' ordering optDescr args
{-|
This is almost the same as 'getOpt', but returns a quadruple
consisting of the option arguments, a list of non-options, a list of
unrecognized options, and a list of error messages.
-}
getOpt' :: ArgOrder a -- non-option handling
-> [OptDescr a] -- option descriptors
-> [String] -- the command-line arguments
-> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages)
getOpt' _ _ [] = ([],[],[],[])
getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering
where procNextOpt (Opt o) _ = (o:os,xs,us,es)
procNextOpt (UnreqOpt u) _ = (os,xs,u:us,es)
procNextOpt (NonOpt x) RequireOrder = ([],x:rest,[],[])
procNextOpt (NonOpt x) Permute = (os,x:xs,us,es)
procNextOpt (NonOpt x) (ReturnInOrder f) = (f x :os, xs,us,es)
procNextOpt EndOfOpts RequireOrder = ([],rest,[],[])
procNextOpt EndOfOpts Permute = ([],rest,[],[])
procNextOpt EndOfOpts (ReturnInOrder f) = (map f rest,[],[],[])
procNextOpt (OptErr e) _ = (os,xs,us,e:es)
(opt,rest) = getNext arg args optDescr
(os,xs,us,es) = getOpt' ordering optDescr rest
-- take a look at the next cmd line arg and decide what to do with it
getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
getNext ('-':'-':[]) rest _ = (EndOfOpts,rest)
getNext ('-':xs) rest optDescr = handleOpt xs rest optDescr
getNext arg rest _ = (NonOpt arg,rest)
handleOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])
handleOpt ls rs optDescr = opt ads rs
where options = [ o | o@(Option name _ _) <- optDescr
, ls == name ]
ads = [ ad | Option _ ad _ <- options ]
optStr = '-':ls
opt [NoArg a ] rest = (Opt a,rest)
opt [ReqArg _ d] [] = (errReq d optStr,[])
opt [ReqArg f _] (r:rest) = (Opt (f r),rest)
opt [OptArg f _] rest = (Opt (f Nothing),rest)
opt [] rest = (UnreqOpt optStr,rest)
opt _ rest = (errAmbig options optStr,rest)
-- miscellaneous error formatting
errAmbig :: [OptDescr a] -> String -> OptKind a
errAmbig ods optStr = OptErr (usageInfo header ods)
where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"
errReq :: String -> String -> OptKind a
errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")
errUnrec :: String -> String
errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n"
{-
-----------------------------------------------------------------------------------------
-- and here a small and hopefully enlightening example:
data Flag = Verbose | Version | Name String | Output String | Arg String deriving Show
options :: [OptDescr Flag]
options =
[Option "ve" (NoArg Verbose) "verbosely list files",
Option "v" (NoArg Version) "show version info",
Option "o" (OptArg out "FILE") "use FILE for dump",
Option "n" (ReqArg Name "USER") "only dump USER's files"]
out :: Maybe String -> Flag
out Nothing = Output "stdout"
out (Just o) = Output o
test :: ArgOrder Flag -> [String] -> String
test order cmdline = case getOpt order options cmdline of
(o,n,[] ) -> "options=" ++ show o ++ " args=" ++ show n ++ "\n"
(_,_,errs) -> concat errs ++ usageInfo header options
where header = "Usage: foobar [OPTION...] files..."
-- example runs:
-- putStr (test RequireOrder ["foo","-v"])
-- ==> options=[] args=["foo", "-v"]
-- putStr (test Permute ["foo","-v"])
-- ==> options=[Verbose] args=["foo"]
-- putStr (test (ReturnInOrder Arg) ["foo","-v"])
-- ==> options=[Arg "foo", Verbose] args=[]
-- putStr (test Permute ["foo","--","-v"])
-- ==> options=[] args=["foo", "-v"]
-----------------------------------------------------------------------------------------
-}
{- $example1
A simple choice for the type associated with flags is to define a type
@Flag@ as an algebraic type representing the possible flags and their
arguments:
> module Opts1 where
>
> import System.Console.GetOpt
> import Data.Maybe ( fromMaybe )
>
> data Flag
> = Verbose | Version
> | Input String | Output String | LibDir String
> deriving Show
>
> options :: [OptDescr Flag]
> options =
> [ Option "verbose" (NoArg Verbose) "chatty output on stderr"
> , Option "v" (NoArg Version) "show version number"
> , Option "o" (OptArg outp "FILE") "output FILE"
> , Option "c" (OptArg inp "FILE") "input FILE"
> , Option "L" (ReqArg LibDir "DIR") "library directory"
> ]
>
> inp,outp :: Maybe String -> Flag
> outp = Output . fromMaybe "stdout"
> inp = Input . fromMaybe "stdin"
>
> compilerOpts :: [String] -> IO ([Flag], [String])
> compilerOpts argv =
> case getOpt Permute options argv of
> (o,n,[] ) -> return (o,n)
> (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
> where header = "Usage: ic [OPTION...] files..."
Then the rest of the program will use the constructed list of flags
to determine it\'s behaviour.
-}
{- $example2
A different approach is to group the option values in a record of type
@Options@, and have each flag yield a function of type
@Options -> Options@ transforming this record.
> module Opts2 where
>
> import System.Console.GetOpt
> import Data.Maybe ( fromMaybe )
>
> data Options = Options
> { optVerbose :: Bool
> , optShowVersion :: Bool
> , optOutput :: Maybe FilePath
> , optInput :: Maybe FilePath
> , optLibDirs :: [FilePath]
> } deriving Show
>
> defaultOptions = Options
> { optVerbose = False
> , optShowVersion = False
> , optOutput = Nothing
> , optInput = Nothing
> , optLibDirs = []
> }
>
> options :: [OptDescr (Options -> Options)]
> options =
> [ Option "verbose"
> (NoArg (\ opts -> opts { optVerbose = True }))
> "chatty output on stderr"
> , Option "v"
> (NoArg (\ opts -> opts { optShowVersion = True }))
> "show version number"
> , Option "o"
> (OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output")
> "FILE")
> "output FILE"
> , Option "c"
> (OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input")
> "FILE")
> "input FILE"
> , Option "L"
> (ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR")
> "library directory"
> ]
>
> compilerOpts :: [String] -> IO (Options, [String])
> compilerOpts argv =
> case getOpt Permute options argv of
> (o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
> (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
> where header = "Usage: ic [OPTION...] files..."
Similarly, each flag could yield a monadic function transforming a record,
of type @Options -> IO Options@ (or any other monad), allowing option
processing to perform actions of the chosen monad, e.g. printing help or
version messages, checking that file arguments exist, etc.
-}
| Athas/getflag | System/Console/GetFlag.hs | mit | 12,578 | 0 | 12 | 3,545 | 1,700 | 954 | 746 | 88 | 9 |
{-
Main file for 'comet', handles commands and provides documentation regarding
usage.
Author(s): Lewis Deane
License: MIT
Last Modified: 20/7/2016
-}
{-
TODO Get it so we use the current settings when appending and updating as opposed to simply using defaults everytime.
TODO Get it to print overview of current directory.
TODO Add force option where you can get the program can treat a file as another type.
TODO Add auto recognise file ext.
TODO Stop functions returning 'IO ()', only print to command line when necessary and don't throw errors in functions that may be used by functions outside of the primary usage.
TODO Allow 'comet update' to take multiple files.
TODO Rewrite parsing logic so doesn't matter what order arguments are passed.
-}
import Control.Applicative
import Data.List (delete, intercalate, isPrefixOf)
import Data.List.Split (splitOn)
import Paths_comet
import System.Environment
import System.Directory
import System.IO
import Text.Regex.Posix
import qualified Config as C
import qualified CommentTools as T
-- Type synonyms for increased readability.
type FileName = String
type Comment = String
-- Where everything begins.
main :: IO ()
main = getArgs >>= parse
-- Allowable settings.
settings :: [String]
settings = ["author", "comment-width", "date-format", "doc", "license", "maintainer", "default-fields", "website", "email"]
-- Parses the input from the command line and handles what should be done.
parse :: [String] -> IO ()
parse [] = doc
parse ["v"] = printVersion
parse ["version"] = printVersion
parse ["ls"] = printSettings
parse ["list-settings"] = printSettings
parse ["author"] = configG "author"
parse ["comment-width"] = configG "comment-width"
parse ["date-format"] = configG "date-format"
parse ["default-fields"] = configG "default-fields"
parse ["doc"] = configG "doc"
parse ["email"] = configG "email"
parse ["license"] = configG "license"
parse ["maintainer"] = configG "maintainer"
parse ["website"] = configG "website"
parse ["author", x] = configS "author" x
parse ["comment-width", x] = configS "comment-width" x
parse ["email", x] = if isLegalEmail x then configS "email" x else error $ x ++ " is not a valid email address."
parse ["date-format", x] = if isLegalDateFormat x then configS "date-format" x else error $ x ++ " is not a valid date format."
parse ["default-fields", x] = if isFieldShortcut $ tail x then configS' "default-fields" x else error $ tail x ++ " is not a valid field shortcut."
parse ["doc", x] = configS "doc" x
parse ["license", x] = configS "license" x
parse ["maintainer", x] = configS "maintainer" x
parse ["website", x] = configS "website" x
parse ["g", x] = T.currentComment x
parse ["get", x] = T.currentComment x
parse ["d", x] = T.deleteComment x
parse ["delete", x] = T.deleteComment x
parse ("u":x:xs) = T.updateComment x xs
parse ("update":x:xs) = T.updateComment x xs
parse ("s":x:y:xs) = T.setComment x y xs
parse ("set":x:y:xs) = T.setComment x y xs
parse ("a":x:y:xs) = T.appendComment x y xs
parse ("append" :x:y:xs) = T.appendComment x y xs
parse _ = putStrLn usage
-- Checks if the passed symbol is a shortcut for a setting.
isFieldShortcut :: String -> Bool
isFieldShortcut x | x == "a" = True
| x == "d" = True
| x == "e" = True
| x == "m" = True
| x == "l" = True
| x == "lm" = True
| x == "w" = True
| otherwise = False
-- Checks if the user has supplied a legal date format pattern.
isLegalDateFormat :: String -> Bool
isLegalDateFormat s | s =~ "(dd(/|-)mm(/|-)(yy|yyyy))" = True
| s =~ "(mm(/|-)dd(/|-)(yy|yyyy))" = True
| s =~ "(dd(/|-)(yy|yyyy)(/|-)mm)" = True
| s =~ "(mm(/|-)(yy|yyyy)(/|-)dd)" = True
| s =~ "((yy|yyyy)(/|-)dd(/|-)mm)" = True
| s =~ "((yy|yyyy)(/|-)mm(/|-)dd)" = True
| otherwise = False
-- Do a Regex check to see if the passed string is a valid email, e.g. xxx@yyy.zzz
isLegalEmail :: String -> Bool
isLegalEmail x = x =~ "(.+@.+\\..+)"
-- Provides a reusable string to be used after errors explaining what the user can do to get help.
usage :: String
usage = "Run 'comet' for a list of legal commands."
-- Launches the appropriate config action.
configS :: String -> String -> IO ()
configS k v = if k `elem` settings then C.writeValue (k, v) else error $ "No such setting '" ++ k ++ "' " ++ usage
-- This version of the above function handles the adding and removing of shortcuts within the value associated with the key.
configS' :: String -> String -> IO ()
configS' k v = do
values <- splitOn "," <$> C.readValue k
let v' = tail v
mode = head v
new = if v' `elem` values
then if mode == '-'
then delete v' values
else values
else if mode == '+'
then v' : values
else values
new' = intercalate "," new
configS k new'
-- Gets the current setting from confifg.
configG :: String -> IO ()
configG k = if k `elem` settings then prettyPrint <$> C.readValue k >>= putStrLn else error $ "No such setting '" ++ k ++ "' " ++ usage
-- Adds a new line before and after a string.
prettyPrint :: String -> String
prettyPrint s = "\n" ++ s ++ "\n"
-- What should be printed out when no args are passed to our inital command.
doc :: IO ()
doc = (putStrLn . unlines) $ [prettyPrint "---- USAGE ----"]
++ commands
++ [prettyPrint "You can also pass parameters when setting, appending or updating."]
++ parameters
++ [prettyPrint "With the following valid shortcuts."]
++ validParams
++ [prettyPrint "\n---- SUPPORTED LANGUAGES ----"]
++ languages
++ [prettyPrint "\n---- EXAMPLES ----"]
++ examples
++ [""]
-- List of commands to be outputted when 'comet' is run.
commands = T.genBlock "" 4 c
where c = [("COMMAND" , "DESCRIPTION"),
("comet s|set FILE COMMENT", "Write comment to file."),
("comet a|append FILE COMMENT", "Append comment to file."),
("comet d|delete FILE" , "Delete comment from file."),
("comet g|get FILE" , "Get comment block from file."),
("comet u|update FILE" , "Updates file with current settings."),
("comet v|version" , "Get current version."),
("comet ls|list-settings" , "List settings with values."),
("comet author" , "Get author."),
("comet author NAME" , "Set author to name."),
("comet comment-width" , "Get comment width."),
("comet comment-width NUM" , "Set comment width to num."),
("comet date-format" , "Get date format."),
("comet date-format PATTERN" , "Set date format to pattern."),
("comet default-fields" , "Get default-fields."),
("comet default-fields +l" , "Add license to default-fields."),
("comet default-fields -m" , "Remove maintainer from default-fields."),
("comet doc" , "Get doc."),
("comet doc DOC" , "Set doc to DOC."),
("comet email" , "Get email address."),
("comet email EMAIL" , "Set email address to EMAIL."),
("comet license" , "Get license."),
("comet license NAME" , "Set license to name."),
("comet maintainer" , "Get maintainer."),
("comet maintainer PATTERN" , "Set maintainer to name."),
("comet website" , "Get website url."),
("comet website URL" , "Set website url to URL.")]
-- Explains what the parameters mean.
parameters :: [String]
parameters = T.genBlock "" 4 c
where c = [("PARAMETER", "ACTION"),
("-p" , "Hide field associated with 'p'."),
("+p" , "Show field associated with 'p'."),
("+p VALUE" , "Show field associated with 'p' with value VALUE.")]
validParams :: [String]
validParams = T.genBlock "" 4 c
where c = [("SHORTCUT", "PARAMETER"),
("a" , "Author"),
("d" , "Documentation"),
("e" , "Email"),
("l" , "License"),
("lm" , "Last Modified"),
("m" , "Maintainer"),
("w" , "Website")]
-- Nicely formats allowed files and extensions.
languages :: [String]
languages = T.genBlock "" 4 l
where l = [("LANGUAGE" , "FILE EXTENSION"),
("Arduino" , ".pde .ino"),
("C" , ".c .h"),
("C++" , ".cpp"),
("CoffeeScript", ".coffee"),
("Common Lisp" , ".lisp"),
("C#" , ".cs"),
("CSS" , ".css"),
("ERB" , ".erb"),
("Go" , ".go"),
("HAML" , ".haml"),
("Haskell" , ".hs"),
("HTML" , ".html .htm .xhtml"),
("Java" , ".java"),
("JavaScript" , ".js"),
("Lisp" , ".lisp"),
("MatLab" , ".matlab"),
("Perl" , ".pl"),
("PHP" , ".php"),
("Python" , ".py"),
("R" , ".r"),
("Ruby" , ".rb"),
("Scala" , ".scala"),
("Scheme" , ".scm .ss"),
("SASS" , ".sass"),
("SCSS" , ".scss"),
("Swift" , ".swift"),
("XML" , ".xml")]
-- List of example usages to be printed.
examples :: [String]
examples = ["comet g Main.hs -> Get the comment block from Main.hs.",
"comet s Main.hs 'Hello' -l -> Set 'hello' as comment and hide the license field.",
"comet delete Main.hs -> Removes the comment block from Main.hs.",
"comet author 'Mark Twain' -> Set current author to 'Mark Twain'."]
-- Returns the current version number.
printVersion :: IO ()
printVersion = putStrLn "v1.2.0"
-- Prints a formatted block containing settings and their current values.
printSettings :: IO ()
printSettings = do
path <- getDataFileName "config.txt"
content <- lines <$> readFile path
(putStrLn . unlines . T.genBlock ":" 1 . map (\x -> let a = splitOn ":" x in (head a, last a))) content
| lewisjdeane/Comet | Main.hs | mit | 11,872 | 2 | 17 | 4,477 | 2,417 | 1,330 | 1,087 | 190 | 4 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.String.HTML (
-- * The HTML Widget
HTMLWidget,
-- * Constructor
mkHTMLWidget) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (when, join)
import Data.Aeson
import Data.IORef (newIORef)
import Data.Text (Text)
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
-- | A 'HTMLWidget' represents a HTML widget from IPython.html.widgets.
type HTMLWidget = IPythonWidget HTMLType
-- | Create a new HTML widget
mkHTMLWidget :: IO HTMLWidget
mkHTMLWidget = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetState = WidgetState $ defaultStringWidget "HTMLView"
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay HTMLWidget where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget HTMLWidget where
getCommUUID = uuid
| beni55/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/String/HTML.hs | mit | 1,455 | 0 | 11 | 340 | 253 | 143 | 110 | 32 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Game.MapReader(parseMap,mapToExport,GameMap (..)) where
import qualified Data.Map.Strict as Map
import Data.Char
import Data.Bits
import Data.Maybe
import Data.List
import Data.Ord
data GameMap = GameMap {size :: (Int, Int), items::[Int], sprites :: [(Int, Int, Int)]} deriving (Show, Eq)
type MapFromFile = Map.Map (Int, Int) Int
parseMap :: String -> IO MapFromFile
parseMap fileName = do
content <- readFile fileName
let linesOfFile = lines content
return (centerMap (Map.fromList (zipWith2dIndex (fmap (fmap digitToInt) linesOfFile))))
centerMap :: MapFromFile -> MapFromFile
centerMap mff = Map.foldrWithKey (\ (x,y) z acc -> Map.insert (x-(maxX `div` 2),y-(maxY `div` 2)) z acc) Map.empty mff
where
(maxX, maxY) = (maximum $ Map.keys mff)
(minX, minY) = (minimum $ Map.keys mff)
middleX = maxX - minX
middleY = maxY - minY
zipWith2dIndex :: [[a]] -> [((Int, Int), a)]
zipWith2dIndex xss = [((i, j), x) | (j,xs) <- zip [0..] xss
, (i,x) <- zip [0..] xs
]
test = [0,0,2,2,0,0,0,4,9,5,8,0,0,4,10,6,8,0,0,0,1,1,0,0]
test2= [15,15,15,15,15,15,15,15,0,0,15,15,15,15,0,0,15,15,15,15,15,15,15,15]
mapToExport :: MapFromFile -> GameMap
mapToExport gameMap = GameMap (x + 1, y + 1) (fmap snd $ sortBy (comparing comp) $ Map.assocs gameMap){-(Map.elems $ neonSprites gameMap)-} [( i, i*32, 0) | i <- [0..15]]
where
comp ((x,y), _) = (y,x)
(maxX, maxY) = (maximum $ Map.keys gameMap)
(minX, minY) = (minimum $ Map.keys gameMap)
x = maxX - minX
y = maxY - minY
neonSprites :: MapFromFile -> MapFromFile
neonSprites gameMap = Map.mapWithKey getSprite gameMap
where
getSprite k v = neighborScore $ neighbors k v gameMap
neighbors :: (Int, Int) -> Int -> MapFromFile -> [Int]
neighbors (x, y) v gameMap = fmap (\k-> differentValues $ fromMaybe 1 $ Map.lookup k gameMap) [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
where
differentValues i = if i == v then 0 else 1
neighborScore :: [Int] -> Int
neighborScore = foldl1 (.|.) . zipWith (*) [8,4,1,2]
| bruno-cadorette/TheLambdaReactor | src/Backend/Game/MapReader.hs | mit | 2,137 | 0 | 17 | 465 | 1,053 | 606 | 447 | 41 | 2 |
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
win = InWindow "" (400, 300) (10, 10)
main = play win white 60 (replicate 30 (0,0)) draw ev step
draw (_:blobs) = Pictures (map blob blobs)
blob (x,y) = Translate x y (Color c (ThickCircle 5 10))
c = withAlpha 0.3 azure
ev (EventMotion xy) (_:b) = xy:b
ev _ w = w
step _ (m:blobs) = m : (zipWith drift blobs (m:blobs))
drift (x,y) (u,v) = (0.9 * x + 0.1 * u,
0.9 * y + 0.1 * v)
| dominicprior/gloss-demo | demo5.hs | mit | 463 | 5 | 9 | 107 | 283 | 146 | 137 | 12 | 1 |
module Day8Spec (spec) where
import Day8
import Test.Hspec
import Data.Array.Unboxed ((//), listArray)
main :: IO ()
main = hspec spec
sampleInput :: String
sampleInput = unlines
[ "rect 3x2"
, "rotate column x=1 by 1"
, "rotate row y=0 by 4"
, "rotate column x=1 by 1 "
]
sampleParsed :: [Instruction]
sampleParsed =
[ Rect 3 2
, RotateColumn 1 1
, RotateRow 0 4
, RotateColumn 1 1
]
-- Screens obtained, in order, by starting with empty and moving through the
-- sample instructions
sampleScreens :: [Screen]
sampleScreens =
[ turnOn [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1)]
, turnOn [(0, 0), (2, 0), (0, 1), (1, 1), (2, 1), (1, 2)]
, turnOn [(4, 0), (6, 0), (0, 1), (1, 1), (2, 1), (1, 2)]
, turnOn [(1, 0), (4, 0), (6, 0), (0, 1), (2, 1), (1, 2)]
]
empty = listArray ((0, 0), (6, 2)) (repeat False)
turnOn :: [(Int, Int)] -> Screen
turnOn source = empty // [(i, True) | i <- source]
spec :: Spec
spec = do
describe "day8" $ do
it "finds 6 lit bulbs after following the sample instructions" $ do
day8 sampleInput `shouldBe` 6
it "finds 110 lit bulbs after following the actual instructions" $ do
actualInput <- readFile "inputs/day8.txt"
day8 actualInput `shouldBe` 110
describe "parseInput" $ do
it "works for sample input" $ do
parseInput sampleInput `shouldBe` Right sampleParsed
describe "applyInstructions"$ do
it "works for sample input" $ do
foldl applyInstruction empty sampleParsed `shouldBe` last sampleScreens
it "works for rect" $ do
applyInstruction empty (sampleParsed !! 0) `shouldBe` sampleScreens !! 0
it "works for rotate column" $ do
applyInstruction (sampleScreens !! 0) (sampleParsed !! 1) `shouldBe` sampleScreens !! 1
it "works for rotate row" $ do
applyInstruction (sampleScreens !! 1) (sampleParsed !! 2) `shouldBe` sampleScreens !! 2
it "works for rotate column a second time" $ do
applyInstruction (sampleScreens !! 2) (sampleParsed !! 3) `shouldBe` sampleScreens !! 3
| brianshourd/adventOfCode2016 | test/Day8Spec.hs | mit | 2,160 | 0 | 17 | 579 | 766 | 429 | 337 | -1 | -1 |
module Main (main) where
import Test.Tasty (TestTree, defaultMain, testGroup)
import qualified CyclicList
import qualified QuadraticIrrational
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests =
testGroup "quadratic-irrational"
[ CyclicList.tests
, QuadraticIrrational.tests
]
| ion1/quadratic-irrational | tests/tasty.hs | mit | 308 | 0 | 7 | 53 | 76 | 45 | 31 | 11 | 1 |
module Main where
main :: IO ()
main = do
-- multiline String
putStrLn "Hello\
\ World!\n"
-- more haskell-ish way
putStrLn $ unwords ["This", "is", "an", "example", "text!\n"]
-- now with multiple lines
putStrLn $ unlines [
unwords ["This", "is", "the", "first" , "line."]
, unwords ["This", "is", "the", "second", "line."]
, unwords ["This", "is", "the", "third" , "line."]
] | cirquit/Personal-Repository | Haskell/RosettaCode/Multiline-Strings/MultiLineStrings.hs | mit | 445 | 0 | 11 | 128 | 126 | 73 | 53 | 9 | 1 |
module Grid where
import Prelude hiding ((+), (-), (*), sum, negate)
import NumericPrelude
import Data.Map (Map)
import qualified Data.Map as Map
import Utils (range, inRange)
type Square = (Int, Int)
squares :: (Int, Int) -> [Square]
squares (width, height) = [(x, y) | x <- range width, y <- range height]
type Delta = (Int, Int)
deltas :: [Delta]
deltas = [(1, 0), (0, 1), (1, 1), (1, -1)]
cardinal = [(1, 0), (0, 1), (-1, 0), (0, -1)]
adjacent :: Square -> [Square]
adjacent square = map (square +) cardinal
isValid :: (Int, Int) -> Square -> Bool
isValid (width, height) (x, y) = inRange (0, width) x && inRange (0, height) y
grid :: (Int, Int) -> Map Square [Square]
grid ranges = Map.fromList [(square, filter (isValid ranges) (adjacent square)) | square <- squares ranges]
| vladfi1/game-ai | lib/Grid.hs | mit | 792 | 2 | 10 | 148 | 415 | 249 | 166 | 19 | 1 |
module ThrtyMn000 where
-- : retab
-- single line comments
{- multi-line comments -}
{-
Who am I?
I have done Slam Poetry, LiveTV, music composition, and journalism.
Basic -> in high school, my unremarkable intro to programming.
Pascal -> in College left me with a profound sense of pointlessness.
C/C++ -> same as above
tech support & system administration
a better understanding of tech systems and people using it.
Java for Android -> programming as intro to pain driven development.
GO -> exciting but not ready for prime-time;(that has since changed.)
Lisp -> Exuberance at what was possible soon to be dashed by the scarcity of it's implementation.
JavaScript -> Loved it at first. Easiest install ever; now I fear it like the plague.
Php -> a necessary evil because it's useful and quick // but a hot-mess
Ruby -> good enough, maybe a lisp with objects.
Rails -> too magical, too forgiving of my dyslexic mistakes.
Clojure -> True love at first sight, but came with a pet dinosaur (the JVM)
Haskell -> Marriage Material, not only programming but math and logic as well.
Objective-C -> a Faustian bargain for lots of typing and $$$$$.
Swift -> Great but not ready for prime time just yet.
F# -> about as close to Haskell I was gonna get and get paid for it.
Prolog -> good that I hadn't experienced it before Haskell as I might have succumbed to it's siren song.
C# -> another Faustian bargain I made for $$$$$.
Spent about 3+ years proving to my self, Paul Graham's observation all programming is some derivation of of C occasionally informed by Lisp.
Haskell is my Lisp, C# is my C, presently.
I consider Clojure as my first love,
but Haskell turned out to be marriage material.
What is it?
http://www.haskell.org/haskellwiki/Haskell
Pure
no "real world" compromises
thus more consistent
few W.T.F.s
Purely Functional
functions are the primary means of getting work done
functions can be passed as values.
functions are values.
functions can be partially evaluated.
functions are easier to reason about than are objects
see smalltalk example: thirtyMinHaskell000a.hs
2+3=5
2+3=5 ± 1
Immutable like mathematics
for the life of the runtime (until you the programmer change it)
no swappable shared memory
because shared swappable memory is the devil
no four horsemen of the parallel apocalypse
race conditions
priority inversions
Live Locks
Deadlocks
changes are pointers to new values
this sounds expensive but it's not
this sounds restrictive but it's not
Lazy (opposite of eager)
nothing gets computed until it is called
and only so much as is needed to be called
save on resources
can tackle infinite data sets
Statically typed ("strongly" "not weakly")
no casting to mutate types
no wrapping to obscure types
by stronger we mean stronger than:
C or C# or Java or C++ (weak static)
allows for some coercion of types.
Parallelization
turns out that
purity,
laziness,
immutability,
static typing,
make Parallelization easier
Concision about as much code as Ruby but 25x faster.
Haskell "feels" dynamic most of the time
because of type inference thanks to the Hindley-Milner type system.
-- Haskell lets you play with sharp objects and not cut yourself.
Video -- knife game.
https://www.youtube.com/watch?v=DzjMKM9449M
The ass you save may be your own.
-}
| HaskellForCats/HaskellForCats | 30MinHaskell/z_notes/thirtyMinHaskell000.hs | mit | 3,761 | 0 | 2 | 1,041 | 8 | 7 | 1 | 1 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Diagrams.Plots.Axis
( AxisFn(..)
, LabelOpt
, Axis(..)
, axisMap
, axisLabels
, axisDiag
, axisLabelOpt
, offsetX
, offsetY
, rotation
, size
, fontFamily
, realAxis
, indexAxis
, emptyAxis
, axis
, tickLen
, minorTickLen
, labelOpt
) where
import Diagrams.Prelude hiding (pad, rotation, size)
import Diagrams.Plots.Types
import Diagrams.Plots.Utils
-- | control the rendering of labels
data LabelOpt = LabelOpt
{ _labelOptOffsetX :: !Double
, _labelOptOffsetY :: !Double
, _labelOptRotation :: !Double
, _labelOptSize :: !Double
, _labelOptFontFamily :: !String
} deriving (Show)
makeFields ''LabelOpt
instance Default LabelOpt where
def = LabelOpt
{ _labelOptOffsetX = 0
, _labelOptOffsetY = 0
, _labelOptRotation = 0
, _labelOptSize = 12
, _labelOptFontFamily = "helvetica"
}
data AxisOpt = AxisOpt
{ _nTick :: !Int
, _nMinorTick :: !Int
, _tickLen :: !Double
, _minorTickLen :: !Double
, _labelOpt :: !LabelOpt
}
makeLenses ''AxisOpt
instance Default AxisOpt where
def = AxisOpt
{ _nTick = 5
, _nMinorTick = 4
, _tickLen = 0.1
, _minorTickLen = 0.05
, _labelOpt = def
}
-- | axis data type
data Axis = Axis
{ _axisMap :: !(PointMap Double)
, _axisDiag :: !DiaR2
, _axisLabels :: ![((Double, Double), String)]
, _axisLabelOpt :: !LabelOpt
}
makeLenses ''Axis
-- | given the length, draw axis
newtype AxisFn = AxisFn { makeAxis :: Double -> Axis }
instance Default AxisFn where
def = emptyAxis
{-
flipAxisFn :: AxisFn -> AxisFn
flipAxisFn axisF = AxisFn $ do (Axis m labels diag) <- makeAxis axisF
let (labelP, label) = unzip labels
newLabels = zip labelP $ reverse label
return $ Axis (flipMap m) newLabels diag
-}
realAxis :: (Double, Double) -> Double -> AxisOpt -> AxisFn
realAxis r pad' opt = AxisFn ( \len ->
let pMap = linearMap (fromRational l, fromRational u) (pad', len-pad')
(l, u, step) = autoSteps ((opt^.nTick)-1) r
axis' = lwO 1 $ axis len pad' $ opt & nTick .~ tickN'
labels = zip labelP
$ map ((show :: Float -> String) . fromRational) [l, l+step .. u]
tickN' = truncate ((u - l) / step) + 1
labelP = zip (enumFromThenTo pad' (pad'+stepLabel) (len-pad')) $ repeat 0
stepLabel = (len - 2*pad') / fromIntegral (tickN' - 1)
in Axis pMap axis' labels (opt^.labelOpt) )
indexAxis :: Int -> [String] -> Double -> AxisOpt -> AxisFn
indexAxis num labels pad' opt = AxisFn
( \len -> let axis' = axis len pad' $ opt & nTick .~ num
& nMinorTick .~ 0
& minorTickLen .~ 0
pMap = linearMap (1, fromIntegral num) (pad', len-pad')
labels' = zip labelP labels
labelP = zip (enumFromThenTo pad' (pad'+stepLabel) (len-pad')) $ repeat 0
stepLabel = (len - 2*pad') / fromIntegral (num - 1)
in Axis pMap axis' labels' (opt^.labelOpt)
)
emptyAxis :: AxisFn
emptyAxis = AxisFn $ const $ Axis pMap mempty [] def
where
pMap = PointMap (const Nothing) (0, -1)
axis :: Double -> Double -> AxisOpt -> DiaR2
axis len pad opt = l <> translateX pad (majorTicks <> minorTicks)
where
l = fromVertices [ 0 ^& 0, len ^& 0 ]
majorTicks = ticks (len - 2*pad) (opt^.nTick) (opt^.tickLen)
minorTicks = ticks (len - 2*pad) minorN (opt^.minorTickLen)
minorN = ((opt^.nMinorTick) + 1) * ((opt^.nTick) - 1) + 1
ticks :: Double -> Int -> Double -> DiaR2
ticks len tickNum tickL = mconcat [ fromVertices [ x ^& 0, x ^& tickL ] | x <- ticksPos ]
where
ticksPos = enumFromThenTo 0 step len
step = len / (fromIntegral tickNum - 1)
| kaizhang/haskell-plot | src/Diagrams/Plots/Axis.hs | mit | 4,189 | 0 | 19 | 1,295 | 1,256 | 694 | 562 | 128 | 1 |
import Control.Monad
--f x y = x * x + y * y
f x = x + 2
g x = x * x
mysum = \x -> \y -> x + y
h = f . g
h' = g >.> f
k = (+ 2)
zero = \f -> \x -> x
one = \f -> \x -> f x
(>.>) = flip (.)
main :: IO ()
--main = getLine >>= putStrLn
--main = flip (>>=) putStrLn getLine
| gitrookie/functionalcode | code/Haskell/snippets/genconcepts.hs | mit | 278 | 17 | 7 | 91 | 169 | 78 | 91 | 11 | 1 |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where
import Import
import Language.Haskell.TH ( Exp(..) )
-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getHomeR :: Handler Html
getHomeR = do
(formWidget, formEnctype) <- generateFormPost sampleForm
let submission = Nothing :: Maybe (FileInfo, Text)
handlerName = "getHomeR" :: Text
defaultLayout $ do
aDomId <- newIdent
setTitle "Welcome To Yesod!"
$(widgetFile "homepage")
$(fayFile' (ConE 'StaticR) "Home")
postHomeR :: Handler Html
postHomeR = do
((result, formWidget), formEnctype) <- runFormPost sampleForm
let handlerName = "postHomeR" :: Text
submission = case result of
FormSuccess res -> Just res
_ -> Nothing
defaultLayout $ do
aDomId <- newIdent
setTitle "Welcome To Yesod!"
$(widgetFile "homepage")
sampleForm :: Form (FileInfo, Text)
sampleForm = renderDivs $ (,)
<$> fileAFormReq "Choose a file"
<*> areq textField "What's on the file?" Nothing
| tagami-keisuke/yesod-blog | Handler/Home.hs | mit | 1,369 | 0 | 14 | 320 | 287 | 149 | 138 | -1 | -1 |
main = interact $ filter (/='\NUL')
| ducis/multitouch-visualizer | lineclean.hs | gpl-2.0 | 37 | 0 | 7 | 7 | 17 | 9 | 8 | 1 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright (C) 2012 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.PDF
Copyright : Copyright (C) 2012 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of LaTeX documents to PDF.
-}
module Text.Pandoc.PDF ( tex2pdf ) where
import System.IO.Temp
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as BC
import System.Exit (ExitCode (..))
import System.FilePath
import System.Directory
import System.Process
import Control.Exception (evaluate)
import System.IO (hClose)
import Control.Concurrent (putMVar, takeMVar, newEmptyMVar, forkIO)
import Text.Pandoc.UTF8 as UTF8
import Control.Monad (unless)
import Data.List (isInfixOf)
tex2pdf :: String -- ^ tex program (pdflatex, lualatex, xelatex)
-> String -- ^ latex source
-> IO (Either ByteString ByteString)
tex2pdf program source = withSystemTempDirectory "tex2pdf" $ \tmpdir ->
tex2pdf' tmpdir program source
tex2pdf' :: FilePath -- ^ temp directory for output
-> String -- ^ tex program
-> String -- ^ tex source
-> IO (Either ByteString ByteString)
tex2pdf' tmpDir program source = do
let numruns = if "\\tableofcontents" `isInfixOf` source
then 3 -- to get page numbers
else 2 -- 1 run won't give you PDF bookmarks
(exit, log', mbPdf) <- runTeXProgram program numruns tmpDir source
let msg = "Error producing PDF from TeX source."
case (exit, mbPdf) of
(ExitFailure _, _) -> return $ Left $
msg <> "\n" <> extractMsg log'
(ExitSuccess, Nothing) -> return $ Left msg
(ExitSuccess, Just pdf) -> return $ Right pdf
(<>) :: ByteString -> ByteString -> ByteString
(<>) = B.append
-- parsing output
extractMsg :: ByteString -> ByteString
extractMsg log' = do
let msg' = dropWhile (not . ("!" `BC.isPrefixOf`)) $ BC.lines log'
let (msg'',rest) = break ("l." `BC.isPrefixOf`) msg'
let lineno = take 1 rest
if null msg'
then log'
else BC.unlines (msg'' ++ lineno)
-- running tex programs
-- Run a TeX program on an input bytestring and return (exit code,
-- contents of stdout, contents of produced PDF if any). Rerun
-- a fixed number of times to resolve references.
runTeXProgram :: String -> Int -> FilePath -> String
-> IO (ExitCode, ByteString, Maybe ByteString)
runTeXProgram program runsLeft tmpDir source = do
let file = tmpDir </> "input.tex"
exists <- doesFileExist file
unless exists $ UTF8.writeFile file source
let programArgs = ["-halt-on-error", "-interaction", "nonstopmode",
"-output-directory", tmpDir, file]
(exit, out, err) <- readCommand program programArgs
if runsLeft > 1
then runTeXProgram program (runsLeft - 1) tmpDir source
else do
let pdfFile = replaceDirectory (replaceExtension file ".pdf") tmpDir
pdfExists <- doesFileExist pdfFile
pdf <- if pdfExists
then Just `fmap` B.readFile pdfFile
else return Nothing
return (exit, out <> err, pdf)
-- utility functions
-- Run a command and return exitcode, contents of stdout, and
-- contents of stderr. (Based on
-- 'readProcessWithExitCode' from 'System.Process'.)
readCommand :: FilePath -- ^ command to run
-> [String] -- ^ any arguments
-> IO (ExitCode,ByteString,ByteString) -- ^ exit, stdout, stderr
readCommand cmd args = do
(Just inh, Just outh, Just errh, pid) <-
createProcess (proc cmd args){ std_in = CreatePipe,
std_out = CreatePipe,
std_err = CreatePipe }
outMVar <- newEmptyMVar
-- fork off a thread to start consuming stdout
out <- B.hGetContents outh
_ <- forkIO $ evaluate (B.length out) >> putMVar outMVar ()
-- fork off a thread to start consuming stderr
err <- B.hGetContents errh
_ <- forkIO $ evaluate (B.length err) >> putMVar outMVar ()
-- now write and flush any input
hClose inh -- done with stdin
-- wait on the output
takeMVar outMVar
takeMVar outMVar
hClose outh
-- wait on the process
ex <- waitForProcess pid
return (ex, out, err)
| castaway/pandoc | src/Text/Pandoc/PDF.hs | gpl-2.0 | 5,270 | 0 | 15 | 1,392 | 1,048 | 562 | 486 | 83 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.