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 DeriveFunctor #-}
-- | Work on the ideas presented at http://degoes.net/articles/modern-fp
module CloudFiles where
import Control.Monad.Free
import Data.Functor.Coproduct
import Data.Functor.Sum
import Data.List.Split
import Prelude hiding (log)
--------------------------------------------------------------------------------
-- The DSL for cloud files.
data CloudFilesF a
= SaveFile Path Bytes a
| ListFiles Path ([Path] -> a)
deriving Functor
type Path = String
type Bytes = String
saveFile :: Path -> Bytes -> Free CloudFilesF ()
-- | To define `saveFile` we use `liftF`:
--
-- liftF :: (Functor f, MonadFree f m) => f a -> m a
--
saveFile path bytes = liftF $ SaveFile path bytes ()
listFiles :: Path -> Free CloudFilesF [Path]
listFiles path = liftF $ ListFiles path id
--------------------------------------------------------------------------------
-- The DSL for logging.
data Level = Debug | Info | Warning | Error deriving Show
data LogF a = Log Level String a deriving Functor
-- | Utility functions to build log programs.
log :: Level -> String -> Free LogF ()
log level msg = liftF $ Log level msg ()
-- | An interpreter for the logging DSL, in terms of the IO monad.
interpLogIO :: LogF a -> IO a
interpLogIO (Log level msg next) = do
putStrLn $ (show level) ++ ": " ++ msg
return next
--------------------------------------------------------------------------------
-- The DSL for REST clients.
data RestF a = Get Path (Bytes -> a)
| Put Path Bytes (Bytes -> a)
deriving Functor
get :: Path -> Free RestF Bytes
get path = liftF $ Get path id
put :: Path -> Bytes -> Free RestF Bytes
put path bytes = liftF $ Put path bytes id
-- | An interpreter for the cloud DSL that uses the REST DLS.
cloudFtoRestM :: CloudFilesF a -> Free RestF a
cloudFtoRestM (SaveFile path bytes next) = do
put path bytes
return next
-- | For this case let's do something slightly more interesting.
cloudFtoRestM (ListFiles path withFiles) = do
content <- get path
let files = splitOn " " content
return (withFiles files)
-- | A decorator for the cloud DSL that adds logging.
--
addLogToRest :: CloudFilesF a -> Free (Sum LogF RestF) a
addLogToRest inst@(SaveFile path bytes _) = do
hoistFree InL $ log Debug ("Saving " ++ bytes ++ " to " ++ path)
next <- hoistFree InR $ cloudFtoRestM inst
hoistFree InL $ log Debug ("Saved to " ++ path)
return next
addLogToRest inst@(ListFiles path _) = do
hoistFree InL $ log Debug ("Listing contents in " ++ path)
next <- hoistFree InR $ cloudFtoRestM inst
hoistFree InL $ log Debug ("Listing done in " ++ path)
return next
interpRestIO :: RestF a -> IO a
interpRestIO (Get path withResponse) = do
putStrLn $ "I should GET " ++ path
result <- return "mocked GET response"
return (withResponse result)
interpRestIO (Put path bytes withResponse) = do
putStrLn $ "I should PUT " ++ path ++ " " ++ bytes
result <- return "mocked PUT response"
return (withResponse result)
interpLogRestIO :: (Sum LogF RestF) a -> IO a
interpLogRestIO (InL logF) = interpLogIO logF
interpLogRestIO (InR restF) = interpRestIO restF
-- Test the interpreter for the REST DSL with a program.
sampleProgram :: Free RestF Bytes
sampleProgram = do
put "/artist/0" "juan"
get "/artist/0"
runSampleProgram = foldFree interpRestIO sampleProgram
-- Test the intepreter for the cloud DSL that used the REST DSL.
sampleCloudFilesProgram :: Free CloudFilesF ()
sampleCloudFilesProgram = do
saveFile "/myfolder/pepino" "verde"
saveFile "/myfolder/tomate" "rojo"
_ <- listFiles "/myfolder"
return ()
-- | Run the sample program using the REST interpreter.
runSampleCloudProgram =
foldFree interpRestIO $ foldFree cloudFtoRestM sampleCloudFilesProgram
interpretClouldFilesProgram :: Free CloudFilesF a -> IO a
interpretClouldFilesProgram = foldFree interpLogRestIO . foldFree addLogToRest
runSampleCloudProgram1 = interpretClouldFilesProgram sampleCloudFilesProgram
-- | The upshot after doing these exercises seems to be that the interpreters
-- always have type:
--
-- f a -> m a
--
-- where `f` is a functor and `m` is a monad. In case we are interpreting
-- functors in terms of other functors, `m` will be the free monad.
--
-- f a -> Free g a
--
-- for some other functor `g`.
--
-- At the borders of the application, we will be using mostly an iterpreter
-- with type:
--
-- f a -> IO a
--
| capitanbatata/sandbox | free-monads/src/CloudFiles.hs | gpl-3.0 | 4,497 | 0 | 12 | 907 | 1,080 | 546 | 534 | 79 | 1 |
-- Exercise 3.6
--
-- A binomial heap implementation that stores rank information at the top level
-- of each binomial tree (since, by definition, the child nodes of a binomial
-- tree node of rank r have ranks r-1,r-2,...,0).
module Ex3_6(
BinomialTopRankHeap(BH), root, rank, empty, isEmpty, insert, merge,
findMin, deleteMin, sampleHeap
) where
import Heap
data Tree a = NODE a [Tree a] deriving Show
newtype BinomialTopRankHeap a = BH [(Int, Tree a)] deriving Show
rank (r, n) = r
root (r, (NODE x ts)) = x
heapFromChildren (_, NODE _ [t]) acc = (0, t) : acc
heapFromChildren (r, NODE x (t:ts)) acc =
heapFromChildren (r - 1, NODE x ts) ((r - 1, t) : acc)
link (r, t1@(NODE x1 c1)) (_, t2@(NODE x2 c2)) =
if x1 <= x2 then (r + 1, NODE x1 (t2:c1)) else (r + 1, NODE x2 (t1:c2))
insTree rt [] = [rt]
insTree rt@(r, t) rts@(rt'@(r', t') : rts') =
if r < r' then rt : rts else insTree (link rt rt') rts'
mrg rts1 [] = rts1
mrg [] rts2 = rts2
mrg rts1@(rt1 : rts1') rts2@(rt2 : rts2')
| rank rt1 < rank rt2 = rt1 : (mrg rts1' rts2)
| rank rt2 < rank rt1 = rt2 : (mrg rts1 rts2')
| otherwise = insTree (link rt1 rt2) (mrg rts1' rts2')
removeMinTree [] = Nothing
removeMinTree [rt] = Just (rt, [])
removeMinTree (rt:rts) = do
(rt', rts') <- removeMinTree rts
if root rt < root rt' then return (rt, rts) else return (rt', rt:rts')
instance Heap BinomialTopRankHeap where
empty = BH []
isEmpty (BH rts) = null rts
insert x (BH rts) = BH (insTree (0, NODE x []) rts)
merge (BH rts1) (BH rts2) = BH (mrg rts1 rts2)
findMin (BH rts) = do
(rt, _) <- removeMinTree rts
return (root rt)
deleteMin (BH rts) = do
(rt'@(r, NODE x ts), rts') <- removeMinTree rts
if null ts then return (BH rts')
else return (BH (mrg (heapFromChildren rt' []) rts'))
sampleHeap :: BinomialTopRankHeap Char
sampleHeap = foldl (\h -> \c -> insert c h) empty ['a', 'b', 'c', 'd', 'g', 'f', 'h']
| fishbee/pfds-haskell | chapter3/Ex3_6.hs | gpl-3.0 | 1,941 | 0 | 16 | 438 | 962 | 515 | 447 | 43 | 2 |
module ListMail where
import Import hiding (toLower)
import Handler.Events (eventsTables)
import Data.Char
import qualified Data.Text as T
canonicalizeListName :: Text -> Text
canonicalizeListName = T.map canonicalize
where canonicalize c
| isAsciiUpper c = toLower c
| isAsciiLower c = c
| isDigit c = c
| otherwise = '-'
sendMessageToList :: Message -> MailingListId -> Handler ()
sendMessageToList msg listId = runDB $ do
addrs <- selectList [MailingListUserList ==. listId] []
lift $ mapM_ (sendMessageToListUser msg listId) addrs
sendMessageToListUser :: Message -> MailingListId -> Entity MailingListUser -> Handler ()
sendMessageToListUser msg listId (Entity _ mLU) = do
settings <- appSettings <$> getYesod
renderUrl <- getUrlRender
mEvents <- eventsTables listId
(user, list) <- runDB $ do
usr <- get404 $ mailingListUserUser mLU
lst <- get404 listId
return (usr, lst)
let unsubscribeR key = renderUrl $ UnsubscribeDirectlyR listId key
sender = mailSenderAddress settings
subject = T.concat [ "["
, mailingListName list
, "] "
, messageSubject msg
]
body = textareaToBody . messageBody $ msg
listid = T.concat [ "<"
, canonicalizeListName $ mailingListName list
, ".minitrue."
, appMailListIdSuffix settings
, ">"
]
headers key = [ ("List-Id", listid)
, ("List-Unsubscribe", unsubscribeR key)
]
ad = Address Nothing
message' (addr, key) = mailFromToList sender (ad addr) (unsubscribeR key) mEvents subject body
message ak@(_, key) = sendMail $ addHeaders (headers key) $ message' ak
message (userEmail user, mailingListUserUnsubkey mLU)
| mmarx/minitrue | ListMail.hs | gpl-3.0 | 1,928 | 0 | 14 | 608 | 545 | 273 | 272 | 43 | 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.CloudMonitoring.Timeseries.Write
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Put data points to one or more time series for one or more metrics. If a
-- time series does not exist, a new time series will be created. It is not
-- allowed to write a time series point that is older than the existing
-- youngest point of that time series. Points that are older than the
-- existing youngest point of that time series will be discarded silently.
-- Therefore, users should make sure that points of a time series are
-- written sequentially in the order of their end time.
--
-- /See:/ <https://cloud.google.com/monitoring/v2beta2/ Cloud Monitoring API Reference> for @cloudmonitoring.timeseries.write@.
module Network.Google.Resource.CloudMonitoring.Timeseries.Write
(
-- * REST Resource
TimeseriesWriteResource
-- * Creating a Request
, timeseriesWrite
, TimeseriesWrite
-- * Request Lenses
, twProject
, twPayload
) where
import Network.Google.CloudMonitoring.Types
import Network.Google.Prelude
-- | A resource alias for @cloudmonitoring.timeseries.write@ method which the
-- 'TimeseriesWrite' request conforms to.
type TimeseriesWriteResource =
"cloudmonitoring" :>
"v2beta2" :>
"projects" :>
Capture "project" Text :>
"timeseries:write" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] WriteTimeseriesRequest :>
Post '[JSON] WriteTimeseriesResponse
-- | Put data points to one or more time series for one or more metrics. If a
-- time series does not exist, a new time series will be created. It is not
-- allowed to write a time series point that is older than the existing
-- youngest point of that time series. Points that are older than the
-- existing youngest point of that time series will be discarded silently.
-- Therefore, users should make sure that points of a time series are
-- written sequentially in the order of their end time.
--
-- /See:/ 'timeseriesWrite' smart constructor.
data TimeseriesWrite = TimeseriesWrite'
{ _twProject :: !Text
, _twPayload :: !WriteTimeseriesRequest
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TimeseriesWrite' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'twProject'
--
-- * 'twPayload'
timeseriesWrite
:: Text -- ^ 'twProject'
-> WriteTimeseriesRequest -- ^ 'twPayload'
-> TimeseriesWrite
timeseriesWrite pTwProject_ pTwPayload_ =
TimeseriesWrite'
{ _twProject = pTwProject_
, _twPayload = pTwPayload_
}
-- | The project ID. The value can be the numeric project ID or string-based
-- project name.
twProject :: Lens' TimeseriesWrite Text
twProject
= lens _twProject (\ s a -> s{_twProject = a})
-- | Multipart request metadata.
twPayload :: Lens' TimeseriesWrite WriteTimeseriesRequest
twPayload
= lens _twPayload (\ s a -> s{_twPayload = a})
instance GoogleRequest TimeseriesWrite where
type Rs TimeseriesWrite = WriteTimeseriesResponse
type Scopes TimeseriesWrite =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring"]
requestClient TimeseriesWrite'{..}
= go _twProject (Just AltJSON) _twPayload
cloudMonitoringService
where go
= buildClient
(Proxy :: Proxy TimeseriesWriteResource)
mempty
| rueshyna/gogol | gogol-cloudmonitoring/gen/Network/Google/Resource/CloudMonitoring/Timeseries/Write.hs | mpl-2.0 | 4,262 | 0 | 14 | 947 | 402 | 247 | 155 | 64 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.ReplicaPool
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- [Deprecated. Please use Instance Group Manager in Compute API] Provides
-- groups of homogenous Compute Engine instances.
--
-- /See:/ <https://developers.google.com/compute/docs/instance-groups/manager/v1beta2 Google Compute Engine Instance Group Manager API Reference>
module Network.Google.ReplicaPool
(
-- * Service Configuration
replicaPoolService
-- * OAuth Scopes
, computeScope
, cloudPlatformReadOnlyScope
, cloudPlatformScope
, computeReadOnlyScope
-- * API Declaration
, ReplicaPoolAPI
-- * Resources
-- ** replicapool.instanceGroupManagers.abandonInstances
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.AbandonInstances
-- ** replicapool.instanceGroupManagers.delete
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Delete
-- ** replicapool.instanceGroupManagers.deleteInstances
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.DeleteInstances
-- ** replicapool.instanceGroupManagers.get
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Get
-- ** replicapool.instanceGroupManagers.insert
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Insert
-- ** replicapool.instanceGroupManagers.list
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.List
-- ** replicapool.instanceGroupManagers.recreateInstances
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.RecreateInstances
-- ** replicapool.instanceGroupManagers.resize
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Resize
-- ** replicapool.instanceGroupManagers.setInstanceTemplate
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.SetInstanceTemplate
-- ** replicapool.instanceGroupManagers.setTargetPools
, module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.SetTargetPools
-- ** replicapool.zoneOperations.get
, module Network.Google.Resource.ReplicaPool.ZoneOperations.Get
-- ** replicapool.zoneOperations.list
, module Network.Google.Resource.ReplicaPool.ZoneOperations.List
-- * Types
-- ** OperationWarningsItemDataItem
, OperationWarningsItemDataItem
, operationWarningsItemDataItem
, owidiValue
, owidiKey
-- ** InstanceGroupManagersAbandonInstancesRequest
, InstanceGroupManagersAbandonInstancesRequest
, instanceGroupManagersAbandonInstancesRequest
, igmairInstances
-- ** InstanceGroupManagersSetInstanceTemplateRequest
, InstanceGroupManagersSetInstanceTemplateRequest
, instanceGroupManagersSetInstanceTemplateRequest
, igmsitrInstanceTemplate
-- ** OperationWarningsItemCode
, OperationWarningsItemCode (..)
-- ** OperationList
, OperationList
, operationList
, olNextPageToken
, olKind
, olItems
, olSelfLink
, olId
-- ** InstanceGroupManagerList
, InstanceGroupManagerList
, instanceGroupManagerList
, igmlNextPageToken
, igmlKind
, igmlItems
, igmlSelfLink
, igmlId
-- ** ReplicaPoolAutoHealingPolicyActionType
, ReplicaPoolAutoHealingPolicyActionType (..)
-- ** Operation
, Operation
, operation
, oTargetId
, oStatus
, oInsertTime
, oProgress
, oStartTime
, oKind
, oError
, oHTTPErrorMessage
, oZone
, oWarnings
, oHTTPErrorStatusCode
, oUser
, oSelfLink
, oName
, oStatusMessage
, oCreationTimestamp
, oEndTime
, oId
, oOperationType
, oRegion
, oTargetLink
, oClientOperationId
-- ** InstanceGroupManager
, InstanceGroupManager
, instanceGroupManager
, igmCurrentSize
, igmGroup
, igmKind
, igmFingerprint
, igmBaseInstanceName
, igmAutoHealingPolicies
, igmInstanceTemplate
, igmTargetSize
, igmSelfLink
, igmName
, igmCreationTimestamp
, igmId
, igmTargetPools
, igmDescription
-- ** ReplicaPoolAutoHealingPolicy
, ReplicaPoolAutoHealingPolicy
, replicaPoolAutoHealingPolicy
, rpahpHealthCheck
, rpahpActionType
-- ** InstanceGroupManagersRecreateInstancesRequest
, InstanceGroupManagersRecreateInstancesRequest
, instanceGroupManagersRecreateInstancesRequest
, igmrirInstances
-- ** OperationStatus
, OperationStatus (..)
-- ** InstanceGroupManagersDeleteInstancesRequest
, InstanceGroupManagersDeleteInstancesRequest
, instanceGroupManagersDeleteInstancesRequest
, igmdirInstances
-- ** OperationError
, OperationError
, operationError
, oeErrors
-- ** InstanceGroupManagersSetTargetPoolsRequest
, InstanceGroupManagersSetTargetPoolsRequest
, instanceGroupManagersSetTargetPoolsRequest
, igmstprFingerprint
, igmstprTargetPools
-- ** OperationErrorErrorsItem
, OperationErrorErrorsItem
, operationErrorErrorsItem
, oeeiLocation
, oeeiCode
, oeeiMessage
-- ** OperationWarningsItem
, OperationWarningsItem
, operationWarningsItem
, owiData
, owiCode
, owiMessage
) where
import Network.Google.Prelude
import Network.Google.ReplicaPool.Types
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.AbandonInstances
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Delete
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.DeleteInstances
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Get
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Insert
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.List
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.RecreateInstances
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Resize
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.SetInstanceTemplate
import Network.Google.Resource.ReplicaPool.InstanceGroupManagers.SetTargetPools
import Network.Google.Resource.ReplicaPool.ZoneOperations.Get
import Network.Google.Resource.ReplicaPool.ZoneOperations.List
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Google Compute Engine Instance Group Manager API service.
type ReplicaPoolAPI =
ZoneOperationsListResource :<|>
ZoneOperationsGetResource
:<|> InstanceGroupManagersSetTargetPoolsResource
:<|> InstanceGroupManagersInsertResource
:<|> InstanceGroupManagersResizeResource
:<|> InstanceGroupManagersListResource
:<|> InstanceGroupManagersAbandonInstancesResource
:<|> InstanceGroupManagersSetInstanceTemplateResource
:<|> InstanceGroupManagersGetResource
:<|> InstanceGroupManagersDeleteInstancesResource
:<|> InstanceGroupManagersDeleteResource
:<|> InstanceGroupManagersRecreateInstancesResource
| rueshyna/gogol | gogol-replicapool/gen/Network/Google/ReplicaPool.hs | mpl-2.0 | 7,524 | 0 | 15 | 1,398 | 665 | 483 | 182 | 146 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Partners.Types
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Partners.Types
(
-- * Service Configuration
partnersService
-- * LatLng
, LatLng
, latLng
, llLatitude
, llLongitude
-- * ListUserStatesResponse
, ListUserStatesResponse
, listUserStatesResponse
, lusrUserStates
, lusrResponseMetadata
-- * EventData
, EventData
, eventData
, edValues
, edKey
-- * RequestMetadata
, RequestMetadata
, requestMetadata
, rmExperimentIds
, rmTrafficSource
, rmLocale
, rmUserOverrides
, rmPartnersSessionId
-- * CertificationStatus
, CertificationStatus
, certificationStatus
, csIsCertified
, csType
, csExamStatuses
-- * DebugInfo
, DebugInfo
, debugInfo
, diServiceURL
, diServerTraceInfo
, diServerInfo
-- * GetCompanyResponse
, GetCompanyResponse
, getCompanyResponse
, gcrResponseMetadata
, gcrCompany
-- * PublicProFile
, PublicProFile
, publicProFile
, ppfURL
, ppfDisplayImageURL
, ppfDisplayName
, ppfId
-- * CertificationExamStatus
, CertificationExamStatus
, certificationExamStatus
, cesNumberUsersPass
, cesType
-- * Location
, Location
, location
, lLatLng
, lAddress
-- * TrafficSource
, TrafficSource
, trafficSource
, tsTrafficSubId
, tsTrafficSourceId
-- * Money
, Money
, money
, mCurrencyCode
, mNanos
, mUnits
-- * ListCompaniesResponse
, ListCompaniesResponse
, listCompaniesResponse
, lcrNextPageToken
, lcrResponseMetadata
, lcrCompanies
-- * RecaptchaChallenge
, RecaptchaChallenge
, recaptchaChallenge
, rcResponse
, rcId
-- * CreateLeadResponse
, CreateLeadResponse
, createLeadResponse
, clrRecaptchaStatus
, clrResponseMetadata
, clrLead
-- * UserOverrides
, UserOverrides
, userOverrides
, uoIPAddress
, uoUserId
-- * ResponseMetadata
, ResponseMetadata
, responseMetadata
, rmDebugInfo
-- * LogMessageRequest
, LogMessageRequest
, logMessageRequest
, lmrRequestMetadata
, lmrClientInfo
, lmrDetails
, lmrLevel
-- * LocalizedCompanyInfo
, LocalizedCompanyInfo
, localizedCompanyInfo
, lciLanguageCode
, lciOverview
, lciCountryCodes
, lciDisplayName
-- * LogMessageRequestClientInfo
, LogMessageRequestClientInfo
, logMessageRequestClientInfo
, lmrciAddtional
-- * Lead
, Lead
, lead
, lGivenName
, lEmail
, lFamilyName
, lPhoneNumber
, lMinMonthlyBudget
, lId
, lComments
, lWebsiteURL
, lType
, lGpsMotivations
-- * LogMessageResponse
, LogMessageResponse
, logMessageResponse
, lmrResponseMetadata
-- * Company
, Company
, company
, cPublicProFile
, cOriginalMinMonthlyBudget
, cIndustries
, cConvertedMinMonthlyBudget
, cName
, cLocalizedInfos
, cCertificationStatuses
, cRanks
, cId
, cWebsiteURL
, cLocations
, cServices
-- * LogUserEventResponse
, LogUserEventResponse
, logUserEventResponse
, luerResponseMetadata
-- * LogUserEventRequest
, LogUserEventRequest
, logUserEventRequest
, luerEventCategory
, luerRequestMetadata
, luerURL
, luerEventScope
, luerLead
, luerEventDatas
, luerEventAction
-- * Rank
, Rank
, rank
, rValue
, rType
-- * CreateLeadRequest
, CreateLeadRequest
, createLeadRequest
, cRequestMetadata
, cRecaptchaChallenge
, cLead
) where
import Network.Google.Partners.Types.Product
import Network.Google.Partners.Types.Sum
import Network.Google.Prelude
-- | Default request referring to version 'v2' of the Google Partners API. This contains the host and root path used as a starting point for constructing service requests.
partnersService :: ServiceConfig
partnersService
= defaultService (ServiceId "partners:v2")
"partners.googleapis.com"
| rueshyna/gogol | gogol-partners/gen/Network/Google/Partners/Types.hs | mpl-2.0 | 4,625 | 0 | 7 | 1,274 | 525 | 363 | 162 | 158 | 1 |
module Moonbase.Panel.Items.Cpu where
import Control.Applicative
import Control.Arrow
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import System.IO
import qualified Graphics.UI.Gtk as Gtk
import Data.Time.Format
import Data.Time.LocalTime
import Moonbase.DBus
import Moonbase.Panel
import Moonbase.Theme
import Moonbase.Util
import Moonbase.Util.Css
import Moonbase.Util.Gtk
import Moonbase.Util.Widget.Bar
defaultCpuBarConfig :: BarConfig
defaultCpuBarConfig = BarConfig
{ barOrientation = HorizontalBar
, barSegmentColor = "#9ec400"
, barFrameColor = "#151515"
, barTextColor = "#151515"
, barMin = 0
, barMax = 100
, barWidth = 40 }
data Cpu = CpuAll
| CpuCore Int
instance Show Cpu where
show (CpuAll) = "cpuAll"
show (CpuCore i) = "core" ++ show i
data CpuStat = CpuStat
{ cpuUser :: Int
, cpuNice :: Int
, cpuSystem :: Int
, cpuIdle :: Int
, cpuIOWait :: Int
, cpuIRQ :: Int
, cpuSoftIRQ :: Int
, cpuSteal :: Int } deriving (Show)
type CpuBar = PanelItems
cpuBar :: Cpu -> Int -> BarConfig -> CpuBar
cpuBar cpu ms conf = item $ do
bar <- liftIO $ barNew conf
i <- liftIO $ readStat cpu
runCpuBar cpu ms i bar
return $ PanelItem (show cpu ++ "Bar") (Gtk.toWidget bar) Gtk.PackNatural
cpuBarWithLabel :: Cpu -> Int -> BarConfig -> CpuBar
cpuBarWithLabel cpu ms conf = item $ do
box <- liftIO $ do
box <- Gtk.hBoxNew False 2
bar <- barNew conf
label <- Gtk.labelNew (Just "0%")
i <- readStat cpu
(_, h) <- widgetGetSize label
Gtk.labelSetJustify label Gtk.JustifyLeft
Gtk.widgetSetName label $ show cpu ++ "-label"
Gtk.widgetSetSizeRequest label 40 h
Gtk.boxPackStart box bar Gtk.PackNatural 0
Gtk.boxPackStart box label Gtk.PackNatural 0
withCss label $ fgColor (barTextColor conf)
pollForever 0 i $ \p -> do
a <- readStat cpu
threadDelay (ms * 1000)
b <- readStat cpu
let value = calcCpuLoad p a b
Gtk.labelSetText label (show value ++ "%")
Gtk.set bar [barValue Gtk.:= value]
return b
return box
return $ PanelItem (show cpu ++ "Bar") (Gtk.toWidget box) Gtk.PackNatural
runCpuBar :: (MonadIO m) => Cpu -> Int -> CpuStat -> Bar -> m ()
runCpuBar cpu ms i bar = liftIO $ pollForever 0 i $ \p -> do
a <- readStat cpu
threadDelay (ms * 1000)
b <- readStat cpu
Gtk.set bar [barValue Gtk.:= calcCpuLoad p a b]
return b
calcCpuLoad :: CpuStat -> CpuStat -> CpuStat -> Int
calcCpuLoad p a b = ((totalAll p a b - idleAll p a b) * 100) `div` totalAll p a b
where
idle c = cpuIdle c + cpuIOWait c
nonIdle c = cpuUser c + cpuNice c + cpuSystem c + cpuIRQ c + cpuSoftIRQ c + cpuSteal c
total c = idle c + nonIdle c
totalAll p a b = total b - (total a + total p) `div` 2
idleAll p a b = idle b - (idle a + idle p) `div` 2
readStat :: Cpu -> IO CpuStat
readStat cpu= do
hdl <- openFile "/proc/stat" ReadMode
stats <- readCpuStats hdl []
hClose hdl
return $ case cpu of
CpuAll -> head stats
CpuCore x -> stats !! x
where
readCpuStats hdl stats = do
(name, stat) <- parse <$> hGetLine hdl
if name == "intr"
then return stats
else readCpuStats hdl (stats ++ [stat])
parse = (head . words) &&& (mkCpuStat . map read . tail . words)
mkCpuStat (u:n:s:i:io:irq:sirq:st:_) = CpuStat u n s i io irq sirq st
mkCpuStat _ = CpuStat 0 0 0 0 0 0 0 0
| felixsch/moonbase-ng | src/Moonbase/Panel/Items/Cpu.hs | lgpl-2.1 | 3,701 | 0 | 19 | 1,100 | 1,371 | 686 | 685 | 101 | 4 |
-- file: ch02/Assign.hs
x = 10
x = 11
| chinaran/haskell-study | ch02/Assigh.hs | apache-2.0 | 38 | 0 | 4 | 9 | 12 | 7 | 5 | 2 | 1 |
-- | Type and functions for first-order predicate logic.
module Akarui.Parser.FOL where
import qualified Data.Text as T
import Text.Parsec
import Text.Parsec.String (Parser)
import qualified Text.Parsec.Expr as Ex
import Akarui.FOL.Formula
import Akarui.FOL.FOL
import Akarui.Parser.LogicOps
import Akarui.Parser.Core
import Akarui.Parser.Numbers
import Akarui.Parser.Term as Term
import Akarui.FOL.Predicate
import Akarui.FOL.QuanT
-- | Parser for weighted first-order logic. Parses a double following by
-- a formula (or a formula followed by a double).
--
-- The /smoking/ example for Markov logic:
--
-- @
-- parseWFOL \"∀x∀y∀z Friend(x, y) ∧ Friend(y, z) ⇒ Friend(x, z) 0.7\"
-- parseWFOL \"∀x Smoking(x) ⇒ Cancer(x) 1.5\"
-- parseWFOL \"1.1 ∀x∀y Friend(x, y) ∧ Smoking(x) ⇒ Smoking(y)\"
-- @
parseWFOL :: String -> Either ParseError (FOL, Double)
parseWFOL = parse (contents parseWeighted) "<stdin>"
-- | Parser for first-order logic. The parser will read a string and output
-- an either type with (hopefully) the formula on the right.
--
-- This parser makes the assumption that variables start with a lowercase
-- character, while constants start with an uppercase character.
--
-- Some examples of valid strings for the parser:
--
-- @
-- parseFOL \"ForAll x, y PositiveInteger(y) => GreaterThan(Add(x, y), x)\"
-- parseFOL \"A.x,y: Integer(x) and PositiveInteger(y) => GreaterThan(Add(x, y), x)\"
-- parseFOL \"∀ x Add(x, 0) = x\"
-- @
parseFOL :: String -> Either ParseError FOL
parseFOL = parse (contents parseFOLAll) "<stdin>"
parseFOLAll, parseSentence, parseTop, parseBot, parseAtoms, parsePred, parsePredLike, parseIdentity, parseNIdentity, parseQuan, parseNQuan, parseNegation :: Parser FOL
parseFOLAll = try parseNQuan<|> try parseQuan <|> parseSentence
parseSentence = Ex.buildExpressionParser logicTbl parseAtoms
parseTop = reservedOps ["True", "TRUE", "true", "T", "⊤"] >> return top
parseBot = reservedOps ["False", "FALSE", "false", "F", "⊥"] >> return bot
parseNQuan = do
nots <- many1 parseNot
(q, vs, a) <- parseQuanForm
return $ foldr (\_ acc -> Not acc) (foldr (Quantifier q) a vs) nots
parseQuan = do
(q, vs, a) <- parseQuanForm
return $ foldr (Quantifier q) a vs
parseNegation = do
n <- parseNot
a <- parseAtoms
return $ n a
parsePredLike = try parseIdentity <|> try parseNIdentity <|> parsePred
parseAtoms =
try parsePredLike
<|> parseNegation
<|> parseTop
<|> parseBot
<|> parens parseFOLAll
parsePred = do
args <- Term.parseFunForm
return $ Atom $ uncurry Predicate args
parseIdentity = do
left <- Term.parseTerm
reservedOps ["=", "=="]
right <- Term.parseTerm
return $ Atom $ Predicate "Identity" [left, right]
parseNIdentity = do
left <- Term.parseTerm
reservedOps ["!=", "/=", "\\neq"]
right <- Term.parseTerm
return $ Not $ Atom $ Predicate "Identity" [left, right]
parseNot :: Parser (FOL -> FOL)
parseNot = reservedOps ["Not", "NOT", "not", "~", "!", "¬"] >> return Not
parseExists, parseForAll :: Parser QuanT
parseExists = reservedOps ["E.", "Exists", "exists", "∃"] >> return Exists
parseForAll = reservedOps ["A.", "ForAll", "Forall", "forall", "∀"] >> return ForAll
-- Parse a weight and then a first-order logic formula
parseLeftW :: Parser (FOL, Double)
parseLeftW = do
n <- getDouble
f <- parseFOLAll
return (f, n)
-- Parse a first-order logic formula and then a weight
parseRightW :: Parser (FOL, Double)
parseRightW = do
f <- parseFOLAll
n <- getDouble
return (f, n)
parseWeighted :: Parser (FOL, Double)
parseWeighted = try parseLeftW <|> parseRightW
parseQuanForm :: Parser (QuanT, [T.Text], FOL)
parseQuanForm = do
q <- parseExists <|> parseForAll -- many1
v <- commaSep identifier
optional $ reservedOp ":"
a <- parseFOLAll
return (q, map T.pack v, a)
| PhDP/Manticore | Akarui/Parser/FOL.hs | apache-2.0 | 3,851 | 0 | 12 | 662 | 963 | 533 | 430 | 77 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveDataTypeable #-}
module System.Monitoring.Nrpe.Protocol (
Service (..)
, nrpe
, check
, Result (..)
, Code (..)
) where
import Prelude hiding (read)
import Data.Binary (Binary (..), encode, decode)
import Data.Binary.Put (putWord16be, putWord32be, putWord8, putByteString)
import Data.Binary.Get (getWord16be, getWord32be, getByteString)
import Data.ByteString hiding (repeat)
import Data.ByteString.Internal (toForeignPtr)
import Data.ByteString.Lazy (fromStrict)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString as B
import Data.Typeable
import Data.Word (Word16, Word32)
import Data.Digest.CRC32 (crc32)
import Network.Simple.TCP (connect, send, recv)
import OpenSSL (withOpenSSL)
import OpenSSL.Session hiding (connect)
import qualified OpenSSL.Session as SSL
type Host = String
type Port = Word16
type Version = Word16
data QueryType = Req | Res
deriving (Show, Eq, Ord)
data Code = Ok | Warning | Error | Unknown
deriving (Show, Eq, Ord, Enum)
data Packet = Packet
{ packetVersion :: Version
, packetType :: QueryType
, packetCRC :: Word32
, packetRetCode :: Maybe Code
, packetByteString :: ByteString
} deriving (Show, Eq, Ord)
packetMessage :: Packet -> ByteString
packetMessage = B.takeWhile (/= 0) . packetByteString
e2w16 :: Enum a => a -> Word16
e2w16 = fromIntegral . fromEnum
w162e :: Enum a => Word16 -> a
w162e = toEnum . fromInteger . toInteger
computeCRC :: Packet -> Word32
computeCRC = crc32 . encode
updateCRC :: Packet -> Packet
updateCRC pkt@(Packet v q _ c b) = Packet v q crc c b
where crc = computeCRC pkt
instance Binary QueryType where
put Req = putWord16be 1
put Res = putWord16be 2
get = do
x <- getWord16be
case x of
1 -> return Req
_ -> return Res
instance Binary Packet where
put (Packet v q crc c b) = do
putWord16be v
put q
putWord32be crc
putWord16be $ maybe 0 e2w16 c
putByteString b' >> putWord8 0
putByteString pad
putByteString reserved
where pad = C.replicate padLen '\0'
padLen = 1024 - (1 + B.length b')
b' = B.take 1023 b
reserved = ":P"
get = do
v <- getWord16be
q <- get
crc <- getWord32be
c <- getWord16be
b <- getByteString 1024
_pad <- getByteString 2
return $ Packet v q crc (Just $ w162e c) b
-- | Data type to represent an NRPE service.
data Service = Service
{ nrpeHost :: Host -- ^ the hostname/IP address of the NRPE service
, nrpePort :: Port -- ^ the TCP port
, nrpeUseSSl :: Bool -- ^ whether or not the service implements SSL
} deriving (Show, Eq, Ord)
-- | Newtype to wrap requests.
newtype Request = Request ByteString
deriving (Show, Eq, Ord)
-- | Newtype to wrap results.
newtype Result a = Result (Code, a)
deriving (Show, Eq, Ord, Functor, Typeable)
packRequest :: Request -> Packet
packRequest (Request b) = updateCRC $ Packet version Req 0 Nothing b
where version = 2
unpackResult :: Packet -> Result ByteString
unpackResult pkt = Result (code, buf)
where code = maybe Unknown id $ packetRetCode pkt
buf = packetMessage pkt
-- TODO: verify that results always span at most one packet
raw_check :: Service -> Request -> IO (Result ByteString)
raw_check s r@(Request b) = do
let sbuf = encode (packRequest r)
connect (nrpeHost s) (show $ nrpePort s) (uncurry (act (nrpeUseSSl s) sbuf))
where act True sbuf skt _ = withOpenSSL $ do
ctx <- context
contextSetCiphers ctx "ADH"
ssl <- connection ctx skt
SSL.connect ssl
write ssl (L.toStrict sbuf)
rbuf <- read ssl 1036
return $ unpackResult . decode $ fromStrict rbuf
act False sbuf skt _ = do
send skt (L.toStrict sbuf)
Just rbuf <- recv skt 1036
return $ unpackResult . decode $ fromStrict rbuf
-- | Runs an NRPE check against a service.
check :: Service -> ByteString -> IO (Result ByteString)
check s x = raw_check s $ Request x
-- | Returns a default service for a given host (port 5666 and SSL=true).
nrpe :: Host -> Service
nrpe h = Service h 5666 True
| lucasdicioccio/nrpe | src/System/Monitoring/Nrpe/Protocol.hs | apache-2.0 | 4,321 | 0 | 13 | 1,050 | 1,362 | 726 | 636 | 116 | 2 |
module Lycopene.Core.Free where
data Free f a = Free (f (Free f a)) | Pure a
instance Functor f => Functor (Free f) where
fmap f (Pure x) = Pure $ f x
fmap f (Free x) = Free $ fmap (fmap f) x
instance Functor f => Applicative (Free f) where
pure = Pure
(Pure f) <*> x = fmap f x
(Free f) <*> x = Free $ fmap (<*> x) f
instance Functor f => Monad (Free f) where
return = pure
(Pure x) >>= k = k x
(Free x) >>= k = Free $ fmap (>>= k) x
foldF :: Functor f => (f a -> a) -> Free f a -> a
foldF phi (Free x) = phi $ fmap (foldF phi) x
foldF _ (Pure x) = x
liftF :: Functor f => f a -> Free f a
liftF x = Free $ fmap Pure x
| utky/lycopene | src/Lycopene/Core/Free.hs | apache-2.0 | 641 | 0 | 10 | 176 | 389 | 192 | 197 | 18 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QToolBar_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QToolBar_h where
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QToolBar ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QToolBar_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QToolBar_unSetUserMethod" qtc_QToolBar_unSetUserMethod :: Ptr (TQToolBar a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QToolBarSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QToolBar_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QToolBar ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QToolBar_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QToolBarSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QToolBar_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QToolBar ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QToolBar_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QToolBarSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QToolBar_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QToolBar ()) (QToolBar x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QToolBar setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QToolBar_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QToolBar_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setUserMethod" qtc_QToolBar_setUserMethod :: Ptr (TQToolBar a) -> CInt -> Ptr (Ptr (TQToolBar x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QToolBar :: (Ptr (TQToolBar x0) -> IO ()) -> IO (FunPtr (Ptr (TQToolBar x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QToolBar_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QToolBarSc a) (QToolBar x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QToolBar setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QToolBar_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QToolBar_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QToolBar ()) (QToolBar x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QToolBar setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QToolBar_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QToolBar_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setUserMethodVariant" qtc_QToolBar_setUserMethodVariant :: Ptr (TQToolBar a) -> CInt -> Ptr (Ptr (TQToolBar x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QToolBar :: (Ptr (TQToolBar x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQToolBar x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QToolBar_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QToolBarSc a) (QToolBar x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QToolBar setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QToolBar_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QToolBar_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QToolBar ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QToolBar_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QToolBar_unSetHandler" qtc_QToolBar_unSetHandler :: Ptr (TQToolBar a) -> CWString -> IO (CBool)
instance QunSetHandler (QToolBarSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QToolBar_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QToolBar ()) (QToolBar x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler1" qtc_QToolBar_setHandler1 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar1 :: (Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QToolBar1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QactionEvent_h (QToolBar ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_actionEvent" qtc_QToolBar_actionEvent :: Ptr (TQToolBar a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QToolBarSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_actionEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QToolBar ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_changeEvent" qtc_QToolBar_changeEvent :: Ptr (TQToolBar a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QToolBarSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_changeEvent cobj_x0 cobj_x1
instance QsetHandler (QToolBar ()) (QToolBar x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler2" qtc_QToolBar_setHandler2 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar2 :: (Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QToolBar2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QToolBar ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_event cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_event" qtc_QToolBar_event :: Ptr (TQToolBar a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QToolBarSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_event cobj_x0 cobj_x1
instance QpaintEvent_h (QToolBar ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_paintEvent" qtc_QToolBar_paintEvent :: Ptr (TQToolBar a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QToolBarSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_paintEvent cobj_x0 cobj_x1
instance QresizeEvent_h (QToolBar ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_resizeEvent" qtc_QToolBar_resizeEvent :: Ptr (TQToolBar a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QToolBarSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_resizeEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QToolBar ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_closeEvent" qtc_QToolBar_closeEvent :: Ptr (TQToolBar a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QToolBarSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QToolBar ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_contextMenuEvent" qtc_QToolBar_contextMenuEvent :: Ptr (TQToolBar a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QToolBarSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QToolBar ()) (QToolBar x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qToolBarFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler3" qtc_QToolBar_setHandler3 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar3 :: (Ptr (TQToolBar x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQToolBar x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QToolBar3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qToolBarFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QToolBar ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_devType cobj_x0
foreign import ccall "qtc_QToolBar_devType" qtc_QToolBar_devType :: Ptr (TQToolBar a) -> IO CInt
instance QdevType_h (QToolBarSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_devType cobj_x0
instance QdragEnterEvent_h (QToolBar ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_dragEnterEvent" qtc_QToolBar_dragEnterEvent :: Ptr (TQToolBar a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QToolBarSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QToolBar ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_dragLeaveEvent" qtc_QToolBar_dragLeaveEvent :: Ptr (TQToolBar a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QToolBarSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QToolBar ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_dragMoveEvent" qtc_QToolBar_dragMoveEvent :: Ptr (TQToolBar a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QToolBarSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QToolBar ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_dropEvent" qtc_QToolBar_dropEvent :: Ptr (TQToolBar a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QToolBarSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QToolBar ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_enterEvent" qtc_QToolBar_enterEvent :: Ptr (TQToolBar a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QToolBarSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_enterEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QToolBar ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_focusInEvent" qtc_QToolBar_focusInEvent :: Ptr (TQToolBar a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QToolBarSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QToolBar ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_focusOutEvent" qtc_QToolBar_focusOutEvent :: Ptr (TQToolBar a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QToolBarSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QToolBar ()) (QToolBar x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler4" qtc_QToolBar_setHandler4 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar4 :: (Ptr (TQToolBar x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQToolBar x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QToolBar4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QToolBar ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QToolBar_heightForWidth" qtc_QToolBar_heightForWidth :: Ptr (TQToolBar a) -> CInt -> IO CInt
instance QheightForWidth_h (QToolBarSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QToolBar ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_hideEvent" qtc_QToolBar_hideEvent :: Ptr (TQToolBar a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QToolBarSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_hideEvent cobj_x0 cobj_x1
instance QsetHandler (QToolBar ()) (QToolBar x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler5" qtc_QToolBar_setHandler5 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar5 :: (Ptr (TQToolBar x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQToolBar x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QToolBar5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QToolBar ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QToolBar_inputMethodQuery" qtc_QToolBar_inputMethodQuery :: Ptr (TQToolBar a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QToolBarSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent_h (QToolBar ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_keyPressEvent" qtc_QToolBar_keyPressEvent :: Ptr (TQToolBar a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QToolBarSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QToolBar ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_keyReleaseEvent" qtc_QToolBar_keyReleaseEvent :: Ptr (TQToolBar a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QToolBarSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QToolBar ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_leaveEvent" qtc_QToolBar_leaveEvent :: Ptr (TQToolBar a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QToolBarSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_leaveEvent cobj_x0 cobj_x1
instance QsetHandler (QToolBar ()) (QToolBar x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qToolBarFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler6" qtc_QToolBar_setHandler6 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar6 :: (Ptr (TQToolBar x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQToolBar x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QToolBar6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qToolBarFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QToolBar ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_minimumSizeHint cobj_x0
foreign import ccall "qtc_QToolBar_minimumSizeHint" qtc_QToolBar_minimumSizeHint :: Ptr (TQToolBar a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QToolBarSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QToolBar ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QToolBar_minimumSizeHint_qth" qtc_QToolBar_minimumSizeHint_qth :: Ptr (TQToolBar a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QToolBarSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QmouseDoubleClickEvent_h (QToolBar ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_mouseDoubleClickEvent" qtc_QToolBar_mouseDoubleClickEvent :: Ptr (TQToolBar a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QToolBarSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QToolBar ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_mouseMoveEvent" qtc_QToolBar_mouseMoveEvent :: Ptr (TQToolBar a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QToolBarSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QToolBar ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_mousePressEvent" qtc_QToolBar_mousePressEvent :: Ptr (TQToolBar a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QToolBarSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QToolBar ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_mouseReleaseEvent" qtc_QToolBar_mouseReleaseEvent :: Ptr (TQToolBar a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QToolBarSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_mouseReleaseEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QToolBar ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_moveEvent" qtc_QToolBar_moveEvent :: Ptr (TQToolBar a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QToolBarSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QToolBar ()) (QToolBar x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qToolBarFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler7" qtc_QToolBar_setHandler7 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar7 :: (Ptr (TQToolBar x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQToolBar x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QToolBar7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qToolBarFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QToolBar ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_paintEngine cobj_x0
foreign import ccall "qtc_QToolBar_paintEngine" qtc_QToolBar_paintEngine :: Ptr (TQToolBar a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QToolBarSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_paintEngine cobj_x0
instance QsetHandler (QToolBar ()) (QToolBar x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler8" qtc_QToolBar_setHandler8 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar8 :: (Ptr (TQToolBar x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQToolBar x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QToolBar8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qToolBarFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QToolBar ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QToolBar_setVisible" qtc_QToolBar_setVisible :: Ptr (TQToolBar a) -> CBool -> IO ()
instance QsetVisible_h (QToolBarSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QToolBar ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_showEvent" qtc_QToolBar_showEvent :: Ptr (TQToolBar a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QToolBarSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_showEvent cobj_x0 cobj_x1
instance QqsizeHint_h (QToolBar ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_sizeHint cobj_x0
foreign import ccall "qtc_QToolBar_sizeHint" qtc_QToolBar_sizeHint :: Ptr (TQToolBar a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QToolBarSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_sizeHint cobj_x0
instance QsizeHint_h (QToolBar ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QToolBar_sizeHint_qth" qtc_QToolBar_sizeHint_qth :: Ptr (TQToolBar a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QToolBarSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QToolBar_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QtabletEvent_h (QToolBar ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_tabletEvent" qtc_QToolBar_tabletEvent :: Ptr (TQToolBar a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QToolBarSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_tabletEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QToolBar ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QToolBar_wheelEvent" qtc_QToolBar_wheelEvent :: Ptr (TQToolBar a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QToolBarSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QToolBar_wheelEvent cobj_x0 cobj_x1
instance QsetHandler (QToolBar ()) (QToolBar x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qToolBarFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QToolBar_setHandler9" qtc_QToolBar_setHandler9 :: Ptr (TQToolBar a) -> CWString -> Ptr (Ptr (TQToolBar x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QToolBar9 :: (Ptr (TQToolBar x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQToolBar x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QToolBar9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QToolBarSc a) (QToolBar x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QToolBar9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QToolBar9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QToolBar_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQToolBar x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qToolBarFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QToolBar ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QToolBar_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QToolBar_eventFilter" qtc_QToolBar_eventFilter :: Ptr (TQToolBar a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QToolBarSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QToolBar_eventFilter cobj_x0 cobj_x1 cobj_x2
| uduki/hsQt | Qtc/Gui/QToolBar_h.hs | bsd-2-clause | 55,950 | 0 | 18 | 12,269 | 18,819 | 9,078 | 9,741 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveFunctor #-}
-- | Ultimate data representation.
module NLP.MorfNCP.Base
(
-- * Basics
DAG
, Edge (..)
, Token (..)
, Interp (..)
, fromList
-- * Indices
, recalcIxs
, recalcIxsLen
, recalcIxs1
-- * Merging
, merge
) where
import qualified Data.Set as S
import qualified Data.Char as C
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.MemoCombinators as Memo
import NLP.Morfeusz (DAG, Edge(..))
import qualified NLP.Morfeusz as Morf
---------------------------------------------------
-- Data Types
---------------------------------------------------
-- | A token with a list of potential interpretations. If the list of
-- interpretations is empty, the token is unknown.
data Token t = Token
{ orth :: T.Text
, interps :: [Interp t]
} deriving (Show, Functor)
-- | An interpretation of the word.
data Interp t = Interp
{ base :: T.Text -- ^ Base form
, msd :: t -- ^ Morphosyntactic description
, choice :: Bool -- ^ Is it chosen?
} deriving (Show, Functor)
-- | Create a trivial DAG from a list of elements.
fromList :: [t] -> DAG t
fromList xs =
[ Edge
{ from = i
, to = i + 1
, label = x }
| (x, i) <- zip xs [0..] ]
------------------------------------------------------
-- Recalculating indices
------------------------------------------------------
-- | Recalculate the `from` and `to` values of the individual labels to reflect
-- the distance from the beginning of the sentence to the given position (with
-- the goal to simplify merging several DAGs).
-- The way distance is calculated depends on the first argument, which
-- computes the length of the token (typical values: the actual length
-- or 1).
recalcIxs :: (Token t -> Int) -> DAG (Token t) -> DAG (Token t)
recalcIxs tokLen dag =
[ edge
{ from = dist (from edge)
, to = dist (to edge) }
| edge <- dag ]
where
dist = Memo.integral dist'
dist' i = maximumDef 0
[ dist from + tokLen label
| Edge{..} <- findEdgeTo i dag ]
maximumDef x xs = case xs of
[] -> x
_ -> maximum xs
-- | Run `recalcIxs` with the length of token set to the number of non-space
-- characters inside.
recalcIxsLen :: DAG (Token t) -> DAG (Token t)
recalcIxsLen = recalcIxs $ T.length . T.filter (not . C.isSpace) . orth
-- -- The previous version: simply the length of the orth of a token.
-- recalcIxsLen :: DAG (Token t) -> DAG (Token t)
-- recalcIxsLen = recalcIxs $ T.length . orth
recalcIxs1 :: DAG (Token t) -> DAG (Token t)
recalcIxs1 = recalcIxs $ const 1
-- | Find edge ending on the given position.
findEdgeTo :: Int -> DAG a -> [Edge a]
findEdgeTo i = filter ((==i) . to)
-- oneElem :: (Ord a, Show a, Num a) => [a] -> a
-- oneElem xs = case S.toList (S.fromList xs) of
-- [] -> 0
-- [x] -> x
-- _ -> error $ "oneElem: |" ++ show xs ++ "| <> 1"
------------------------------------------------------
-- Merging
------------------------------------------------------
-- | Merge a list of DAGs.
merge :: (Ord t) => [DAG (Token t)] -> DAG (Token t)
merge dags =
[ Edge
{ from = from
, to = to
, label = label }
| ((from, to), label) <- M.toList dagMap ]
where
dagMap = M.fromListWith mergeTok
[ ((from, to), label)
| Edge{..} <- concat dags ]
mergeTok x y = mergeToks [x, y]
-- | Assumption: input list non-empty and all tokens have
-- the same `orth` value.
mergeToks :: (Ord t) => [Token t] -> Token t
mergeToks toks =
(head toks) {interps = newInterps}
where
newInterps =
[ Interp
{ base = base
, msd = msd
, choice = choice }
| (msd, (choice, base)) <- M.toList interpsMap ]
interpsMap = M.fromListWith orBase
[ (msd, (choice, base))
| Interp{..} <- concatMap interps toks ]
-- differences on base values are ignored
orBase (choice1, base1) (choice2, _base2) = (choice1 || choice2, base1)
| kawu/morf-nkjp | src/NLP/MorfNCP/Base.hs | bsd-2-clause | 4,002 | 0 | 12 | 939 | 978 | 567 | 411 | 79 | 2 |
{-# LANGUAGE Haskell2010 #-}
module Classes where
class Foo a where
bar :: a -> Int
baz :: Int -> (a, a)
instance Foo Int where
bar = id
baz x = (x, x)
instance Foo [a] where
bar = length
baz _ = ([], [])
class Foo a => Foo' a where
quux :: (a, a) -> a
quux (x, y) = norf [x, y]
norf :: [a] -> a
norf = quux . baz . sum . map bar
instance Foo' Int where
norf = sum
instance Foo' [a] where
quux = uncurry (++)
class Plugh p where
plugh :: p a a -> p b b -> p (a -> b) (b -> a)
instance Plugh Either where
plugh (Left a) _ = Right $ const a
plugh (Right a) _ = Right $ const a
plugh _ (Left b) = Left $ const b
plugh _ (Right b) = Left $ const b
| haskell/haddock | hypsrc-test/src/Classes.hs | bsd-2-clause | 724 | 0 | 11 | 237 | 370 | 194 | 176 | 27 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Text.HTML.SanitizeXSS
( -- * Default HTML sanitizers.
sanitize
, sanitizeBalance
, sanitizeXSS
-- * Helper functions to build your own sanitizer.
, filterTags
, sanitizeWith
, balance
-- * Default tag sanitizer.
, safeTags
-- * Internal helper functions that can be composed into custom filters.
, safeTagName
, safeAttribute
, sanitizeURIAttribute
, sanitizeStyleAttribute
, sanitizeCSS
, sanitaryURI
) where
import Text.HTML.SanitizeXSS.Css
import Text.HTML.TagSoup
import Control.Monad
import Data.Set (Set(), member, notMember, (\\), fromList)
import Data.Char ( toLower )
import Data.Text.Lazy (Text)
import Data.Maybe (mapMaybe)
import qualified Data.Text.Lazy as T
import Network.URI ( parseURIReference, URI (..),
isAllowedInURI, escapeURIString, uriScheme )
import Codec.Binary.UTF8.String ( encodeString )
import qualified Data.Map as Map
-- | santize the html to prevent XSS attacks. See README.md <http://github.com/gregwebs/haskell-xss-sanitize> for more details
sanitize :: Text -> Text
sanitize = sanitizeXSS
-- | alias of sanitize function
sanitizeXSS :: Text -> Text
sanitizeXSS = filterTags (mapMaybe safeTags)
-- | same as sanitize but makes sure there are no lone closing tags. See README.md <http://github.com/gregwebs/haskell-xss-sanitize> for more details
sanitizeBalance :: Text -> Text
sanitizeBalance = filterTags (balance Map.empty . mapMaybe safeTags)
-- | insert custom tag filtering. Don't forget to compose your filter with safeTags!
filterTags :: ([Tag Text] -> [Tag Text]) -> Text -> Text
filterTags f = renderTagsOptions renderOptions {
optMinimize = \x -> x `elem` ["br","img"] -- <img><img> converts to <img />, <a/> converts to <a></a>
, optEmptyAttr = False
} . f . canonicalizeTags . parseTags
-- | default tag and attribute sanitizer based on whitelist.
safeTags :: Tag Text -> Maybe (Tag Text)
safeTags = sanitizeWith safeTagName (sanitizeStyleAttribute <=< sanitizeURIAttribute <=< safeAttribute)
-- | sanitize a tag and attributes using two custom filters.
sanitizeWith
:: (Text -> Bool) -- ^ The tag name sanitizer.
-> (Attribute Text -> Maybe (Attribute Text)) -- ^ The attribute sanitizer.
-> Tag Text -> Maybe (Tag Text)
sanitizeWith ft _ t@(TagClose name)
| ft name = Just t
| otherwise = Nothing
sanitizeWith ft fa (TagOpen name attributes)
| ft name = Just (TagOpen name (mapMaybe fa attributes))
| otherwise = Nothing
sanitizeWith _ _ t = Just t
-- | make sure all tags are properly balanced.
balance :: Map.Map Text Int -> [Tag Text] -> [Tag Text]
balance m [] =
concatMap go $ Map.toList m
where
go (name, i)
| noClosing name = []
| otherwise = replicate i $ TagClose name
noClosing = flip elem ["br", "img"]
balance m (t@(TagClose name):tags) =
case Map.lookup name m of
Nothing -> TagOpen name [] : TagClose name : balance m tags
Just i ->
let m' = if i == 1
then Map.delete name m
else Map.insert name (i - 1) m
in t : balance m' tags
balance m (TagOpen name as : tags) =
TagOpen name as : balance m' tags
where
m' = case Map.lookup name m of
Nothing -> Map.insert name 1 m
Just i -> Map.insert name (i + 1) m
balance m (t:ts) = t : balance m ts
-- | whitelist based safety check for tag name.
safeTagName :: Text -> Bool
safeTagName tagname = tagname `member` sanitaryTags
-- | whitelist based sanitizer for attribute names.
safeAttribute :: (Text, Text) -> Maybe (Text, Text)
safeAttribute (name, value) =
if name `member` sanitaryAttributes
then Just (name, value)
else Nothing
-- | whitelist based sanitizer for attribute URI values.
sanitizeURIAttribute :: (Text, Text) -> Maybe (Text, Text)
sanitizeURIAttribute (name, value) =
if name `notMember` uri_attributes || sanitaryURI value
then Just (name, value)
else Nothing
-- | whitelist based sanitizer inline CSS within style attributes.
sanitizeStyleAttribute :: (Text, Text) -> Maybe (Text, Text)
sanitizeStyleAttribute ("style", value) =
let css = sanitizeCSS value in if T.null css then Nothing else Just ("style", css)
sanitizeStyleAttribute attr = Just attr
-- | Returns @True@ if the specified URI is not a potential security risk.
sanitaryURI :: Text -> Bool
sanitaryURI u =
case parseURIReference (escapeURI $ T.unpack u) of
Just p -> (null (uriScheme p)) ||
((map toLower $ init $ uriScheme p) `member` safeURISchemes)
Nothing -> False
-------------------------------------------------------------------------------
-- | Escape unicode characters in a URI. Characters that are
-- already valid in a URI, including % and ?, are left alone.
escapeURI :: String -> String
escapeURI = escapeURIString isAllowedInURI . encodeString
safeURISchemes :: Set String
safeURISchemes = fromList acceptable_protocols
sanitaryTags :: Set Text
sanitaryTags = fromList (acceptable_elements ++ mathml_elements ++ svg_elements)
\\ (fromList svg_allow_local_href) -- extra filtering not implemented
sanitaryAttributes :: Set Text
sanitaryAttributes = fromList (allowed_html_uri_attributes ++ acceptable_attributes ++ mathml_attributes ++ svg_attributes)
\\ (fromList svg_attr_val_allows_ref) -- extra unescaping not implemented
allowed_html_uri_attributes :: [Text]
allowed_html_uri_attributes = ["href", "src", "cite", "action", "longdesc"]
uri_attributes :: Set Text
uri_attributes = fromList $ allowed_html_uri_attributes ++ ["xlink:href", "xml:base"]
acceptable_elements :: [Text]
acceptable_elements = ["a", "abbr", "acronym", "address", "area",
"article", "aside", "audio", "b", "big", "blockquote", "br", "button",
"canvas", "caption", "center", "cite", "code", "col", "colgroup",
"command", "datagrid", "datalist", "dd", "del", "details", "dfn",
"dialog", "dir", "div", "dl", "dt", "em", "event-source", "fieldset",
"figure", "footer", "font", "form", "header", "h1", "h2", "h3", "h4",
"h5", "h6", "hr", "i", "img", "input", "ins", "keygen", "kbd",
"label", "legend", "li", "m", "map", "menu", "meter", "multicol",
"nav", "nextid", "ol", "output", "optgroup", "option", "p", "pre",
"progress", "q", "s", "samp", "section", "select", "small", "sound",
"source", "spacer", "span", "strike", "strong", "sub", "sup", "table",
"tbody", "td", "textarea", "time", "tfoot", "th", "thead", "tr", "tt",
"u", "ul", "var", "video"]
mathml_elements :: [Text]
mathml_elements = ["maction", "math", "merror", "mfrac", "mi",
"mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom",
"mprescripts", "mroot", "mrow", "mspace", "msqrt", "mstyle", "msub",
"msubsup", "msup", "mtable", "mtd", "mtext", "mtr", "munder",
"munderover", "none"]
-- this should include altGlyph I think
svg_elements :: [Text]
svg_elements = ["a", "animate", "animateColor", "animateMotion",
"animateTransform", "clipPath", "circle", "defs", "desc", "ellipse",
"font-face", "font-face-name", "font-face-src", "g", "glyph", "hkern",
"linearGradient", "line", "marker", "metadata", "missing-glyph",
"mpath", "path", "polygon", "polyline", "radialGradient", "rect",
"set", "stop", "svg", "switch", "text", "title", "tspan", "use"]
acceptable_attributes :: [Text]
acceptable_attributes = ["abbr", "accept", "accept-charset", "accesskey",
"align", "alt", "autocomplete", "autofocus", "axis",
"background", "balance", "bgcolor", "bgproperties", "border",
"bordercolor", "bordercolordark", "bordercolorlight", "bottompadding",
"cellpadding", "cellspacing", "ch", "challenge", "char", "charoff",
"choff", "charset", "checked", "class", "clear", "color",
"cols", "colspan", "compact", "contenteditable", "controls", "coords",
-- "data", TODO: allow this with further filtering
"datafld", "datapagesize", "datasrc", "datetime", "default",
"delay", "dir", "disabled", "draggable", "dynsrc", "enctype", "end",
"face", "for", "form", "frame", "galleryimg", "gutter", "headers",
"height", "hidefocus", "hidden", "high", "hreflang", "hspace",
"icon", "id", "inputmode", "ismap", "keytype", "label", "leftspacing",
"lang", "list", "loop", "loopcount", "loopend",
"loopstart", "low", "lowsrc", "max", "maxlength", "media", "method",
"min", "multiple", "name", "nohref", "noshade", "nowrap", "open",
"optimum", "pattern", "ping", "point-size", "prompt", "pqg",
"radiogroup", "readonly", "rel", "repeat-max", "repeat-min",
"replace", "required", "rev", "rightspacing", "rows", "rowspan",
"rules", "scope", "selected", "shape", "size", "span", "start",
"step",
"style", -- gets further filtering
"summary", "suppress", "tabindex", "target",
"template", "title", "toppadding", "type", "unselectable", "usemap",
"urn", "valign", "value", "variable", "volume", "vspace", "vrml",
"width", "wrap", "xml:lang"]
acceptable_protocols :: [String]
acceptable_protocols = [ "ed2k", "ftp", "http", "https", "irc",
"mailto", "news", "gopher", "nntp", "telnet", "webcal",
"xmpp", "callto", "feed", "urn", "aim", "rsync", "tag",
"ssh", "sftp", "rtsp", "afs" ]
mathml_attributes :: [Text]
mathml_attributes = ["actiontype", "align", "columnalign", "columnalign",
"columnalign", "columnlines", "columnspacing", "columnspan", "depth",
"display", "displaystyle", "equalcolumns", "equalrows", "fence",
"fontstyle", "fontweight", "frame", "height", "linethickness", "lspace",
"mathbackground", "mathcolor", "mathvariant", "mathvariant", "maxsize",
"minsize", "other", "rowalign", "rowalign", "rowalign", "rowlines",
"rowspacing", "rowspan", "rspace", "scriptlevel", "selection",
"separator", "stretchy", "width", "width", "xlink:href", "xlink:show",
"xlink:type", "xmlns", "xmlns:xlink"]
svg_attributes :: [Text]
svg_attributes = ["accent-height", "accumulate", "additive", "alphabetic",
"arabic-form", "ascent", "attributeName", "attributeType",
"baseProfile", "bbox", "begin", "by", "calcMode", "cap-height",
"class", "clip-path", "color", "color-rendering", "content", "cx",
"cy", "d", "dx", "dy", "descent", "display", "dur", "end", "fill",
"fill-opacity", "fill-rule", "font-family", "font-size",
"font-stretch", "font-style", "font-variant", "font-weight", "from",
"fx", "fy", "g1", "g2", "glyph-name", "gradientUnits", "hanging",
"height", "horiz-adv-x", "horiz-origin-x", "id", "ideographic", "k",
"keyPoints", "keySplines", "keyTimes", "lang", "marker-end",
"marker-mid", "marker-start", "markerHeight", "markerUnits",
"markerWidth", "mathematical", "max", "min", "name", "offset",
"opacity", "orient", "origin", "overline-position",
"overline-thickness", "panose-1", "path", "pathLength", "points",
"preserveAspectRatio", "r", "refX", "refY", "repeatCount",
"repeatDur", "requiredExtensions", "requiredFeatures", "restart",
"rotate", "rx", "ry", "slope", "stemh", "stemv", "stop-color",
"stop-opacity", "strikethrough-position", "strikethrough-thickness",
"stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap",
"stroke-linejoin", "stroke-miterlimit", "stroke-opacity",
"stroke-width", "systemLanguage", "target", "text-anchor", "to",
"transform", "type", "u1", "u2", "underline-position",
"underline-thickness", "unicode", "unicode-range", "units-per-em",
"values", "version", "viewBox", "visibility", "width", "widths", "x",
"x-height", "x1", "x2", "xlink:actuate", "xlink:arcrole",
"xlink:href", "xlink:role", "xlink:show", "xlink:title", "xlink:type",
"xml:base", "xml:lang", "xml:space", "xmlns", "xmlns:xlink", "y",
"y1", "y2", "zoomAndPan"]
-- the values for these need to be escaped
svg_attr_val_allows_ref :: [Text]
svg_attr_val_allows_ref = ["clip-path", "color-profile", "cursor", "fill",
"filter", "marker", "marker-start", "marker-mid", "marker-end",
"mask", "stroke"]
svg_allow_local_href :: [Text]
svg_allow_local_href = ["altGlyph", "animate", "animateColor",
"animateMotion", "animateTransform", "cursor", "feImage", "filter",
"linearGradient", "pattern", "radialGradient", "textpath", "tref",
"set", "use"]
| silkapp/haskell-xss-sanitize | Text/HTML/SanitizeXSS.hs | bsd-2-clause | 12,385 | 0 | 15 | 2,154 | 3,140 | 1,908 | 1,232 | 215 | 4 |
module MostOverlapping ( mostOverlapping , SP(..) ) where
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Ord ( comparing )
import Debug.Trace ( trace )
-- package 'prettyclass'
import Text.PrettyPrint.HughesPJClass ( text , hang , Pretty , pPrint)
data SP a = Single a | Pair a a
deriving (Show)
-- | Find pairs of most overlapping sets in a given list of sets.
-- A list of objects 'a' plus a function to extract a set 'b'
-- from an object have to be provided.
-- Pairs are held by a 'Pair', the rest is enclosed in 'Single'.
mostOverlapping :: (Ord b, Show a, Show b)
=> (a -> S.Set b) -> [a] -> [SP a]
mostOverlapping ex xs =
[ Pair a b | ((_, a), (_, b)) <- pairs ]
++ [ Single a | (aid, a) <- ys, S.notMember aid used ]
where ys = zip [1..] xs
pairs = map snd $ recur ex 1 ys (const True)
used = S.fromList $ concat
[ [aid,bid] | ((aid, _), (bid, _)) <- pairs]
type Level = Int
type SetId = Int
-- | At each level the sets are 'partitioned' by every occuring
-- element. This is repeated recursively. At the deepest level
-- occuring pairs are tagged with their level. On the way back up,
-- the pairs occuring deepest, the one with the largest overlap,
-- are kept, and it is taken care to not use any set more often than
-- once.
recur :: (Ord b, Show a, Show b) =>
(a -> S.Set b)
-> Int
-> [(SetId, a)]
-> (b -> Bool)
-> [(Level, ((SetId, a), (SetId, a)))]
recur ex level ys elpred =
let partitions =
M.unionsWith (++)
[ M.fromList
[ (element, [(id,x)])
| element <- S.toList $ ex x
, elpred element ]
| (id,x) <- ys ]
in
-- trace ("partitions:\n" ++ show partitions)$
keepLargestPairs $ concat $ map (pairs level) $
M.toList partitions
where
pairs _ (_, [_]) = []
pairs _ (_, [(aid, a),(bid, b)]) =
[( S.size (S.intersection (ex a) (ex b))
, ((aid, a), (bid, b)))]
pairs level (el, partition) =
let pairsWithLevel = recur ex (succ level) partition (>el)
usedIds =
S.fromList $ concat
[ [aid,bid]
| (_, ((aid, _), (bid, _))) <- pairsWithLevel]
morePairs =
[ (level, (a,b))
| (a,b) <- pairSequence
[ x
| x@(id,_) <- partition
, S.notMember id usedIds]]
in morePairs ++ pairsWithLevel
keepLargestPairs :: [(Level, ((SetId, a), (SetId, b)))]
-> [(Level, ((SetId, a), (SetId, b)))]
keepLargestPairs ps =
keep S.empty (reverse $ L.sortBy (comparing fst) ps) []
where
keep _ [] res = res
keep seen (p@(_, ((aid, _), (bid, _))):ps) res =
if S.member aid seen || S.member bid seen
then keep seen ps res
else keep (S.union seen (S.fromList [aid, bid]))
ps
(p:res)
pairSequence :: [a] -> [(a,a)]
pairSequence (a:b:xs) = (a,b) : pairSequence xs
pairSequence _ = []
instance Pretty a => Pretty (SP a) where
pPrint (Single a) = hang (text "Single") 2 $ pPrint a
pPrint (Pair a b) = hang (text "Pair") 2 $ pPrint [a,b]
| malie/drolesat | MostOverlapping.hs | bsd-3-clause | 3,221 | 0 | 19 | 970 | 1,249 | 705 | 544 | 70 | 3 |
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
module Parse.Declaration where
import Control.Applicative ((<$>))
import Text.Parsec ((<|>), (<?>), choice, digit, optionMaybe, string, try)
import qualified AST.Declaration as D
import qualified Parse.Expression as Expr
import Parse.Helpers
import qualified Parse.Type as Type
declaration :: IParser D.SourceDecl
declaration =
typeDecl <|> infixDecl <|> port <|> definition
definition :: IParser D.SourceDecl
definition = D.Definition <$> Expr.def
typeDecl :: IParser D.SourceDecl
typeDecl =
do reserved "type" <?> "type declaration"
forcedWS
isAlias <- optionMaybe (string "alias" >> forcedWS)
name <- capVar
args <- spacePrefix lowVar
padded equals
case isAlias of
Just _ ->
do tipe <- Type.expr <?> "a type"
return (D.TypeAlias name args tipe)
Nothing ->
do tcs <- pipeSep1 Type.constructor <?> "a constructor for a union type"
return $ D.Datatype name args tcs
infixDecl :: IParser D.SourceDecl
infixDecl = do
assoc <- choice [ reserved "infixl" >> return D.L
, reserved "infix" >> return D.N
, reserved "infixr" >> return D.R ]
forcedWS
n <- digit
forcedWS
D.Fixity assoc (read [n]) <$> anyOp
port :: IParser D.SourceDecl
port =
do try (reserved "port")
whitespace
name <- lowVar
whitespace
let port' op ctor expr = do { try op ; whitespace ; ctor name <$> expr }
D.Port <$> choice [ port' hasType D.PPAnnotation Type.expr
, port' equals D.PPDef Expr.expr ]
| JoeyEremondi/haskelm | src/Parse/Declaration.hs | bsd-3-clause | 1,619 | 0 | 15 | 417 | 511 | 255 | 256 | 46 | 2 |
module Test where
import qualified Data.ByteString.Lazy as BS
import Data.Binary.Get
import Data.Binary as B
import GisServer.Data.ISO8211
import GisServer.Data.S57
import Int
main :: IO ()
main = do
bs <- BS.readFile f1
let r :: ExchangeFile
r = B.decode bs
print $ ddr r
let rs = records r
print rs
--print $ take 5 $ filter (hasRecordField "DSPR") rs
where f = "/home/alios/tmp/ENC_ROOT/US3AK21M/US3AK21M.000"
f1 = "/home/alios/tmp/ENC_ROOT/CATALOG.031"
xxx :: Word8
xxx = -1
foo :: Word8 -> Int8
foo x = fromIntegral ((fromIntegral x) :: Word64)
| alios/gisserver | Test.hs | bsd-3-clause | 592 | 0 | 11 | 127 | 172 | 94 | 78 | 21 | 1 |
{-# OPTIONS_GHC -O #-}
{-# LANGUAGE NoMonomorphismRestriction, ViewPatterns, TupleSections #-}
import Prelude as P
import QCUtils
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit
import Test.QuickCheck
import Data.Iteratee hiding (head, break)
import qualified Data.Iteratee.Char as IC
import qualified Data.Iteratee as Iter
import Data.Functor.Identity
import qualified Data.List as List (groupBy, unfoldr)
import Data.Monoid
import qualified Data.ListLike as LL
import Control.Monad as CM
import Control.Monad.Writer
import Control.Exception (SomeException)
instance Show (a -> b) where
show _ = "<<function>>"
-- ---------------------------------------------
-- Stream instances
type ST = Stream [Int]
prop_eq str = str == str
where types = str :: ST
prop_mempty = mempty == (Chunk [] :: Stream [Int])
prop_mappend str1 str2 | isChunk str1 && isChunk str2 =
str1 `mappend` str2 == Chunk (chunkData str1 ++ chunkData str2)
prop_mappend str1 str2 = isEOF $ str1 `mappend` str2
where types = (str1 :: ST, str2 :: ST)
prop_mappend2 str = str `mappend` mempty == mempty `mappend` str
where types = str :: ST
isChunk (Chunk _) = True
isChunk (EOF _) = False
chunkData (Chunk xs) = xs
isEOF (EOF _) = True
isEOF (Chunk _) = False
-- ---------------------------------------------
-- Iteratee instances
runner1 = runIdentity . Iter.run . runIdentity
enumSpecial xs n = enumPure1Chunk LL.empty >=> enumPureNChunk xs n
prop_iterFmap xs f a = runner1 (enumPure1Chunk xs (fmap f $ return a))
== runner1 (enumPure1Chunk xs (return $ f a))
where types = (xs :: [Int], f :: Int -> Int, a :: Int)
prop_iterFmap2 xs f i = runner1 (enumPure1Chunk xs (fmap f i))
== f (runner1 (enumPure1Chunk xs i))
where types = (xs :: [Int], i :: I, f :: [Int] -> [Int])
prop_iterMonad1 xs a f = runner1 (enumSpecial xs 1 (return a >>= f))
== runner1 (enumPure1Chunk xs (f a))
where types = (xs :: [Int], a :: Int, f :: Int -> I)
prop_iterMonad2 m xs = runner1 (enumSpecial xs 1 (m >>= return))
== runner1 (enumPure1Chunk xs m)
where types = (xs :: [Int], m :: I)
prop_iterMonad3 m f g xs = runner1 (enumSpecial xs 1 ((m >>= f) >>= g))
== runner1 (enumPure1Chunk xs (m >>= (\x -> f x >>= g)))
where types = (xs :: [Int], m :: I, f :: [Int] -> I, g :: [Int] -> I)
-- ---------------------------------------------
-- List <-> Stream
prop_list xs = runner1 (enumPure1Chunk xs stream2list) == xs
where types = xs :: [Int]
prop_clist xs n = n > 0 ==> runner1 (enumSpecial xs n stream2list) == xs
where types = xs :: [Int]
prop_break f xs = runner1 (enumPure1Chunk xs (Iter.break f)) == fst (break f xs)
where types = xs :: [Int]
prop_break2 f xs = runner1 (enumPure1Chunk xs (Iter.break f >> stream2list)) == snd (break f xs)
where types = xs :: [Int]
prop_breakE f xs = runner1 (enumPure1Chunk xs (joinI $ Iter.breakE f stream2stream)) == fst (break f xs)
where types = xs :: [Int]
prop_breakE2 f xs = runner1 (enumPure1Chunk xs (joinI (Iter.breakE f stream2stream) >> stream2list)) == snd (break f xs)
where types = xs :: [Int]
prop_head xs = P.length xs > 0 ==> runner1 (enumPure1Chunk xs Iter.head) == head xs
where types = xs :: [Int]
prop_head2 xs = P.length xs > 0 ==> runner1 (enumPure1Chunk xs (Iter.head >> stream2list)) == tail xs
where types = xs :: [Int]
prop_tryhead xs = case xs of
[] -> runner1 (enumPure1Chunk xs tryHead) == Nothing
_ -> runner1 (enumPure1Chunk xs tryHead) == Just (P.head xs)
where types = xs :: [Int]
prop_heads xs n = n > 0 ==>
runner1 (enumSpecial xs n $ heads xs) == P.length xs
where types = xs :: [Int]
prop_heads2 xs = runner1 (enumPure1Chunk xs $ heads [] >>= \c ->
stream2list >>= \s -> return (c,s))
== (0, xs)
where types = xs :: [Int]
prop_peek xs = runner1 (enumPure1Chunk xs peek) == sHead xs
where
types = xs :: [Int]
sHead [] = Nothing
sHead (x:_) = Just x
prop_peek2 xs = runner1 (enumPure1Chunk xs (peek >> stream2list)) == xs
where types = xs :: [Int]
prop_skip xs = runner1 (enumPure1Chunk xs (skipToEof >> stream2list)) == []
where types = xs :: [Int]
prop_last1 xs = P.length xs > 0 ==>
runner1 (enumPure1Chunk xs (Iter.last)) == P.last xs
where types = xs :: [Int]
prop_last2 xs = P.length xs > 0 ==>
runner1 (enumPure1Chunk xs (Iter.last >> Iter.peek)) == Nothing
where types = xs :: [Int]
prop_drop xs n k = (n > 0 && k >= 0) ==>
runner1 (enumSpecial xs n (Iter.drop k >> stream2list)) == P.drop k xs
where types = xs :: [Int]
prop_dropWhile f xs =
runner1 (enumPure1Chunk xs (Iter.dropWhile f >> stream2list))
== P.dropWhile f xs
where types = (xs :: [Int], f :: Int -> Bool)
prop_length xs = runner1 (enumPure1Chunk xs Iter.length) == P.length xs
where types = xs :: [Int]
-- length 0 is an odd case. enumPureNChunk skips null inputs, returning
-- the original iteratee, which is then given to `enumEof` by `run`.
-- This is different from enumPure1Chunk, which will provide a null chunk
-- to the iteratee.
--
-- not certain ATM which should be correct...
prop_chunkLength xs n = n > 0 ==>
runner1 (enumPureNChunk xs n (liftM2 (,) chunkLength stream2list))
== case P.length xs of
0 -> (Nothing, xs)
xl | xl >= n -> (Just n, xs)
| otherwise -> (Just (P.length xs), xs)
where types = xs :: [Int]
prop_chunkLength2 xs =
runner1 ((enumEof >=> enumPure1Chunk xs) chunkLength) == Nothing
where types = xs :: [Int]
prop_takeFromChunk xs n k = n > 0 ==>
runner1 (enumPureNChunk xs n (liftM2 (,) (takeFromChunk k) stream2list))
== if k > n then splitAt n xs else splitAt k xs
where types = xs :: [Int]
-- ---------------------------------------------
-- Simple enumerator tests
type I = Iteratee [Int] Identity [Int]
prop_enumChunks n xs i = n > 0 ==>
runner1 (enumPure1Chunk xs i) == runner1 (enumSpecial xs n i)
where types = (n :: Int, xs :: [Int], i :: I)
prop_app1 xs ys i = runner1 (enumPure1Chunk ys (joinIM $ enumPure1Chunk xs i))
== runner1 (enumPure1Chunk (xs ++ ys) i)
where types = (xs :: [Int], ys :: [Int], i :: I)
prop_app2 xs ys = runner1 ((enumPure1Chunk xs >>> enumPure1Chunk ys) stream2list)
== runner1 (enumPure1Chunk (xs ++ ys) stream2list)
where types = (xs :: [Int], ys :: [Int])
prop_app3 xs ys i = runner1 ((enumPure1Chunk xs >>> enumPure1Chunk ys) i)
== runner1 (enumPure1Chunk (xs ++ ys) i)
where types = (xs :: [Int], ys :: [Int], i :: I)
prop_eof xs ys i = runner1 (enumPure1Chunk ys $ runIdentity $
(enumPure1Chunk xs >>> enumEof) i)
== runner1 (enumPure1Chunk xs i)
where types = (xs :: [Int], ys :: [Int], i :: I)
prop_isFinished = runner1 (enumEof (isFinished :: Iteratee [Int] Identity Bool)) == True
prop_isFinished2 = runner1 (enumErr (iterStrExc "Error") (isFinished :: Iteratee [Int] Identity Bool)) == True
prop_null xs i = runner1 (enumPure1Chunk xs =<< enumPure1Chunk [] i)
== runner1 (enumPure1Chunk xs i)
where types = (xs :: [Int], i :: I)
prop_nullH xs = P.length xs > 0 ==>
runner1 (enumPure1Chunk xs =<< enumPure1Chunk [] Iter.head)
== runner1 (enumPure1Chunk xs Iter.head)
where types = xs :: [Int]
prop_enumList xs i =
not (P.null xs) ==>
runner1 (enumList (replicate 100 xs) i)
== runner1 (enumPure1Chunk (concat $ replicate 100 xs) i)
where types = (xs :: [Int], i :: I)
prop_enumCheckIfDone xs i =
runner1 (enumPure1Chunk xs (lift (enumCheckIfDone i) >>= snd))
== runner1 (enumPure1Chunk xs i)
where types = (xs :: [Int], i :: I)
-- ---------------------------------------------
-- Enumerator Combinators
prop_enumWith xs f n = n > 0 ==> runner1 (enumSpecial xs n $ fmap fst $ enumWith (Iter.dropWhile f) (stream2list))
== runner1 (enumSpecial xs n $ Iter.dropWhile f)
where types = (xs :: [Int])
prop_enumWith2 xs f n = n > 0 ==> runner1 (enumSpecial xs n $ enumWith (Iter.dropWhile f) (stream2list) >> stream2list)
== runner1 (enumSpecial xs n $ Iter.dropWhile f >> stream2list)
where types = (xs :: [Int])
prop_enumWith3 xs i n =
n > 0
==> runner1 (enumSpecial xs n $ enumWith i stream2list >> stream2list)
== runner1 (enumSpecial xs n (i >> stream2list))
where types = (xs :: [Int], i :: I)
prop_countConsumed (Positive (min (2^10) -> n)) (Positive (min (2^20) -> a)) (Positive k) =
runner1 (enumPureNChunk [1..] n iter) == (a, a)
where
iter = countConsumed . joinI $ (takeUpTo (a + k) ><> Iter.take a) Iter.last
-- ---------------------------------------------
-- Nested Iteratees
-- take, mapStream, convStream, and takeR
runner2 = runIdentity . run . runner1
prop_mapStream xs i = runner2 (enumPure1Chunk xs $ mapStream id i)
== runner1 (enumPure1Chunk xs i)
where types = (i :: I, xs :: [Int])
prop_mapStream2 xs n i = n > 0 ==>
runner2 (enumSpecial xs n $ mapStream id i)
== runner1 (enumPure1Chunk xs i)
where types = (i :: I, xs :: [Int])
prop_mapjoin xs i =
runIdentity (run (joinI . runIdentity $ enumPure1Chunk xs $ mapStream id i))
== runner1 (enumPure1Chunk xs i)
where types = (i :: I, xs :: [Int])
prop_rigidMapStream xs n f = n > 0 ==>
runner2 (enumSpecial xs n $ rigidMapStream f stream2list) == map f xs
where types = (xs :: [Int])
prop_foldl xs n f x0 = n > 0 ==>
runner1 (enumSpecial xs n (Iter.foldl f x0)) == P.foldl f x0 xs
where types = (xs :: [Int], x0 :: Int)
prop_foldl' xs n f x0 = n > 0 ==>
runner1 (enumSpecial xs n (Iter.foldl' f x0)) == LL.foldl' f x0 xs
where types = (xs :: [Int], x0 :: Int)
prop_foldl1 xs n f = (n > 0 && not (null xs)) ==>
runner1 (enumSpecial xs n (Iter.foldl1 f)) == P.foldl1 f xs
where types = (xs :: [Int])
prop_foldl1' xs n f = (n > 0 && not (null xs)) ==>
runner1 (enumSpecial xs n (Iter.foldl1' f)) == P.foldl1 f xs
where types = (xs :: [Int])
prop_sum xs n = n > 0 ==> runner1 (enumSpecial xs n Iter.sum) == P.sum xs
where types = (xs :: [Int])
prop_product xs n = n > 0 ==>
runner1 (enumSpecial xs n Iter.product) == P.product xs
where types = (xs :: [Int])
convId :: (LL.ListLike s el, Monad m) => Iteratee s m s
convId = liftI (\str -> case str of
s@(Chunk xs) | LL.null xs -> convId
s@(Chunk xs) -> idone xs (Chunk mempty)
s@(EOF e) -> idone mempty (EOF e)
)
prop_convId xs = runner1 (enumPure1Chunk xs convId) == xs
where types = xs :: [Int]
prop_convstream xs i = P.length xs > 0 ==>
runner2 (enumPure1Chunk xs $ convStream convId i)
== runner1 (enumPure1Chunk xs i)
where types = (xs :: [Int], i :: I)
prop_convstream2 xs = P.length xs > 0 ==>
runner2 (enumPure1Chunk xs $ convStream convId Iter.head)
== runner1 (enumPure1Chunk xs Iter.head)
where types = xs :: [Int]
prop_convstream3 xs = P.length xs > 0 ==>
runner2 (enumPure1Chunk xs $ convStream convId stream2list)
== runner1 (enumPure1Chunk xs stream2list)
where types = xs :: [Int]
prop_take xs n = n >= 0 ==>
runner2 (enumPure1Chunk xs $ Iter.take n stream2list)
== runner1 (enumPure1Chunk (P.take n xs) stream2list)
where types = xs :: [Int]
prop_take2 xs n = n > 0 ==>
runner2 (enumPure1Chunk xs $ Iter.take n peek)
== runner1 (enumPure1Chunk (P.take n xs) peek)
where types = xs :: [Int]
prop_takeUpTo xs n = n >= 0 ==>
runner2 (enumPure1Chunk xs $ Iter.take n stream2list)
== runner2 (enumPure1Chunk xs $ takeUpTo n stream2list)
where types = xs :: [Int]
prop_takeUpTo2 xs n = n >= 0 ==>
runner2 (enumPure1Chunk xs (takeUpTo n identity)) == ()
where types = xs :: [Int]
-- check for final stream state
prop_takeUpTo3 xs n d t = n > 0 ==>
runner1 (enumPureNChunk xs n (joinI (takeUpTo t (Iter.drop d)) >> stream2list))
== P.drop (min t d) xs
where types = xs :: [Int]
prop_takeWhile xs n f = n > 0 ==>
runner1 (enumSpecial xs n (liftM2 (,) (Iter.takeWhile f) stream2list))
== (P.takeWhile f xs, P.dropWhile f xs)
where types = xs :: [Int]
prop_filter xs n f = n > 0 ==>
runner2 (enumSpecial xs n (Iter.filter f stream2list)) == P.filter f xs
where types = xs :: [Int]
prop_group xs n = n > 0 ==>
runner2 (enumPure1Chunk xs $ Iter.group n stream2list)
== runner1 (enumPure1Chunk groups stream2list)
where types = xs :: [Int]
groups :: [[Int]]
groups = List.unfoldr groupOne xs
where groupOne [] = Nothing
groupOne elts@(_:_) = Just . splitAt n $ elts
prop_groupBy xs = forAll (choose (2,5)) $ \m ->
let pred z1 z2 = (z1 `mod` m == z2 `mod` m)
in runner2 (enumPure1Chunk xs $ Iter.groupBy pred stream2list)
== runner1 (enumPure1Chunk (List.groupBy pred xs) stream2list)
where types = xs :: [Int]
prop_mapChunksM xs n = n > 0 ==>
runWriter ((enumSpecial xs n (joinI $ Iter.mapChunksM f stream2list)) >>= run)
== (xs, Sum (P.length xs))
where f ck = tell (Sum $ P.length ck) >> return ck
types = xs :: [Int]
{-
prop_mapjoin xs i =
runIdentity (run (joinI . runIdentity $ enumPure1Chunk xs $ mapStream id i))
== runner1 (enumPure1Chunk xs i)
where types = (i :: I, xs :: [Int])
-}
prop_mapChunksM_ xs n = n > 0 ==>
snd (runWriter ((enumSpecial xs n (Iter.mapChunksM_ f)) >>= run))
== Sum (P.length xs)
where f ck = tell (Sum $ P.length ck)
types = xs :: [Int]
prop_mapM_ xs n = n > 0 ==>
runWriter ((enumSpecial xs n (Iter.mapM_ f)) >>= run)
== runWriter (CM.mapM_ f xs)
where f = const $ tell (Sum 1)
types = xs :: [Int]
prop_foldChunksM xs x0 n = n > 0 ==>
runWriter ((enumSpecial xs n (Iter.foldChunksM f x0)) >>= run)
== runWriter (f x0 xs)
where f acc ck = CM.foldM f' acc ck
f' acc el = tell (Sum 1) >> return (acc+el)
types = xs :: [Int]
prop_foldM xs x0 n = n > 0 ==>
runWriter ((enumSpecial xs n (Iter.foldM f x0)) >>= run)
== runWriter (CM.foldM f x0 xs)
where f acc el = tell (Sum 1) >> return (acc - el)
types = xs :: [Int]
-- ---------------------------------------------
-- Zips
prop_zip xs i1 i2 n = n > 0 ==>
runner1 (enumPureNChunk xs n $ liftM2 (,) (Iter.zip i1 i2) stream2list)
== let (r1, t1) = runner1 $ enumPure1Chunk xs $ liftM2 (,) i1 stream2list
(r2, t2) = runner1 $ enumPure1Chunk xs $ liftM2 (,) i2 stream2list
shorter = if P.length t1 > P.length t2 then t2 else t1
in ((r1,r2), shorter)
where types = (i1 :: I, i2 :: I, xs :: [Int])
-- ---------------------------------------------
-- Sequences
test_sequence_ =
assertEqual "sequence_: no duplicate runs" ((),[4,5])
(runWriter (Iter.enumList [[4],[5::Int]] (Iter.sequence_ [iter])
>>= run))
where
iter = do
x <- Iter.head
lift $ tell [x]
y <- Iter.head
lift $ tell [y]
-- ---------------------------------------------
-- Data.Iteratee.PTerm
mk_prop_pt_id etee p_etee i xs n = n > 0 ==>
runner1 (enumSpecial xs n $ joinI (p_etee i))
== runner1 (enumSpecial xs n $ joinI (etee i))
where types = (etee, p_etee, i, xs) :: (Etee, Etee, Itee, [Int])
instance Eq SomeException where
l == r = show l == show r
type Etee = Enumeratee [Int] [Int] Identity [Int]
type Itee = Iteratee [Int] Identity [Int]
prop_mapChunksPT f i = mk_prop_pt_id (mapChunks f) (mapChunksPT f)
where types = (i :: Itee)
prop_mapChunksMPT f i =
mk_prop_pt_id (mapChunksM (return . f)) (mapChunksMPT (return . f))
where types = (i :: Itee)
-- would like to test with arbitrary iteratees, but we need to guarantee
-- that they will return a value from the stream, which isn't always true
-- for the arbitrary instance.
-- could use a newtype to make it work...
prop_convStreamPT = mk_prop_pt_id (convStream getChunk) (convStreamPT getChunk)
prop_unfoldConvStreamPT f =
mk_prop_pt_id (unfoldConvStream f' (0 :: Int)) (unfoldConvStreamPT f' 0)
where f' x = fmap (f x,) getChunk
prop_breakEPT i = mk_prop_pt_id (breakE i) (breakEPT i)
prop_takePT i = mk_prop_pt_id (Iter.take i) (takePT i)
prop_takeUpToPT i = mk_prop_pt_id (Iter.takeUpTo i) (takeUpToPT i)
prop_takeWhileEPT i = mk_prop_pt_id (Iter.takeWhileE i) (takeWhileEPT i)
prop_mapStreamPT i = mk_prop_pt_id (Iter.mapStream i) (mapStreamPT i)
prop_rigidMapStreamPT i =
mk_prop_pt_id (Iter.rigidMapStream i) (rigidMapStreamPT i)
prop_filterPT i = mk_prop_pt_id (Iter.filter i) (filterPT i)
-- ---------------------------------------------
-- Data.Iteratee.Char
{-
-- this isn't true, since lines "\r" returns ["\r"], and IC.line should
-- return Right "". Not sure what a real test would be...
prop_line xs = P.length xs > 0 ==>
fromEither (runner1 (enumPure1Chunk xs $ IC.line))
== head (lines xs)
where
types = xs :: [Char]
fromEither (Left l) = l
fromEither (Right l) = l
-}
-- ---------------------------------------------
tests = [
testGroup "Elementary" [
testProperty "list" prop_list
,testProperty "chunkList" prop_clist]
,testGroup "Stream tests" [
testProperty "mempty" prop_mempty
,testProperty "mappend" prop_mappend
,testProperty "mappend associates" prop_mappend2
,testProperty "eq" prop_eq
]
,testGroup "Simple Iteratees" [
testProperty "break" prop_break
,testProperty "break remainder" prop_break2
,testProperty "head" prop_head
,testProperty "head remainder" prop_head2
,testProperty "tryhead" prop_tryhead
,testProperty "heads" prop_heads
,testProperty "null heads" prop_heads2
,testProperty "peek" prop_peek
,testProperty "peek2" prop_peek2
,testProperty "last" prop_last1
,testProperty "last ends properly" prop_last2
,testProperty "length" prop_length
,testProperty "chunkLength" prop_chunkLength
,testProperty "chunkLength of EoF" prop_chunkLength2
,testProperty "takeFromChunk" prop_takeFromChunk
,testProperty "drop" prop_drop
,testProperty "dropWhile" prop_dropWhile
,testProperty "skipToEof" prop_skip
,testProperty "iteratee Functor 1" prop_iterFmap
,testProperty "iteratee Functor 2" prop_iterFmap2
,testProperty "iteratee Monad LI" prop_iterMonad1
,testProperty "iteratee Monad RI" prop_iterMonad2
,testProperty "iteratee Monad Assc" prop_iterMonad3
]
,testGroup "Simple Enumerators/Combinators" [
testProperty "enumPureNChunk" prop_enumChunks
,testProperty "enum append 1" prop_app1
,testProperty "enum sequencing" prop_app2
,testProperty "enum sequencing 2" prop_app3
,testProperty "enumEof" prop_eof
,testProperty "isFinished" prop_isFinished
,testProperty "isFinished error" prop_isFinished2
,testProperty "null data idempotence" prop_null
,testProperty "null data head idempotence" prop_nullH
,testProperty "enumList" prop_enumList
,testProperty "enumCheckIfDone" prop_enumCheckIfDone
]
,testGroup "Nested iteratees" [
testProperty "mapStream identity" prop_mapStream
,testProperty "mapStream identity 2" prop_mapStream2
,testProperty "mapStream identity joinI" prop_mapjoin
,testProperty "rigidMapStream" prop_rigidMapStream
,testProperty "breakE" prop_breakE
,testProperty "breakE remainder" prop_breakE2
,testProperty "take" prop_take
,testProperty "take (finished iteratee)" prop_take2
,testProperty "takeUpTo" prop_takeUpTo
,testProperty "takeUpTo (finished iteratee)" prop_takeUpTo2
,testProperty "takeUpTo (remaining stream)" prop_takeUpTo3
,testProperty "takeWhile" prop_takeWhile
,testProperty "filter" prop_filter
,testProperty "group" prop_group
,testProperty "groupBy" prop_groupBy
,testProperty "convStream EOF" prop_convstream2
,testProperty "convStream identity" prop_convstream
,testProperty "convStream identity 2" prop_convstream3
]
,testGroup "Enumerator Combinators" [
testProperty "enumWith" prop_enumWith
,testProperty "enumWith remaining" prop_enumWith2
,testProperty "enumWith remaining 2" prop_enumWith3
,testProperty "countConsumed" prop_countConsumed
]
,testGroup "Folds" [
testProperty "foldl" prop_foldl
,testProperty "foldl'" prop_foldl'
,testProperty "foldl1" prop_foldl1
,testProperty "foldl1'" prop_foldl1'
,testProperty "sum" prop_sum
,testProperty "product" prop_product
]
,testGroup "Zips" [
testProperty "zip" prop_zip
,testCase "sequence_" test_sequence_
]
,testGroup "Data.Iteratee.Char" [
--testProperty "line" prop_line
]
,testGroup "PT variants" [
testProperty "mapChunksPT" prop_mapChunksPT
,testProperty "mapChunksMPT" prop_mapChunksMPT
,testProperty "convStreamPT" prop_convStreamPT
,testProperty "unfoldConvStreamPT" prop_unfoldConvStreamPT
,testProperty "breakEPT" prop_breakEPT
,testProperty "takePT" prop_takePT
,testProperty "takeUpToPT" prop_takeUpToPT
,testProperty "takeWhileEPT" prop_takeWhileEPT
,testProperty "mapStreamPT" prop_mapStreamPT
,testProperty "rigidMapStreamPT" prop_rigidMapStreamPT
,testProperty "filterPT" prop_filterPT
]
,testGroup "Monadic functions" [
testProperty "mapM_" prop_mapM_
,testProperty "foldM" prop_foldM
,testProperty "mapChunksM" prop_mapChunksM
,testProperty "mapChunksM_" prop_mapChunksM_
,testProperty "foldChunksM" prop_foldChunksM
]
]
------------------------------------------------------------------------
-- The entry point
main = defaultMain tests
| iteloo/tsuru-sample | iteratee-0.8.9.6/tests/testIteratee.hs | bsd-3-clause | 21,902 | 0 | 17 | 4,961 | 7,731 | 4,026 | 3,705 | -1 | -1 |
module Data.Tree.Pure where
import Control.Applicative
import Data.List
import Data.Monoid
import Data.Monoid.Bounds
import Data.Maybe
import Data.Ord
import Data.Tuples
import Data.Tree.Abstract
import Prelude
import qualified Data.Morphism.Anamorphism as Ana
import qualified Data.Morphism.Catamorphism as Cata
import qualified Data.Morphism.Endoapomorphism as Endoapo
-- import qualified Data.Morphism.Endoparamorphism as Endopara
import qualified Data.Tree.Algebras as Alg
fromList :: Ord k => [(k, v)] -> Tree k v
fromList = Ana.anamorphism Alg.fromSortedList . sortBy (comparing fst)
empty :: Ord k => Tree k v
empty = fromList []
lookup :: Ord k => k -> Tree k v -> Maybe v
lookup = Cata.catamorphism . Alg.lookup
lookupAll :: Ord k => k -> Tree k v -> [v]
lookupAll = Cata.catamorphism . Alg.lookupAll
insert :: Ord k => k -> v -> Tree k v -> Tree k v
insert k v = Endoapo.endoapomorphism (Alg.insert k v)
foldMap :: Monoid m => (v -> m) -> Tree k v -> m
foldMap = Cata.catamorphism . Alg.foldMap
foldMapR :: Monoid m => (v -> m) -> Tree k v -> m
foldMapR = Cata.catamorphism . Alg.foldMapR
fold :: Monoid v => Tree k v -> v
fold = foldMap id
foldR :: Monoid v => Tree k v -> v
foldR = foldMapR id
collect :: (Applicative f, Monoid (f v)) => Tree k v -> f v
collect = foldMap pure
collectR :: (Applicative f, Monoid (f v)) => Tree k v -> f v
collectR = foldMapR pure
asList :: Tree k v -> [v]
asList = collect
asListR :: Tree k v -> [v]
asListR = collectR
size :: Num n => Tree k v -> n
size = getSum . foldMap (const (Sum 1))
depth :: (Num r, Ord r) => Tree k v -> r
depth = Cata.catamorphism Alg.depth
head :: Tree k v -> Maybe v
head = getFirst . foldMap (First . Just)
last :: Tree k v -> Maybe v
last = getFirst . foldMapR (First . Just)
sum :: Num v => Tree k v -> v
sum = getSum . foldMap Sum
product :: Num v => Tree k v -> v
product = getProduct . foldMap Product
minimum :: (Ord v, Bounded v) => Tree k v -> v
minimum = getMinimum . foldMap Minimum
maximum :: (Ord v, Bounded v) => Tree k v -> v
maximum = getMaximum . foldMap Maximum
prettyPrint :: (Show k, Show v) => Tree k v -> String
prettyPrint = intercalate "\n" . fromMaybe [] . trd3 . Cata.catamorphism Alg.prettyPrint
| sebastiaanvisser/fixpoints | src/Data/Tree/Pure.hs | bsd-3-clause | 2,230 | 0 | 10 | 451 | 963 | 499 | 464 | 58 | 1 |
module Main where
import Text.ParserCombinators.Parsec hiding (optional)
import Data.Either (either)
import Data.Serialize (runGet, getWord16be)
import Data.ByteString.Base64 (decodeLenient)
import qualified Data.ByteString.Char8 as B
import Control.Monad (replicateM)
import Data.Maybe (catMaybes)
import Control.Applicative (optional)
import Data.Char (chr)
xs = ["&AOkA6QDp-", "&bElbVw-", "&bElbVw-/&byJbVw-"]
eitherIntVal :: B.ByteString -> Either String [Integer]
eitherIntVal = runGet (do
xs <- replicateM 5 (optional getWord16be)
return $ map fromIntegral $ catMaybes xs)
intVal :: B.ByteString -> [Integer]
intVal x = either error id (eitherIntVal x)
charNums :: String -> [Int]
charNums = map fromIntegral . intVal . decodeLenient . B.pack
-- parsec functions
plain :: GenParser Char st String
plain = many1 (noneOf "&")
special :: GenParser Char st String
special = do
char '&'
x <- many (noneOf "-")
char '-'
return $ (map chr . charNums) x
utf7Letter = plain <|> special
utf7Letters :: GenParser Char st String
utf7Letters = fmap concat (many1 utf7Letter)
parseUtf7 :: String -> Either ParseError String
parseUtf7 = parse utf7Letters "(unknown)"
main = do
mapM_ (\x -> do
let r = either (error . show) id $ parseUtf7 x
putStrLn r
) xs
| danchoi/imapget | utf7/utf7.hs | bsd-3-clause | 1,309 | 0 | 18 | 243 | 455 | 239 | 216 | 37 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Control.Natural
import Control.Remote.Haxl as M
import Control.Remote.Haxl.Applicative as A
import Control.Remote.Haxl.Packet.Weak as WP
import Control.Remote.Haxl.Packet.Applicative as AP
data Procedure :: * -> * where
Say :: String -> Procedure ()
Temperature :: Procedure Int
Temperature2 :: Procedure Int
sayA :: String -> RemoteHaxlApplicative Procedure ()
sayA s = A.query (Say s)
temperatureA :: RemoteHaxlApplicative Procedure Int
temperatureA = A.query Temperature
temperature2A :: RemoteHaxlApplicative Procedure Int
temperature2A = A.query Temperature2
sayM :: String -> RemoteHaxlMonad Procedure ()
sayM s = M.query (Say s)
temperatureM :: RemoteHaxlMonad Procedure Int
temperatureM = M.query Temperature
temperature2M :: RemoteHaxlMonad Procedure Int
temperature2M = M.query Temperature2
--Server Side Functions
---------------------------------------------------------
runWP :: WeakPacket Procedure a -> IO a
runWP (WP.Query Temperature) = do
putStrLn "Temp Call"
return 42
runWP (WP.Query Temperature2) = do
putStrLn "Temp2 Call"
return 52
runWP (WP.Query (Say s)) = print s
---------------------------------------------------------
runAP :: ApplicativePacket Procedure a -> IO a
runAP (AP.Query (Say s)) = print s
runAP (AP.Query Temperature) =do
putStrLn "Temp Call"
return 42
runAP (AP.Query Temperature2) = do
putStrLn "Temp2 Call"
return 52
runAP (AP.Zip f g h) = do
f <$> runAP g <*> runAP h
runAP (AP.Pure a) = do
putStrLn "Pure"
return a
---------------------------------------------------------
sendWeakM :: RemoteHaxlMonad Procedure a -> IO a
sendWeakM = unwrapNT $ runHaxlMonad $ wrapNT (\pkt -> do putStrLn "-----"; runWP pkt)
sendAppM :: RemoteHaxlMonad Procedure a -> IO a
sendAppM = unwrapNT $ runHaxlMonad $ wrapNT (\pkt -> do putStrLn "-----"; runAP pkt)
sendWeakA :: RemoteHaxlApplicative Procedure a -> IO a
sendWeakA = unwrapNT $ runHaxlApplicative $ wrapNT (\pkt -> do putStrLn "-----"; runWP pkt)
sendAppA :: RemoteHaxlApplicative Procedure a -> IO a
sendAppA = unwrapNT $ runHaxlApplicative $ wrapNT (\pkt -> do putStrLn "-----"; runAP pkt)
---------------------------------------------------------
main :: IO ()
main = do
putStrLn "WeakSendM\n"
runTestM $ wrapNT sendWeakM
putStrLn "\nAppSendM\n"
runTestM $ wrapNT sendAppM
putStrLn "WeakSendA\n"
runTestA $ wrapNT sendWeakA
putStrLn "\nAppSendA\n"
runTestA $ wrapNT sendAppA
--Run Test Suite
runTestM :: (RemoteHaxlMonad Procedure :~> IO)-> IO ()
runTestM (NT f) = do
f testM
f testBind
f testAppM
r <- f haxlExample
print r
runTestA :: (RemoteHaxlApplicative Procedure :~> IO) -> IO ()
runTestA (NT f) = do
f testA
t <- f testAppA
print t
-- Original test case
testM :: RemoteHaxlMonad Procedure ()
testM = do
sayM "Howdy doodly do"
sayM "How about a muffin?"
t <- temperatureM
sayM (show t ++ "F")
-- Test bind
testBind :: RemoteHaxlMonad Procedure ()
testBind = sayM "one" >> sayM "two" >> temperatureM >>= sayM . ("Temperature: " ++) .show
testAppM :: RemoteHaxlMonad Procedure ()
testAppM = do
r<- add <$> temperatureM<*>temperatureM <*> temperatureM
sayM (show r)
where
add :: Int -> Int -> Int -> Int
add x y z= x + y + z
testA :: RemoteHaxlApplicative Procedure ()
testA = sayA "Howdy doodly do" *> sayA "How about a muffin?"
testAppA :: RemoteHaxlApplicative Procedure Int
testAppA = (add <$> temperatureA <*> temperatureA <*> temperatureA)
where
add :: Int -> Int -> Int -> Int
add x y z = x + y + z
haxlExample :: RemoteHaxlMonad Procedure (Int,Int)
haxlExample = do
(,) <$> (temperature2M >>= f) <*> (temperatureM >>= f)
where
f a = if a > 50 then
return 1
else
return 0
| jtdawso/remote-haxl | examples/Main.hs | bsd-3-clause | 4,574 | 1 | 11 | 1,445 | 1,296 | 633 | 663 | 102 | 2 |
{-# LANGUAGE CPP #-}
{-|
Module : Idris.CmdOptions
Description : A parser for the CmdOptions for the Idris executable.
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE Arrows #-}
module Idris.CmdOptions
(
module Idris.CmdOptions
, opt
, getClient, getPkg, getPkgCheck, getPkgClean, getPkgMkDoc
, getPkgREPL, getPkgTest, getPort, getIBCSubDir
) where
import Idris.AbsSyntax (getClient, getIBCSubDir, getPkg, getPkgCheck,
getPkgClean, getPkgMkDoc, getPkgREPL, getPkgTest,
getPort, opt)
import Idris.AbsSyntaxTree
import Idris.Info (getIdrisVersion)
import IRTS.CodegenCommon
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Except (throwE)
import Control.Monad.Trans.Reader (ask)
import Data.Char
import Data.Maybe
#if MIN_VERSION_optparse_applicative(0,13,0)
import Data.Monoid ((<>))
#endif
import Options.Applicative
import Options.Applicative.Arrows
import Options.Applicative.Types (ReadM(..))
import Text.ParserCombinators.ReadP hiding (many, option)
import Safe (lastMay)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
runArgParser :: IO [Opt]
runArgParser = do opts <- execParser $ info parser
(fullDesc
<> headerDoc (Just idrisHeader)
<> progDescDoc (Just idrisProgDesc)
<> footerDoc (Just idrisFooter)
)
return $ preProcOpts opts
where
idrisHeader = PP.hsep [PP.text "Idris version", PP.text getIdrisVersion, PP.text ", (C) The Idris Community 2016"]
idrisProgDesc = PP.vsep [PP.empty,
PP.text "Idris is a general purpose pure functional programming language with dependent",
PP.text "types. Dependent types allow types to be predicated on values, meaning that",
PP.text "some aspects of a program's behaviour can be specified precisely in the type.",
PP.text "It is compiled, with eager evaluation. Its features are influenced by Haskell",
PP.text "and ML.",
PP.empty,
PP.vsep $ map (PP.indent 4 . PP.text) [
"+ Full dependent types with dependent pattern matching",
"+ Simple case expressions, where-clauses, with-rule",
"+ Pattern matching let- and lambda-bindings",
"+ Overloading via Interfaces (Type class-like), Monad comprehensions",
"+ do-notation, idiom brackets",
"+ Syntactic conveniences for lists, tuples, dependent pairs",
"+ Totality checking",
"+ Coinductive types",
"+ Indentation significant syntax, Extensible syntax",
"+ Tactic based theorem proving (influenced by Coq)",
"+ Cumulative universes",
"+ Simple Foreign Function Interface",
"+ Hugs style interactive environment"
]]
idrisFooter = PP.vsep [PP.text "It is important to note that Idris is first and foremost a research tool",
PP.text "and project. Thus the tooling provided and resulting programs created",
PP.text "should not necessarily be seen as production ready nor for industrial use.",
PP.empty,
PP.text "More details over Idris can be found online here:",
PP.empty,
PP.indent 4 (PP.text "http://www.idris-lang.org/")]
pureArgParser :: [String] -> [Opt]
pureArgParser args = case getParseResult $ execParserPure (prefs idm) (info parser idm) args of
Just opts -> preProcOpts opts
Nothing -> []
parser :: Parser [Opt]
parser = runA $ proc () -> do
flags <- asA parseFlags -< ()
files <- asA (many $ argument (fmap Filename str) (metavar "FILES")) -< ()
A parseVersion >>> A helper -< (flags ++ files)
parseFlags :: Parser [Opt]
parseFlags = many $
flag' NoBanner (long "nobanner" <> help "Suppress the banner")
<|> flag' Quiet (short 'q' <> long "quiet" <> help "Quiet verbosity")
-- IDE Mode Specific Flags
<|> flag' Idemode (long "ide-mode" <> help "Run the Idris REPL with machine-readable syntax")
<|> flag' IdemodeSocket (long "ide-mode-socket" <> help "Choose a socket for IDE mode to listen on")
-- Client flags
<|> Client <$> strOption (long "client")
-- Logging Flags
<|> OLogging <$> option auto (long "log" <> metavar "LEVEL" <> help "Debugging log level")
<|> OLogCats <$> option (str >>= parseLogCats)
(long "logging-categories"
<> metavar "CATS"
<> help "Colon separated logging categories. Use --listlogcats to see list.")
-- Turn off things
<|> flag' NoBasePkgs (long "nobasepkgs" <> help "Do not use the given base package")
<|> flag' NoPrelude (long "noprelude" <> help "Do not use the given prelude")
<|> flag' NoBuiltins (long "nobuiltins" <> help "Do not use the builtin functions")
<|> flag' NoREPL (long "check" <> help "Typecheck only, don't start the REPL")
<|> Output <$> strOption (short 'o' <> long "output" <> metavar "FILE" <> help "Specify output file")
-- <|> flag' TypeCase (long "typecase")
<|> flag' Interface (long "interface" <> help "Generate interface files from ExportLists")
<|> flag' TypeInType (long "typeintype" <> help "Turn off Universe checking")
<|> flag' DefaultTotal (long "total" <> help "Require functions to be total by default")
<|> flag' DefaultPartial (long "partial")
<|> flag' WarnPartial (long "warnpartial" <> help "Warn about undeclared partial functions")
<|> flag' WarnReach (long "warnreach" <> help "Warn about reachable but inaccessible arguments")
<|> flag' AuditIPkg (long "warnipkg" <> help "Warn about possible incorrect package specifications")
<|> flag' NoCoverage (long "nocoverage")
<|> flag' ErrContext (long "errorcontext")
-- Show things
<|> flag' ShowAll (long "info" <> help "Display information about installation.")
<|> flag' ShowLoggingCats (long "listlogcats" <> help "Display logging categories")
<|> flag' ShowLibs (long "link" <> help "Display link flags")
<|> flag' ShowPkgs (long "listlibs" <> help "Display installed libraries")
<|> flag' ShowLibDir (long "libdir" <> help "Display library directory")
<|> flag' ShowDocDir (long "docdir" <> help "Display idrisdoc install directory")
<|> flag' ShowIncs (long "include" <> help "Display the includes flags")
<|> flag' (Verbose 3) (long "V2" <> help "Loudest verbosity")
<|> flag' (Verbose 2) (long "V1" <> help "Louder verbosity")
<|> flag' (Verbose 1) (short 'V' <> long "V0" <>long "verbose" <> help "Loud verbosity")
<|> IBCSubDir <$> strOption (long "ibcsubdir" <> metavar "FILE" <> help "Write IBC files into sub directory")
<|> ImportDir <$> strOption (short 'i' <> long "idrispath" <> help "Add directory to the list of import paths")
<|> SourceDir <$> strOption (long "sourcepath" <> help "Add directory to the list of source search paths")
<|> flag' WarnOnly (long "warn")
<|> Pkg <$> strOption (short 'p' <> long "package" <> help "Add package as a dependency")
<|> Port <$> option portReader (long "port" <> metavar "PORT" <> help "REPL TCP port - pass \"none\" to not bind any port")
-- Package commands
<|> PkgBuild <$> strOption (long "build" <> metavar "IPKG" <> help "Build package")
<|> PkgInstall <$> strOption (long "install" <> metavar "IPKG" <> help "Install package")
<|> PkgREPL <$> strOption (long "repl" <> metavar "IPKG" <> help "Launch REPL, only for executables")
<|> PkgClean <$> strOption (long "clean" <> metavar "IPKG" <> help "Clean package")
<|> (PkgDocBuild <$> strOption (long "mkdoc" <> metavar "IPKG" <> help "Generate IdrisDoc for package"))
<|> PkgDocInstall <$> strOption (long "installdoc" <> metavar "IPKG" <> help "Install IdrisDoc for package")
<|> PkgCheck <$> strOption (long "checkpkg" <> metavar "IPKG" <> help "Check package only")
<|> PkgTest <$> strOption (long "testpkg" <> metavar "IPKG" <> help "Run tests for package")
-- Interactive Editing Flags
<|> IndentWith <$> option auto (long "indent-with"
<> metavar "INDENT"
<> help "Indentation to use with :makewith (default 2)")
<|> IndentClause <$> option auto (long "indent-clause"
<> metavar "INDENT"
<> help "Indentation to use with :addclause (default 2)")
-- Misc options
<|> BCAsm <$> strOption (long "bytecode")
<|> flag' (OutputTy Raw) (short 'S' <> long "codegenonly" <> help "Do no further compilation of code generator output")
<|> flag' (OutputTy Object) (short 'c' <> long "compileonly" <> help "Compile to object files rather than an executable")
<|> DumpDefun <$> strOption (long "dumpdefuns")
<|> DumpCases <$> strOption (long "dumpcases")
<|> (UseCodegen . parseCodegen) <$> strOption (long "codegen"
<> metavar "TARGET"
<> help "Select code generator: C, Javascript, Node and bytecode are bundled with Idris")
<|> ((UseCodegen . Via JSONFormat) <$> strOption (long "portable-codegen"
<> metavar "TARGET"
<> help "Pass the name of the code generator. This option is for codegens that take JSON formatted IR."))
<|> CodegenArgs <$> strOption (long "cg-opt"
<> metavar "ARG"
<> help "Arguments to pass to code generator")
<|> EvalExpr <$> strOption (long "eval"
<> short 'e'
<> metavar "EXPR"
<> help "Evaluate an expression without loading the REPL")
<|> flag' (InterpretScript "Main.main") (long "execute" <> help "Execute as idris")
<|> InterpretScript <$> strOption (long "exec" <> metavar "EXPR" <> help "Execute as idris")
<|> ((Extension . getExt) <$> strOption (long "extension"
<> short 'X'
<> metavar "EXT"
<> help "Turn on language extension (TypeProviders or ErrorReflection)"))
-- Optimisation Levels
<|> flag' (OptLevel 3) (long "O3")
<|> flag' (OptLevel 2) (long "O2")
<|> flag' (OptLevel 1) (long "O1")
<|> flag' (OptLevel 0) (long "O0")
<|> flag' (AddOpt PETransform) (long "partial-eval")
<|> flag' (RemoveOpt PETransform) (long "no-partial-eval" <> help "Switch off partial evaluation, mainly for debugging purposes")
<|> OptLevel <$> option auto (short 'O' <> long "level")
<|> TargetTriple <$> strOption (long "target" <> metavar "TRIPLE" <> help "If supported the codegen will target the named triple.")
<|> TargetCPU <$> strOption (long "cpu" <> metavar "CPU" <> help "If supported the codegen will target the named CPU e.g. corei7 or cortex-m3")
-- Colour Options
<|> flag' (ColourREPL True) (long "colour" <> long "color" <> help "Force coloured output")
<|> flag' (ColourREPL False) (long "nocolour" <> long "nocolor" <> help "Disable coloured output")
<|> (UseConsoleWidth <$> option (str >>= parseConsoleWidth) (long "consolewidth" <> metavar "WIDTH" <> help "Select console width: auto, infinite, nat"))
<|> flag' DumpHighlights (long "highlight" <> help "Emit source code highlighting")
<|> flag' NoElimDeprecationWarnings (long "no-elim-deprecation-warnings" <> help "Disable deprecation warnings for %elim")
<|> flag' NoOldTacticDeprecationWarnings (long "no-tactic-deprecation-warnings" <> help "Disable deprecation warnings for the old tactic sublanguage")
where
getExt :: String -> LanguageExt
getExt s = fromMaybe (error ("Unknown extension " ++ s)) (maybeRead s)
maybeRead :: String -> Maybe LanguageExt
maybeRead = fmap fst . listToMaybe . reads
portReader :: ReadM REPLPort
portReader =
((ListenPort . fromIntegral) <$> auto) <|>
(ReadM $ do opt <- ask
if map toLower opt == "none"
then return $ DontListen
else lift $ throwE $ ErrorMsg $
"got " <> opt <> " expected port number or \"none\"")
parseVersion :: Parser (a -> a)
parseVersion = infoOption getIdrisVersion (short 'v' <> long "version" <> help "Print version information")
preProcOpts :: [Opt] -> [Opt]
preProcOpts (NoBuiltins : xs) = NoBuiltins : NoPrelude : preProcOpts xs
preProcOpts (Output s : xs) = Output s : NoREPL : preProcOpts xs
preProcOpts (BCAsm s : xs) = BCAsm s : NoREPL : preProcOpts xs
preProcOpts (x:xs) = x : preProcOpts xs
preProcOpts [] = []
parseCodegen :: String -> Codegen
parseCodegen "bytecode" = Bytecode
parseCodegen cg = Via IBCFormat (map toLower cg)
parseLogCats :: Monad m => String -> m [LogCat]
parseLogCats s =
case lastMay (readP_to_S doParse s) of
Just (xs, _) -> return xs
_ -> fail "Incorrect categories specified"
where
doParse :: ReadP [LogCat]
doParse = do
cs <- sepBy1 parseLogCat (char ':')
eof
return (concat cs)
parseLogCat :: ReadP [LogCat]
parseLogCat = (string (strLogCat IParse) *> return parserCats)
<|> (string (strLogCat IElab) *> return elabCats)
<|> (string (strLogCat ICodeGen) *> return codegenCats)
<|> (string (strLogCat ICoverage) *> return [ICoverage])
<|> (string (strLogCat IIBC) *> return [IIBC])
<|> (string (strLogCat IErasure) *> return [IErasure])
<|> parseLogCatBad
parseLogCatBad :: ReadP [LogCat]
parseLogCatBad = do
s <- look
fail $ "Category: " ++ s ++ " is not recognised."
parseConsoleWidth :: Monad m => String -> m ConsoleWidth
parseConsoleWidth "auto" = return AutomaticWidth
parseConsoleWidth "infinite" = return InfinitelyWide
parseConsoleWidth s =
case lastMay (readP_to_S integerReader s) of
Just (r, _) -> return $ ColsWide r
_ -> fail $ "Cannot parse: " ++ s
integerReader :: ReadP Int
integerReader = do
digits <- many1 $ satisfy isDigit
return $ read digits
| FranklinChen/Idris-dev | src/Idris/CmdOptions.hs | bsd-3-clause | 15,470 | 1 | 110 | 4,858 | 3,593 | 1,756 | 1,837 | 221 | 2 |
{-# LANGUAGE DeriveDataTypeable, DeriveFoldable, DeriveTraversable, DeriveFunctor #-}
module Language.Haskell.AST.Exts.Patterns
where
import Data.Data
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import Language.Haskell.AST.Core hiding (Pat)
-- | Bang patterns extension to @Pat@
data BangPat pat id l
= PBangPat l (pat id l) -- ^ strict (bang) pattern: @f !x = ...@
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | Type signature in pattern (extension to @Pat@)
data PatTySig ty pat id l
= PatTypeSig l (pat id l) (ty id l) -- ^ pattern with type signature
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- Not really sure what this extension is....
data PatExplTyArg ty id l
= PExplTypeArg l (QName id l) (ty id l) -- ^ Explicit generics style type argument e.g. @f {| Int |} x = ...@
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | n+k patterns extension to @Pat@
data NPlusKPat id l
= PNPlusK l (Name id l) Integer -- ^ n+k pattern
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
instance Annotated (BangPat pat id) where
ann (PBangPat l _) = l
instance Annotated (PatTySig ty pat id) where
ann (PatTypeSig l _ _) = l
instance Annotated (PatExplTyArg ty id) where
ann (PExplTypeArg l _ _) = l
instance Annotated (NPlusKPat id) where
ann (PNPlusK l _ _) = l
| jcpetruzza/haskell-ast | src/Language/Haskell/AST/Exts/Patterns.hs | bsd-3-clause | 1,436 | 0 | 8 | 265 | 440 | 242 | 198 | 26 | 0 |
{-# OPTIONS_GHC -fno-warn-tabs #-}
import Base64
import Common
import Hex
import Test.QuickCheck
main = do
putStrLn "=== Challange1 ==="
quickCheck $ \v -> base64Decode (base64Encode v) === v
quickCheck $ \v -> hexDecode (hexEncode v) === v
putStrLn $ base64Encode $ hexDecode
"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
| andrewcchen/matasano-cryptopals-solutions | set1/Challange1.hs | bsd-3-clause | 385 | 2 | 12 | 52 | 93 | 46 | 47 | 11 | 1 |
{-# LANGUAGE OverloadedStrings, UnicodeSyntax #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-|
Module : Reflex.Dom.HTML5.Elements.Interactive
Description : HTML5 interactive elements
Copyright : (c) gspia 2017
License : BSD
Maintainer : gspia
= Interactive
This module contains the following elements:
button; details; embed; iframe; keygen; label; select; textarea;
and a-element.
Note that tabindex-attribute (in globals) can make any element into
interactive content.
Audio, Iframe, Img, Video elements are in Embedded-module. This
choice is arbitrary.
The naming convention sligthly differs from that of others by
adding 2 other functions for each element.
* aC - takes attributes and 'm ()', gives 'm (Event t ())'
* aCD - takes dynamic attributes and 'm ()', gives 'm (Event t ())'
TBD: are the inputs and outputs ok and should something similar
be provided for all elements as the tabindex-attribute can make any
element interactive. (hmm)
'Label' has 'labelCForId' convenience function.
== Note
You probably don't want to use these definitions but rather the
widgets defined either in reflex-dom or reflex-dom-contrib (or in
some other) library.
(Occasionally, the elements given in this module are convenient,
anyway.)
-}
module Reflex.Dom.HTML5.Elements.Interactive where
import Data.Foldable (fold)
import Data.Maybe (catMaybes, fromMaybe, maybeToList)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Reflex.Dom.Core (DomBuilder, Element, EventResult, Dynamic,
DomBuilderSpace, PostBuild, elAttr',
elDynAttr', Event, EventName (Click),
domEvent, blank, el')
import qualified Reflex.Dom.HTML5.Attrs as A
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | A-element is an interactive element, if its Href-attribute is defined.
-- A-element has the following attributes:
-- globals; href; target; download; rel; hreflang; type
-- Type-attribute is of media_type.
-- Look at IANA Media Types for a complete list of standard media types.
-- http://www.iana.org/assignments/media-types/media-types.xhtml
--
-- Media-attribute?
--
-- Charset, coords, name, rev and shape attributes are not supported in HTML5.
--
data A = A
{ _aGlobals ∷ Maybe A.Globals
, _aDownload ∷ Maybe A.Download
, _aHref ∷ Maybe A.Href
, _aHrefLang ∷ Maybe A.HrefLang
, _aRel ∷ Maybe A.Rel
, _aTarget ∷ Maybe A.Target
, _aMediaType ∷ Maybe A.MediaType
, _aCustom ∷ Maybe A.Attr
}
-- | An instance.
instance A.AttrMap A where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _aGlobals bm
, A.attrMap <$> _aDownload bm
, A.attrMap <$> _aHref bm
, A.attrMap <$> _aHrefLang bm
, A.attrMap <$> _aRel bm
, A.attrMap <$> _aTarget bm
, A.attrMap <$> _aMediaType bm
] <> maybeToList (_aCustom bm)
-- | A default value for A.
defA ∷ A
defA = A Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | An instance.
instance Semigroup A where
(<>) (A a1 a2 a3 a4 a5 a6 a7 a8) (A b1 b2 b3 b4 b5 b6 b7 b8)
= A (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <> b5)
(a6 <> b6) (a7 <> b7) (a8 <> b8)
-- | An instance.
instance Monoid A where
mempty = defA
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals A where
attrSetGlobals pp bm = bm { _aGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey A
where attrSetAccessKey pp g = g { _aGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval A
where attrSetAnmval pp g = g { _aGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable A
where attrSetContentEditable pp g = g { _aGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu A
where attrSetContextMenu pp g = g { _aGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasClass A
where attrSetClassName pp g = g { _aGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval A
where attrSetDnmval pp g = g { _aGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasDir A
where attrSetDir pp g = g { _aGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable A
where attrSetDraggable pp g = g { _aGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasHidden A
where attrSetHidden pp g = g { _aGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasId A
where attrSetId pp g = g { _aGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasLang A
where attrSetLang pp g = g { _aGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasRole A
where attrSetRole pp g = g { _aGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasSlot A
where attrSetSlot pp g = g { _aGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck A
where attrSetSpellCheck pp g = g { _aGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasStyle A
where attrSetStyle pp g = g { _aGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex A
where attrSetTabIndex pp g = g { _aGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasTitle A
where attrSetTitle pp g = g { _aGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate A
where attrSetTranslate pp g = g { _aGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_aGlobals g))) }
-- | An instance.
instance A.AttrGetClassName A where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_aGlobals g)
-- | An instance.
instance A.AttrHasDownload A where attrSetDownload pp g = g { _aDownload = Just pp }
-- | An instance.
instance A.AttrHasHref A where attrSetHref pp g = g { _aHref = Just pp }
-- | An instance.
instance A.AttrHasHrefLang A where attrSetHrefLang pp g = g { _aHrefLang = Just pp }
-- | An instance.
instance A.AttrHasRel A where attrSetRel pp g = g { _aRel = Just pp }
-- | An instance.
instance A.AttrHasTarget A where attrSetTarget pp g = g { _aTarget = Just pp }
-- | An instance.
instance A.AttrHasMediaType A where attrSetMediaType pp g = g { _aMediaType = Just pp }
-- | An instance.
instance A.AttrHasCustom A where attrSetCustom pp g = g { _aCustom = Just pp }
-- instance (Reflex t, AttrHasAccessKey a) ⇒ AttrHasAccessKey (Dynamic t a) where
-- attrSetAccessKey c = fmap (A.attrSetAccessKey c)
-- instance (Reflex t, AttrHasAnmval a) ⇒ AttrHasAnmval (Dynamic t a) where
-- attrSetAnmval c = fmap (A.attrSetAnmval c)
-- | A short-hand notion for @ elAttr\' \"a\" ... @
a' ∷ forall t m a. DomBuilder t m ⇒ A → m a → m (Element EventResult (DomBuilderSpace m) t, a)
a' bm = elAttr' "a" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"a\" ... @
a ∷ forall t m a. DomBuilder t m ⇒ A → m a → m a
a bm children = snd <$> a' bm children
-- | A short-hand notion for @ el\' \"a\" ... @
aN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
aN' = el' "a"
-- | A short-hand notion for @ el \"a\" ... @
aN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
aN children = snd <$> aN' children
-- | A short-hand notion for @ elDynAttr\' \"a\" ... @
aD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t A → m a → m (Element EventResult (DomBuilderSpace m) t, a)
aD' bm = elDynAttr' "a" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"a\" ... @
aD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t A → m a → m a
aD bm children = snd <$> aD' bm children
aC ∷ (DomBuilder t m, PostBuild t m) ⇒ A → m () → m (Event t ())
aC bm children = do
(e,_) ← elAttr' "a" (A.attrMap bm) children
return $ domEvent Click e
aCD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t A → m () → m (Event t ())
aCD bDyn children = do
(e,_) ← elDynAttr' "a" (A.attrMap <$> bDyn) children
return $ domEvent Click e
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Button-element has the following attributes:
-- autofocus; disabled; form; formaction; formenctype; formmethod;
-- formnovalidate; formtarget; name; type; value
--
-- Value of button is Text (inside Value_).
--
data Button = Button
{ _buttonGlobals ∷ Maybe A.Globals
, _buttonAutoFocus ∷ Maybe A.AutoFocus
, _buttonDisabled ∷ Maybe A.Disabled
, _buttonForm ∷ Maybe A.Form
, _buttonFormAction ∷ Maybe A.FormAction
, _buttonFormEncType ∷ Maybe A.FormEncType
, _buttonFormNoValidate ∷ Maybe A.FormNoValidate
, _buttonFormTarget ∷ Maybe A.FormTarget
, _buttonName ∷ Maybe A.Name
, _buttonType ∷ Maybe A.ButtonType
, _buttonValueText ∷ Maybe A.ValueText
, _buttonCustom ∷ Maybe A.Attr
}
-- | An instance.
instance A.AttrMap Button where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _buttonGlobals bm
, A.attrMap <$> _buttonAutoFocus bm
, A.attrMap <$> _buttonDisabled bm
, A.attrMap <$> _buttonForm bm
, A.attrMap <$> _buttonFormAction bm
, A.attrMap <$> _buttonFormEncType bm
, A.attrMap <$> _buttonFormNoValidate bm
, A.attrMap <$> _buttonFormTarget bm
, A.attrMap <$> _buttonName bm
, A.attrMap <$> _buttonType bm
, A.attrMap <$> _buttonValueText bm
] <> maybeToList (_buttonCustom bm)
-- | A default value for Button.
defButton ∷ Button
defButton = Button Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | An instance.
instance Semigroup Button where
(<>) (Button a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12)
(Button b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12)
= Button (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <>b5) (a6 <> b6)
(a7 <> b7) (a8 <> b8) (a9 <> b9) (a10 <> b10) (a11 <> b11) (a12 <> b12)
-- | An instance.
instance Monoid Button where
mempty = defButton
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals Button where
attrSetGlobals pp bm = bm { _buttonGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey Button
where attrSetAccessKey pp g = g { _buttonGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval Button
where attrSetAnmval pp g = g { _buttonGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable Button
where attrSetContentEditable pp g = g { _buttonGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu Button
where attrSetContextMenu pp g = g { _buttonGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasClass Button
where attrSetClassName pp g = g { _buttonGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval Button
where attrSetDnmval pp g = g { _buttonGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasDir Button
where attrSetDir pp g = g { _buttonGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable Button
where attrSetDraggable pp g = g { _buttonGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasHidden Button
where attrSetHidden pp g = g { _buttonGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasId Button
where attrSetId pp g = g { _buttonGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasLang Button
where attrSetLang pp g = g { _buttonGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasRole Button
where attrSetRole pp g = g { _buttonGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasSlot Button
where attrSetSlot pp g = g { _buttonGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck Button
where attrSetSpellCheck pp g = g { _buttonGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasStyle Button
where attrSetStyle pp g = g { _buttonGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex Button
where attrSetTabIndex pp g = g { _buttonGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasTitle Button
where attrSetTitle pp g = g { _buttonGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate Button
where attrSetTranslate pp g = g { _buttonGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_buttonGlobals g))) }
-- | An instance.
instance A.AttrGetClassName Button where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_buttonGlobals g)
-- | An instance.
instance A.AttrHasAutoFocus Button where attrSetAutoFocus pp g = g { _buttonAutoFocus = Just pp }
-- | An instance.
instance A.AttrHasDisabled Button where attrSetDisabled pp g = g { _buttonDisabled = Just pp }
-- | An instance.
instance A.AttrHasForm Button where attrSetForm pp g = g { _buttonForm = Just pp }
-- | An instance.
instance A.AttrHasFormAction Button where attrSetFormAction pp g = g { _buttonFormAction = Just pp }
-- | An instance.
instance A.AttrHasFormEncType Button where attrSetFormEncType pp g = g { _buttonFormEncType = Just pp }
-- | An instance.
instance A.AttrHasFormNoValidate Button where attrSetFormNoValidate pp g = g { _buttonFormNoValidate = Just pp }
-- | An instance.
instance A.AttrHasFormTarget Button where attrSetFormTarget pp g = g { _buttonFormTarget = Just pp }
-- | An instance.
instance A.AttrHasName Button where attrSetName pp g = g { _buttonName = Just pp }
-- | An instance.
instance A.AttrHasButtonType Button where attrSetButtonType pp g = g { _buttonType = Just pp }
-- | An instance.
instance A.AttrHasValueText Button where attrSetValueText pp g = g { _buttonValueText = Just pp }
-- | An instance.
instance A.AttrHasCustom Button where attrSetCustom pp g = g { _buttonCustom = Just pp }
-- instance (Reflex t, AttrHasAccessKey a) ⇒ AttrHasAccessKey (Dynamic t a) where
-- attrSetAccessKey c = fmap (A.attrSetAccessKey c)
-- instance (Reflex t, AttrHasAnmval a) ⇒ AttrHasAnmval (Dynamic t a) where
-- attrSetAnmval c = fmap (A.attrSetAnmval c)
-- | A short-hand notion for @ elAttr\' \"button\" ... @
button' ∷ forall t m a. DomBuilder t m ⇒ Button → m a → m (Element EventResult (DomBuilderSpace m) t, a)
button' bm = elAttr' "button" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"button\" ... @
button ∷ forall t m a. DomBuilder t m ⇒ Button → m a → m a
button bm children = snd <$> button' bm children
-- | A short-hand notion for @ el\' \"button\" ... @
buttonN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
buttonN' = el' "button"
-- | A short-hand notion for @ el \"button\" ... @
buttonN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
buttonN children = snd <$> buttonN' children
-- | A short-hand notion for @ elDynAttr\' \"button\" ... @
buttonD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Button → m a → m (Element EventResult (DomBuilderSpace m) t, a)
buttonD' bm = elDynAttr' "button" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"button\" ... @
buttonD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Button → m a → m a
buttonD bm children = snd <$> buttonD' bm children
buttonC ∷ (DomBuilder t m, PostBuild t m) ⇒ Button → m () → m (Event t ())
buttonC bm children = do
(e,_) ← elAttr' "button" (A.attrMap bm) children
return $ domEvent Click e
buttonCD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Button → m () → m (Event t ())
buttonCD bDyn children = do
(e,_) ← elDynAttr' "button" (A.attrMap <$> bDyn) children
return $ domEvent Click e
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Details-element
data Details = Details
{ _detailsGlobals ∷ Maybe A.Globals
, _detailsOpen ∷ Maybe A.Open
, _detailsCustom ∷ Maybe A.Attr
}
-- | An instance.
instance A.AttrMap Details where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _detailsGlobals bm
, A.attrMap <$> _detailsOpen bm
] <> maybeToList (_detailsCustom bm)
-- | A default value for Details.
defDetails ∷ Details
defDetails = Details Nothing Nothing Nothing
-- | An instance.
instance Semigroup Details where
(<>) (Details a1 a2 a3) (Details b1 b2 b3)
= Details (a1 <> b1) (a2 <> b2) (a3 <> b3)
-- | An instance.
instance Monoid Details where
mempty = defDetails
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals Details where
attrSetGlobals pp bm = bm { _detailsGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey Details
where attrSetAccessKey pp g = g { _detailsGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval Details
where attrSetAnmval pp g = g { _detailsGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable Details
where attrSetContentEditable pp g = g { _detailsGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu Details
where attrSetContextMenu pp g = g { _detailsGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasClass Details
where attrSetClassName pp g = g { _detailsGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval Details
where attrSetDnmval pp g = g { _detailsGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasDir Details
where attrSetDir pp g = g { _detailsGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable Details
where attrSetDraggable pp g = g { _detailsGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasHidden Details
where attrSetHidden pp g = g { _detailsGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasId Details
where attrSetId pp g = g { _detailsGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasLang Details
where attrSetLang pp g = g { _detailsGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasRole Details
where attrSetRole pp g = g { _detailsGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasSlot Details
where attrSetSlot pp g = g { _detailsGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck Details
where attrSetSpellCheck pp g = g { _detailsGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasStyle Details
where attrSetStyle pp g = g { _detailsGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex Details
where attrSetTabIndex pp g = g { _detailsGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasTitle Details
where attrSetTitle pp g = g { _detailsGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate Details
where attrSetTranslate pp g = g { _detailsGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_detailsGlobals g))) }
-- | An instance.
instance A.AttrGetClassName Details where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_detailsGlobals g)
-- | An instance.
instance A.AttrHasOpen Details where attrSetOpen pp g = g {_detailsOpen = Just pp }
-- | An instance.
instance A.AttrHasCustom Details where attrSetCustom pp g = g { _detailsCustom = Just pp }
-- | A short-hand notion for @ elAttr\' \"details\" ... @
details' ∷ forall t m a. DomBuilder t m ⇒ Details → m a → m (Element EventResult (DomBuilderSpace m) t, a)
details' bm = elAttr' "details" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"details\" ... @
details ∷ forall t m a. DomBuilder t m ⇒ Details → m a → m a
details bm children = snd <$> details' bm children
-- | A short-hand notion for @ el\' \"details\" ... @
detailsN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
detailsN' = el' "details"
-- | A short-hand notion for @ el \"details\" ... @
detailsN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
detailsN children = snd <$> detailsN' children
-- | A short-hand notion for @ elDynAttr\' \"details\" ... @
detailsD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Details → m a → m (Element EventResult (DomBuilderSpace m) t, a)
detailsD' bm = elDynAttr' "details" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"details\" ... @
detailsD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Details → m a → m a
detailsD bm children = snd <$> detailsD' bm children
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Embed-element has the following attributes:
-- globals; src; type; width; height; any*
-- Type-attribute is of media_type.
--
-- Any namespace-less attribute other than name, align, hspace, and vspace may
-- be specified on the embed element, so long as its name is XML-compatible and
-- contains no uppercase ASCII letters. These attributes are then passed as
-- parameters to the plugin.
--
data Embed = Embed
{ _embedGlobals ∷ Maybe A.Globals
, _embedHeight ∷ Maybe A.Height
, _embedMediaType ∷ Maybe A.MediaType
, _embedSrc ∷ Maybe A.Src
, _embedWidth ∷ Maybe A.Width
, _embedCustom ∷ Maybe A.Attr
}
-- | An instance.
instance A.AttrMap Embed where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _embedGlobals bm
, A.attrMap <$> _embedHeight bm
, A.attrMap <$> _embedMediaType bm
, A.attrMap <$> _embedSrc bm
, A.attrMap <$> _embedWidth bm
] <> maybeToList (_embedCustom bm)
-- | A default value for Embed.
defEmbed ∷ Embed
defEmbed = Embed Nothing Nothing Nothing Nothing Nothing Nothing
-- | An instance.
instance Semigroup Embed where
(<>) (Embed a1 a2 a3 a4 a5 a6) (Embed b1 b2 b3 b4 b5 b6)
= Embed (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <> b5) (a6 <> b6)
-- | An instance.
instance Monoid Embed where
mempty = defEmbed
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals Embed where
attrSetGlobals pp bm = bm { _embedGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey Embed
where attrSetAccessKey pp g = g { _embedGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval Embed
where attrSetAnmval pp g = g { _embedGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable Embed
where attrSetContentEditable pp g = g { _embedGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu Embed
where attrSetContextMenu pp g = g { _embedGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasClass Embed
where attrSetClassName pp g = g { _embedGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval Embed
where attrSetDnmval pp g = g { _embedGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasDir Embed
where attrSetDir pp g = g { _embedGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable Embed
where attrSetDraggable pp g = g { _embedGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasHidden Embed
where attrSetHidden pp g = g { _embedGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasId Embed
where attrSetId pp g = g { _embedGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasLang Embed
where attrSetLang pp g = g { _embedGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasRole Embed
where attrSetRole pp g = g { _embedGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasSlot Embed
where attrSetSlot pp g = g { _embedGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck Embed
where attrSetSpellCheck pp g = g { _embedGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasStyle Embed
where attrSetStyle pp g = g { _embedGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex Embed
where attrSetTabIndex pp g = g { _embedGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasTitle Embed
where attrSetTitle pp g = g { _embedGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate Embed
where attrSetTranslate pp g = g { _embedGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_embedGlobals g))) }
-- | An instance.
instance A.AttrGetClassName Embed where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_embedGlobals g)
-- | An instance.
instance A.AttrHasHeight Embed where attrSetHeight pp g = g { _embedHeight = Just pp }
-- | An instance.
instance A.AttrHasMediaType Embed where attrSetMediaType pp g = g { _embedMediaType = Just pp }
-- | An instance.
instance A.AttrHasSrc Embed where attrSetSrc pp g = g { _embedSrc = Just pp }
-- | An instance.
instance A.AttrHasWidth Embed where attrSetWidth pp g = g { _embedWidth = Just pp }
-- | An instance.
instance A.AttrHasCustom Embed where attrSetCustom pp g = g { _embedCustom = Just pp }
-- instance (Reflex t, AttrHasAccessKey a) ⇒ AttrHasAccessKey (Dynamic t a) where
-- attrSetAccessKey c = fmap (A.attrSetAccessKey c)
-- instance (Reflex t, AttrHasAnmval a) ⇒ AttrHasAnmval (Dynamic t a) where
-- attrSetAnmval c = fmap (A.attrSetAnmval c)
-- | A short-hand notion for @ elAttr\' \"embed\" ... @
embed' ∷ forall t m a. DomBuilder t m ⇒ Embed → m a → m (Element EventResult (DomBuilderSpace m) t, a)
embed' bm = elAttr' "embed" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"embed\" ... @
embed ∷ forall t m a. DomBuilder t m ⇒ Embed → m a → m a
embed bm children = snd <$> embed' bm children
-- | A short-hand notion for @ el\' \"embed\" ... @
embedN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
embedN' = el' "embed"
-- | A short-hand notion for @ el \"embed\" ... @
embedN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
embedN children = snd <$> embedN' children
-- | A short-hand notion for @ elDynAttr\' \"embed\" ... @
embedD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Embed → m a → m (Element EventResult (DomBuilderSpace m) t, a)
embedD' bm = elDynAttr' "embed" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"embed\" ... @
embedD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Embed → m a → m a
embedD bm children = snd <$> embedD' bm children
-- uiEmbedC ∷ (DomBuilder t m, PostBuild t m) ⇒ Embed → m () → m (Event t ())
-- uiEmbedC bm children = do
embedC ∷ (DomBuilder t m, PostBuild t m) ⇒ Embed → m (Event t ())
embedC bm = do
(e,_) ← elAttr' "embed" (A.attrMap bm) blank
return $ domEvent Click e
-- uiEmbedD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Embed → m () → m (Event t ())
-- uiEmbedD bDyn children = do
embedCD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Embed → m (Event t ())
embedCD bDyn = do
(e,_) ← elDynAttr' "embed" (A.attrMap <$> bDyn) blank
return $ domEvent Click e
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Input-element is interactive if the type-attribute is not in hidden
-- state).
-- globals; accept; alt; autocomplete; autofocus; checked; dirname; disabled;
-- form; formaction; formenctype; formmethod; formnovalidate; formtarget;
-- height; inputmode; list; max; maxlength; min; minlength; multiple; name;
-- pattern; placeholder; readonly; required; size; src; step; type; value;
-- width
--
data Input = Input
{ _inputGlobals ∷ Maybe A.Globals -- 1.
, _inputAccept ∷ Maybe A.Accept -- 2.
, _inputAlt ∷ Maybe A.Alt_ -- 3.
, _inputAutoComplete ∷ Maybe A.AutoComplete -- 4.
, _inputAutoFocus ∷ Maybe A.AutoFocus -- 5.
, _inputChecked ∷ Maybe A.Checked -- 6.
, _inputDirName ∷ Maybe A.DirName -- 7.
, _inputDisabled ∷ Maybe A.Disabled -- 8.
, _inputForm ∷ Maybe A.Form -- 9.
, _inputFormAction ∷ Maybe A.FormAction -- 10.
, _inputFormEncType ∷ Maybe A.FormEncType -- 11.
, _inputFormMethod ∷ Maybe A.FormMethod -- 12.
, _inputFormNoValidate ∷ Maybe A.FormNoValidate -- 13.
, _inputFormTarget ∷ Maybe A.FormTarget -- 14.
, _inputHeight ∷ Maybe A.Height -- 15.
, _inputInputMode ∷ Maybe A.InputMode -- 16.
, _inputList ∷ Maybe A.List -- 17.
, _inputMax ∷ Maybe A.Max -- 18.
, _inputMaxLength ∷ Maybe A.MaxLength -- 19.
, _inputMin ∷ Maybe A.Min -- 20.
, _inputMinLength ∷ Maybe A.MinLength -- 21.
, _inputMultiple ∷ Maybe A.Multiple -- 22.
, _inputName ∷ Maybe A.Name -- 23.
, _inputPattern ∷ Maybe A.Pattern -- 24.
, _inputPlaceholder ∷ Maybe A.Placeholder -- 25.
, _inputReadOnly ∷ Maybe A.ReadOnly -- 26.
, _inputRequired ∷ Maybe A.Required -- 27.
, _inputSize ∷ Maybe A.Size -- 28.
, _inputSrc ∷ Maybe A.Src -- 29.
, _inputStep ∷ Maybe A.Step -- 30.
, _inputType ∷ Maybe A.InputType -- 31.
, _inputValueText ∷ Maybe A.ValueText -- 32.
, _inputWidth ∷ Maybe A.Width -- 33.
, _inputCustom ∷ Maybe A.Attr -- 34.
}
-- | An instance.
instance A.AttrMap Input where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _inputGlobals bm
, A.attrMap <$> _inputAccept bm
, A.attrMap <$> _inputAlt bm
, A.attrMap <$> _inputAutoComplete bm
, A.attrMap <$> _inputAutoFocus bm
, A.attrMap <$> _inputChecked bm
, A.attrMap <$> _inputDirName bm
, A.attrMap <$> _inputDisabled bm
, A.attrMap <$> _inputForm bm
, A.attrMap <$> _inputFormAction bm
, A.attrMap <$> _inputFormEncType bm
, A.attrMap <$> _inputFormMethod bm
, A.attrMap <$> _inputFormNoValidate bm
, A.attrMap <$> _inputFormTarget bm
, A.attrMap <$> _inputHeight bm
, A.attrMap <$> _inputInputMode bm
, A.attrMap <$> _inputList bm
, A.attrMap <$> _inputMax bm
, A.attrMap <$> _inputMaxLength bm
, A.attrMap <$> _inputMin bm
, A.attrMap <$> _inputMinLength bm
, A.attrMap <$> _inputMultiple bm
, A.attrMap <$> _inputName bm
, A.attrMap <$> _inputPattern bm
, A.attrMap <$> _inputPlaceholder bm
, A.attrMap <$> _inputReadOnly bm
, A.attrMap <$> _inputRequired bm
, A.attrMap <$> _inputSize bm
, A.attrMap <$> _inputSrc bm
, A.attrMap <$> _inputStep bm
, A.attrMap <$> _inputType bm
, A.attrMap <$> _inputValueText bm
, A.attrMap <$> _inputWidth bm
] <> maybeToList (_inputCustom bm)
-- | A default value for Input.
defInput ∷ Input
defInput = Input Nothing Nothing Nothing Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | An instance.
instance Semigroup Input where
(<>)
(Input a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17
a18 a19 a20 a21 a22 a23 a24 a25 a26 a27 a28 a29 a30 a31 a32 a33 a34)
(Input b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 b17
b18 b19 b20 b21 b22 b23 b24 b25 b26 b27 b28 b29 b30 b31 b32 b33 b34)
= Input (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <> b5)
(a6 <> b6) (a7 <> b7) (a8 <> b8) (a9 <> b9) (a10 <> b10)
(a11 <> b11) (a12 <> b12) (a13 <> b13) (a14 <> b14) (a15 <> b15)
(a16 <> b16) (a17 <> b17) (a18 <> b18) (a19 <> b19) (a20 <> b20)
(a21 <> b21) (a22 <> b22) (a23 <> b23) (a24 <> b24) (a25 <> b25)
(a26 <> b26) (a27 <> b27) (a28 <> b28) (a29 <> b29) (a30 <> b30)
(a31 <> b31) (a32 <> b32) (a33 <> b33) (a34 <> b34)
-- | An instance.
instance Monoid Input where
mempty = defInput
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals Input where
attrSetGlobals pp bm = bm { _inputGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey Input
where attrSetAccessKey pp g = g { _inputGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval Input
where attrSetAnmval pp g = g { _inputGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable Input
where attrSetContentEditable pp g = g { _inputGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu Input
where attrSetContextMenu pp g = g { _inputGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasClass Input
where attrSetClassName pp g = g { _inputGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval Input
where attrSetDnmval pp g = g { _inputGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasDir Input
where attrSetDir pp g = g { _inputGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable Input
where attrSetDraggable pp g = g { _inputGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasHidden Input
where attrSetHidden pp g = g { _inputGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasId Input
where attrSetId pp g = g { _inputGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasLang Input
where attrSetLang pp g = g { _inputGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasRole Input
where attrSetRole pp g = g { _inputGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasSlot Input
where attrSetSlot pp g = g { _inputGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck Input
where attrSetSpellCheck pp g = g { _inputGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasStyle Input
where attrSetStyle pp g = g { _inputGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex Input
where attrSetTabIndex pp g = g { _inputGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasTitle Input
where attrSetTitle pp g = g { _inputGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate Input
where attrSetTranslate pp g = g { _inputGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_inputGlobals g))) }
-- | An instance.
instance A.AttrGetClassName Input where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_inputGlobals g)
-- | An instance.
instance A.AttrHasAccept Input where attrSetAccept pp g = g { _inputAccept = Just pp }
-- | An instance.
instance A.AttrHasAlt Input where attrSetAlt pp g = g { _inputAlt = Just pp }
-- | An instance.
instance A.AttrHasAutoComplete Input where attrSetAutoComplete pp g = g { _inputAutoComplete = Just pp }
-- | An instance.
instance A.AttrHasAutoFocus Input where attrSetAutoFocus pp g = g { _inputAutoFocus = Just pp }
-- | An instance.
instance A.AttrHasChecked Input where attrSetChecked pp g = g { _inputChecked = Just pp }
-- | An instance.
instance A.AttrHasDirName Input where attrSetDirName pp g = g { _inputDirName = Just pp }
-- | An instance.
instance A.AttrHasDisabled Input where attrSetDisabled pp g = g { _inputDisabled = Just pp }
-- | An instance.
instance A.AttrHasForm Input where attrSetForm pp g = g { _inputForm = Just pp }
-- | An instance.
instance A.AttrHasFormAction Input where attrSetFormAction pp g = g { _inputFormAction = Just pp }
-- | An instance.
instance A.AttrHasFormEncType Input where attrSetFormEncType pp g = g { _inputFormEncType = Just pp }
-- | An instance.
instance A.AttrHasFormMethod Input where attrSetFormMethod pp g = g { _inputFormMethod = Just pp }
-- | An instance.
instance A.AttrHasFormNoValidate Input where attrSetFormNoValidate pp g = g { _inputFormNoValidate = Just pp }
-- | An instance.
instance A.AttrHasFormTarget Input where attrSetFormTarget pp g = g { _inputFormTarget = Just pp }
-- | An instance.
instance A.AttrHasHeight Input where attrSetHeight pp g = g { _inputHeight = Just pp }
-- | An instance.
instance A.AttrHasInputMode Input where attrSetInputMode pp g = g { _inputInputMode = Just pp }
-- | An instance.
instance A.AttrHasList Input where attrSetList pp g = g { _inputList = Just pp }
-- | An instance.
instance A.AttrHasMax Input where attrSetMax pp g = g { _inputMax = Just pp }
-- | An instance.
instance A.AttrHasMaxLength Input where attrSetMaxLength pp g = g { _inputMaxLength = Just pp }
-- | An instance.
instance A.AttrHasMin Input where attrSetMin pp g = g { _inputMin = Just pp }
-- | An instance.
instance A.AttrHasMinLength Input where attrSetMinLength pp g = g { _inputMinLength = Just pp }
-- | An instance.
instance A.AttrHasMultiple Input where attrSetMultiple pp g = g { _inputMultiple = Just pp }
-- | An instance.
instance A.AttrHasName Input where attrSetName pp g = g { _inputName = Just pp }
-- | An instance.
instance A.AttrHasPattern Input where attrSetPattern pp g = g { _inputPattern = Just pp }
-- | An instance.
instance A.AttrHasPlaceholder Input where attrSetPlaceholder pp g = g { _inputPlaceholder = Just pp }
-- | An instance.
instance A.AttrHasReadOnly Input where attrSetReadOnly pp g = g { _inputReadOnly = Just pp }
-- | An instance.
instance A.AttrHasRequired Input where attrSetRequired pp g = g { _inputRequired = Just pp }
-- | An instance.
instance A.AttrHasSize Input where attrSetSize pp g = g { _inputSize = Just pp }
-- | An instance.
instance A.AttrHasSrc Input where attrSetSrc pp g = g { _inputSrc = Just pp }
-- | An instance.
instance A.AttrHasStep Input where attrSetStep pp g = g { _inputStep = Just pp }
-- | An instance.
instance A.AttrHasInputType Input where attrSetInputType pp g = g { _inputType = Just pp }
-- | An instance.
instance A.AttrHasValueText Input where attrSetValueText pp g = g { _inputValueText = Just pp }
-- | An instance.
instance A.AttrHasWidth Input where attrSetWidth pp g = g { _inputWidth = Just pp }
-- | An instance.
instance A.AttrHasCustom Input where attrSetCustom pp g = g { _inputCustom = Just pp }
-- | A short-hand notion for @ elAttr\' \"input\" ... @
input' ∷ forall t m a. DomBuilder t m ⇒ Input → m a → m (Element EventResult (DomBuilderSpace m) t, a)
input' bm = elAttr' "input" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"input\" ... @
input ∷ forall t m a. DomBuilder t m ⇒ Input → m a → m a
input bm children = snd <$> input' bm children
-- | A short-hand notion for @ el\' \"input\" ... @
inputN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
inputN' = el' "input"
-- | A short-hand notion for @ el \"input\" ... @
inputN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
inputN children = snd <$> inputN' children
-- | A short-hand notion for @ elDynAttr\' \"input\" ... @
inputD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Input → m a → m (Element EventResult (DomBuilderSpace m) t, a)
inputD' bm = elDynAttr' "input" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"input\" ... @
inputD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Input → m a → m a
inputD bm children = snd <$> inputD' bm children
inputC ∷ (DomBuilder t m, PostBuild t m) ⇒ Input → m () → m (Event t ())
inputC bm children = do
(e,_) ← elAttr' "input" (A.attrMap bm) children
return $ domEvent Click e
inputCD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Input → m () → m (Event t ())
inputCD bDyn children = do
(e,_) ← elDynAttr' "input" (A.attrMap <$> bDyn) children
return $ domEvent Click e
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Keygen is likely to be removed from HTML 5.2.
-- Thus, we don't have it here.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Label-element has the following attributes:
-- globals; form; for
--
data Label = Label
{ _labelGlobals ∷ Maybe A.Globals
-- , _labelForm ∷ Maybe Form -- Not in HTML 5.2.
, _labelForId ∷ Maybe A.ForId
, _labelCustom ∷ Maybe A.Attr
}
-- | An instance.
instance A.AttrMap Label where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _labelGlobals bm
-- , A.attrMap <$> _labelForm bm
, A.attrMap <$> _labelForId bm
] <> maybeToList (_labelCustom bm)
-- | A default value for Label.
defLabel ∷ Label
defLabel = Label Nothing Nothing Nothing
-- | An instance.
instance Semigroup Label where
(<>) (Label a1 a2 a3) (Label b1 b2 b3)
= Label (a1 <> b1) (a2 <> b2) (a3 <> b3)
-- | An instance.
instance Monoid Label where
mempty = defLabel
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals Label where
attrSetGlobals pp bm = bm { _labelGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey Label
where attrSetAccessKey pp g = g { _labelGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval Label
where attrSetAnmval pp g = g { _labelGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable Label
where attrSetContentEditable pp g = g { _labelGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu Label
where attrSetContextMenu pp g = g { _labelGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasClass Label
where attrSetClassName pp g = g { _labelGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval Label
where attrSetDnmval pp g = g { _labelGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasDir Label
where attrSetDir pp g = g { _labelGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable Label
where attrSetDraggable pp g = g { _labelGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasHidden Label
where attrSetHidden pp g = g { _labelGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasId Label
where attrSetId pp g = g { _labelGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasLang Label
where attrSetLang pp g = g { _labelGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasRole Label
where attrSetRole pp g = g { _labelGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasSlot Label
where attrSetSlot pp g = g { _labelGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck Label
where attrSetSpellCheck pp g = g { _labelGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasStyle Label
where attrSetStyle pp g = g { _labelGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex Label
where attrSetTabIndex pp g = g { _labelGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasTitle Label
where attrSetTitle pp g = g { _labelGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate Label
where attrSetTranslate pp g = g { _labelGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_labelGlobals g))) }
-- | An instance.
instance A.AttrGetClassName Label where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_labelGlobals g)
-- instance A.AttrHasForm Label where attrSetForm pp g = g { _labelForm = Just pp }
-- | An instance.
instance A.AttrHasForId Label where attrSetForId pp g = g { _labelForId = Just pp }
-- | An instance.
instance A.AttrHasCustom Label where attrSetCustom pp g = g { _labelCustom = Just pp }
-- | A short-hand notion for @ elAttr\' \"label\" ... @
label' ∷ forall t m a. DomBuilder t m ⇒ Label → m a → m (Element EventResult (DomBuilderSpace m) t, a)
label' bm = elAttr' "label" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"label\" ... @
label ∷ forall t m a. DomBuilder t m ⇒ Label → m a → m a
label bm children = snd <$> label' bm children
-- | A short-hand notion for @ el\' \"label\" ... @
labelN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
labelN' = el' "label"
-- | A short-hand notion for @ el \"label\" ... @
labelN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
labelN children = snd <$> labelN' children
-- | A short-hand notion for @ elDynAttr\' \"label\" ... @
labelD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Label → m a → m (Element EventResult (DomBuilderSpace m) t, a)
labelD' bm = elDynAttr' "label" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"label\" ... @
labelD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Label → m a → m a
labelD bm children = snd <$> labelD' bm children
labelC ∷ (DomBuilder t m, PostBuild t m) ⇒ Label → m () → m (Event t ())
labelC bm children = do
(e,_) ← elAttr' "label" (A.attrMap bm) children
return $ domEvent Click e
labelCD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Label → m () → m (Event t ())
labelCD bDyn children = do
(e,_) ← elDynAttr' "label" (A.attrMap <$> bDyn) children
return $ domEvent Click e
labelCForId ∷ (DomBuilder t m, PostBuild t m) ⇒ Maybe A.Globals → A.ForId → m (Event t ())
labelCForId bm f = labelC (Label bm (Just f) Nothing) blank
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Select-element has the following attributes:
-- globals; autofocus; disabled; form; multiple; name; required; size
--
data Select = Select
{ _selectGlobals ∷ Maybe A.Globals
, _selectAutoFocus ∷ Maybe A.AutoFocus
, _selectDisabled ∷ Maybe A.Disabled
, _selectForm ∷ Maybe A.Form
, _selectMultiple ∷ Maybe A.Multiple
, _selectName ∷ Maybe A.Name
, _selectRequired ∷ Maybe A.Required
, _selectSize ∷ Maybe A.Size
, _selectCustom ∷ Maybe A.Attr
}
-- | An instance.
instance A.AttrMap Select where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _selectGlobals bm
, A.attrMap <$> _selectAutoFocus bm
, A.attrMap <$> _selectDisabled bm
, A.attrMap <$> _selectForm bm
, A.attrMap <$> _selectMultiple bm
, A.attrMap <$> _selectName bm
, A.attrMap <$> _selectRequired bm
, A.attrMap <$> _selectSize bm
] <> maybeToList (_selectCustom bm)
-- | A default value for Select.
defSelect ∷ Select
defSelect = Select Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | An instance.
instance Semigroup Select where
(<>) (Select a1 a2 a3 a4 a5 a6 a7 a8 a9)
(Select b1 b2 b3 b4 b5 b6 b7 b8 b9)
= Select (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <> b5)
(a6 <> b6) (a7 <> b7) (a8 <> b8) (a9 <> b9)
-- | An instance.
instance Monoid Select where
mempty = defSelect
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals Select where
attrSetGlobals pp bm = bm { _selectGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey Select
where attrSetAccessKey pp g = g { _selectGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval Select
where attrSetAnmval pp g = g { _selectGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable Select
where attrSetContentEditable pp g = g { _selectGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu Select
where attrSetContextMenu pp g = g { _selectGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasClass Select
where attrSetClassName pp g = g { _selectGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval Select
where attrSetDnmval pp g = g { _selectGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasDir Select
where attrSetDir pp g = g { _selectGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable Select
where attrSetDraggable pp g = g { _selectGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasHidden Select
where attrSetHidden pp g = g { _selectGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasId Select
where attrSetId pp g = g { _selectGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasLang Select
where attrSetLang pp g = g { _selectGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasRole Select
where attrSetRole pp g = g { _selectGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasSlot Select
where attrSetSlot pp g = g { _selectGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck Select
where attrSetSpellCheck pp g = g { _selectGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasStyle Select
where attrSetStyle pp g = g { _selectGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex Select
where attrSetTabIndex pp g = g { _selectGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasTitle Select
where attrSetTitle pp g = g { _selectGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate Select
where attrSetTranslate pp g = g { _selectGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_selectGlobals g))) }
-- | An instance.
instance A.AttrGetClassName Select where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_selectGlobals g)
-- | An instance.
instance A.AttrHasAutoFocus Select where attrSetAutoFocus pp g = g { _selectAutoFocus = Just pp }
-- | An instance.
instance A.AttrHasDisabled Select where attrSetDisabled pp g = g { _selectDisabled = Just pp }
-- | An instance.
instance A.AttrHasForm Select where attrSetForm pp g = g { _selectForm = Just pp }
-- | An instance.
instance A.AttrHasMultiple Select where attrSetMultiple pp g = g { _selectMultiple = Just pp }
-- | An instance.
instance A.AttrHasName Select where attrSetName pp g = g { _selectName = Just pp }
-- | An instance.
instance A.AttrHasRequired Select where attrSetRequired pp g = g { _selectRequired = Just pp }
-- | An instance.
instance A.AttrHasSize Select where attrSetSize pp g = g { _selectSize = Just pp }
-- | An instance.
instance A.AttrHasCustom Select where attrSetCustom pp g = g { _selectCustom = Just pp }
-- | A short-hand notion for @ elAttr\' \"select\" ... @
select' ∷ forall t m a. DomBuilder t m ⇒ Select → m a → m (Element EventResult (DomBuilderSpace m) t, a)
select' bm = elAttr' "select" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"select\" ... @
select ∷ forall t m a. DomBuilder t m ⇒ Select → m a → m a
select bm children = snd <$> select' bm children
-- | A short-hand notion for @ el\' \"select\" ... @
selectN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
selectN' = el' "select"
-- | A short-hand notion for @ el \"select\" ... @
selectN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
selectN children = snd <$> selectN' children
-- | A short-hand notion for @ elDynAttr\' \"select\" ... @
selectD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Select → m a → m (Element EventResult (DomBuilderSpace m) t, a)
selectD' bm = elDynAttr' "select" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"select\" ... @
selectD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Select → m a → m a
selectD bm children = snd <$> selectD' bm children
selectC ∷ (DomBuilder t m, PostBuild t m) ⇒ Select → m () → m (Event t ())
selectC bm children = do
(e,_) ← elAttr' "select" (A.attrMap bm) children
return $ domEvent Click e
selectCD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t Select → m () → m (Event t ())
selectCD bDyn children = do
(e,_) ← elDynAttr' "select" (A.attrMap <$> bDyn) children
return $ domEvent Click e
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | TextArea-element has the following attributes:
-- globals; autofocus; cols; dirname; disabled; form; maxlength; minlength;
-- name; placeholder; readonly; required; rows; wrap
--
data TextArea = TextArea
{ _textAreaGlobals ∷ Maybe A.Globals
, _textAreaAutoFocus ∷ Maybe A.AutoFocus
, _textAreaCols ∷ Maybe A.Cols
, _textAreaDirName ∷ Maybe A.DirName
, _textAreaDisabled ∷ Maybe A.Disabled
, _textAreaForm ∷ Maybe A.Form
, _textAreaMaxLength ∷ Maybe A.MaxLength
, _textAreaMinLength ∷ Maybe A.MinLength
, _textAreaName ∷ Maybe A.Name
, _textAreaPlaceholder ∷ Maybe A.Placeholder
, _textAreaReadOnly ∷ Maybe A.ReadOnly
, _textAreaRequired ∷ Maybe A.Required
, _textAreaRows ∷ Maybe A.Rows
, _textAreaWrap ∷ Maybe A.Wrap
, _textAreaCustom ∷ Maybe A.Attr
}
-- | An instance.
instance A.AttrMap TextArea where
attrMap bm = fold $ catMaybes
[ A.attrMap <$> _textAreaGlobals bm
, A.attrMap <$> _textAreaAutoFocus bm
, A.attrMap <$> _textAreaCols bm
, A.attrMap <$> _textAreaDirName bm
, A.attrMap <$> _textAreaDisabled bm
, A.attrMap <$> _textAreaForm bm
, A.attrMap <$> _textAreaMaxLength bm
, A.attrMap <$> _textAreaMinLength bm
, A.attrMap <$> _textAreaName bm
, A.attrMap <$> _textAreaPlaceholder bm
, A.attrMap <$> _textAreaReadOnly bm
, A.attrMap <$> _textAreaRequired bm
, A.attrMap <$> _textAreaRows bm
, A.attrMap <$> _textAreaWrap bm
] <> maybeToList (_textAreaCustom bm)
-- | A default value for TextArea
defTextArea ∷ TextArea
defTextArea = TextArea Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | An instance.
instance Semigroup TextArea where
(<>)
(TextArea a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15)
(TextArea b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15)
= TextArea (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4) (a5 <> b5)
(a6 <> b6) (a7 <> b7) (a8 <> b8) (a9 <> b9) (a10 <> b10)
(a11 <> b11) (a12 <> b12) (a13 <> b13) (a14 <> b14) (a15 <> b15)
-- | An instance.
instance Monoid TextArea where
mempty = defTextArea
mappend = (<>)
-- | An instance.
instance A.AttrHasGlobals TextArea where
attrSetGlobals pp bm = bm { _textAreaGlobals = Just pp }
-- Global attributes require the following instances.
-- | An instance.
instance A.AttrHasAccessKey TextArea
where attrSetAccessKey pp g = g { _textAreaGlobals = Just (A.attrSetAccessKey pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasAnmval TextArea
where attrSetAnmval pp g = g { _textAreaGlobals = Just (A.attrSetAnmval pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasContentEditable TextArea
where attrSetContentEditable pp g = g { _textAreaGlobals = Just (A.attrSetContentEditable pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasContextMenu TextArea
where attrSetContextMenu pp g = g { _textAreaGlobals = Just (A.attrSetContextMenu pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasClass TextArea
where attrSetClassName pp g = g { _textAreaGlobals = Just (A.attrSetClassName pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasDnmval TextArea
where attrSetDnmval pp g = g { _textAreaGlobals = Just (A.attrSetDnmval pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasDir TextArea
where attrSetDir pp g = g { _textAreaGlobals = Just (A.attrSetDir pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasDraggable TextArea
where attrSetDraggable pp g = g { _textAreaGlobals = Just (A.attrSetDraggable pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasHidden TextArea
where attrSetHidden pp g = g { _textAreaGlobals = Just (A.attrSetHidden pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasId TextArea
where attrSetId pp g = g { _textAreaGlobals = Just (A.attrSetId pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasLang TextArea
where attrSetLang pp g = g { _textAreaGlobals = Just (A.attrSetLang pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasRole TextArea
where attrSetRole pp g = g { _textAreaGlobals = Just (A.attrSetRole pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasSlot TextArea
where attrSetSlot pp g = g { _textAreaGlobals = Just (A.attrSetSlot pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasSpellCheck TextArea
where attrSetSpellCheck pp g = g { _textAreaGlobals = Just (A.attrSetSpellCheck pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasStyle TextArea
where attrSetStyle pp g = g { _textAreaGlobals = Just (A.attrSetStyle pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasTabIndex TextArea
where attrSetTabIndex pp g = g { _textAreaGlobals = Just (A.attrSetTabIndex pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasTitle TextArea
where attrSetTitle pp g = g { _textAreaGlobals = Just (A.attrSetTitle pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrHasTranslate TextArea
where attrSetTranslate pp g = g { _textAreaGlobals = Just (A.attrSetTranslate pp (fromMaybe A.defGlobals (_textAreaGlobals g))) }
-- | An instance.
instance A.AttrGetClassName TextArea where attrGetClassName g = maybe (A.ClassName T.empty) A.attrGetClassName (_textAreaGlobals g)
-- | An instance.
instance A.AttrHasAutoFocus TextArea where attrSetAutoFocus pp g = g { _textAreaAutoFocus = Just pp }
-- | An instance.
instance A.AttrHasCols TextArea where attrSetCols pp g = g { _textAreaCols = Just pp }
-- | An instance.
instance A.AttrHasDirName TextArea where attrSetDirName pp g = g { _textAreaDirName = Just pp }
-- | An instance.
instance A.AttrHasDisabled TextArea where attrSetDisabled pp g = g { _textAreaDisabled = Just pp }
-- | An instance.
instance A.AttrHasForm TextArea where attrSetForm pp g = g { _textAreaForm = Just pp }
-- | An instance.
instance A.AttrHasMaxLength TextArea where attrSetMaxLength pp g = g { _textAreaMaxLength = Just pp }
-- | An instance.
instance A.AttrHasMinLength TextArea where attrSetMinLength pp g = g { _textAreaMinLength = Just pp }
-- | An instance.
instance A.AttrHasName TextArea where attrSetName pp g = g { _textAreaName = Just pp }
-- | An instance.
instance A.AttrHasPlaceholder TextArea where attrSetPlaceholder pp g = g { _textAreaPlaceholder = Just pp }
-- | An instance.
instance A.AttrHasReadOnly TextArea where attrSetReadOnly pp g = g { _textAreaReadOnly = Just pp }
-- | An instance.
instance A.AttrHasRequired TextArea where attrSetRequired pp g = g { _textAreaRequired = Just pp }
-- | An instance.
instance A.AttrHasRows TextArea where attrSetRows pp g = g { _textAreaRows = Just pp }
-- | An instance.
instance A.AttrHasWrap TextArea where attrSetWrap pp g = g { _textAreaWrap = Just pp }
-- | An instance.
instance A.AttrHasCustom TextArea where attrSetCustom pp g = g { _textAreaCustom = Just pp }
-- | A short-hand notion for @ elAttr\' \"textarea\" ... @
textArea' ∷ forall t m a. DomBuilder t m ⇒ TextArea → m a → m (Element EventResult (DomBuilderSpace m) t, a)
textArea' bm = elAttr' "textarea" (A.attrMap bm)
-- | A short-hand notion for @ elAttr \"textarea\" ... @
textArea ∷ forall t m a. DomBuilder t m ⇒ TextArea → m a → m a
textArea bm children = snd <$> textArea' bm children
-- | A short-hand notion for @ el\' \"textarea\" ... @
textAreaN' ∷ forall t m a. DomBuilder t m ⇒ m a → m (Element EventResult (DomBuilderSpace m) t, a)
textAreaN' = el' "textarea"
-- | A short-hand notion for @ el \"textarea\" ... @
textAreaN ∷ forall t m a. DomBuilder t m ⇒ m a → m a
textAreaN children = snd <$> textAreaN' children
-- | A short-hand notion for @ elDynAttr\' \"textarea\" ... @
textAreaD' ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t TextArea → m a → m (Element EventResult (DomBuilderSpace m) t, a)
textAreaD' bm = elDynAttr' "textarea" (A.attrMap <$> bm)
-- | A short-hand notion for @ elDynAttr \"textarea\" ... @
textAreaD ∷ forall t m a. (DomBuilder t m, PostBuild t m) ⇒ Dynamic t TextArea → m a → m a
textAreaD bm children = snd <$> textAreaD' bm children
textAreaC ∷ (DomBuilder t m, PostBuild t m) ⇒ TextArea → m () → m (Event t ())
textAreaC bm children = do
(e,_) ← elAttr' "textarea" (A.attrMap bm) children
return $ domEvent Click e
textAreaCD ∷ (DomBuilder t m, PostBuild t m) ⇒ Dynamic t TextArea → m () → m (Event t ())
textAreaCD bDyn children = do
(e,_) ← elDynAttr' "textarea" (A.attrMap <$> bDyn) children
return $ domEvent Click e
| gspia/reflex-dom-htmlea | lib/src/Reflex/Dom/HTML5/Elements/Interactive.hs | bsd-3-clause | 70,513 | 0 | 14 | 15,128 | 20,737 | 10,853 | 9,884 | 851 | 1 |
newtype State s a = State { runState :: s -> (a, s) }
retS :: a -> State s a
retS x = State $ \s -> (x, s)
bindS :: State s a -> (a -> State s b) -> State s b
State m `bindS` f = State $ \s -> let (x, s') = m s in runState (f x) s'
instance Functor (State s) where
fmap f m = m `bindS` (retS . f)
instance Applicative (State s) where
pure = retS
mf <*> mx = mf `bindS` \f -> mx `bindS` \x -> retS $ f x
instance Monad (State s) where
return = retS
(>>=) = bindS
get :: State s s
get = State $ \s -> (s, s)
put :: s -> State s ()
put x = State $ \_ -> ((), x)
modify :: (s -> s) -> State s ()
modify f = get >>= put . f
madd :: Integer -> State Integer ()
madd x = modify (+ x)
example :: State Integer Integer
example = do
madd $ 3 * 4
madd $ 2 * 5
(* 7) <$> get
data Operation = E Expression | ErasePreLine deriving Show
data Expression
= Expression :+: Expression
| Expression :-: Expression
| Expression :*: Expression
| I Integer
deriving Show
type Result = (Operation, Maybe Integer)
withOp :: String -> String -> String -> String
withOp op e1 e2 = "(" ++ e1 ++ " " ++ op ++ " " ++ e2 ++ ")"
showExp :: Expression -> String
showExp (e1 :+: e2) = withOp "+" (showExp e1) (showExp e2)
showExp (e1 :-: e2) = withOp "-" (showExp e1) (showExp e2)
showExp (e1 :*: e2) = withOp "*" (showExp e1) (showExp e2)
showExp (I n) = show n
evaluate :: Expression -> Integer
evaluate (o1 :+: o2) = evaluate o1 + evaluate o2
evaluate (o1 :-: o2) = evaluate o1 - evaluate o2
evaluate (o1 :*: o2) = evaluate o1 * evaluate o2
evaluate (I n) = n
operate :: Operation -> State [String] Result
operate o@(E e) = do
modify ((showExp e ++ " = " ++ show r) :)
return (o, Just r)
where r = evaluate e
operate o@ErasePreLine = do
modify (\ls -> if null ls then [] else tail ls)
return (o, Nothing)
operateAll :: [Operation] -> State [String] [Result]
operateAll (o : os) = (:) <$> operate o <*> operateAll os
operateAll [] = pure []
sampleOperation :: [Operation]
sampleOperation = [
E $ I 3 :+: I 5,
E $ I 8 :*: I 9,
E $ I 7 :-: I 5,
ErasePreLine,
E $ I 3 :*: I 5 ]
| YoshikuniJujo/funpaala | samples/37_list_and_monad/state1.hs | bsd-3-clause | 2,085 | 14 | 12 | 494 | 1,114 | 579 | 535 | 64 | 2 |
module Meadowstalk.Handlers.Admin
where
import Yesod.Core
import Meadowstalk.Foundation
import Meadowstalk.Model
-------------------------------------------------------------------------------
getAdminR :: Handler Html
getAdminR = undefined
-------------------------------------------------------------------------------
getAdminArticlesR :: Handler Html
getAdminArticlesR = undefined
postAdminArticlesR :: Handler ()
postAdminArticlesR = undefined
getAdminArticleR :: ArticleId -> Handler Html
getAdminArticleR _ = undefined
postAdminArticleR :: ArticleId -> Handler ()
postAdminArticleR _ = undefined
deleteAdminArticleR :: ArticleId -> Handler ()
deleteAdminArticleR _ = undefined
-------------------------------------------------------------------------------
getAdminTagsR :: Handler Html
getAdminTagsR = undefined
postAdminTagsR :: Handler ()
postAdminTagsR = undefined
getAdminTagR :: TagId -> Handler Html
getAdminTagR _ = undefined
postAdminTagR :: TagId -> Handler ()
postAdminTagR _ = undefined
deleteAdminTagR :: TagId -> Handler ()
deleteAdminTagR _ = undefined
-------------------------------------------------------------------------------
getAdminUsersR :: Handler Html
getAdminUsersR = undefined
postAdminUsersR :: Handler ()
postAdminUsersR = undefined
getAdminUserR :: UserId -> Handler Html
getAdminUserR _ = undefined
postAdminUserR :: UserId -> Handler ()
postAdminUserR _ = undefined
deleteAdminUserR :: UserId -> Handler ()
deleteAdminUserR _ = undefined
-------------------------------------------------------------------------------
getAdminUserSignInR :: Handler Html
getAdminUserSignInR = undefined
postAdminUserSignInR :: Handler Html
postAdminUserSignInR = undefined
getAdminUserSignOutR :: Handler ()
getAdminUserSignOutR = undefined
| HalfWayMan/meadowstalk | src/Meadowstalk/Handlers/Admin.hs | bsd-3-clause | 1,793 | 0 | 7 | 202 | 357 | 189 | 168 | 42 | 1 |
{-
- DumpTruck.hs
- By Steven Smith
-}
-- | DumpTruck is a micro web framework. It is built up from two components:
-- 'Route's and 'EndPoint's.
--
-- 'Route's describe the @URI@ heirarchy for a web site. They are based around
-- matching path fragments. The recommended way to build up 'Route's is through
-- @do@ notation as 'Route' is a 'Monad'.
--
-- 'EndPoint's represent monadic actions to be executed to produce the final
-- 'Response' once 'Route' matching has reached a "terminal node". A terminal
-- node optionally matches on the 'Request' 'Method' and contains an associated
-- 'EndPoint'.
--
-- Once a 'Route' has been built with some number of 'EndPoint's it can be
-- converted into a @WAI@ 'Application' and run on a @WAI@ handler
-- (<http://hackage.haskell.org/package/warp Warp> is recommended) through
-- 'mkDumpTruckApp'. This will produce a web application server using the
-- 'Route' to match @URI@s and serve 'Response's from its 'EndPoint's.
--
-- Consider this simple web app (assuming the language extension
-- @OverloadedStrings@ is enabled):
--
-- @
-- myApp :: Route s ()
-- myApp = matchAny (raw "Hello!")
-- @
--
-- 'matchAny' is a smart constructor for a 'Route' terminal node that will
-- always succeed in matching, executing the 'EndPoint' passed to it. 'raw'
-- constructs an 'EndPoint' that will simply respond with the lazy 'ByteString'
-- passed to it. Thus, this DumpTruck app will always return the string
-- "Hello!" regardless of 'Request' 'Method' or @URI@. Now consider a slightly
-- more complicated app:
--
-- @
-- myApp :: Route s ()
-- myApp = do get (raw "HTTP GET")
-- matchAny (raw "Not HTTP GET")
-- @
--
-- 'get' is a smart constructor for a 'Route' terminal node that will match if
-- the 'Request' 'Method' is @GET@. If matching fails for it, matching will
-- continue to the next node. Thus, the app will return "HTTP GET" if the
-- 'Request' 'Method' is @GET@, and "Not HTTP GET" otherwise. Similar smart
-- constructors exist:
--
-- @
-- myApp :: Route s ()
-- myApp = do get (raw "HTTP GET")
-- post (raw "HTTP POST")
-- put (raw "HTTP PUT")
-- delete (raw "HTTP DELETE")
-- @
--
-- This app will match against each of the 'Request' 'Method's and execute the
-- corresponding 'EndPoint' if matching succeeds. This app doesn't have a
-- 'matchAny' node at the end, so matching can potentially fail. In this case a
-- @404 Not Found@ 'Response' is returned.
--
-- So far all the apps have ignored the @URI@. This app matches against a
-- specific path segment:
--
-- @
-- myApp :: Route s ()
-- myApp = do
-- route "foo" $ do
-- matchAny (raw "Matched foo")
-- matchAny (raw "Didn't match foo")
-- @
--
-- This app will match the @URI@ "\/foo" and return the string "Matched foo" in
-- this case, or return "Didn't match foo" otherwise. This will also match the
-- @URI@ "\/foo\/bar". To cap the matching @URI@ use 'routeEnd':
--
-- @
-- myApp :: Route s ()
-- myApp = do
-- route "foo" $ do
-- routeEnd $ do
-- matchAny (raw "Matched foo exactly")
-- matchAny (raw "Didn't match foo")
-- @
--
-- Now the app will match the @URI@ "\/foo" but not "\/foo\/bar". 'Route's will
-- consume the path segment when matching 'route', but will restore it if it
-- needs to backtrack. This allows arbitrary nesting of 'Route's to create full
-- @URI@ paths.
--
-- @
-- myApp :: Route s ()
-- myApp = do
-- route "foo" $ do
-- route "bar" $ do
-- routeEnd $ do
-- matchAny (raw "Matched exactly \/foo\/bar")
-- route "baz" $ do
-- matchAny (raw "Matched at least \/foo\/baz")
-- route "foo" $ do
-- route "bar" $ do
-- route "foobar" $ do
-- matchAny (raw "Matched \/foo\/bar\/foobar")
-- route "quux" $ do
-- matchAny (raw "Matched /quux")
-- @
--
-- This can be shortened by using fewer @do@ blocks and combining redundant
-- segments:
--
-- @
-- myApp :: Route s ()
-- myApp = do
-- route "foo" $ do
-- route "bar" $ do
-- routeEnd $ matchAny (raw "Matched exactly \/foo\/bar")
-- route "foobar" $ matchAny (raw "Matched \/foo\/bar\/foobar")
-- route "baz $ matchAny (raw "Matched at least \/foo\/baz")
-- route "quux" $ matchAny (raw "Matched \/quux")
-- @
--
-- Multiple 'route' nodes can also be compressed by simply including multiple
-- segments delineated by "\/":
--
-- @
-- myApp :: Route s ()
-- myApp = do
-- route "foo\/bar" . routeEnd $ matchAny (raw "Matched exactly \/foo\/bar")
-- route "foo\/bar\/foobar" $ matchAny (raw "Matched \/foo\/bar\/foobar")
-- route "foo\/baz" $ matchAny (raw "Matched at least \/foo\/baz")
-- route "quux" $ matchAny (raw "Matched \/quux")
-- @
--
-- (Note that routes expressed in this manner are always fully expanded with no
-- attempt at merging branches, so this example will backtrack more than the one
-- preceding it.)
--
-- It is also possible to capture path segments as any type that is
-- 'Captureable'. Instances of this type class have a corresponding parser used
-- when attempting to capture. A number of common instances are provided, and
-- users can also write instances of 'Captureable' for their own data types and
-- use 'capture' with them normally. Matching will fail if the segment doesn't
-- exist or if parsing fails.
--
-- In addition to 'capture', there is 'captureInt' which is 'capture'
-- specialized to 'Int'. This can be convenient as the polymorphic 'capture' can
-- cause ambiguous types necessitating explicit type annotations.
--
-- @
-- import qualified Data.ByteString.Lazy as LBS
--
-- myApp :: Route s ()
-- myApp = do
-- route "text" $ capture $ \t ->
-- matchAny (raw $ "Captured: " LBS.++ t)
-- route "int" $ captureInt $ \i ->
-- if i > 3
-- then matchAny (raw "Greater than 3!")
-- else matchAny (raw "Less than 3!")
-- @
--
-- There are a number of other features available, as well as a set of
-- 'EndPoint's. See the rest of the documentation for more details.
--
module Web.DumpTruck
-- Web.DumpTruck.Route
( Route
, route
, routeEnd
, capture
, captureInt
, get
, post
, put
, delete
, options
, patch
, method
, matchAny
, remainingPath
, directory
, directory'
, mkDumpTruckApp
, mkDumpTruckApp'
-- Web.DumpTruck.EndPoint
, EndPoint
, getRequest
, getState
, addHeader
, buildResponse
, generateResponse
, file
, cacheOnMod
, cacheOnEtag
, raw
, rawJson
, json
, notFound
, redirect
, redirectPermanent
, methodNotAllowed
, withFormData
, withJson
, withRequestData
, addCookie
)
where
import Web.DumpTruck.Route
import Web.DumpTruck.EndPoint
| stevely/DumpTruck | src/Web/DumpTruck.hs | bsd-3-clause | 6,701 | 0 | 4 | 1,446 | 298 | 253 | 45 | 41 | 0 |
import Language.Cube
house :: Block Cube
house = let house'' = (house' + square)*line
in rfmap (12 * dz +) house''
where
house' :: Block Cube
house' = block $ [cube 1 x y| x<-[-10..10], y<-[-10..10], y < x , y < (-x)]
square :: Block Cube
square = rfmap ((+) (-12 * dz)) $ block $ [cube 1 x y| x<-[-5..5], y<-[-5..5]]
line :: Block Cube
line = block $ [cube x 0 0 | x<-[-5..5]]
main :: IO ()
main = do
writeFileStl "house.stl" $ house
| junjihashimoto/cube | sample/house.hs | bsd-3-clause | 483 | 0 | 14 | 136 | 282 | 147 | 135 | 13 | 1 |
module Network.TeleHash.Bucket
(
bucket_load
, bucket_get
) where
import Control.Exception
import Data.Aeson.Types
import Data.Maybe
import Network.TeleHash.Hn
import Network.TeleHash.Types
import Network.TeleHash.Utils
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as HM
import qualified Data.Set as Set
-- ---------------------------------------------------------------------
{-
typedef struct bucket_struct
{
int count;
hn_t *hns;
} *bucket_t;
bucket_t bucket_new();
void bucket_free(bucket_t b);
void bucket_add(bucket_t b, hn_t h);
hn_t bucket_in(bucket_t b, hn_t h);
-}
-- ---------------------------------------------------------------------
{-
// simple array index function
hn_t bucket_get(bucket_t b, int index);
-}
-- |simple array index function
bucket_get :: Bucket -> Int -> Maybe HashName
bucket_get b index =
if index > Set.size b || Set.size b == 0
then Nothing
else Just $ ghead "bucket_get" $ drop index $ Set.toList b
{-
hn_t bucket_get(bucket_t b, int index)
{
if(index >= b->count) return NULL;
return b->hns[index];
}
-}
-- ---------------------------------------------------------------------
bucket_load :: FilePath -> TeleHash Bucket
bucket_load fname = do
fc <- io $ BL.readFile fname
-- let ms = Aeson.decode fc :: Maybe [SeedInfo]
-- logT $ "seedinfo=" ++ show ms
let mv = Aeson.decode fc :: Maybe Value
logT $ "seedinfo=" ++ show mv
case mv of
Nothing -> return Set.empty
Just (Object vv) -> do
let go (Object o) = hn_fromjson (packet_new_rx { rtJs = o})
go _ = return Nothing
hns <- mapM go $ HM.elems vv
logT $ "bucket_load: hns=" ++ show hns
return $ Set.fromList $ catMaybes hns
Just _ -> assert False undefined
{-
bucket_t bucket_load(xht_t index, char *file)
{
packet_t p, p2;
hn_t hn;
bucket_t b = NULL;
int i;
p = util_file2packet(file);
if(!p) return b;
if(*p->json != '{')
{
packet_free(p);
return b;
}
// check each value, since js0n is key,len,value,len,key,len,value,len for objects
for(i=0;p->js[i];i+=4)
{
p2 = packet_new();
packet_json(p2, p->json+p->js[i+2], p->js[i+3]);
hn = hn_fromjson(index, p2);
packet_free(p2);
if(!hn) continue;
if(!b) b = bucket_new();
bucket_add(b, hn);
}
packet_free(p);
return b;
}
-}
| alanz/htelehash | src/Network/TeleHash/Bucket.hs | bsd-3-clause | 2,413 | 0 | 18 | 491 | 381 | 201 | 180 | 33 | 4 |
{-# LANGUAGE QuasiQuotes #-}
module Feldspar.Multicore.Compile.Parallella.Esdk where
import Feldspar.Multicore.Compile.Parallella.Access (isCTypeOf)
import Feldspar.Multicore.Compile.Parallella.Imports
import qualified Language.C.Monad as C (addGlobal, CGen)
import Language.C.Quote.C as C
import qualified Language.C.Syntax as C (Type)
--------------------------------------------------------------------------------
-- Hardware and (e)SDK specific utilities
--------------------------------------------------------------------------------
type CoreCoords = (Word32, Word32)
groupCoord :: CoreId -> CoreCoords
groupCoord coreId
| isValidCoreId coreId = coreId `divMod` 4
| otherwise = error $ "invalid core id: " ++ show coreId
isValidCoreId :: CoreId -> Bool
isValidCoreId = flip elem [0..15]
systemCoord :: CoreId -> CoreCoords
systemCoord coreId = let (gr, gc) = groupCoord coreId in (gr + 32, gc + 8)
addCoreSpecification :: CoreId -> C.CGen ()
addCoreSpecification coreId = do
let (sr, sc) = systemCoord coreId
setRow = "asm(\".set __CORE_ROW_," ++ show sr ++ "\");"
setCol = "asm(\".set __CORE_COL_," ++ show sc ++ "\");"
C.addGlobal [cedecl| extern int _CORE_ROW_; |]
C.addGlobal [cedecl| $esc:("asm(\".global __CORE_ROW_\");") |]
C.addGlobal [cedecl| $esc:setRow |]
C.addGlobal [cedecl| extern int _CORE_COL_; |]
C.addGlobal [cedecl| $esc:("asm(\".global __CORE_COL_\");") |]
C.addGlobal [cedecl| $esc:setCol |]
type LocalAddress = Word32
type GlobalAddress = Word32
toGlobal :: LocalAddress -> CoreId -> GlobalAddress
toGlobal addr coreId
-- external memory addresses are relative to a fixed base pointer
| coreId == sharedId = addr
| otherwise = let (sr, sc) = systemCoord coreId
-- 6 bit row number, 6 bit column number, 20 bit local address
in (sr `shift` 26) .|. (sc `shift` 20) .|. addr
aligned :: LocalAddress -> LocalAddress
aligned addr
| m == 0 = addr
| otherwise = addr - m + dmaAlign
where m = addr `mod` dmaAlign
dmaAlign :: Word32
dmaAlign = 16
bank1Base :: LocalAddress -- local in the address space of a core
bank1Base = 0x2000
sharedBase :: LocalAddress -- relative to external memory base
sharedBase = 0x1000000
sizeOf :: C.Type -> Length
sizeOf (isCTypeOf (Proxy :: Proxy Bool) -> True) = 1
sizeOf (isCTypeOf (Proxy :: Proxy Int8) -> True) = 1
sizeOf (isCTypeOf (Proxy :: Proxy Int16) -> True) = 2
sizeOf (isCTypeOf (Proxy :: Proxy Int32) -> True) = 4
sizeOf (isCTypeOf (Proxy :: Proxy Int64) -> True) = 8
sizeOf (isCTypeOf (Proxy :: Proxy Word8) -> True) = 1
sizeOf (isCTypeOf (Proxy :: Proxy Word16) -> True) = 2
sizeOf (isCTypeOf (Proxy :: Proxy Word32) -> True) = 4
sizeOf (isCTypeOf (Proxy :: Proxy Word64) -> True) = 8
sizeOf (isCTypeOf (Proxy :: Proxy Float) -> True) = 4
sizeOf (isCTypeOf (Proxy :: Proxy Double) -> True) = 8
sizeOf (isCTypeOf (Proxy :: Proxy (Complex Float)) -> True) = 8
sizeOf (isCTypeOf (Proxy :: Proxy (Complex Double)) -> True) = 16
sizeOf cty = error $ "size of C type is unknown: " ++ show cty
| kmate/raw-feldspar-mcs | src/Feldspar/Multicore/Compile/Parallella/Esdk.hs | bsd-3-clause | 3,211 | 0 | 12 | 698 | 946 | 515 | 431 | -1 | -1 |
module Mud.ConfigSpec where
import Control.Monad.Except
import Mud.Config
import Mud.Error
import SpecHelpers
spec :: Spec
spec = do
let files = [ ( "/etc/mud/simple.conf"
, "deploy=/etc/mud/different.deploy\n\
\user=somebody\n\
\var:var1=one\n\
\var:var2=two\n" )
, ("/etc/mud/complex/01_first.conf", "basepath=/one")
, ("/etc/mud/complex/02_second.conf", "basepath=/two")
, ("/etc/mud/wrong.conf", "mistake=some value")
]
dirs = [("/etc/mud/complex", ["01_first.conf", "02_second.conf"])]
canonicalize = \case
"/etc/mud" -> "/etc/mud"
"/etc/mud/simple" -> "/etc/mud/simple"
"/etc/mud/complex" -> "/etc/mud/complex"
"/etc/mud/missing" -> "/etc/mud/missing"
"/etc/mud/wrong" -> "/etc/mud/wrong"
"/etc/mud/../blah" -> "/etc/blah"
path -> error $ "no mock found for canonicalizePath " ++ show path
run = runFakeFileSystem files dirs canonicalize . runExceptT
describe "actualParseConfigFiles" $ do
it "returns a config for /etc/mud/simple.conf" $ do
let config = (defaultConfig "/etc/mud/simple")
{ cfgDeployScript = "/etc/mud/different.deploy"
, cfgUser = Just "somebody"
, cfgVars = [("var1", "one"), ("var2", "two")]
}
run (actualParseConfigFiles "/etc/mud" "simple") `shouldBe` Right [config]
it "returns several configs for /etc/mud/complex/*.conf" $ do
let mk path = (defaultConfig "/etc/mud/complex") { cfgBasePath = path }
config1 = mk "/one"
config2 = mk "/two"
run (actualParseConfigFiles "/etc/mud" "complex")
`shouldBe` Right [config1, config2]
it "throws MudErrorNoConfigFound if the config does not exist" $ do
run (actualParseConfigFiles "/etc/mud" "missing")
`shouldBe` Left (MudErrorNoConfigFound "/etc/mud/missing")
it "throws MudErrorUnreadableConfig if the config is wrong" $ do
run (actualParseConfigFiles "/etc/mud" "wrong")
`shouldBe` Left (MudErrorUnreadableConfig "invalid variable 'mistake'")
it "throws MudErrorNotInMudDirectory if we attempt to go out of the\
\ configuration directory" $ do
run (actualParseConfigFiles "/etc/mud" "../blah")
`shouldBe` Left MudErrorNotInMudDirectory
| thoferon/mud | tests/Mud/ConfigSpec.hs | bsd-3-clause | 2,423 | 0 | 19 | 638 | 470 | 246 | 224 | -1 | -1 |
{-
Copyright James d'Arcy 2010
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of James d'Arcy nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Hastur.Types
(
DicomPatient(..),
DicomStudy(..),
DicomSeries(..),
DicomSopInstance(..),
DicomImage(..)
) where
import Data.Int
import Graphics.UI.WX (Var)
import Data.Dicom
data DicomPatient = DicomPatient {
patientName :: String,
patientPk :: Int64
} deriving (Show)
data DicomStudy = DicomStudy {
studyUid :: String,
studyDate :: String,
studyDescription :: String,
studyPk :: Int64,
patientFk :: Int64,
studyPatient :: DicomPatient
} deriving (Show)
data DicomSeries = DicomSeries {
seriesUid :: String,
seriesDescription :: String,
seriesNumber :: Int32,
modality :: String,
seriesPk :: Int64,
studyFk :: Int64
} deriving (Show)
data DicomSopInstance = DicomSopInstance {
sopInstancePath :: String,
sopInstanceUid :: String,
sopInstancePk :: Int64,
seriesFk :: Int64,
sopInstanceFrameCount :: Int32,
varDicom :: Var (Maybe EncapDicomObject)
}
data DicomImage = DicomImage {
imageUid :: String,
sopInstanceFk :: Int64,
sopInstance :: DicomSopInstance,
imageFrame :: Int32
} deriving (Show)
instance Show DicomSopInstance where
show dsi = "DicomSopInstance { UID=\"" ++ (sopInstanceUid dsi) ++
"\", Key=\"" ++ show (sopInstancePk dsi) ++ "\", Series Key=\"" ++
show (seriesFk dsi) ++ "\", Frame Count=\"" ++ show (sopInstanceFrameCount dsi) ++
"\", Path=\"" ++ (sopInstancePath dsi) ++ "\" }"
| jamesdarcy/Hastur | src/Hastur/Types.hs | bsd-3-clause | 2,933 | 0 | 17 | 560 | 386 | 231 | 155 | 48 | 0 |
-- |
-- Module : Portager.Writes
-- Copyright : (C) 2017 Jiri Marsicek
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Jiri Marsicek <[email protected]>
--
-- This module provides functionality for serialization of portage configuration to configuration files.
--
{-# LANGUAGE OverloadedStrings #-}
module Portager.Writes where
import Control.Monad (unless)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Reader (ReaderT, asks)
import Data.List (partition)
import Data.Maybe (mapMaybe)
import Data.Semigroup ((<>))
import qualified Data.Set as Set (toAscList)
import Data.Text (Text)
import qualified Data.Text as Text (unlines, unpack, unwords)
import qualified Data.Text.IO as Text (putStrLn, writeFile)
import System.Directory (createDirectoryIfMissing)
import System.FilePath (FilePath, (</>))
import Text.Printf (printf)
import Portager.DSL
import Portager.Flatten (FlatPackage(..), flattenSet)
import Portager.Options (Options(..), WorldSet)
-- |Adds Atom name as a prefix to text given as parameter.
withAtom :: FlatPackage -> Text -> Text
withAtom fp t = showText (_fpAtom fp) <> " " <> t
-- |Creates a text record for package in a format required by @package.use@ file.
toPackageUseRecord :: FlatPackage -> Maybe Text
toPackageUseRecord fp
| null useflags = Nothing
| otherwise = Just $ withAtom fp $ showText useflags
where useflags = Set.toAscList $_fpUseflags fp
-- |Creates a list of records to be written to portage use file @/etc/portage/package.use/*@
-- See 'toPackageUseRecord'
toPackageUse :: [FlatPackage] -> [Text]
toPackageUse = mapMaybe toPackageUseRecord
-- |Creates a text record for a package in a format required by @package.accept_keywords@ file.
toPackageAcceptKeywordRecord :: FlatPackage -> Maybe Text
toPackageAcceptKeywordRecord fp
| null kws = Nothing
| otherwise = Just $ withAtom fp $ showText kws
where kws = Set.toAscList $_fpKeywords fp
-- |Creates a list of lines to be written to portage accept_keywords file @/etc/portage/package.accept_keywords/*@
-- See 'toPackageAcceptKeywordRecord'
toPackageAcceptKeywords :: [FlatPackage] -> [Text]
toPackageAcceptKeywords = mapMaybe toPackageAcceptKeywordRecord
-- |Creates a text record for a package in a format required by @package.license@ files.
toPackageLicenseRecord :: FlatPackage -> Maybe Text
toPackageLicenseRecord fp
| null licenses = Nothing
| otherwise = Just $ withAtom fp $ showText licenses
where licenses = Set.toAscList $_fpLicenses fp
-- |Creates a list of lines to be written to a portage license file @/etc/portage/package.license@
-- See 'toPackageLicenseRecord'
toPackageLicense :: [FlatPackage] -> [Text]
toPackageLicense = mapMaybe toPackageLicenseRecord
-- |Creates a collection of lines to be written to a portage set file @/etc/portage/sets/*@
toPortageSet :: SetConfiguration -> [Text]
toPortageSet = map (showText . _atom) . _setPackages
data PortageSetConfig =
PortageSetConfig
{ _portageSetName :: Name
, _portageSet :: [Text]
, _portagePackageUse :: [Text]
, _portagePackageAcceptKeywords :: [Text]
, _portagePackageLicense :: [Text]
} deriving (Eq, Show)
-- |Converts a 'PackageSet' to 'PortageSetConfig' that can
createPortageSetConfig :: PackageSet -> PortageSetConfig
createPortageSetConfig s =
let cfg = _setConfiguration s
flat = Set.toAscList $ flattenSet s
in PortageSetConfig
{ _portageSetName = _setName s
, _portageSet = toPortageSet cfg
, _portagePackageUse = toPackageUse flat
, _portagePackageAcceptKeywords = toPackageAcceptKeywords flat
, _portagePackageLicense = toPackageLicense flat
}
writeLines :: FilePath -> [Text] -> IO ()
writeLines fp = Text.writeFile fp . Text.unlines
-- |Writes text lines to a file enclosed in directory, creating the directory if it does not exist.
-- If there are no lines to be written, no action is performed.
-- Parent of a directory is read from 'Options'.
writePortageSetFile :: FilePath -> FilePath -> [Text] -> ReaderT Options IO ()
writePortageSetFile dir file lns = unless (null lns) $ do
root <- asks _targetDir
lift $ createDirectoryIfMissing False (root </> dir)
lift $ writeLines (root </> dir </> file) lns
-- |Writes a 'PortageSetConfig' with specified index to respective files.
-- @package.use@ file is prefixed with an index, since it is sensitive to order.
writePortageSetConfig :: Int -> PortageSetConfig -> ReaderT Options IO ()
writePortageSetConfig index (PortageSetConfig pName pSet pUseflags pKeywords pLicenses) =
do writePortageSetFile "sets" name pSet
writePortageSetFile "package.use" (printf "%02d" index <> name) pUseflags
writePortageSetFile "package.accept_keywords" name pKeywords
writePortageSetFile "package.license" name pLicenses
where name = Text.unpack pName
-- |Performs 'writePortageSetConfig' for WorldSets given as parameter
writePortageSetConfigs :: [WorldSet] -> [PortageSetConfig] -> ReaderT Options IO ()
writePortageSetConfigs ws cfgs =
let (process, skipped) = partition (\psc -> _portageSetName psc `elem` ws) cfgs
in do unless (null skipped) $ lift $ Text.putStrLn $ "Skipping configuration for sets not listed in world_sets files: " <> (Text.unwords $ map _portageSetName skipped)
mapM_ (uncurry $ writePortageSetConfig) $ zip [1..] process
| j1r1k/portager | src/Portager/Writes.hs | bsd-3-clause | 5,388 | 0 | 15 | 887 | 1,134 | 612 | 522 | 80 | 1 |
{-# LANGUAGE RankNTypes #-}
{- |
Module : ./Static/ChangeGraph.hs
Description : functions for changing a development graphs
Copyright : (c) Christian Maeder, DFKI GmbH 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(Logic)
functions to manipulate a development graph for change management
All of the following functions may fail, therefore the result type should
not be taken literally, but maybe changed to some monadic result type.
Also all functions modify an development graph when the are successful, which
may be captured by some form of a state monad.
-}
module Static.ChangeGraph where
import Static.DgUtils
import Static.GTheory
import Static.DevGraph
import Static.History
import Logic.Grothendieck
import Common.AS_Annotation
import Common.Consistency
import qualified Common.OrderedMap as OMap
import Common.Result
import Data.Graph.Inductive.Graph as Graph
import qualified Data.Set as Set
import Data.List
import Control.Monad
-- * deleting and adding nodes
{- | delete a node.
If a node is deleted all in- and outgoing links will be lost. This is intended
for ingoing definitions links. The targets of outgoing definitions links (aka
"depending nodes") need to me marked as "reduced".
theorem links from A to B state that all sentences in A can be proven by the
axioms (and proven theorems) from B (note the reversal). This means the
sentences of A are translated and moved to B as theorems (to be proven) by
"local inference".
removing ingoing theorem links means: we loose properties of B, which is no
problem since we delete B. (If we just delete the theorem link we must inform
depending nodes that fewer axioms are now available. Since a proof for the
link will be lost other proofs in depending nodes may become invalid.)
removing outgoing (local) theorem links means: target nodes may contain theorems
from the source node that need to be deleted, too. So these nodes are
"reduced" (fewer theorems only). (We do not keep even valid theorems, if we
are told to delete them.)
The node to be deleted may have been subject to global decomposition. So
outgoing global theorems of depending nodes may get a deleted edge-id in
their proof-basis, that should be deleted, too.
Outgoing theorem links of source nodes that have definition links to the
target node to be deleted may be theorem links created by global decomposition
which should be deleted, too.
So, when deleting a node, let's delete the edges in reverse order of their
creation. remove:
- (outgoing) local theorem links (with reversal of "local-inference")
whose corresponding global theorem link has only this local theorem link
as proof basis.
- sentences in targets are removed (or the target is deleted node anyway)
(if the local theorem was proven)
- corresponding global theorem links become unproven again and loose
their proof basis (or are deleted together with the node)
- unproven global theorem links (with reversal of "global-decomposition")
- the proof basis of other proven global theorem links with the same
target is reduced and marked as incomplete (since a corresponding local
theorem link and the definition link is not deleted yet).
- so proven global theorems links are removed after removing the links in
their proof basis first
- outgoing definition links
- target nodes need to be marked as reduced (outgoing global theorem links
may become complete again)
(Proofs relying on imported axioms become invalid, provided the sentence
are still well-formed in the reduced signature)
- ingoing definition links
this just marks the current node as reduced which will be deleted later
Later on reduced nodes need to be re-computed possibly causing depending nodes
to become reduced. Incomplete global theorem links need to be completed (by
the user).
If the node index is unknown then auxiliary functions (or a mapping between
node names and node indices) can be supplied to delete nodes by name. -}
deleteDGNode :: Node -> DGraph -> Result DGraph
deleteDGNode t dg = case fst . match t $ dgBody dg of
Just (ins, _, nl, outs) -> case dgn_nf nl of
Just n -> do
dg2 <- deleteDGNode n dg
deleteDGNode t $ changeDGH dg2 $ SetNodeLab nl
(t, nl { dgn_nf = Nothing, dgn_sigma = Nothing })
Nothing -> case dgn_freenf nl of
Just n -> do
dg2 <- deleteDGNode n dg
deleteDGNode t $ changeDGH dg2 $ SetNodeLab nl
(t, nl { dgn_freenf = Nothing, dgn_phi = Nothing })
Nothing ->
if null $ ins ++ outs then return $ changeDGH dg $ DeleteNode (t, nl)
else do
dg2 <- foldM (\ dgx (el, sr) -> delDGLink (Just sr) t (dgl_id el) dgx)
dg ins
dg3 <- foldM (\ dgx (el, rt) -> delDGLink (Just t) rt (dgl_id el) dgx)
dg2 outs
deleteDGNode t dg3
_ -> justWarn dg $ "node not in graph: " ++ show t
{- | add a node supplying the necessary information.
We should allow to add a node without knowing its final signature. We just
know the 'XNode' information. Later on definition and theorem links may be
added. Only after all ingoing definition links (and their sources) are known
we can compute the actual signature (and theory).
The node index will be new and returned. The name should be unique. The theory
is a closed signature plus local sentences. The origin could be anything (to
be added yet), but for basic specs it is the list of the newly introduced
symbols.
The required conservativity is some value from
`Common.Consistency.Conservativity' like usually 'None' or 'Cons'.
Reference nodes can not be added this way. Also the references and morphisms
to normal forms for hiding or free links cannot be set this way. So further
function are needed. -}
addDGNode :: NodeName -> G_theory -> DGOrigin -> Conservativity -> DGraph
-> Result (DGraph, Node)
addDGNode nn th o cs dg = let
n = getNewNodeDG dg
inf = newConsNodeInfo o cs
sn = showName nn
nl = newInfoNodeLab nn inf th
in case lookupNodeByName sn dg of
[] -> return (changeDGH dg $ InsertNode (n, nl), n)
ns -> fail $ "node name '" ++ sn
++ "' already defined in graph for node(s): "
++ show (map fst ns)
-- | Maybe a function to rename nodes is desirable
renameNode :: Node -> NodeName -> DGraph -> Result DGraph
renameNode n nn dg = let
sn = showName nn
nl = labDG dg n
in case lookupNodeByName sn dg of
[] -> return $ changeDGH dg $ SetNodeLab nl (n, nl { dgn_name = nn })
ns -> fail $ "node name '" ++ sn
++ "' already defined in graph for node(s): "
++ show (map fst ns)
-- * deleting and adding links
{- | delete a link given the source and target node by index and the edge-id.
Edge-ids are globally unique, but locating source and target nodes would be
inefficient if not given.
Getting the edge-id if only source node name, target
node name, link type, possibly an origin, and the link morphism is given,
needs auxiliary functions.
Edge-ids maybe reused.
Local theorem links are proven by moving sentences from the source to target
node and changing them to theorems. So if such a proven local theorem link is
removed the target node needs to be reduced, too.
target nodes of definition links are "reduced" (see deleteDGNode)
-}
delDGLink :: Maybe Node -> Node -> EdgeId -> DGraph -> Result DGraph
delDGLink ms t i dg = let
(ins, _, nl, loopsAndOuts) = safeContextDG "delDGLink" dg t
loops = filter ((== t) . snd) loopsAndOuts
allIns = loops ++ ins
in case partition ((== i) . dgl_id . fst) allIns of
([], _) -> justWarn dg $ "link not found: " ++ show (t, i)
((lbl, s) : os, rs) -> do
unless (null os) $ justWarn ()
$ "ambiguous link: " ++ shows (t, i) " other sources are: "
++ show (map snd os)
case ms of
Just sr | sr /= s -> fail
$ "non-matching source node: " ++ show (s, t, i)
++ " given: " ++ show sr
_ -> let delE dg' = return $ changeDGH dg' $ DeleteEdge (s, t, lbl)
-- links proven by current link
gs = filter (edgeInProofBasis i . getProofBasis . fst) rs
dgCh = changeDGH dg $ SetNodeLab nl (t, updNodeMod delSymMod nl)
delDef = delE dgCh
in case dgl_type lbl of
ScopedLink lOrG lk _ -> case lOrG of
Local -> do
dg2 <- case lk of
ThmLink (Proven (DGRuleLocalInference renms) _) -> do
nl2 <- deleteDGNodeSens (\ nSen -> not (isAxiom nSen)
&& senAttr nSen `elem` map snd renms) nl
return $ updDGNodeLab dg nl (t, nl2)
_ -> return dg
-- find global link(s) that contain(s) the edge-id as proof-basis
let dg3 = invalDGLinkProofs dg2 $ map (\ (l, sr) -> (sr, t, l)) gs
delE dg3
Global -> case lk of
ThmLink pst -> let
pB = proofBasisOfThmLinkStatus pst
{- delete all links created by global decomposition,
(this may delete also manually inserted theorem links!)
all links have the same target. -}
createdLinks =
filter ((`edgeInProofBasis` pB) . dgl_id . fst) rs
in if null createdLinks then
let dg3 = invalDGLinkProofs dg
$ map (\ (l, sr) -> (sr, t, l)) gs
in delE dg3
else do
dg2 <- foldM (\ dgx (el, sr) ->
delDGLink (Just sr) t (dgl_id el) dgx) dg createdLinks
delDGLink ms t i dg2
DefLink -> delDef
HidingFreeOrCofreeThm {} -> delE dg
{- just delete the theorem link, we don't know what links can be
in the proof basis by the shifting rules -}
_ -> delDef -- delete other def links
updNodeMod :: NodeMod -> DGNodeLab -> DGNodeLab
updNodeMod m nl = nl { nodeMod = mergeNodeMod m $ nodeMod nl }
updDGNodeLab :: DGraph
-> DGNodeLab -- ^ old label
-> LNode DGNodeLab -- ^ node with new label
-> DGraph
updDGNodeLab dg l n = let
dg0 = changeDGH dg $ SetNodeLab l n
in togglePending dg0 $ changedLocalTheorems dg0 n
deleteDGNodeSens :: (forall a . Named a -> Bool) -> DGNodeLab
-> Result DGNodeLab
deleteDGNodeSens p nl = case dgn_theory nl of
G_theory lid s si sens _ ->
case OMap.partitionWithKey (\ n -> p . reName (const n)) sens of
(del, rest) -> let
es = OMap.elems del
chg | all isAxiom es = delAxMod
| all (not . isAxiom) es = delThMod
| otherwise = delSenMod
in if OMap.null del
then justWarn nl $ "no sentence deleted in: " ++ getDGNodeName nl
else return $ updNodeMod chg $ nl
{ dgn_theory = G_theory lid s si rest startThId }
invalidateDGLinkProof :: DGLinkLab -> DGLinkLab
invalidateDGLinkProof el = el { dgl_type = setProof LeftOpen $ dgl_type el }
invalDGLinkProof :: LEdge DGLinkLab -> [DGChange]
invalDGLinkProof e@(s, t, l) =
[DeleteEdge e, InsertEdge (s, t, invalidateDGLinkProof l)]
invalDGLinkProofs :: DGraph -> [LEdge DGLinkLab] -> DGraph
invalDGLinkProofs dg = changesDGH dg . concatMap invalDGLinkProof
{- | add a link supplying the necessary information.
Morphisms do not store source and target signatures. Only the source signature
is taken from the node. The induced signature of the morphism will be a
subsignature of the target signature.
- adding an (unproven) global theorem link:
this states that more theorems are supposed to hold in target nodes.
- adding a global definition link:
- the signature of the target is enlarged (Proofs remain valid).
- proven outgoing global theorem links for new ingoing definition links may
become unproven and incomplete
- outgoing local theorem links for new ingoing definition links add proof
obligations the target nodes of the local theorem links.
Additional theorems need to be moved or we mark the proven local theorem
link as incomplete.
The link type may also contain a conservativity and isn't easy to set up for
free and hiding links. The origin is again basically for documentation
purposes.
The returned edge-id will be new or an edge-id may be supplied as input. -}
addDGLink :: Node -> Node -> GMorphism -> DGLinkType -> DGLinkOrigin -> DGraph
-> (DGraph, EdgeId)
addDGLink = undefined
-- * modifying links
{- | Do we need functions to modify links?
Yes, later, for example, if a conservativity as part of the link type should
be set or changed.
Some link types contain proof information that needs to be kept up-to-date.
For example, a global theorem link will (after decomposition) refer to a local
theorem link and maybe another global theorem link. A local theorem link will
(after local inference) refer to (possibly renamed) theorems in the target
node.
Maybe some more thoughts are needed to decide which link type information may
be set or changed explicitely and which information should be adjusted
automatically. -}
modifyDGLinkType :: Node -> Node -> EdgeId -> DGLinkType -> DGraph -> DGraph
modifyDGLinkType = undefined
{- |
If the link morphism should change, this most likely (but not necessarily)
involves signature changes of the source or target node (or both nodes).
In the latter case, either the old link was invalidated before, by changing
the signature of the source or target node, or the modification of the link
will invalidate the contents of the source or target.
Instead of tricky morphism changes it may be better to simply delete old edges
and nodes and reinsert new nodes and edges propagating some old attributes. -}
modifyDGLinkMorphism :: Node -> Node -> EdgeId -> GMorphism -> DGraph -> DGraph
modifyDGLinkMorphism = undefined
-- | Modifying the documenting link origin should also be possible.
modifyDGLinkOrigin :: Node -> Node -> EdgeId -> DGLinkOrigin -> DGraph -> DGraph
modifyDGLinkOrigin = undefined
-- * modifying the signature of a node
{- | replace the signature of a node.
This function should be used as basis to add or delete symbols from a node.
Changing the signature means that the codomain of incoming and the domain of
outgoing links change. Therefore we would invalidate all attached links and
expect further link morphism modifications to adjust these links.
If the signature is not enlarged some local sentences may become invalid.
Therefore the class logic must supply a checking function that takes a
signature and a sentence and checks if the sentence is still well-formed
according to the given signature. A logic specific implementation my choose to
first extract all symbols from a sentence and compare it to the set of
signature symbols. (Extracting symbols from sentences is no method of the
class logic.)
Since there are functions to remove sentences explicitely, we leave it to the
user to remove sentences first before reducing or changing the signature and
simply fail if invalid sentences are left! -}
setSignature :: Node -> G_sign -> DGraph -> DGraph
setSignature = undefined
{- | delete symbols from a node's signature.
Deleting symbols is a special case of setting a node's signature. The new
signature is computed using the method for the co-generated signature that is
also used when symbols are hidden.
It is only checked that the symbol set difference of the new and old signature
corresponds to the supplied symbol set. (Alternatively it could be checked if
the new signature is a sub-signature of the old one.)
The target nodes of outgoing definition links will be adjusted according to
the reduced closed signature automatically.
Invalid sentences should have been removed before.
This function can be easily extended to delete raw symbol via the logic
specific matching between raw and signature symbols. -}
deleteSymbols :: Node -> Set.Set G_symbol -> DGraph -> DGraph
deleteSymbols = undefined
{- | extending a node's signature.
Adding symbols requires the new signature directly supplied as argument, since
the class logic supplies no way to extend a signature by a given set of
symbols. In fact symbols can only be extracted from a given signature.
It is only checked if the old signature is a sub-signature of the new one.
Sentences are not checked, because fully analyzed sentences are expected to
remain well-formed in an enlarged signature, although re-parsing and
type-checking may fail for the syntactic representation of these sentences.
It is, however, possible to extend a given signature by a basic spec as
happens for usual spec extensions, but note that the basic analysis may also
yield sentences that might need to be added separately.
Again target nodes of outgoing definition links will be adjusted
automatically. -}
extendSignature :: Node -> G_sign -> DGraph -> DGraph
extendSignature = undefined
-- * modifying local sentences of a node
{- | a logic independent sentence data type, yet missing in Logic.Grothendieck
Local sentences have been either directly added or have been inserted by
local inference. Sentences inserted by local inference should not be
manipulated at the target node but only at the original source. But maybe it
should be possible to delete such sentences explicitly to match the
corresponding deletion of the proven local theorem link? Alternatively a
function to undo a local inference step could be applied.
All sentences are uniquely named. User given duplicate names or missing names
are removed by generating unique names.
If additional sentences are added by local inference they may be
renamed to ensure unique names. The renaming is stored to keep the
correspondence to the original sentences.
The global theory of node should be computed if needed but is cached for
efficiency reason. It contains all sentences as axioms along incoming
definition links. All these axioms may be used to prove a theorem, assuming
that the used axioms are valid in their original theory.
So a change of a sentence may invalidate proofs in nodes reachable via theorem
or definition links. -}
data GSentence = GSentence
{- | delete the sentences that fulfill the given predicate.
Should this function fail if the predicate does not determine a unique
sentence? Surely, simply all sentences could be deleted fulfilling the
predicate (possibly none). -}
deleteSentence :: Node -> (Named GSentence -> Bool) -> DGraph -> Result DGraph
deleteSentence = undefined
{- | delete a sentence by name
This is a more efficient version of deleting a single sentence. All sentences
of one node have a unique name, but it may be a generated name that the user
needs to look up.
Only sentences not inserted by local inference can be deleted.
-}
deleteSentenceByName :: Node -> String -> DGraph -> DGraph
deleteSentenceByName = undefined
{- | add a sentence.
The unproven named sentence given as argument is added as new sentence. The
name must be different from those of all other sentences, including those
inserted by local inference.
Adding axioms will not invalidate proofs (if the logic is monotone), but the
addition may trigger the addition of theorems in a neighbor node if linked to
via a proven local theorem link. Theorems are not propagated further.
Sentences can not be added with some old proof, that could be retried by the
corresponding prover. -}
addSentence :: Node -> Named GSentence -> DGraph -> DGraph
addSentence = undefined
{- | It may be desirable to rename sentences or change there role (axiom or
theorem) and even to invalid but keep an old proof. -}
changeSentence :: Node -> (Named GSentence -> Named GSentence) -> DGraph
-> DGraph
changeSentence = undefined
| spechub/Hets | Static/ChangeGraph.hs | gpl-2.0 | 19,786 | 90 | 34 | 4,367 | 2,318 | 1,198 | 1,120 | 158 | 9 |
module S06_Ex1 where
{-
Module : S06_Ex1
Description : Series 06 of the Functionnal and Logic Programming course at UniFR
Author : Sylvain Julmy
Email : sylvain.julmy(at)unifr.ch
-}
-- imports for tests
import Test.QuickCheck
import Control.Monad
import qualified Data.List as L
import qualified Data.Set as S
-- Ex1.a
product' :: Num a => [a] -> a
product' [] = 1
product' (x:xs) = foldr (*) x xs
-- Ex1.b
flatten' :: [[a]] -> [a]
flatten' [] = []
flatten' xss = foldr (++) [] xss
-- Ex1.c
deleteAll :: Eq a => a -> [a] -> [a]
deleteAll elt xs = foldr (\v -> \acc -> if v == elt then acc else v:acc) [] xs
-- Ex1.d
allDifferent,allDifferent',allDifferent'',allDifferent''' :: Eq a => [a] -> Bool
allDifferent [] = True
allDifferent (x:xs) = if elem x xs then False else allDifferent xs
allDifferent' [] = True
allDifferent' (x:xs) = inner [x] xs where
inner :: Eq a => [a] -> [a] -> Bool
inner _ [] = True
inner presentValues (x:xs)
| elem x presentValues = False
| otherwise = inner (x:presentValues) xs
allDifferent'' xs = inner xs (\x -> x) where
inner :: Eq a => [a] -> (Bool -> Bool) -> Bool
inner [] cont = cont True
inner (x:xs) cont = inner xs (\n -> cont(n && (not (elem x xs))))
allDifferent''' xs = fst (foldr (
\v ->
\(b,ys) -> if b
then if elem v ys
then (False,[])
else (True,v:ys)
else (False,[])
)(True,[]) xs)
---------------
---- Tests ----
---------------
-- Function properties
prop_product :: (Num a, Eq a) => [a] -> Bool
prop_product xs = (product' xs) == (product xs)
prop_flatten :: Eq a => [[a]] -> Bool
prop_flatten xss = (flatten' xss) == (join xss)
prop_deleteAll :: Eq a => a -> [a] -> Bool
prop_deleteAll n xs = (deleteAll n xs) == (filter (\x -> x /= n) xs)
prop_allDifferent :: Eq a => [a] -> Bool
prop_allDifferent xs = do
let referenceValue = (L.nub xs) == xs
referenceValue == (allDifferent xs)
&& referenceValue == (allDifferent' xs)
&& referenceValue == (allDifferent'' xs)
&& referenceValue == (allDifferent''' xs)
-- run the tests using main
main = do
quickCheck (prop_product :: [Int] -> Bool)
quickCheck (prop_flatten :: [[Int]] -> Bool)
quickCheck (prop_flatten :: [[Char]] -> Bool)
quickCheck (prop_flatten :: [[String]] -> Bool)
quickCheck (prop_deleteAll :: Int -> [Int] -> Bool)
quickCheck (prop_deleteAll :: Char -> [Char] -> Bool)
quickCheck (prop_deleteAll :: String -> [String] -> Bool)
quickCheck (prop_allDifferent :: [Int] -> Bool)
quickCheck (prop_allDifferent :: [Char] -> Bool)
quickCheck (prop_allDifferent :: [String] -> Bool)
| SnipyJulmy/mcs_notes_and_resume | fun-and-log-prog/exercices/s06/s06_Julmy_Sylvain/ex1.hs | lgpl-3.0 | 2,781 | 0 | 16 | 724 | 1,103 | 594 | 509 | 59 | 3 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, BangPatterns
#-}
{-# OPTIONS_GHC -Wno-identities #-}
-- Whether there are identities depends on the platform
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.FD
-- Copyright : (c) The University of Glasgow, 1994-2008
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable
--
-- Raw read/write operations on file descriptors
--
-----------------------------------------------------------------------------
module GHC.IO.FD (
FD(..),
openFile, mkFD, release,
setNonBlockingMode,
readRawBufferPtr, readRawBufferPtrNoBlock, writeRawBufferPtr,
stdin, stdout, stderr
) where
import GHC.Base
import GHC.Num
import GHC.Real
import GHC.Show
import GHC.Enum
import GHC.IO
import GHC.IO.IOMode
import GHC.IO.Buffer
import GHC.IO.BufferedIO
import qualified GHC.IO.Device
import GHC.IO.Device (SeekMode(..), IODeviceType(..))
import GHC.Conc.IO
import GHC.IO.Exception
#ifdef mingw32_HOST_OS
import GHC.Windows
#endif
import Foreign
import Foreign.C
import qualified System.Posix.Internals
import System.Posix.Internals hiding (FD, setEcho, getEcho)
import System.Posix.Types
#ifdef mingw32_HOST_OS
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
c_DEBUG_DUMP :: Bool
c_DEBUG_DUMP = False
-- -----------------------------------------------------------------------------
-- The file-descriptor IO device
data FD = FD {
fdFD :: {-# UNPACK #-} !CInt,
#ifdef mingw32_HOST_OS
-- On Windows, a socket file descriptor needs to be read and written
-- using different functions (send/recv).
fdIsSocket_ :: {-# UNPACK #-} !Int
#else
-- On Unix we need to know whether this FD has O_NONBLOCK set.
-- If it has, then we can use more efficient routines to read/write to it.
-- It is always safe for this to be off.
fdIsNonBlocking :: {-# UNPACK #-} !Int
#endif
}
#ifdef mingw32_HOST_OS
fdIsSocket :: FD -> Bool
fdIsSocket fd = fdIsSocket_ fd /= 0
#endif
-- | @since 4.1.0.0
instance Show FD where
show fd = show (fdFD fd)
-- | @since 4.1.0.0
instance GHC.IO.Device.RawIO FD where
read = fdRead
readNonBlocking = fdReadNonBlocking
write = fdWrite
writeNonBlocking = fdWriteNonBlocking
-- | @since 4.1.0.0
instance GHC.IO.Device.IODevice FD where
ready = ready
close = close
isTerminal = isTerminal
isSeekable = isSeekable
seek = seek
tell = tell
getSize = getSize
setSize = setSize
setEcho = setEcho
getEcho = getEcho
setRaw = setRaw
devType = devType
dup = dup
dup2 = dup2
-- We used to use System.Posix.Internals.dEFAULT_BUFFER_SIZE, which is
-- taken from the value of BUFSIZ on the current platform. This value
-- varies too much though: it is 512 on Windows, 1024 on OS X and 8192
-- on Linux. So let's just use a decent size on every platform:
dEFAULT_FD_BUFFER_SIZE :: Int
dEFAULT_FD_BUFFER_SIZE = 8096
-- | @since 4.1.0.0
instance BufferedIO FD where
newBuffer _dev state = newByteBuffer dEFAULT_FD_BUFFER_SIZE state
fillReadBuffer fd buf = readBuf' fd buf
fillReadBuffer0 fd buf = readBufNonBlocking fd buf
flushWriteBuffer fd buf = writeBuf' fd buf
flushWriteBuffer0 fd buf = writeBufNonBlocking fd buf
readBuf' :: FD -> Buffer Word8 -> IO (Int, Buffer Word8)
readBuf' fd buf = do
when c_DEBUG_DUMP $
puts ("readBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")
(r,buf') <- readBuf fd buf
when c_DEBUG_DUMP $
puts ("after: " ++ summaryBuffer buf' ++ "\n")
return (r,buf')
writeBuf' :: FD -> Buffer Word8 -> IO (Buffer Word8)
writeBuf' fd buf = do
when c_DEBUG_DUMP $
puts ("writeBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")
writeBuf fd buf
-- -----------------------------------------------------------------------------
-- opening files
-- | Open a file and make an 'FD' for it. Truncates the file to zero
-- size when the `IOMode` is `WriteMode`.
openFile
:: FilePath -- ^ file to open
-> IOMode -- ^ mode in which to open the file
-> Bool -- ^ open the file in non-blocking mode?
-> IO (FD,IODeviceType)
openFile filepath iomode non_blocking =
withFilePath filepath $ \ f ->
let
oflags1 = case iomode of
ReadMode -> read_flags
WriteMode -> write_flags
ReadWriteMode -> rw_flags
AppendMode -> append_flags
#ifdef mingw32_HOST_OS
binary_flags = o_BINARY
#else
binary_flags = 0
#endif
oflags2 = oflags1 .|. binary_flags
oflags | non_blocking = oflags2 .|. nonblock_flags
| otherwise = oflags2
in do
-- the old implementation had a complicated series of three opens,
-- which is perhaps because we have to be careful not to open
-- directories. However, the man pages I've read say that open()
-- always returns EISDIR if the file is a directory and was opened
-- for writing, so I think we're ok with a single open() here...
fd <- throwErrnoIfMinus1Retry "openFile"
(if non_blocking then c_open f oflags 0o666
else c_safe_open f oflags 0o666)
(fD,fd_type) <- mkFD fd iomode Nothing{-no stat-}
False{-not a socket-}
non_blocking
`catchAny` \e -> do _ <- c_close fd
throwIO e
-- we want to truncate() if this is an open in WriteMode, but only
-- if the target is a RegularFile. ftruncate() fails on special files
-- like /dev/null.
when (iomode == WriteMode && fd_type == RegularFile) $
setSize fD 0
return (fD,fd_type)
std_flags, output_flags, read_flags, write_flags, rw_flags,
append_flags, nonblock_flags :: CInt
std_flags = o_NOCTTY
output_flags = std_flags .|. o_CREAT
read_flags = std_flags .|. o_RDONLY
write_flags = output_flags .|. o_WRONLY
rw_flags = output_flags .|. o_RDWR
append_flags = write_flags .|. o_APPEND
nonblock_flags = o_NONBLOCK
-- | Make a 'FD' from an existing file descriptor. Fails if the FD
-- refers to a directory. If the FD refers to a file, `mkFD` locks
-- the file according to the Haskell 2010 single writer/multiple reader
-- locking semantics (this is why we need the `IOMode` argument too).
mkFD :: CInt
-> IOMode
-> Maybe (IODeviceType, CDev, CIno)
-- the results of fdStat if we already know them, or we want
-- to prevent fdToHandle_stat from doing its own stat.
-- These are used for:
-- - we fail if the FD refers to a directory
-- - if the FD refers to a file, we lock it using (cdev,cino)
-> Bool -- ^ is a socket (on Windows)
-> Bool -- ^ is in non-blocking mode on Unix
-> IO (FD,IODeviceType)
mkFD fd iomode mb_stat is_socket is_nonblock = do
let _ = (is_socket, is_nonblock) -- warning suppression
(fd_type,dev,ino) <-
case mb_stat of
Nothing -> fdStat fd
Just stat -> return stat
let write = case iomode of
ReadMode -> False
_ -> True
case fd_type of
Directory ->
ioException (IOError Nothing InappropriateType "openFile"
"is a directory" Nothing Nothing)
-- regular files need to be locked
RegularFile -> do
-- On Windows we need an additional call to get a unique device id
-- and inode, since fstat just returns 0 for both.
(unique_dev, unique_ino) <- getUniqueFileInfo fd dev ino
r <- lockFile fd unique_dev unique_ino (fromBool write)
when (r == -1) $
ioException (IOError Nothing ResourceBusy "openFile"
"file is locked" Nothing Nothing)
_other_type -> return ()
#ifdef mingw32_HOST_OS
when (not is_socket) $ setmode fd True >> return ()
#endif
return (FD{ fdFD = fd,
#ifndef mingw32_HOST_OS
fdIsNonBlocking = fromEnum is_nonblock
#else
fdIsSocket_ = fromEnum is_socket
#endif
},
fd_type)
getUniqueFileInfo :: CInt -> CDev -> CIno -> IO (Word64, Word64)
#ifndef mingw32_HOST_OS
getUniqueFileInfo _ dev ino = return (fromIntegral dev, fromIntegral ino)
#else
getUniqueFileInfo fd _ _ = do
with 0 $ \devptr -> do
with 0 $ \inoptr -> do
c_getUniqueFileInfo fd devptr inoptr
liftM2 (,) (peek devptr) (peek inoptr)
#endif
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "__hscore_setmode"
setmode :: CInt -> Bool -> IO CInt
#endif
-- -----------------------------------------------------------------------------
-- Standard file descriptors
stdFD :: CInt -> FD
stdFD fd = FD { fdFD = fd,
#ifdef mingw32_HOST_OS
fdIsSocket_ = 0
#else
fdIsNonBlocking = 0
-- We don't set non-blocking mode on standard handles, because it may
-- confuse other applications attached to the same TTY/pipe
-- see Note [nonblock]
#endif
}
stdin, stdout, stderr :: FD
stdin = stdFD 0
stdout = stdFD 1
stderr = stdFD 2
-- -----------------------------------------------------------------------------
-- Operations on file descriptors
close :: FD -> IO ()
close fd =
do let closer realFd =
throwErrnoIfMinus1Retry_ "GHC.IO.FD.close" $
#ifdef mingw32_HOST_OS
if fdIsSocket fd then
c_closesocket (fromIntegral realFd)
else
#endif
c_close (fromIntegral realFd)
-- release the lock *first*, because otherwise if we're preempted
-- after closing but before releasing, the FD may have been reused.
-- (#7646)
release fd
closeFdWith closer (fromIntegral (fdFD fd))
release :: FD -> IO ()
release fd = do _ <- unlockFile (fdFD fd)
return ()
#ifdef mingw32_HOST_OS
foreign import WINDOWS_CCONV unsafe "HsBase.h closesocket"
c_closesocket :: CInt -> IO CInt
#endif
isSeekable :: FD -> IO Bool
isSeekable fd = do
t <- devType fd
return (t == RegularFile || t == RawDevice)
seek :: FD -> SeekMode -> Integer -> IO ()
seek fd mode off = do
throwErrnoIfMinus1Retry_ "seek" $
c_lseek (fdFD fd) (fromIntegral off) seektype
where
seektype :: CInt
seektype = case mode of
AbsoluteSeek -> sEEK_SET
RelativeSeek -> sEEK_CUR
SeekFromEnd -> sEEK_END
tell :: FD -> IO Integer
tell fd =
fromIntegral `fmap`
(throwErrnoIfMinus1Retry "hGetPosn" $
c_lseek (fdFD fd) 0 sEEK_CUR)
getSize :: FD -> IO Integer
getSize fd = fdFileSize (fdFD fd)
setSize :: FD -> Integer -> IO ()
setSize fd size = do
throwErrnoIf_ (/=0) "GHC.IO.FD.setSize" $
c_ftruncate (fdFD fd) (fromIntegral size)
devType :: FD -> IO IODeviceType
devType fd = do (ty,_,_) <- fdStat (fdFD fd); return ty
dup :: FD -> IO FD
dup fd = do
newfd <- throwErrnoIfMinus1 "GHC.IO.FD.dup" $ c_dup (fdFD fd)
return fd{ fdFD = newfd }
dup2 :: FD -> FD -> IO FD
dup2 fd fdto = do
-- Windows' dup2 does not return the new descriptor, unlike Unix
throwErrnoIfMinus1_ "GHC.IO.FD.dup2" $
c_dup2 (fdFD fd) (fdFD fdto)
return fd{ fdFD = fdFD fdto } -- original FD, with the new fdFD
setNonBlockingMode :: FD -> Bool -> IO FD
setNonBlockingMode fd set = do
setNonBlockingFD (fdFD fd) set
#if defined(mingw32_HOST_OS)
return fd
#else
return fd{ fdIsNonBlocking = fromEnum set }
#endif
ready :: FD -> Bool -> Int -> IO Bool
ready fd write msecs = do
r <- throwErrnoIfMinus1Retry "GHC.IO.FD.ready" $
fdReady (fdFD fd) (fromIntegral $ fromEnum $ write)
(fromIntegral msecs)
#if defined(mingw32_HOST_OS)
(fromIntegral $ fromEnum $ fdIsSocket fd)
#else
0
#endif
return (toEnum (fromIntegral r))
foreign import ccall safe "fdReady"
fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
-- ---------------------------------------------------------------------------
-- Terminal-related stuff
isTerminal :: FD -> IO Bool
isTerminal fd =
#if defined(mingw32_HOST_OS)
if fdIsSocket fd then return False
else is_console (fdFD fd) >>= return.toBool
#else
c_isatty (fdFD fd) >>= return.toBool
#endif
setEcho :: FD -> Bool -> IO ()
setEcho fd on = System.Posix.Internals.setEcho (fdFD fd) on
getEcho :: FD -> IO Bool
getEcho fd = System.Posix.Internals.getEcho (fdFD fd)
setRaw :: FD -> Bool -> IO ()
setRaw fd raw = System.Posix.Internals.setCooked (fdFD fd) (not raw)
-- -----------------------------------------------------------------------------
-- Reading and Writing
fdRead :: FD -> Ptr Word8 -> Int -> IO Int
fdRead fd ptr bytes
= do { r <- readRawBufferPtr "GHC.IO.FD.fdRead" fd ptr 0 (fromIntegral bytes)
; return (fromIntegral r) }
fdReadNonBlocking :: FD -> Ptr Word8 -> Int -> IO (Maybe Int)
fdReadNonBlocking fd ptr bytes = do
r <- readRawBufferPtrNoBlock "GHC.IO.FD.fdReadNonBlocking" fd ptr
0 (fromIntegral bytes)
case fromIntegral r of
(-1) -> return (Nothing)
n -> return (Just n)
fdWrite :: FD -> Ptr Word8 -> Int -> IO ()
fdWrite fd ptr bytes = do
res <- writeRawBufferPtr "GHC.IO.FD.fdWrite" fd ptr 0 (fromIntegral bytes)
let res' = fromIntegral res
if res' < bytes
then fdWrite fd (ptr `plusPtr` res') (bytes - res')
else return ()
-- XXX ToDo: this isn't non-blocking
fdWriteNonBlocking :: FD -> Ptr Word8 -> Int -> IO Int
fdWriteNonBlocking fd ptr bytes = do
res <- writeRawBufferPtrNoBlock "GHC.IO.FD.fdWriteNonBlocking" fd ptr 0
(fromIntegral bytes)
return (fromIntegral res)
-- -----------------------------------------------------------------------------
-- FD operations
-- Low level routines for reading/writing to (raw)buffers:
#ifndef mingw32_HOST_OS
{-
NOTE [nonblock]:
Unix has broken semantics when it comes to non-blocking I/O: you can
set the O_NONBLOCK flag on an FD, but it applies to the all other FDs
attached to the same underlying file, pipe or TTY; there's no way to
have private non-blocking behaviour for an FD. See bug #724.
We fix this by only setting O_NONBLOCK on FDs that we create; FDs that
come from external sources or are exposed externally are left in
blocking mode. This solution has some problems though. We can't
completely simulate a non-blocking read without O_NONBLOCK: several
cases are wrong here. The cases that are wrong:
* reading/writing to a blocking FD in non-threaded mode.
In threaded mode, we just make a safe call to read().
In non-threaded mode we call select() before attempting to read,
but that leaves a small race window where the data can be read
from the file descriptor before we issue our blocking read().
* readRawBufferNoBlock for a blocking FD
NOTE [2363]:
In the threaded RTS we could just make safe calls to read()/write()
for file descriptors in blocking mode without worrying about blocking
other threads, but the problem with this is that the thread will be
uninterruptible while it is blocked in the foreign call. See #2363.
So now we always call fdReady() before reading, and if fdReady
indicates that there's no data, we call threadWaitRead.
-}
readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int
readRawBufferPtr loc !fd !buf !off !len
| isNonBlocking fd = unsafe_read -- unsafe is ok, it can't block
| otherwise = do r <- throwErrnoIfMinus1 loc
(unsafe_fdReady (fdFD fd) 0 0 0)
if r /= 0
then read
else do threadWaitRead (fromIntegral (fdFD fd)); read
where
do_read call = fromIntegral `fmap`
throwErrnoIfMinus1RetryMayBlock loc call
(threadWaitRead (fromIntegral (fdFD fd)))
read = if threaded then safe_read else unsafe_read
unsafe_read = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)
safe_read = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)
-- return: -1 indicates EOF, >=0 is bytes read
readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int
readRawBufferPtrNoBlock loc !fd !buf !off !len
| isNonBlocking fd = unsafe_read -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 0 0 0
if r /= 0 then safe_read
else return 0
-- XXX see note [nonblock]
where
do_read call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))
case r of
(-1) -> return 0
0 -> return (-1)
n -> return (fromIntegral n)
unsafe_read = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)
safe_read = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)
writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtr loc !fd !buf !off !len
| isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 1 0 0
if r /= 0
then write
else do threadWaitWrite (fromIntegral (fdFD fd)); write
where
do_write call = fromIntegral `fmap`
throwErrnoIfMinus1RetryMayBlock loc call
(threadWaitWrite (fromIntegral (fdFD fd)))
write = if threaded then safe_write else unsafe_write
unsafe_write = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)
safe_write = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)
writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtrNoBlock loc !fd !buf !off !len
| isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block
| otherwise = do r <- unsafe_fdReady (fdFD fd) 1 0 0
if r /= 0 then write
else return 0
where
do_write call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))
case r of
(-1) -> return 0
n -> return (fromIntegral n)
write = if threaded then safe_write else unsafe_write
unsafe_write = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)
safe_write = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)
isNonBlocking :: FD -> Bool
isNonBlocking fd = fdIsNonBlocking fd /= 0
foreign import ccall unsafe "fdReady"
unsafe_fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
#else /* mingw32_HOST_OS.... */
readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
readRawBufferPtr loc !fd !buf !off !len
| threaded = blockingReadRawBufferPtr loc fd buf off len
| otherwise = asyncReadRawBufferPtr loc fd buf off len
writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtr loc !fd !buf !off !len
| threaded = blockingWriteRawBufferPtr loc fd buf off len
| otherwise = asyncWriteRawBufferPtr loc fd buf off len
readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
readRawBufferPtrNoBlock = readRawBufferPtr
writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
writeRawBufferPtrNoBlock = writeRawBufferPtr
-- Async versions of the read/write primitives, for the non-threaded RTS
asyncReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
asyncReadRawBufferPtr loc !fd !buf !off !len = do
(l, rc) <- asyncRead (fromIntegral (fdFD fd)) (fdIsSocket_ fd)
(fromIntegral len) (buf `plusPtr` off)
if l == (-1)
then
ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
else return (fromIntegral l)
asyncWriteRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
asyncWriteRawBufferPtr loc !fd !buf !off !len = do
(l, rc) <- asyncWrite (fromIntegral (fdFD fd)) (fdIsSocket_ fd)
(fromIntegral len) (buf `plusPtr` off)
if l == (-1)
then
ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
else return (fromIntegral l)
-- Blocking versions of the read/write primitives, for the threaded RTS
blockingReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt
blockingReadRawBufferPtr loc !fd !buf !off !len
= throwErrnoIfMinus1Retry loc $
if fdIsSocket fd
then c_safe_recv (fdFD fd) (buf `plusPtr` off) (fromIntegral len) 0
else c_safe_read (fdFD fd) (buf `plusPtr` off) (fromIntegral len)
blockingWriteRawBufferPtr :: String -> FD -> Ptr Word8-> Int -> CSize -> IO CInt
blockingWriteRawBufferPtr loc !fd !buf !off !len
= throwErrnoIfMinus1Retry loc $
if fdIsSocket fd
then c_safe_send (fdFD fd) (buf `plusPtr` off) (fromIntegral len) 0
else do
r <- c_safe_write (fdFD fd) (buf `plusPtr` off) (fromIntegral len)
when (r == -1) c_maperrno
return r
-- we don't trust write() to give us the correct errno, and
-- instead do the errno conversion from GetLastError()
-- ourselves. The main reason is that we treat ERROR_NO_DATA
-- (pipe is closing) as EPIPE, whereas write() returns EINVAL
-- for this case. We need to detect EPIPE correctly, because it
-- shouldn't be reported as an error when it happens on stdout.
-- NOTE: "safe" versions of the read/write calls for use by the threaded RTS.
-- These calls may block, but that's ok.
foreign import WINDOWS_CCONV safe "recv"
c_safe_recv :: CInt -> Ptr Word8 -> CInt -> CInt{-flags-} -> IO CInt
foreign import WINDOWS_CCONV safe "send"
c_safe_send :: CInt -> Ptr Word8 -> CInt -> CInt{-flags-} -> IO CInt
#endif
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
-- -----------------------------------------------------------------------------
-- utils
#ifndef mingw32_HOST_OS
throwErrnoIfMinus1RetryOnBlock :: String -> IO CSsize -> IO CSsize -> IO CSsize
throwErrnoIfMinus1RetryOnBlock loc f on_block =
do
res <- f
if (res :: CSsize) == -1
then do
err <- getErrno
if err == eINTR
then throwErrnoIfMinus1RetryOnBlock loc f on_block
else if err == eWOULDBLOCK || err == eAGAIN
then do on_block
else throwErrno loc
else return res
#endif
-- -----------------------------------------------------------------------------
-- Locking/unlocking
foreign import ccall unsafe "lockFile"
lockFile :: CInt -> Word64 -> Word64 -> CInt -> IO CInt
foreign import ccall unsafe "unlockFile"
unlockFile :: CInt -> IO CInt
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "get_unique_file_info"
c_getUniqueFileInfo :: CInt -> Ptr Word64 -> Ptr Word64 -> IO ()
#endif
| olsner/ghc | libraries/base/GHC/IO/FD.hs | bsd-3-clause | 23,295 | 3 | 17 | 5,971 | 4,300 | 2,238 | 2,062 | 319 | 5 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1993-1998
\section[TcAnnotations]{Typechecking annotations}
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
module TcAnnotations ( tcAnnotations, annCtxt ) where
import GhcPrelude
import {-# SOURCE #-} TcSplice ( runAnnotation )
import Module
import DynFlags
import Control.Monad ( when )
import HsSyn
import Name
import Annotations
import TcRnMonad
import SrcLoc
import Outputable
-- Some platforms don't support the external interpreter, and
-- compilation on those platforms shouldn't fail just due to
-- annotations
#ifndef GHCI
tcAnnotations :: [LAnnDecl GhcRn] -> TcM [Annotation]
tcAnnotations anns = do
dflags <- getDynFlags
case gopt Opt_ExternalInterpreter dflags of
True -> tcAnnotations' anns
False -> warnAnns anns
warnAnns :: [LAnnDecl GhcRn] -> TcM [Annotation]
--- No GHCI; emit a warning (not an error) and ignore. cf Trac #4268
warnAnns [] = return []
warnAnns anns@(L loc _ : _)
= do { setSrcSpan loc $ addWarnTc NoReason $
(text "Ignoring ANN annotation" <> plural anns <> comma
<+> text "because this is a stage-1 compiler without -fexternal-interpreter or doesn't support GHCi")
; return [] }
#else
tcAnnotations :: [LAnnDecl GhcRn] -> TcM [Annotation]
tcAnnotations = tcAnnotations'
#endif
tcAnnotations' :: [LAnnDecl GhcRn] -> TcM [Annotation]
tcAnnotations' anns = mapM tcAnnotation anns
tcAnnotation :: LAnnDecl GhcRn -> TcM Annotation
tcAnnotation (L loc ann@(HsAnnotation _ provenance expr)) = do
-- Work out what the full target of this annotation was
mod <- getModule
let target = annProvenanceToTarget mod provenance
-- Run that annotation and construct the full Annotation data structure
setSrcSpan loc $ addErrCtxt (annCtxt ann) $ do
-- See #10826 -- Annotations allow one to bypass Safe Haskell.
dflags <- getDynFlags
when (safeLanguageOn dflags) $ failWithTc safeHsErr
runAnnotation target expr
where
safeHsErr = vcat [ text "Annotations are not compatible with Safe Haskell."
, text "See https://ghc.haskell.org/trac/ghc/ticket/10826" ]
annProvenanceToTarget :: Module -> AnnProvenance Name
-> AnnTarget Name
annProvenanceToTarget _ (ValueAnnProvenance (L _ name)) = NamedTarget name
annProvenanceToTarget _ (TypeAnnProvenance (L _ name)) = NamedTarget name
annProvenanceToTarget mod ModuleAnnProvenance = ModuleTarget mod
annCtxt :: (SourceTextX p, OutputableBndrId p) => AnnDecl p -> SDoc
annCtxt ann
= hang (text "In the annotation:") 2 (ppr ann)
| ezyang/ghc | compiler/typecheck/TcAnnotations.hs | bsd-3-clause | 2,649 | 0 | 13 | 530 | 566 | 287 | 279 | 47 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Main (templates)
-- Copyright : (C) 2012-14 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This test suite validates that we are able to generate usable lenses with
-- template haskell.
--
-- The commented code summarizes what will be auto-generated below
-----------------------------------------------------------------------------
module Main where
import Control.Lens
-- import Test.QuickCheck (quickCheck)
import T799 ()
data Bar a b c = Bar { _baz :: (a, b) }
makeLenses ''Bar
checkBaz :: Iso (Bar a b c) (Bar a' b' c') (a, b) (a', b')
checkBaz = baz
data Quux a b = Quux { _quaffle :: Int, _quartz :: Double }
makeLenses ''Quux
checkQuaffle :: Lens (Quux a b) (Quux a' b') Int Int
checkQuaffle = quaffle
checkQuartz :: Lens (Quux a b) (Quux a' b') Double Double
checkQuartz = quartz
data Quark a = Qualified { _gaffer :: a }
| Unqualified { _gaffer :: a, _tape :: a }
makeLenses ''Quark
checkGaffer :: Lens' (Quark a) a
checkGaffer = gaffer
checkTape :: Traversal' (Quark a) a
checkTape = tape
data Hadron a b = Science { _a1 :: a, _a2 :: a, _c :: b }
makeLenses ''Hadron
checkA1 :: Lens' (Hadron a b) a
checkA1 = a1
checkA2 :: Lens' (Hadron a b) a
checkA2 = a2
checkC :: Lens (Hadron a b) (Hadron a b') b b'
checkC = c
data Perambulation a b
= Mountains { _terrain :: a, _altitude :: b }
| Beaches { _terrain :: a, _dunes :: a }
makeLenses ''Perambulation
checkTerrain :: Lens' (Perambulation a b) a
checkTerrain = terrain
checkAltitude :: Traversal (Perambulation a b) (Perambulation a b') b b'
checkAltitude = altitude
checkDunes :: Traversal' (Perambulation a b) a
checkDunes = dunes
makeLensesFor [("_terrain", "allTerrain"), ("_dunes", "allTerrain")] ''Perambulation
checkAllTerrain :: Traversal (Perambulation a b) (Perambulation a' b) a a'
checkAllTerrain = allTerrain
data LensCrafted a = Still { _still :: a }
| Works { _still :: a }
makeLenses ''LensCrafted
checkStill :: Lens (LensCrafted a) (LensCrafted b) a b
checkStill = still
data Task a = Task
{ taskOutput :: a -> IO ()
, taskState :: a
, taskStop :: IO ()
}
makeLensesFor [("taskOutput", "outputLens"), ("taskState", "stateLens"), ("taskStop", "stopLens")] ''Task
checkOutputLens :: Lens' (Task a) (a -> IO ())
checkOutputLens = outputLens
checkStateLens :: Lens' (Task a) a
checkStateLens = stateLens
checkStopLens :: Lens' (Task a) (IO ())
checkStopLens = stopLens
data Mono a = Mono { _monoFoo :: a, _monoBar :: Int }
makeClassy ''Mono
-- class HasMono t where
-- mono :: Simple Lens t Mono
-- instance HasMono Mono where
-- mono = id
checkMono :: HasMono t a => Lens' t (Mono a)
checkMono = mono
checkMono' :: Lens' (Mono a) (Mono a)
checkMono' = mono
checkMonoFoo :: HasMono t a => Lens' t a
checkMonoFoo = monoFoo
checkMonoBar :: HasMono t a => Lens' t Int
checkMonoBar = monoBar
data Nucleosis = Nucleosis { _nuclear :: Mono Int }
makeClassy ''Nucleosis
-- class HasNucleosis t where
-- nucleosis :: Simple Lens t Nucleosis
-- instance HasNucleosis Nucleosis
checkNucleosis :: HasNucleosis t => Lens' t Nucleosis
checkNucleosis = nucleosis
checkNucleosis' :: Lens' Nucleosis Nucleosis
checkNucleosis' = nucleosis
checkNuclear :: HasNucleosis t => Lens' t (Mono Int)
checkNuclear = nuclear
instance HasMono Nucleosis Int where
mono = nuclear
-- Dodek's example
data Foo = Foo { _fooX, _fooY :: Int }
makeClassy ''Foo
checkFoo :: HasFoo t => Lens' t Foo
checkFoo = foo
checkFoo' :: Lens' Foo Foo
checkFoo' = foo
checkFooX :: HasFoo t => Lens' t Int
checkFooX = fooX
checkFooY :: HasFoo t => Lens' t Int
checkFooY = fooY
data Dude a = Dude
{ dudeLevel :: Int
, dudeAlias :: String
, dudeLife :: ()
, dudeThing :: a
}
makeFields ''Dude
checkLevel :: HasLevel t a => Lens' t a
checkLevel = level
checkLevel' :: Lens' (Dude a) Int
checkLevel' = level
checkAlias :: HasAlias t a => Lens' t a
checkAlias = alias
checkAlias' :: Lens' (Dude a) String
checkAlias' = alias
checkLife :: HasLife t a => Lens' t a
checkLife = life
checkLife' :: Lens' (Dude a) ()
checkLife' = life
checkThing :: HasThing t a => Lens' t a
checkThing = thing
checkThing' :: Lens' (Dude a) a
checkThing' = thing
data Lebowski a = Lebowski
{ _lebowskiAlias :: String
, _lebowskiLife :: Int
, _lebowskiMansion :: String
, _lebowskiThing :: Maybe a
}
makeFields ''Lebowski
checkAlias2 :: Lens' (Lebowski a) String
checkAlias2 = alias
checkLife2 :: Lens' (Lebowski a) Int
checkLife2 = life
checkMansion :: HasMansion t a => Lens' t a
checkMansion = mansion
checkMansion' :: Lens' (Lebowski a) String
checkMansion' = mansion
checkThing2 :: Lens' (Lebowski a) (Maybe a)
checkThing2 = thing
type family Fam a
type instance Fam Int = String
data FamRec a = FamRec
{ _famRecThing :: Fam a
, _famRecUniqueToFamRec :: Fam a
}
makeFields ''FamRec
checkFamRecThing :: Lens' (FamRec a) (Fam a)
checkFamRecThing = thing
checkFamRecUniqueToFamRec :: Lens' (FamRec a) (Fam a)
checkFamRecUniqueToFamRec = uniqueToFamRec
checkFamRecView :: FamRec Int -> String
checkFamRecView = view thing
data AbideConfiguration a = AbideConfiguration
{ _acLocation :: String
, _acDuration :: Int
, _acThing :: a
}
makeLensesWith abbreviatedFields ''AbideConfiguration
checkLocation :: HasLocation t a => Lens' t a
checkLocation = location
checkLocation' :: Lens' (AbideConfiguration a) String
checkLocation' = location
checkDuration :: HasDuration t a => Lens' t a
checkDuration = duration
checkDuration' :: Lens' (AbideConfiguration a) Int
checkDuration' = duration
checkThing3 :: Lens' (AbideConfiguration a) a
checkThing3 = thing
dudeDrink :: String
dudeDrink = (Dude 9 "El Duderino" () "white russian") ^. thing
lebowskiCarpet :: Maybe String
lebowskiCarpet = (Lebowski "Mr. Lebowski" 0 "" (Just "carpet")) ^. thing
abideAnnoyance :: String
abideAnnoyance = (AbideConfiguration "the tree" 10 "the wind") ^. thing
declareLenses [d|
data Quark1 a = Qualified1 { gaffer1 :: a }
| Unqualified1 { gaffer1 :: a, tape1 :: a }
|]
-- data Quark1 a = Qualified1 a | Unqualified1 a a
checkGaffer1 :: Lens' (Quark1 a) a
checkGaffer1 = gaffer1
checkTape1 :: Traversal' (Quark1 a) a
checkTape1 = tape1
declarePrisms [d|
data Exp = Lit Int | Var String | Lambda { bound::String, body::Exp }
|]
-- data Exp = Lit Int | Var String | Lambda { bound::String, body::Exp }
checkLit :: Int -> Exp
checkLit = Lit
checkVar :: String -> Exp
checkVar = Var
checkLambda :: String -> Exp -> Exp
checkLambda = Lambda
check_Lit :: Prism' Exp Int
check_Lit = _Lit
check_Var :: Prism' Exp String
check_Var = _Var
check_Lambda :: Prism' Exp (String, Exp)
check_Lambda = _Lambda
declarePrisms [d|
data Banana = Banana Int String
|]
-- data Banana = Banana Int String
check_Banana :: Iso' Banana (Int, String)
check_Banana = _Banana
cavendish :: Banana
cavendish = _Banana # (4, "Cavendish")
data family Family a b c
#if __GLASGOW_HASKELL >= 706
declareLenses [d|
data instance Family Int (a, b) a = FamilyInt { fm0 :: (b, a), fm1 :: Int }
|]
-- data instance Family Int (a, b) a = FamilyInt a b
checkFm0 :: Lens (Family Int (a, b) a) (Family Int (a', b') a') (b, a) (b', a')
checkFm0 = fm0
checkFm1 :: Lens' (Family Int (a, b) a) Int
checkFm1 = fm1
#endif
class Class a where
data Associated a
method :: a -> Int
declareLenses [d|
instance Class Int where
data Associated Int = AssociatedInt { mochi :: Double }
method = id
|]
-- instance Class Int where
-- data Associated Int = AssociatedInt Double
-- method = id
checkMochi :: Iso' (Associated Int) Double
checkMochi = mochi
#if __GLASGOW_HASKELL__ >= 706
declareFields [d|
data DeclaredFields f a
= DeclaredField1 { declaredFieldsA0 :: f a , declaredFieldsB0 :: Int }
| DeclaredField2 { declaredFieldsC0 :: String , declaredFieldsB0 :: Int }
deriving (Show)
|]
checkA0 :: HasA0 t a => Traversal' t a
checkA0 = a0
checkB0 :: HasB0 t a => Lens' t a
checkB0 = b0
checkC0 :: HasC0 t a => Traversal' t a
checkC0 = c0
checkA0' :: Traversal' (DeclaredFields f a) (f a)
checkA0' = a0
checkB0' :: Lens' (DeclaredFields f a) Int
checkB0' = b0
checkC0' :: Traversal' (DeclaredFields f a) String
checkC0' = c0
#endif
declareFields [d|
data Aardvark = Aardvark { aardvarkAlbatross :: Int }
data Baboon = Baboon { baboonAlbatross :: Int }
|]
checkAardvark :: Lens' Aardvark Int
checkAardvark = albatross
checkBaboon :: Lens' Baboon Int
checkBaboon = albatross
data Rank2Tests
= C1 { _r2length :: forall a. [a] -> Int
, _r2nub :: forall a. Eq a => [a] -> [a]
}
| C2 { _r2length :: forall a. [a] -> Int }
makeLenses ''Rank2Tests
checkR2length :: Getter Rank2Tests ([a] -> Int)
checkR2length = r2length
checkR2nub :: Eq a => Fold Rank2Tests ([a] -> [a])
checkR2nub = r2nub
data PureNoFields = PureNoFieldsA | PureNoFieldsB { _pureNoFields :: Int }
makeLenses ''PureNoFields
data ReviewTest where ReviewTest :: a -> ReviewTest
makePrisms ''ReviewTest
-- test FieldNamers
data CheckUnderscoreNoPrefixNamer = CheckUnderscoreNoPrefixNamer
{ _fieldUnderscoreNoPrefix :: Int }
makeLensesWith (lensRules & lensField .~ underscoreNoPrefixNamer ) ''CheckUnderscoreNoPrefixNamer
checkUnderscoreNoPrefixNamer :: Lens' CheckUnderscoreNoPrefixNamer Int
checkUnderscoreNoPrefixNamer = fieldUnderscoreNoPrefix
-- how can we test NOT generating a lens for some fields?
data CheckMappingNamer = CheckMappingNamer
{ fieldMappingNamer :: String }
makeLensesWith (lensRules & lensField .~ (mappingNamer (return . ("hogehoge_" ++)))) ''CheckMappingNamer
checkMappingNamer :: Lens' CheckMappingNamer String
checkMappingNamer = hogehoge_fieldMappingNamer
data CheckLookingupNamer = CheckLookingupNamer
{ fieldLookingupNamer :: Int }
makeLensesWith (lensRules & lensField .~ (lookingupNamer [("fieldLookingupNamer", "foobarFieldLookingupNamer")])) ''CheckLookingupNamer
checkLookingupNamer :: Lens' CheckLookingupNamer Int
checkLookingupNamer = foobarFieldLookingupNamer
data CheckUnderscoreNamer = CheckUnderscoreNamer
{ _hogeprefix_fieldCheckUnderscoreNamer :: Int }
makeLensesWith (defaultFieldRules & lensField .~ underscoreNamer) ''CheckUnderscoreNamer
checkUnderscoreNamer :: Lens' CheckUnderscoreNamer Int
checkUnderscoreNamer = fieldCheckUnderscoreNamer
data CheckCamelCaseNamer = CheckCamelCaseNamer
{ _checkCamelCaseNamerFieldCamelCaseNamer :: Int }
makeLensesWith (defaultFieldRules & lensField .~ camelCaseNamer) ''CheckCamelCaseNamer
checkCamelCaseNamer :: Lens' CheckCamelCaseNamer Int
checkCamelCaseNamer = fieldCamelCaseNamer
data CheckAbbreviatedNamer = CheckAbbreviatedNamer
{ _hogeprefixFieldAbbreviatedNamer :: Int }
makeLensesWith (defaultFieldRules & lensField .~ abbreviatedNamer ) ''CheckAbbreviatedNamer
checkAbbreviatedNamer :: Lens' CheckAbbreviatedNamer Int
checkAbbreviatedNamer = fieldAbbreviatedNamer
-- Ensure that `makeClassyPrisms` doesn't generate a redundant catch-all case (#866)
data T866 = MkT866
$(makeClassyPrisms ''T866)
-- Ensure that `makeClassyPrisms` doesn't generate duplicate prism names for
-- data types that share a name with one of its constructors (#865)
data T865 = T865 | T865a | T865b T866
$(makeClassyPrisms ''T865)
instance AsT866 T865 where
_T866 = __T865 . _T866
main :: IO ()
main = putStrLn "test/templates.hs: ok"
| ddssff/lens | tests/templates.hs | bsd-3-clause | 12,128 | 0 | 12 | 2,395 | 3,146 | 1,719 | 1,427 | 263 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell, CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PatternGuards #-}
-- | Static file serving for WAI.
module Network.Wai.Application.Static
( -- * WAI application
staticApp
-- ** Default Settings
, defaultWebAppSettings
, webAppSettingsWithLookup
, defaultFileServerSettings
, embeddedSettings
-- ** Settings
, StaticSettings
, ssLookupFile
, ssMkRedirect
, ssGetMimeType
, ssListing
, ssIndices
, ssMaxAge
, ssRedirectToIndex
, ssAddTrailingSlash
, ss404Handler
) where
import Prelude hiding (FilePath)
import qualified Network.Wai as W
import qualified Network.HTTP.Types as H
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Char8 ()
import Control.Monad.IO.Class (liftIO)
import Data.ByteString.Builder (toLazyByteString)
import Data.FileEmbed (embedFile)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Network.HTTP.Date (parseHTTPDate, epochTimeToHTTPDate, formatHTTPDate)
import WaiAppStatic.Types
import Util
import WaiAppStatic.Storage.Filesystem
import WaiAppStatic.Storage.Embedded
import Network.Mime (MimeType)
data StaticResponse =
-- | Just the etag hash or Nothing for no etag hash
Redirect Pieces (Maybe ByteString)
| RawRedirect ByteString
| NotFound
| FileResponse File H.ResponseHeaders
| NotModified
-- TODO: add file size
| SendContent MimeType L.ByteString
| WaiResponse W.Response
safeInit :: [a] -> [a]
safeInit [] = []
safeInit xs = init xs
filterButLast :: (a -> Bool) -> [a] -> [a]
filterButLast _ [] = []
filterButLast _ [x] = [x]
filterButLast f (x:xs)
| f x = x : filterButLast f xs
| otherwise = filterButLast f xs
-- | Serve an appropriate response for a folder request.
serveFolder :: StaticSettings -> Pieces -> W.Request -> Folder -> IO StaticResponse
serveFolder StaticSettings {..} pieces req folder@Folder {..} =
case ssListing of
Just _ | Just path <- addTrailingSlash req, ssAddTrailingSlash ->
return $ RawRedirect path
Just listing -> do
-- directory listings turned on, display it
builder <- listing pieces folder
return $ WaiResponse $ W.responseBuilder H.status200
[ ("Content-Type", "text/html; charset=utf-8")
] builder
Nothing -> return $ WaiResponse $ W.responseLBS H.status403
[ ("Content-Type", "text/plain")
] "Directory listings disabled"
addTrailingSlash :: W.Request -> Maybe ByteString
addTrailingSlash req
| S8.null rp = Just "/"
| S8.last rp == '/' = Nothing
| otherwise = Just $ S8.snoc rp '/'
where
rp = W.rawPathInfo req
checkPieces :: StaticSettings
-> Pieces -- ^ parsed request
-> W.Request
-> IO StaticResponse
-- If we have any empty pieces in the middle of the requested path, generate a
-- redirect to get rid of them.
checkPieces _ pieces _ | any (T.null . fromPiece) $ safeInit pieces =
return $ Redirect (filterButLast (not . T.null . fromPiece) pieces) Nothing
checkPieces ss@StaticSettings {..} pieces req = do
res <- lookupResult
case res of
Left location -> return $ RawRedirect location
Right LRNotFound -> return NotFound
Right (LRFile file) -> serveFile ss req file
Right (LRFolder folder) -> serveFolder ss pieces req folder
where
lookupResult :: IO (Either ByteString LookupResult)
lookupResult = do
nonIndexResult <- ssLookupFile pieces
case nonIndexResult of
LRFile{} -> return $ Right nonIndexResult
_ -> do
eIndexResult <- lookupIndices (map (\ index -> dropLastIfNull pieces ++ [index]) ssIndices)
return $ case eIndexResult of
Left redirect -> Left redirect
Right indexResult -> case indexResult of
LRNotFound -> Right nonIndexResult
LRFile file | ssRedirectToIndex ->
let relPath =
case reverse pieces of
-- Served at root
[] -> fromPiece $ fileName file
lastSegment:_ ->
case fromPiece lastSegment of
-- Ends with a trailing slash
"" -> fromPiece $ fileName file
-- Lacks a trailing slash
lastSegment' -> T.concat
[ lastSegment'
, "/"
, fromPiece $ fileName file
]
in Left $ TE.encodeUtf8 relPath
_ -> Right indexResult
lookupIndices :: [Pieces] -> IO (Either ByteString LookupResult)
lookupIndices (x : xs) = do
res <- ssLookupFile x
case res of
LRNotFound -> lookupIndices xs
_ -> return $ case (ssAddTrailingSlash, addTrailingSlash req) of
(True, Just redirect) -> Left redirect
_ -> Right res
lookupIndices [] = return $ Right LRNotFound
serveFile :: StaticSettings -> W.Request -> File -> IO StaticResponse
serveFile StaticSettings {..} req file
-- First check etag values, if turned on
| ssUseHash = do
mHash <- fileGetHash file
case (mHash, lookup "if-none-match" $ W.requestHeaders req) of
-- if-none-match matches the actual hash, return a 304
(Just hash, Just lastHash) | hash == lastHash -> return NotModified
-- Didn't match, but we have a hash value. Send the file contents
-- with an ETag header.
--
-- RFC7232 (HTTP 1.1):
-- > A recipient MUST ignore If-Modified-Since if the request contains an
-- > If-None-Match header field; the condition in If-None-Match is
-- > considered to be a more accurate replacement for the condition in
-- > If-Modified-Since, and the two are only combined for the sake of
-- > interoperating with older intermediaries that might not implement
-- > If-None-Match.
(Just hash, _) -> respond [("ETag", hash)]
-- No hash value available, fall back to last modified support.
(Nothing, _) -> lastMod
-- etag turned off, so jump straight to last modified
| otherwise = lastMod
where
mLastSent = lookup "if-modified-since" (W.requestHeaders req) >>= parseHTTPDate
lastMod =
case (fmap epochTimeToHTTPDate $ fileGetModified file, mLastSent) of
-- File modified time is equal to the if-modified-since header,
-- return a 304.
--
-- Question: should the comparison be, date <= lastSent?
(Just mdate, Just lastSent)
| mdate == lastSent -> return NotModified
-- Did not match, but we have a new last-modified header
(Just mdate, _) -> respond [("last-modified", formatHTTPDate mdate)]
-- No modification time available
(Nothing, _) -> respond []
-- Send a file response with the additional weak headers provided.
respond headers = return $ FileResponse file $ cacheControl ssMaxAge headers
-- | Return a difference list of headers based on the specified MaxAge.
--
-- This function will return both Cache-Control and Expires headers, as
-- relevant.
cacheControl :: MaxAge -> (H.ResponseHeaders -> H.ResponseHeaders)
cacheControl maxage =
headerCacheControl . headerExpires
where
ccInt =
case maxage of
NoMaxAge -> Nothing
MaxAgeSeconds i -> Just i
MaxAgeForever -> Just oneYear
oneYear :: Int
oneYear = 60 * 60 * 24 * 365
headerCacheControl =
case ccInt of
Nothing -> id
Just i -> (:) ("Cache-Control", S8.append "public, max-age=" $ S8.pack $ show i)
headerExpires =
case maxage of
NoMaxAge -> id
MaxAgeSeconds _ -> id -- FIXME
MaxAgeForever -> (:) ("Expires", "Thu, 31 Dec 2037 23:55:55 GMT")
-- | Turn a @StaticSettings@ into a WAI application.
staticApp :: StaticSettings -> W.Application
staticApp set req = staticAppPieces set (W.pathInfo req) req
staticAppPieces :: StaticSettings -> [Text] -> W.Application
staticAppPieces _ _ req sendResponse
| notElem (W.requestMethod req) ["GET", "HEAD"] = sendResponse $ W.responseLBS
H.status405
[("Content-Type", "text/plain")]
"Only GET or HEAD is supported"
staticAppPieces _ [".hidden", "folder.png"] _ sendResponse = sendResponse $ W.responseLBS H.status200 [("Content-Type", "image/png")] $ L.fromChunks [$(embedFile "images/folder.png")]
staticAppPieces _ [".hidden", "haskell.png"] _ sendResponse = sendResponse $ W.responseLBS H.status200 [("Content-Type", "image/png")] $ L.fromChunks [$(embedFile "images/haskell.png")]
staticAppPieces ss rawPieces req sendResponse = liftIO $ do
case toPieces rawPieces of
Just pieces -> checkPieces ss pieces req >>= response
Nothing -> sendResponse $ W.responseLBS H.status403
[ ("Content-Type", "text/plain")
] "Forbidden"
where
response :: StaticResponse -> IO W.ResponseReceived
response (FileResponse file ch) = do
mimetype <- ssGetMimeType ss file
-- let filesize = fileGetSize file
let headers = ("Content-Type", mimetype)
-- Let Warp provide the content-length, since it takes
-- range requests into account
-- : ("Content-Length", S8.pack $ show filesize)
: ch
sendResponse $ fileToResponse file H.status200 headers
response NotModified =
sendResponse $ W.responseLBS H.status304 [] ""
response (SendContent mt lbs) = do
-- TODO: set caching headers
sendResponse $ W.responseLBS H.status200
[ ("Content-Type", mt)
-- TODO: set Content-Length
] lbs
response (Redirect pieces' mHash) = do
let loc = ssMkRedirect ss pieces' $ L.toStrict $ toLazyByteString (H.encodePathSegments $ map fromPiece pieces')
let qString = case mHash of
Just hash -> replace "etag" (Just hash) (W.queryString req)
Nothing -> remove "etag" (W.queryString req)
sendResponse $ W.responseLBS H.status302
[ ("Content-Type", "text/plain")
, ("Location", S8.append loc $ H.renderQuery True qString)
] "Redirect"
response (RawRedirect path) =
sendResponse $ W.responseLBS H.status302
[ ("Content-Type", "text/plain")
, ("Location", path)
] "Redirect"
response NotFound = case (ss404Handler ss) of
Just app -> app req sendResponse
Nothing -> sendResponse $ W.responseLBS H.status404
[ ("Content-Type", "text/plain")
] "File not found"
response (WaiResponse r) = sendResponse r
| kazu-yamamoto/wai | wai-app-static/Network/Wai/Application/Static.hs | mit | 11,673 | 3 | 35 | 3,694 | 2,599 | 1,348 | 1,251 | 207 | 13 |
{- |
Module : $Header$
Description : Definition of Dependency Graph with utils
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Definition of Dependency Graph and utils to be applied to dependency stores
-}
module CSL.DependencyGraph
where
import Common.Doc
import Common.DocUtils
import CSL.AS_BASIC_CSL
import CSL.ASUtils
import CSL.Sign as Sign
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Maybe
-- * Dependency Graph datatype for various algorithms on Dependency Graphs
data DepGraph a b c = DepGraph
{ dataMap :: Map.Map a
( b -- the annotation
, Set.Set a -- the direct successors (smaller elements)
, Set.Set c -- the direct predecessors (bigger elements)
)
{- function returning for a given element and value the predecessors
of this element -}
, getPredecessors :: a -> b -> [c]
{- function returning for a given element and value the predecessors
of this element -}
, getKey :: c -> a
}
instance (Show a, Show b, Show c) => Show (DepGraph a b c) where
show = show . dataMap
depGraphLookup :: Ord a =>
DepGraph a b c -> a -> Maybe (b, Set.Set a, Set.Set c)
depGraphLookup gr x = Map.lookup x $ dataMap gr
prettyDepGraph :: (a -> Doc) -> (b -> Doc) -> (c -> Doc) -> DepGraph a b c
-> Doc
prettyDepGraph pa pb pc gr =
ppMap pa pf ((text "DepGraph" <+>) . braces) vcat f $ dataMap gr where
f a b = a <> text ":" <+> b
pf (v, dss, dps) =
ps pa dss <+> text " << x << " <+> ps pc dps <> text ":" <+> pb v
ps g = braces . (sepByCommas . map g) . Set.toList
instance (Pretty a, Pretty b, Pretty c) => Pretty (DepGraph a b c) where
pretty = prettyDepGraph pretty pretty pretty
emptyDepGraph :: (a -> b -> [c]) -> (c -> a) -> DepGraph a b c
emptyDepGraph f pf = DepGraph { dataMap = Map.empty, getPredecessors = f
, getKey = pf }
{- TODO: merge the type Rel2 and DepGraph in order to work only on the
new type, and implement a construction of this graph from a list
without the necessity to order the elements first. -}
{- | It is important to have the elements given in an order with
biggest elements first (elements which depend on nothing) -}
depGraphFromDescList :: (Ord a, Ord c) => (a -> b -> [c]) ->
(c -> a) -> [(a, b)] -> DepGraph a b c
depGraphFromDescList f pf = foldl g (emptyDepGraph f pf) where
g x (y, z) = updateGraph x y z
maybeSetUnions :: Ord a => Set.Set (Maybe (Set.Set a)) -> Set.Set a
maybeSetUnions = Set.fold f Set.empty where
f mS s' = maybe s' (Set.union s') mS
upperLevel :: (Ord a, Ord c) => DepGraph a b c -> Set.Set a -> Set.Set c
upperLevel gr = maybeSetUnions . Set.map f where
f a = fmap g $ Map.lookup a $ dataMap gr
g (_, _, dps) = dps
lowerLevel :: Ord a => DepGraph a b c -> [a] -> Set.Set a
lowerLevel gr = Set.unions . mapMaybe f where
f a = fmap g $ Map.lookup a $ dataMap gr
g (_, dss, _) = dss
setFilterLookup :: (Ord a, Ord b, Ord d, Show a) =>
(d -> a) -- ^ projection function
-> (a -> b -> Bool) -- ^ filter predicate
-> DepGraph a b c -- ^ dependency graph for lookup
-> Set.Set d -- ^ filter this set
-> Set.Set (d, b)
setFilterLookup pf fp gr s = Set.map h $ Set.filter g $ Set.map f s where
f x = (x, fmap ( \ (v, _, _) -> v ) $ Map.lookup (pf x) $ dataMap gr)
g (x, Just val) = fp (pf x) val
g _ = False
h (x, Just val) = (x, val)
h _ = error "setFilterLookup: Impossible case"
lowerUntil :: (Pretty a, Ord a, Ord b, Show a) =>
(a -> b -> Bool) -- ^ cut-off predicate
-> DepGraph a b c -- ^ dependency graph to be traversed
-> [a] -- ^ compare entries to this element
-> Set.Set (a, b)
lowerUntil _ _ [] = Set.empty
lowerUntil cop gr al =
let s = lowerLevel gr al
cop' x = not . cop x
s' = setFilterLookup id cop' gr s
s'' = lowerUntil cop gr $ map fst $ Set.toList s'
in Set.union s' s''
upperUntil :: (Ord a, Ord b, Ord c, Show a) =>
(a -> b -> Bool) -- ^ cut-off predicate
-> DepGraph a b c -- ^ dependency graph to be traversed
-> Set.Set a -- ^ compare entries to these elements
-> Set.Set (c, b)
upperUntil cop gr es
| Set.null es = Set.empty
| otherwise =
let s = upperLevel gr es
cop' x = not . cop x
s' = setFilterLookup (getKey gr) cop' gr s
s'' = upperUntil cop gr $ Set.map (getKey gr . fst) s'
in Set.union s' s''
-- | Reflexive version of 'upperUntil'
upperUntilRefl :: (Ord a, Ord b, Show a) =>
(a -> b -> Bool) -- ^ cut-off predicate
-> DepGraph a b a -- ^ dependency graph to be traversed
-> Set.Set a -- ^ compare entries to these elements
-> Set.Set (a, b)
upperUntilRefl cop gr es
| Set.null es = Set.empty
| otherwise =
Set.union (setFilterLookup (getKey gr) (const $ const True) gr es)
$ upperUntil cop gr es
{- | Updates the depgraph at the given key with the update function.
The dependencies are NOT recomputed. No new elements are added to the graph. -}
updateValue :: Ord a => DepGraph a b c -> (b -> b) -> a -> DepGraph a b c
updateValue gr uf key = gr { dataMap = Map.adjust uf' key $ dataMap gr } where
uf' (x, y, z) = (uf x, y, z)
{- | Updates the depgraph at the given key with the new value.
The dependencies are recomputed. If the key does not exist in the graph
it is added to the graph. -}
updateGraph :: (Ord a, Ord c) => DepGraph a b c -> a -> b -> DepGraph a b c
updateGraph gr key val =
-- update the pred-set of all smaller entries
let (mOv, nm) = Map.insertLookupWithKey f key nval $ dataMap gr
npl = getPredecessors gr key val
nval = (val, Set.empty, Set.fromList npl)
f _ (v', _, nps) (_, oss, _) = (v', oss, nps)
nm' = case mOv of
Just (_, _, ops) ->
Set.fold rmFromSucc nm ops
_ -> nm
rmFromSucc c = Map.adjust g1 (getKey gr c)
g1 (x, dss, dps) = (x, Set.delete key dss, dps)
nm'' = foldl insSucc nm' npl
insSucc m c = Map.adjust g2 (getKey gr c) m
g2 (x, dss, dps) = (x, Set.insert key dss, dps)
in gr { dataMap = nm'' }
data DepGraphAnno a = DepGraphAnno
{ annoDef :: AssDefinition
, annoVal :: a } deriving (Show, Eq, Ord)
instance Pretty a => Pretty (DepGraphAnno a) where
pretty (DepGraphAnno { annoDef = def, annoVal = av }) =
braces $ pretty def <> text ":" <+> pretty av
type AssignmentDepGraph a =
DepGraph ConstantName (DepGraphAnno a) ConstantName
assDepGraphFromDescList :: (ConstantName -> AssDefinition -> a)
-> [(ConstantName, AssDefinition)]
-> AssignmentDepGraph a
assDepGraphFromDescList f l = depGraphFromDescList getPs id $ map g l where
g (cn, ad) = (cn, DepGraphAnno { annoDef = ad, annoVal = f cn ad })
getPs _ = map SimpleConstant . Set.toList . setOfUserDefined . getDefiniens
. annoDef
| mariefarrell/Hets | CSL/DependencyGraph.hs | gpl-2.0 | 7,415 | 0 | 14 | 2,238 | 2,492 | 1,296 | 1,196 | 130 | 3 |
module Yi.Event
(
Event(..), prettyEvent,
Key(..), Modifier(..),
-- * Key codes
eventToChar
) where
import Data.Bits (setBit)
import Data.Char (chr, ord)
data Modifier = MShift | MCtrl | MMeta | MSuper | MHyper
deriving (Show,Eq,Ord)
data Key = KEsc | KFun Int | KPrtScr | KPause | KASCII Char | KBS | KIns
| KHome | KPageUp | KDel | KEnd | KPageDown | KNP5 | KUp | KMenu
| KLeft | KDown | KRight | KEnter | KTab deriving (Eq,Show,Ord)
data Event = Event Key [Modifier] deriving (Eq)
instance Ord Event where
compare (Event k1 m1) (Event k2 m2) = compare m1 m2 `mappend` compare k1 k2
-- so, all Ctrl+char, meta+char, etc. all form a continuous range
instance Show Event where
show = prettyEvent
prettyEvent :: Event -> String
prettyEvent (Event k mods) =
concatMap ((++ "-") . prettyModifier) mods ++ prettyKey k
where prettyKey (KFun i) = 'F' : show i
prettyKey (KASCII c) = [c]
prettyKey key = tail $ show key
prettyModifier m = [ show m !! 1]
-- | Map an Event to a Char. This is used in the emacs keymap for Ctrl-Q and vim keymap 'insertSpecialChar'
eventToChar :: Event -> Char
eventToChar (Event KEnter _) = '\CR'
eventToChar (Event KEsc _) = '\ESC'
eventToChar (Event KBS _) = '\127'
eventToChar (Event KTab _) = '\t'
eventToChar (Event (KASCII c) mods) = (if MMeta `elem` mods then setMeta else id) $
(if MCtrl `elem` mods then ctrlLowcase else id) c
eventToChar _ev = '?'
remapChar :: Char -> Char -> Char -> Char -> Char -> Char
remapChar a1 b1 a2 _ c
| a1 <= c && c <= b1 = chr $ ord c - ord a1 + ord a2
| otherwise = c
ctrlLowcase :: Char -> Char
ctrlLowcase = remapChar 'a' 'z' '\^A' '\^Z'
-- set the meta bit, as if Mod1/Alt had been pressed
setMeta :: Char -> Char
setMeta c = chr (setBit (ord c) metaBit)
metaBit :: Int
metaBit = 7
| siddhanathan/yi | yi-core/src/Yi/Event.hs | gpl-2.0 | 1,954 | 0 | 10 | 541 | 684 | 373 | 311 | 42 | 3 |
module Main (main) where
main :: IO ()
main = putStrLn "Hello World"
| urbanslug/ghc | testsuite/tests/driver/dynHelloWorld.hs | bsd-3-clause | 71 | 0 | 6 | 15 | 27 | 15 | 12 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Data.IORef
import qualified Graphics.UI.FLTK.LowLevel.FL as FL
import Graphics.UI.FLTK.LowLevel.Fl_Enumerations
import Graphics.UI.FLTK.LowLevel.Fl_Types
import Graphics.UI.FLTK.LowLevel.FLTKHS
import qualified Data.Text as T
maxCols, maxRows :: Int
maxCols = 26
maxRows = 500
data SpreadsheetProperties =
SpreadsheetProperties
{
rowEdit :: Int
, colEdit :: Int
, sLeftTop :: TableCoordinate
, sRightBottom :: TableCoordinate
, values :: [[Int]]
}
setIndex :: Int -> (a -> a) -> [a] -> [a]
setIndex idx' f xs =
map
(
\(i,e) -> if (i == idx')
then f e
else e
)
(zip [0..] xs)
setValueHide :: IORef SpreadsheetProperties -> Ref Table -> Ref Input -> IO ()
setValueHide sp' table' intInput' = do
props' <- readIORef sp'
inputValue' <- getValue intInput' >>= return . read . T.unpack
let updatedValues' = setIndex
(rowEdit props')
(setIndex
(colEdit props')
(const inputValue'))
(values props')
updatedProperties' = props' {
values = updatedValues'
}
writeIORef sp' updatedProperties'
hide intInput'
window' <- getWindow table'
maybe (return ()) (\w' -> setCursor w' CursorDefault ) window'
startEditing :: IORef SpreadsheetProperties -> Ref Input -> Ref Table -> TableCoordinate -> IO ()
startEditing props' intInput' table' (TableCoordinate (Row row') (Column col')) = do
modifyIORef props' (\p' -> p' {rowEdit = row', colEdit = col'})
_p <- readIORef props'
setSelection table'
(TableCoordinate (Row (rowEdit _p)) (Column (colEdit _p)))
(TableCoordinate (Row (rowEdit _p)) (Column (colEdit _p)))
rectangle' <- findCell table' ContextCell (TableCoordinate (Row (rowEdit _p)) (Column (colEdit _p)))
case rectangle' of
Just rect' -> do
resize intInput' rect'
let cellContents = (values _p) !! (rowEdit _p) !! (colEdit _p)
_ <- setValue intInput' (T.pack (show cellContents))
_ <- setPosition intInput' 0 (Just (length $ show cellContents))
showWidget intInput'
_ <- takeFocus intInput'
return ()
_ -> return ()
doneEditing :: IORef SpreadsheetProperties -> Ref Input -> Ref Table -> IO ()
doneEditing props' intInput' table' = do
_p <- readIORef props'
visible' <- getVisible intInput'
if visible'
then setValueHide props' table' intInput'
else return ()
eventCallback :: IORef SpreadsheetProperties -> Ref Input -> Ref Table -> IO ()
eventCallback props' intInput' table' = do
_p <- readIORef props'
(Row r') <- callbackRow table'
(Column c') <- callbackCol table'
context' <- callbackContext table'
(Rows numRows') <- getRows table'
(Columns numCols') <- getCols table'
case context' of
ContextCell -> do
event' <- FL.event
case event' of
Push -> do
doneEditing props' intInput' table'
if (r' /= (numRows' -1) && c' /= (numCols' -1))
then startEditing props' intInput' table' (TableCoordinate (Row r') (Column c'))
else return ()
return ()
Keydown -> do
eventKey' <- FL.eventKey
if (eventKey' == (SpecialKeyType Kb_Escape))
then return ()
else if (r' == numRows' - 1 || c' == numCols' -1)
then return ()
else do
doneEditing props' intInput' table'
setSelection table' (TableCoordinate (Row r') (Column c')) (TableCoordinate (Row r') (Column c'))
startEditing props' intInput' table' (TableCoordinate (Row r') (Column c'))
newEvent <- FL.event
if (newEvent == Keydown)
then handle intInput' newEvent >> return ()
else return ()
return ()
_ -> return ()
_c -> if (any (== _c) [ContextTable, ContextRowHeader, ContextColHeader])
then doneEditing props' intInput' table'
else return ()
setBySlider :: Ref ValueSlider -> Ref Table -> (Ref Table -> Int -> IO ()) -> IO ()
setBySlider slider' table' f = do
v' <- getValue slider'
f table' (truncate $ v'+1)
redraw table'
setColsCb :: Ref Table -> Ref ValueSlider -> IO ()
setColsCb table' slider' = do
v' <- getValue slider'
setCols table' (Columns (truncate (v' + 1)))
redraw table'
setRowsCb :: Ref Table -> Ref ValueSlider -> IO ()
setRowsCb table' slider' = do
v' <- getValue slider'
setRows table' (Rows (truncate (v' + 1)))
redraw table'
drawCell :: IORef SpreadsheetProperties -> Ref Input -> Ref Table -> TableContext -> TableCoordinate -> Rectangle -> IO ()
drawCell props' intInput' table' context' (TableCoordinate (Row row') (Column col')) rectangle' = do
_p <- readIORef props'
(Rows numRows') <- getRows table'
(Columns numCols') <- getCols table'
case context' of
ContextStartPage -> do
(p1,p2) <- getSelection table'
modifyIORef props' (\p -> p {sLeftTop = p1, sRightBottom = p2})
ContextColHeader -> do
flcSetFont helveticaBold (FontSize 14)
flcPushClip rectangle'
getColHeaderColor table' >>= flcDrawBox ThinUpBox rectangle'
flcSetColor blackColor
if (col' == numCols' - 1)
then flcDrawInBox "TOTAL" rectangle' alignCenter Nothing Nothing
else flcDrawInBox (T.pack [toEnum $ fromEnum 'A' + col']) rectangle' alignCenter Nothing Nothing
flcPopClip
ContextRowHeader -> do
flcSetFont helveticaBold (FontSize 14)
flcPushClip rectangle'
getRowHeaderColor table' >>= flcDrawBox ThinUpBox rectangle'
flcSetColor blackColor
if (row' == numRows' - 1)
then flcDrawInBox "TOTAL" rectangle' alignCenter Nothing Nothing
else flcDrawInBox (T.pack (show $ row' + 1)) rectangle' alignCenter Nothing Nothing
flcPopClip
ContextCell-> do
visible' <- getVisible intInput'
let (TableCoordinate (Row sTop') (Column sLeft')) = sLeftTop _p
(TableCoordinate (Row sBottom') (Column sRight')) = sRightBottom _p
if (row' == (rowEdit _p) && col' == (colEdit _p) && visible')
then return ()
else do
if (row' >= sTop' && row' <= sBottom' && col' >= sLeft' && col' <= sRight')
then flcDrawBox ThinUpBox rectangle' yellowColor
else if (col' < numCols' - 1 && row' < numRows' - 1)
then do
selected' <- isSelected table' (TableCoordinate (Row row') (Column col'))
flcDrawBox ThinUpBox rectangle' (if selected' then yellowColor else whiteColor)
else flcDrawBox ThinUpBox rectangle' (Color 0xbbddbb00)
flcPushClip rectangle'
flcSetColor blackColor
if (col' == numCols' - 1 || row' == numRows' - 1)
then do
flcSetFont helveticaBold (FontSize 14)
let shownValues = map (take (numCols'- 1)) $ take (numRows' -1) (values _p)
let s' = if (col' == numCols' - 1 && row' == numRows' - 1)
then (show . sum . map sum) shownValues
else if (col' == numCols' - 1)
then (show $ sum $ shownValues !! row')
else if (row' == numRows' - 1)
then (show . sum . map (\r -> r !! col')) shownValues
else ""
let (x',y',w',h') = fromRectangle rectangle'
flcDrawInBox (T.pack s') (toRectangle (x'+3,y'+3,w'-6,h'-6)) alignRight Nothing Nothing
else do
flcSetFont helvetica (FontSize 14)
let s' = show $ (values _p) !! row' !! col'
let (x',y',w',h') = fromRectangle rectangle'
flcDrawInBox (T.pack s') (toRectangle (x'+3,y'+3,w'-6,h'-6)) alignRight Nothing Nothing
flcPopClip
ContextRCResize -> do
visible' <- getVisible intInput'
if (not visible')
then return ()
else do
cellRectangle' <- findCell table' ContextTable (TableCoordinate (Row row') (Column col'))
case cellRectangle' of
Just cr' -> if (cr' == rectangle')
then return ()
else resize intInput' cr'
Nothing -> return ()
_ -> return ()
main :: IO ()
main = do
FL.setOption FL.OptionArrowFocus True
win' <- doubleWindowNew
(Size (Width 922) (Height 382))
Nothing
(Just "Fl_Table Spreadsheet with Keyboard Navigation")
(Width winWidth') <- getW win'
(Height winHeight') <- getH win'
let values' =
map
(\r' ->
map
(\c' -> (r'+2) * (c'+3))
[0 .. (maxCols -1)]
)
[0.. (maxRows - 1)]
props' <- newIORef $
SpreadsheetProperties
0
0
(TableCoordinate (Row 0) (Column 0))
(TableCoordinate (Row 0) (Column 0))
values'
let tableWidth' = winWidth' - 80
tableHeight' = winHeight' - 80
intInput' <- inputNew
(toRectangle
(
(truncate $ ((fromIntegral tableWidth' / 2) :: Double)),
(truncate $ ((fromIntegral tableHeight' / 2) :: Double)),
0,
0
)
)
Nothing
(Just FlIntInput)
hide intInput'
setWhen intInput' [WhenEnterKeyAlways]
setMaximumSize intInput' 5
spreadsheet' <- tableCustom
(toRectangle (20,20,tableWidth', tableHeight'))
Nothing
Nothing
(drawCell props' intInput')
defaultCustomWidgetFuncs
defaultCustomTableFuncs
whens' <- getWhen spreadsheet'
setWhen spreadsheet' $ [WhenNotChanged] ++ whens'
setSelection spreadsheet' (TableCoordinate (Row 0) (Column 0)) (TableCoordinate (Row 0) (Column 0))
setCallback intInput' (setValueHide props' spreadsheet')
setCallback spreadsheet' (eventCallback props' intInput')
setTooltip spreadsheet' "Use keyboard to navigate cells:\n Arrow keys or Tab/Shift-Tab"
-- Table rows
setRowHeader spreadsheet' True
setRowHeaderWidth spreadsheet' 70
setRowResize spreadsheet' True
setRows spreadsheet' (Rows 11)
setRowHeightAll spreadsheet' 25
-- Table cols
setColHeader spreadsheet' True
setColHeaderHeight spreadsheet' 25
setColResize spreadsheet' True
setCols spreadsheet' (Columns 11)
setColWidthAll spreadsheet' 70
begin win'
-- Rows slider
setRows' <- valueSliderNew (toRectangle (winWidth'-40,20,20,winHeight'-80)) Nothing
setType setRows' VertNiceSliderType
bounds setRows' 2 (fromIntegral maxRows)
setStep setRows' 1
(Rows numRows') <- getRows spreadsheet'
_ <- setValue setRows' (fromIntegral $ numRows'-1)
setCallback setRows' (setRowsCb spreadsheet')
setWhen setRows' [WhenChanged]
clearVisibleFocus setRows'
-- Cols slider
setCols' <- valueSliderNew (toRectangle (20,winHeight'-40,winWidth'-80,20)) Nothing
setType setCols' HorNiceSliderType
bounds setCols' 2 (fromIntegral maxCols)
setStep setCols' 1
(Columns numCols') <- getCols spreadsheet'
_ <- setValue setCols' (fromIntegral $ numCols'-1)
setCallback setCols' (setColsCb spreadsheet')
setWhen setCols' [WhenChanged]
clearVisibleFocus setCols'
end win'
setResizable win' (Just spreadsheet')
showWidget win'
_ <- FL.run
return ()
| deech/fltkhs-demos | src/Examples/table-spreadsheet-with-keyboard-nav.hs | mit | 11,763 | 0 | 30 | 3,550 | 3,877 | 1,879 | 1,998 | 278 | 19 |
module Backend.Code
( Code
, new
, parse
, ParseError(..)
) where
import Backend.Prelude
import Backend.Random (HasRandom)
import qualified Backend.Random as Random
import qualified Data.Text as Text
import Data.Vector ((!))
import qualified Data.Vector as V
import Text.Read (Read(..))
-- | Random 8-character code using 32 unambiguous characters
--
-- See http://www.crockford.com/base32.html. We're not encoding
-- anything, just trying to make semi-readable non-numeric ids.
--
newtype Code = Code Text
deriving newtype (Eq, Show, Ord, Hashable, ToJSON, ToHttpApiData, PersistField, PersistFieldSql)
-- | Throws on invalid 'Code's; used only for testing
instance IsString Code where
fromString = either (error . unpack . textDisplay) id . parse . fromString
-- | Errors encountered during parsing
data ParseError
= -- | Code must be 8 characters long
WrongLength Text
| -- | Code must only consist of characters from 'alphabet'
UnrecognizedCharacters Text
deriving stock (Eq, Show)
instance Display ParseError where
display = \case
WrongLength text -> "wrong length for code: " <> display text
UnrecognizedCharacters text ->
"unrecognized characters in code: " <> display text
instance PathPiece Code where
toPathPiece = coerce
fromPathPiece = hush . parse
instance FromHttpApiData Code where
parseUrlPiece = first textDisplay . parse
instance FromJSON Code where
parseJSON =
withText "Code" $ either (fail . unpack . textDisplay) pure . parse
instance Read Code where
readsPrec _ = either mempty ok . parse . pack where ok code = [(code, "")]
-- | Generate a new random 'Code'
new :: forall env . HasRandom env => RIO env Code
new = Code . pack <$> replicateM size char
where char = (alphabet !) <$> Random.range (0, lastIndex)
-- | Parse 'Code' from 'Text'
parse :: Text -> Either ParseError Code
parse raw
| Text.length upper /= size = Left $ WrongLength raw
| Text.any (`notElem` alphabet) upper = Left $ UnrecognizedCharacters raw
| otherwise = pure $ Code upper
where upper = Text.toUpper raw
-- | Set of allowed characters
--
-- NOINLINE - compute once and store as a CAF.
alphabet :: Vector Char
alphabet = V.fromList $ ['0' .. '9'] <> filter unambiguous ['A' .. 'Z']
where unambiguous = (`notElem` ("ILOU" :: String))
{-# NOINLINE alphabet #-}
-- | Last valid index into 'alphabet'
--
-- NOINLINE - compute once and store as a CAF.
lastIndex :: Int
lastIndex = V.length alphabet - 1
{-# NOINLINE lastIndex #-}
-- | 'Code' is always 8 characters long
size :: Int
size = 8
| cdparks/lambda-machine | backend/src/Backend/Code.hs | mit | 2,569 | 0 | 11 | 489 | 650 | 361 | 289 | -1 | -1 |
{-# htermination showsPrec :: Show a => Int -> [a] -> String -> String #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_showsPrec_4.hs | mit | 75 | 0 | 2 | 15 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Jolly.Types.Infer
( inferTop
, Constraint
, Subst(..)
, TypeError(..)
) where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Jolly.Syntax.Types
import Jolly.Types.Env
import Jolly.Types.System
-- Infer contains the state and errors encountered
-- during the inference process
type Infer a = (ReaderT TypeEnv (StateT InferState (Except TypeError)) a)
newtype InferState = InferState
{ count :: Int
}
initInfer :: InferState
initInfer = InferState {count = 0}
type Constraint = (Type, Type)
type Unifier = (Subst, [Constraint])
type Solve a = ExceptT TypeError Identity a
-- Substitution
newtype Subst =
Subst (Map.Map TVar Type)
deriving (Eq, Ord, Show, Monoid)
class Substitutable a where
apply :: Subst -> a -> a
ftv :: a -> Set.Set TVar
instance Substitutable Type where
apply _ (TCon a) = TCon a
apply (Subst s) t@(TVar a) = Map.findWithDefault t a s
apply s (t1 `TArr` t2) = apply s t1 `TArr` apply s t2
ftv TCon {} = Set.empty
ftv (TVar a) = Set.singleton a
ftv (t1 `TArr` t2) = ftv t1 `Set.union` ftv t2
instance Substitutable Scheme where
apply (Subst s) (Forall as t) = Forall as $ apply s' t
where
s' = Subst $ foldr Map.delete s as
ftv (Forall as t) = ftv t `Set.difference` Set.fromList as
instance Substitutable Constraint where
apply s (t1, t2) = (apply s t1, apply s t2)
ftv (t1, t2) = ftv t1 `Set.union` ftv t2
instance Substitutable a => Substitutable [a] where
apply = fmap . apply
ftv = foldr (Set.union . ftv) Set.empty
instance Substitutable TypeEnv where
apply s (TypeEnv env) = TypeEnv $ Map.map (apply s) env
ftv (TypeEnv env) = ftv $ Map.elems env
data TypeError
= UnificationFail Type
Type
| InfiniteType TVar
Type
| UnboundVariable String
| Ambiguous [Constraint]
| UnificationMismatch [Type]
[Type]
runInfer ::
TypeEnv
-> Infer (Type, [Constraint])
-> Either TypeError (Type, [Constraint])
runInfer env m = runExcept $ evalStateT (runReaderT m env) initInfer
inferExpr :: TypeEnv -> Expr -> Either TypeError Scheme
inferExpr env ex =
case runInfer env (infer ex) of
Left err -> Left err
Right (ty, cs) ->
case runSolve cs of
Left err -> Left err
Right subst -> Right $ closeOver $ apply subst ty
constraintsExpr ::
TypeEnv -> Expr -> Either TypeError ([Constraint], Subst, Type, Scheme)
constraintsExpr env ex =
case runInfer env (infer ex) of
Left err -> Left err
Right (ty, cs) ->
case runSolve cs of
Left err -> Left err
Right subst -> Right (cs, subst, ty, sc)
where sc = closeOver $ apply subst ty
closeOver :: Type -> Scheme
closeOver = normalize . generalize emptyTypeEnv
inEnv :: (Name, Scheme) -> Infer a -> Infer a
inEnv (x, sc) m = do
let scope e = remove e x `extend` (x, sc)
local scope m
lookupEnv :: Name -> Infer Type
lookupEnv x = do
(TypeEnv env) <- ask
case Map.lookup x env of
Nothing -> throwError $ UnboundVariable x
Just s -> instantiate s
letters :: [String]
letters = [1 ..] >>= flip replicateM ['a' .. 'z']
fresh :: Infer Type
fresh = do
s <- get
put s {count = count s + 1}
return $ TVar $ TV (letters !! count s)
instantiate :: Scheme -> Infer Type
instantiate (Forall as t) = do
as' <- mapM (const fresh) as
let s = Subst $ Map.fromList $ zip as as'
return $ apply s t
generalize :: TypeEnv -> Type -> Scheme
generalize env t = Forall as t
where
as = Set.toList $ ftv t `Set.difference` ftv env
ops :: BinOp -> Type
ops Add = typeInt `TArr` (typeInt `TArr` typeInt)
ops Mul = typeInt `TArr` (typeInt `TArr` typeInt)
ops Sub = typeInt `TArr` (typeInt `TArr` typeInt)
ops Eql = typeInt `TArr` (typeInt `TArr` typeBool)
-- TODO: These case statements could be combined
infer :: Expr -> Infer (Type, [Constraint])
infer expr =
case expr of
Lit (LInt _) -> return (typeInt, [])
Lit (LBool _) -> return (typeBool, [])
Var x -> do
t <- lookupEnv x
return (t, [])
Lam x e -> do
tv <- fresh
(t, c) <- inEnv (x, Forall [] tv) (infer e)
return (tv `TArr` t, c)
App e1 e2 -> do
(t1, c1) <- infer e1
(t2, c2) <- infer e2
tv <- fresh
return (tv, c1 ++ c2 ++ [(t1, t2 `TArr` tv)])
Let x e1 e2 -> do
(t1, c1) <- infer e1
env <- ask
case runSolve c1 of
Left err -> throwError err
Right sub -> do
let sc = generalize (apply sub env) (apply sub t1)
(t2, c2) <- inEnv (x, sc) $ local (apply sub) (infer e2)
return (t2, c1 ++ c2)
Fix e -> do
(t, c) <- infer e
tv <- fresh
return (tv, c ++ [(tv `TArr` tv, t)])
Op op lhs rhs -> do
(t1, c1) <- infer lhs
(t2, c2) <- infer rhs
tv <- fresh
let u1 = t1 `TArr` (t2 `TArr` tv)
u2 = ops op
return (tv, c1 ++ c2 ++ [(u1, u2)])
If cond tr fl -> do
(t1, c1) <- infer cond
(t2, c2) <- infer tr
(t3, c3) <- infer fl
return (t2, c1 ++ c2 ++ c3 ++ [(t1, typeBool), (t2, t3)])
inferTop :: TypeEnv -> [(String, Expr)] -> Either TypeError TypeEnv
inferTop env [] = Right env
inferTop env ((name, ex):xs) =
case inferExpr env ex of
Left err -> Left err
Right ty -> inferTop (extend env (name, ty)) xs
normalize :: Scheme -> Scheme
normalize (Forall _ body) = Forall (map snd ord) (normtype body)
where
ord = zip (List.nub $ fv body) (map TV letters)
fv (TVar a) = [a]
fv (TArr a b) = fv a ++ fv b
fv (TCon _) = []
normtype (TArr a b) = TArr (normtype a) (normtype b)
normtype (TCon a) = TCon a
normtype (TVar a) =
case Prelude.lookup a ord of
Just x -> TVar x
Nothing -> error "type variable not in signature"
-- Constraint Solver
emptySubst :: Subst
emptySubst = mempty
compose :: Subst -> Subst -> Subst
(Subst s1) `compose` (Subst s2) =
Subst $ Map.map (apply (Subst s1)) s2 `Map.union` s1
runSolve :: [Constraint] -> Either TypeError Subst
runSolve cs = runIdentity $ runExceptT $ solver st
where
st = (emptySubst, cs)
unifyMany :: [Type] -> [Type] -> Solve Subst
unifyMany [] [] = return emptySubst
unifyMany (t1:ts1) (t2:ts2) = do
su1 <- unifies t1 t2
su2 <- unifyMany (apply su1 ts1) (apply su1 ts2)
return (su2 `compose` su1)
unifyMany t1 t2 = throwError $ UnificationMismatch t1 t2
unifies :: Type -> Type -> Solve Subst
unifies t1 t2
| t1 == t2 = return emptySubst
unifies (TVar v) t = v `bind` t
unifies t (TVar v) = v `bind` t
unifies (TArr t1 t2) (TArr t3 t4) = unifyMany [t1, t2] [t3, t4]
unifies t1 t2 = throwError $ UnificationFail t1 t2
solver :: Unifier -> Solve Subst
solver (su, cs) =
case cs of
[] -> return su
((t1, t2):cs0) -> do
su1 <- unifies t1 t2
solver (su1 `compose` su, apply su1 cs0)
bind :: TVar -> Type -> Solve Subst
bind a t
| t == TVar a = return emptySubst
| occursCheck a t = throwError $ InfiniteType a t
| otherwise = return (Subst $ Map.singleton a t)
occursCheck :: Substitutable a => TVar -> a -> Bool
occursCheck a t = a `Set.member` ftv t
| jchildren/jolly | src/Jolly/Types/Infer.hs | mit | 7,547 | 0 | 20 | 2,061 | 3,279 | 1,694 | 1,585 | 212 | 10 |
{-# OPTIONS -XFlexibleContexts #-}
module ChordHist (
chordHist
) where
import Data.Bifunctor (bimap)
import Data.Char (ord, isAlpha, toLower)
import qualified Data.ListLike as LL
import qualified Data.Map.Lazy as M
import Data.Monoid (Monoid(..))
import Text.Printf (printf)
newtype ChordHist = CH (M.Map (Char, Char) Int)
instance Monoid ChordHist where
mempty = CH $ M.fromList [((a, b), 0) | a <- ['a'..'z'], b <- ['a'..'z'], a < b]
mappend (CH a) (CH b) = CH $ M.unionWith (+) a b
instance Show ChordHist where
show (CH m) =
let show' (c1, c2) cnt = printf "%d %c%c" cnt c1 c2
in unlines . M.elems . M.mapWithKey show' $ m
bimap1 f = bimap f f
andTup2 (True, True) = True
andTup2 _ = False
pairs :: LL.ListLike l e => l -> [(e, e)]
pairs l
| LL.null l = []
| otherwise = pairs' [] (LL.head l) (LL.tail l)
where
pairs' res e l
| LL.null l = res
| otherwise =
let (e', l') = (LL.head l, LL.tail l)
in pairs' ((e, e'):res) e' l'
hist :: (Ord e, LL.ListLike l e) => l -> [(e, Int)]
hist l
| LL.null l = []
| otherwise = let l' = LL.sort l in hist' [] (LL.head l') 1 (LL.tail l')
where
hist' res e cnt l
| LL.null l = (e, cnt) : res
| otherwise =
let (e', l') = (LL.head l, LL.tail l)
in if e == e'
then hist' res e (cnt+1) l'
else hist' ((e, cnt) : res) e' 1 l'
chordHist :: LL.ListLike str Char => str -> ChordHist
chordHist =
CH . M.fromList . hist . normalize . pairs
where
normalize = map (arrange . bimap1 toLower) . filter (andTup2 . bimap1 isChord)
arrange p@(a, b)
| b < a = (b, a)
| otherwise = p
isChord ch = ord ch < 0x80 && isAlpha ch
| saidie/key_chord_count | src/ChordHist.hs | mit | 1,699 | 0 | 14 | 462 | 872 | 452 | 420 | -1 | -1 |
{-# LANGUAGE ViewPatterns #-}
{-@ LIQUID "--no-termination" @-}
module InTex where
import Text.Pandoc.JSON
import Text.Pandoc
import Data.Char (isSpace)
import Data.List
import Data.Monoid (mempty)
import Debug.Trace
import Text.Printf (printf)
main :: IO ()
main = toJSONFilter readFootnotes
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
-- readFootnotes :: Inline -> Inline
-- readFootnotes (footnoteText -> Just args) = RawInline (Format "tex") res
-- where
-- parsed = writeLaTeX def . readMarkdown def
-- res = fnString ++ parsed args ++ "}"
-- readFootnotes (Span (id,["footnotetext"],_) is) = RawInline (Format "tex") tex
-- where
-- tex = fnString ++ writeLaTeX def para ++ "}"
-- para = Pandoc mempty [Para is]
readFootnotes (Div (id, [cls], _) bs)
| cls `elem` mydivs = RawBlock (Format "tex") $ toLaTeX cls id bs
readFootnotes i = i
toLaTeX cls id = wrapLatex cls id . writeLaTeX def . Pandoc mempty
wrapLatex "footnotetext" _ str = printf "\\footnotetext{%s}" str
wrapLatex "hwex" name str = printf "\\begin{hwex}[%s]\n%s\n\\end{hwex}" name str
wrapLatex cls name str = error $ printf "WrapLatex: %s %s" cls name
mydivs = ["footnotetext", "hwex"]
-- fnString = "\\footnotetext{"
-- footnoteText :: Inline -> Maybe String
-- footnoteText (RawInline (Format "tex") s) =
-- if fnString `isPrefixOf` s
-- then Just . safeInit . drop (length fnString) $ s -- Remove closing brace
-- else Nothing
--
-- footnoteText x = Nothing
-----------------------------------------------------------------------------------------
safeInit [] = []
safeInit xs = init xs
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-- main = toJSONFilter txBlock
-- bb = CodeBlock ("",["sourceCode","literate","haskell"],[]) "ranjit :: Int\nranjit = 12 + flibbertypopp \n\nflibbertypopp :: Int\nflibbertypopp = 42"
txBlock :: Maybe Format -> Block -> [Block]
txBlock _ cb@(CodeBlock _ _) = expandCodeBlock cb
txBlock _ b = [b]
expandCodeBlock :: Block -> [Block]
expandCodeBlock (CodeBlock a s) = CodeBlock a `fmap` words s
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
data Token = Word String | WhiteSpace String deriving (Eq, Ord, Show)
stringTokens :: String -> [Token]
stringTokens s = go [] s
where
go acc "" = reverse acc
go acc s = let (w, s') = span (not . isSpace) s
(sp, s'') = span (isSpace) s'
in
go ((WhiteSpace sp) : (Word w) : acc) s''
tokensString :: [Token] -> String
tokensString = concat . map tokenString
tokenString :: Token -> String
tokenString (Word s) = s
tokenString (WhiteSpace s) = s
| UCSD-PL/230-web | templates/inside.hs | mit | 3,865 | 0 | 14 | 671 | 615 | 337 | 278 | 38 | 2 |
module Chapter09.And where
-- list, and, True iff no values are False
and' :: [Bool] -> Bool
and' [] = True
and' (b:bools) =
b && and' bools
-- True if any are True
or' :: [Bool] -> Bool
or' [] = False
or' (b:bools) =
b || or' bools
-- returns True if any value applied
-- to f returned True
any' :: (a -> Bool) -> [a] -> Bool
any' _ [] = False
any' f (x:xs) =
f x || any' f xs
-- returns True if one of the values
-- in [a] matches a
elem' :: Eq a => a -> [a] -> Bool
elem' _ [] = False
elem' m (x:xs) =
m == x || elem' m xs
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) =
reverse' xs ++ [x]
-- flatten list of lists into list
squish' :: [[a]] -> [a]
squish' [] = []
squish' (x:xs) =
x ++ squish' xs
-- maps a function over a list
-- and concatenates the results
squishMap :: (a -> [b]) -> [a] -> [b]
squishMap _ [] = []
squishMap f (x:xs) =
f x ++ squishMap f xs
-- flattens a list of lists into a list
-- reuse squishMap
squishAgain :: [[a]] -> [a]
squishAgain [] = []
squishAgain (x:xs) =
squishMap (\x -> [x]) x ++ squishAgain xs
-- why so stuck on this?
-- every other it was clear what we were operating on
-- for some reason the description of the problem was
-- super odd and I can't figure out how to vary
-- what's passed to the compare AND there are very
-- few compare functions in the first place that
-- return Ordering AND I couldn't explain why
-- the second example should work
-- what if we recurse, chaining on the second param?
-- myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
-- myMaximumBy f (x:[]) = x
-- myMaximumBy f (x:xs) =
-- f x $ myMaximumBy f xs
-- myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
-- -- how do we produce a something (a) from nothing ([])?
---- myMaximumBy _ [] = []
-- myMaximumBy _ (x:[]) = x
---- myMaximumBy f (x:y:xs) =
---- let larger = if (f x y == GT) then x else y in
---- larger
---- myMaximumBy f (x:y:xs) =
-- myMaximumBy f (x:xs) =
-- let largest = filter (\item -> if (f item x == GT) then item else x) xs
--
---- let larger = if (f x y == GT) then x else y in
---- larger
--
--
--
---- myMaximumBy f (larger:xs)
--
----
-- myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
-- myMaximumBy :: f xs =
-- head $ filter (\i
--
--
----
----
----
----
--
--
--
--
--
--
| brodyberg/LearnHaskell | HaskellProgramming.hsproj/Chapter09/And.hs | mit | 2,449 | 0 | 9 | 704 | 525 | 305 | 220 | 33 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Presenters.TaskList
( TaskList(..)
) where
import Data.Aeson
import Presenters.UniqueTask
import Presenters.RecurringTask
data TaskList = TaskList
{ uniqueTasks :: [UniqueTask]
, recurringTasks :: [RecurringTask]
}
instance ToJSON TaskList where
toJSON (TaskList ut rt) =
object [ "uniqueTasks" .= ut
, "recurringTasks" .= rt
]
| ostapneko/stld2 | src/main/Presenters/TaskList.hs | mit | 473 | 0 | 9 | 151 | 99 | 58 | 41 | 13 | 0 |
-- Copyright (c) 1999 Chris Okasaki.
-- See COPYRIGHT file for terms and conditions.
module Data.Edison.Test.Bag where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import qualified Prelude
import qualified Data.List as List -- not ListSeq!
import Test.QuickCheck hiding( (===) )
import Test.HUnit (Test(..))
import Data.Edison.Prelude
import Data.Edison.Coll
import Data.Edison.Test.Utils
import qualified Data.Edison.Seq.ListSeq as L
import Data.Edison.Seq.JoinList (Seq)
import qualified Data.Edison.Seq.JoinList as S
--------------------------------------------------------------
-- Bag implementations to test
import qualified Data.Edison.Coll.LazyPairingHeap as LPH
import qualified Data.Edison.Coll.LeftistHeap as LH
import qualified Data.Edison.Coll.SkewHeap as SkH
import qualified Data.Edison.Coll.SplayHeap as SpH
import qualified Data.Edison.Coll.MinHeap as Min
---------------------------------------------------------------
-- A utility classe to propigate class contexts down
-- to the quick check properties
class (Eq (bag a), Arbitrary (bag a),
Show (bag a), Read (bag a),
OrdColl (bag a) a) => BagTest a bag
instance (Ord a, Show a, Read a, Arbitrary a) => BagTest a LPH.Heap
instance (Ord a, Show a, Read a, Arbitrary a) => BagTest a LH.Heap
instance (Ord a, Show a, Read a, Arbitrary a) => BagTest a SkH.Heap
instance (Ord a, Show a, Read a, Arbitrary a) => BagTest a SpH.Heap
instance (Ord a, Show a, Read a, Arbitrary a, BagTest a bag)
=> BagTest a (Min.Min (bag a))
--------------------------------------------------------------
-- List all permutations of bag types to test
allBagTests :: Test
allBagTests = TestList
[ bagTests (empty :: Ord a => LPH.Heap a)
, bagTests (empty :: Ord a => Min.Min (LPH.Heap a) a)
, bagTests (empty :: Ord a => LH.Heap a)
, bagTests (empty :: Ord a => Min.Min (LH.Heap a) a)
, bagTests (empty :: Ord a => SkH.Heap a)
, bagTests (empty :: Ord a => Min.Min (SkH.Heap a) a)
, bagTests (empty :: Ord a => SpH.Heap a)
, bagTests (empty :: Ord a => Min.Min (SpH.Heap a) a)
, bagTests (empty :: Ord a => Min.Min (Min.Min (LPH.Heap a) a) a)
]
---------------------------------------------------------------
-- List all the tests to run for each type
bagTests bag = TestLabel ("Bag test "++(instanceName bag)) . TestList $
[ qcTest $ prop_single bag
, qcTest $ prop_fromSeq bag
, qcTest $ prop_insert bag
, qcTest $ prop_insertSeq bag
, qcTest $ prop_union bag
, qcTest $ prop_unionSeq bag
, qcTest $ prop_delete bag
, qcTest $ prop_deleteAll bag
, qcTest $ prop_deleteSeq bag
, qcTest $ prop_null_size bag -- 10
, qcTest $ prop_member_count bag
, qcTest $ prop_toSeq bag
, qcTest $ prop_lookup bag
, qcTest $ prop_fold bag
, qcTest $ prop_strict_fold bag
, qcTest $ prop_filter_partition bag
, qcTest $ prop_deleteMin_Max bag
, qcTest $ prop_unsafeInsertMin_Max bag
, qcTest $ prop_unsafeFromOrdSeq bag
, qcTest $ prop_filter bag -- 20
, qcTest $ prop_partition bag
, qcTest $ prop_minView_maxView bag
, qcTest $ prop_minElem_maxElem bag
, qcTest $ prop_foldr_foldl bag
, qcTest $ prop_strict_foldr_foldl bag
, qcTest $ prop_foldr1_foldl1 bag
, qcTest $ prop_strict_foldr1_foldl1 bag
, qcTest $ prop_toOrdSeq bag
, qcTest $ prop_unsafeAppend bag
, qcTest $ prop_unsafeMapMonotonic bag -- 30
, qcTest $ prop_read_show bag
, qcTest $ prop_strict bag
]
----------------------------------------------------
-- utility operations
lmerge :: [Int] -> [Int] -> [Int]
lmerge xs [] = xs
lmerge [] ys = ys
lmerge xs@(x:xs') ys@(y:ys')
| x <= y = x : lmerge xs' ys
| otherwise = y : lmerge xs ys'
(===) :: (Eq (bag a),CollX (bag a) a) => bag a -> bag a -> Bool
(===) b1 b2 =
structuralInvariant b1
&&
structuralInvariant b2
&&
b1 == b2
si :: CollX (bag a) a => bag a -> Bool
si = structuralInvariant
-----------------------------------------------------
-- CollX operations
prop_single :: BagTest Int bag => bag Int -> Int -> Bool
prop_single bag x =
let xs = singleton x `asTypeOf` bag
in si xs
&&
toOrdList xs == [x]
prop_fromSeq :: BagTest Int bag => bag Int -> Seq Int -> Bool
prop_fromSeq bag xs =
fromSeq xs `asTypeOf` bag === S.foldr insert empty xs
prop_insert :: BagTest Int bag => bag Int -> Int -> bag Int -> Bool
prop_insert bag x xs =
let x_xs = insert x xs
in si x_xs
&&
toOrdList x_xs == List.insert x (toOrdList xs)
prop_insertSeq :: BagTest Int bag => bag Int -> Seq Int -> bag Int -> Bool
prop_insertSeq bag xs ys =
insertSeq xs ys === union (fromSeq xs) ys
prop_union :: BagTest Int bag => bag Int -> bag Int -> bag Int -> Bool
prop_union bag xs ys =
let xys = union xs ys
in si xys
&&
toOrdList xys == lmerge (toOrdList xs) (toOrdList ys)
prop_unionSeq :: BagTest Int bag => bag Int -> Seq (bag Int) -> Bool
prop_unionSeq bag xss =
unionSeq xss === S.foldr union empty xss
prop_delete :: BagTest Int bag => bag Int -> Int -> bag Int -> Bool
prop_delete bag x xs =
let del_x_xs = delete x xs
in si del_x_xs
&&
toOrdList del_x_xs == List.delete x (toOrdList xs)
prop_deleteAll :: BagTest Int bag => bag Int -> Int -> bag Int -> Bool
prop_deleteAll bag x xs =
let del_x_xs = deleteAll x xs
in si del_x_xs
&&
toOrdList del_x_xs == Prelude.filter (/= x) (toOrdList xs)
prop_deleteSeq :: BagTest Int bag => bag Int -> Seq Int -> bag Int -> Bool
prop_deleteSeq bag xs ys =
deleteSeq xs ys === S.foldr delete ys xs
prop_null_size :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_null_size bag xs =
null xs == (size xs == 0)
&&
size xs == Prelude.length (toOrdList xs)
prop_member_count :: BagTest Int bag => bag Int -> Int -> bag Int -> Bool
prop_member_count bag x xs =
member x xs == (c > 0)
&&
c == Prelude.length (Prelude.filter (== x) (toOrdList xs))
where c = count x xs
-------------------------------------------------------
-- Coll operations
prop_toSeq :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_toSeq bag xs =
List.sort (S.toList (toSeq xs)) == toOrdList xs
prop_lookup :: BagTest Int bag => bag Int -> Int -> bag Int -> Bool
prop_lookup bag x xs =
if member x xs then
lookup x xs == x
&&
lookupM x xs == Just x
&&
lookupWithDefault 999 x xs == x
&&
lookupAll x xs == Prelude.take (count x xs) (repeat x)
else
lookupM x xs == Nothing
&&
lookupWithDefault 999 x xs == 999
&&
lookupAll x xs == []
prop_fold :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_fold bag xs =
List.sort (fold (:) [] xs) == toOrdList xs
&&
(null xs || fold1 (+) xs == sum (toOrdList xs))
prop_strict_fold :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_strict_fold bag xs =
fold' (+) 0 xs == fold (+) 0 xs
&&
(null xs || fold1' (+) xs == fold1 (+) xs)
prop_filter_partition :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_filter_partition bag xs =
let filter_p_xs = filter p xs
filter_not_p_xs = filter (not . p) xs
in si filter_p_xs
&&
si filter_not_p_xs
&&
toOrdList filter_p_xs == Prelude.filter p (toOrdList xs)
&&
partition p xs == (filter_p_xs, filter_not_p_xs)
where p x = x `mod` 3 == 2
------------------------------------------------------------------
-- OrdCollX operations
prop_deleteMin_Max :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_deleteMin_Max bag xs =
let deleteMin_xs = deleteMin xs
deleteMax_xs = deleteMax xs
in si deleteMin_xs
&&
si deleteMax_xs
&&
toOrdList (deleteMin xs) ==
(let l = toOrdList xs
in if L.null l then L.empty else L.ltail l)
&&
toOrdList (deleteMax xs) ==
(let l = toOrdList xs
in if L.null l then L.empty else L.rtail l)
prop_unsafeInsertMin_Max :: BagTest Int bag =>
bag Int -> Int -> bag Int -> Bool
prop_unsafeInsertMin_Max bag i xs =
if null xs then
unsafeInsertMin 0 xs === singleton 0
&&
unsafeInsertMax 0 xs === singleton 0
else
unsafeInsertMin lo xs === insert lo xs
&&
unsafeInsertMax hi xs === insert hi xs
where lo = minElem xs - (if odd i then 1 else 0)
hi = maxElem xs + (if odd i then 1 else 0)
prop_unsafeFromOrdSeq :: BagTest Int bag => bag Int -> [Int] -> Bool
prop_unsafeFromOrdSeq bag xs =
si bag1
&&
toOrdList bag1 == xs'
where xs' = List.sort xs
bag1 = unsafeFromOrdSeq xs' `asTypeOf` bag
prop_filter :: BagTest Int bag => bag Int -> Int -> bag Int -> Bool
prop_filter bag x xs =
si bagLT && si bagLE && si bagGT && si bagGE
&&
toOrdList bagLT == Prelude.filter (< x) (toOrdList xs)
&&
toOrdList bagLE == Prelude.filter (<= x) (toOrdList xs)
&&
toOrdList bagGT == Prelude.filter (> x) (toOrdList xs)
&&
toOrdList bagGE == Prelude.filter (>= x) (toOrdList xs)
where bagLT = filterLT x xs
bagLE = filterLE x xs
bagGT = filterGT x xs
bagGE = filterGE x xs
prop_partition :: BagTest Int bag => bag Int -> Int -> bag Int -> Bool
prop_partition bag x xs =
partitionLT_GE x xs == (filterLT x xs, filterGE x xs)
&&
partitionLE_GT x xs == (filterLE x xs, filterGT x xs)
&&
partitionLT_GT x xs == (filterLT x xs, filterGT x xs)
-----------------------------------------------------------------
-- OrdColl operations
prop_minView_maxView :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_minView_maxView bag xs =
minView xs == (if null xs then Nothing
else Just (minElem xs, deleteMin xs))
&&
maxView xs == (if null xs then Nothing
else Just (maxElem xs, deleteMax xs))
prop_minElem_maxElem :: BagTest Int bag => bag Int -> bag Int -> Property
prop_minElem_maxElem bag xs =
not (null xs) ==>
minElem xs == Prelude.head (toOrdList xs)
&&
maxElem xs == Prelude.last (toOrdList xs)
prop_foldr_foldl :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_foldr_foldl bag xs =
foldr (:) [] xs == toOrdList xs
&&
foldl (flip (:)) [] xs == Prelude.reverse (toOrdList xs)
prop_strict_foldr_foldl :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_strict_foldr_foldl bag xs =
foldr' (+) 0 xs == foldr (+) 0 xs
&&
foldl' (+) 0 xs == foldl (+) 0 xs
prop_foldr1_foldl1 :: BagTest Int bag => bag Int -> bag Int -> Property
prop_foldr1_foldl1 bag xs =
not (null xs) ==>
foldr1 f xs == foldr f 1333 xs
&&
foldl1 (flip f) xs == foldl (flip f) 1333 xs
where f x 1333 = x
f x y = 3*x - 7*y
prop_strict_foldr1_foldl1 :: BagTest Int bag => bag Int -> bag Int -> Property
prop_strict_foldr1_foldl1 bag xs =
not (null xs) ==>
foldr1' (+) xs == foldr1 (+) xs
&&
foldl1' (+) xs == foldl1 (+) xs
prop_toOrdSeq :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_toOrdSeq bag xs =
S.toList (toOrdSeq xs) == toOrdList xs
prop_unsafeAppend :: BagTest Int bag =>
bag Int -> Int -> bag Int -> bag Int -> Bool
prop_unsafeAppend bag i xs ys =
if null xs || null ys then
unsafeAppend xs ys === union xs ys
else
unsafeAppend xs ys' === union xs ys'
where delta = maxElem xs - minElem ys + (if odd i then 1 else 0)
ys' = unsafeMapMonotonic (+delta) ys
-- if unsafeMapMonotonic does any reorganizing in addition
-- to simply replacing the elements, then this test will
-- not provide even coverage
prop_unsafeMapMonotonic :: BagTest Int bag => bag Int -> bag Int -> Bool
prop_unsafeMapMonotonic bag xs =
toOrdList (unsafeMapMonotonic (2*) xs) == Prelude.map (2*) (toOrdList xs)
prop_read_show :: BagTest Int bag
=> bag Int -> bag Int -> Bool
prop_read_show bag xs = xs === read (show xs)
prop_strict :: BagTest a bag => bag a -> bag a -> Bool
prop_strict bag xs =
strict xs === xs
&&
strictWith id xs === xs
| robdockins/edison | test/src/Data/Edison/Test/Bag.hs | mit | 12,343 | 0 | 16 | 3,147 | 4,599 | 2,302 | 2,297 | -1 | -1 |
module Wikidata.Query.Endpoint where
{--
WHEW! Has querying the wikidata endpoint gotten easier or what?!?
Just submit your SPARQL query using the sparql function and you'll ge back
a ByteString response as JSON. Decoding the JSON is on you.
--}
import Data.ByteString.Lazy (ByteString)
import Network.HTTP.Conduit (simpleHttp)
import Network.HTTP (urlEncode)
endpoint :: FilePath
endpoint = "https://query.wikidata.org/sparql?format=json&query="
sparql :: String -> IO ByteString
sparql = simpleHttp . (endpoint ++) . urlEncode
| geophf/1HaskellADay | exercises/HAD/Wikidata/Query/Endpoint.hs | mit | 535 | 0 | 7 | 74 | 79 | 48 | 31 | 8 | 1 |
{- |
Module : $Id$
Copyright : (c) Christian Maeder, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
append a haskell Prelude string for programatica analysis
or add CASL_DL/PredDatatypes.dol to CASL_DL/PredefinedSign.inline.hs
-}
module Main where
import System.Environment
main :: IO ()
main = do
l <- getArgs
preludeString <- readFile $ case l of
[] -> "Haskell/ProgramaticaPrelude.hs"
h : _ -> h
str <- getContents
putStrLn $ str ++ "\n " ++ show preludeString
| spechub/Hets | utils/appendHaskellPreludeString.hs | gpl-2.0 | 622 | 0 | 12 | 140 | 90 | 45 | 45 | 10 | 2 |
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables, MultiParamTypeClasses, FlexibleContexts #-}
module Pump.Inter2 where
import Pump.Type
import Pump.Positiv
import Pump.Negativ
import Language.Syntax
import Language.Inter
import Language
import Language.Sampler
import Pump.Conf2
import Challenger.Partial
import Autolib.Util.Sort
import Autolib.Util.Seed
import Autolib.Util.Zufall
import Autolib.Hash
import Autolib.FiniteMap
import Inter.Types
import Autolib.Reporter
import Autolib.ToDoc
import Autolib.Reader
import qualified Pump.REG as REG
import qualified Pump.CF as CF
import Data.Typeable
------------------------------------------------------------------------
data PUMP = PUMP String
deriving ( Eq, Ord, Typeable )
instance OrderScore PUMP where
scoringOrder _ = None -- ?
instance ToDoc PUMP where
toDoc ( PUMP kind ) = text $ "PUMP-" ++ kind
instance Reader PUMP where
reader = do
my_reserved "PUMP"
-- for backward compatibility
cs <- option "REG" $ do
Autolib.Reader.char '-'
many alphaNum
return $ PUMP cs
instance ( Hash ( Pump z ), Pumping z, Typeable z )
=> Partial PUMP ( Conf z ) ( Pump z ) where
describe ( PUMP {} ) ( conf :: Conf z ) = vcat
[ text $ "Untersuchen Sie, ob die Sprache L = "
, nest 4 $ toDoc (inter $ language $ sampler conf)
, text $ "die " ++ Pump.Type.tag ( undefined :: z ) ++ " erfüllt."
, text ""
, nest 4 $ parens
$ text "Ja-Einsendungen werden bei dieser Aufgabe"
$$ text "nur für n <=" <+> toDoc (ja_bound conf)
<+> text "akzeptiert."
-- , text "Zu dieser Sprache gehören unter anderem die Wörter:"
-- , nest 4 $ toDoc $ take 10 $ samp conf
]
initial ( PUMP {} ) conf =
let ( yeah, noh ) = Language.Sampler.create
( sampler conf ) ( 314159 ) $ Just 10
start = 3
in Ja { n = start, zerlege = listToFM $ do
w <- positive_liste ( sampler conf ) start
return ( w, exem w )
}
total ( PUMP {} ) conf p @ ( Nein {} ) = do
negativ ( inter $ language $ sampler conf ) p
return ()
total ( PUMP {} ) conf p @ ( Ja {} ) = do
assert ( n p <= ja_bound conf )
$ text "Ist Ihr n kleiner als die Schranke?"
let ws = positive_liste ( sampler conf ) ( n p )
positiv ( inter $ language $ sampler conf ) p ws
return ()
positive_liste s n =
let ( yeah, noh ) = Language.Sampler.create s 314159 $ Just (2 * n)
in filter ( ( >= 2 * n) . length ) yeah
----------------------------------------------------------------------
reg = direct
( PUMP "REG" ) ( Pump.Conf2.example :: Conf REG.Zerlegung )
cf = direct
( PUMP "CF" ) ( Pump.Conf2.example :: Conf CF.Zerlegung )
| Erdwolf/autotool-bonn | src/Pump/Inter2.hs | gpl-2.0 | 2,828 | 19 | 16 | 772 | 850 | 453 | 397 | 70 | 1 |
module Zepto.Primitives.ConversionPrimitives where
import Data.Char (ord)
import Control.Monad.Except (throwError)
import Zepto.Types
symbol2String :: [LispVal] -> ThrowsError LispVal
symbol2String [SimpleVal (Atom a)] = return $ fromSimple $ String a
symbol2String [notAtom] = throwError $ TypeMismatch "symbol" notAtom
symbol2String [] = throwError $ NumArgs 1 []
symbol2String args@(_ : _) = throwError $ NumArgs 1 args
string2Symbol :: [LispVal] -> ThrowsError LispVal
string2Symbol [SimpleVal (String s)] = return $ fromSimple $ Atom s
string2Symbol [notString] = throwError $ TypeMismatch "string" notString
string2Symbol [] = throwError $ NumArgs 1 []
string2Symbol args@(_ : _) = throwError $ NumArgs 1 args
charToInteger :: [LispVal] -> ThrowsError LispVal
charToInteger [] = return $ fromSimple $ Bool False
charToInteger [SimpleVal (Character c)] = return $ fromSimple $ Number $ NumI $ toInteger $ ord c
charToInteger [notChar] = throwError $ TypeMismatch "character" notChar
charToInteger args@(_ : _) = throwError $ NumArgs 1 args
number2String :: [LispVal] -> ThrowsError LispVal
number2String [SimpleVal (Number x)] = return $ fromSimple $ String $ show x
number2String [notNumber] = throwError $ TypeMismatch "number" notNumber
number2String [] = throwError $ NumArgs 1 []
number2String args@(_ : _) = throwError $ NumArgs 1 args
buildNil:: [LispVal] -> ThrowsError LispVal
buildNil [] = return $ fromSimple $ Nil ""
buildNil badArgList = throwError $ NumArgs 0 badArgList
list2Simple :: [LispVal] -> ThrowsError LispVal
list2Simple [] = return $ fromSimple $ SimpleList []
list2Simple [List x] = if all simple x
then return $ fromSimple $ SimpleList $ map toSimple x
else throwError $ BadSpecialForms "expected simple elements" $
(filter (\e -> not $ simple e) x)
where simple (SimpleVal _) = True
simple _ = False
list2Simple [notList] = throwError $ TypeMismatch "list" notList
list2Simple badArgList = throwError $ NumArgs 1 badArgList
| zepto-lang/zepto-js | src/Zepto/Primitives/ConversionPrimitives.hs | gpl-2.0 | 2,055 | 0 | 12 | 387 | 735 | 371 | 364 | 37 | 3 |
{- |
Module : $Header$
Description : Internal data types of the CMDL interface
Copyright : uni-bremen and DFKI
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
CMDL.DataTypes describes the internal states(or datatypes) of the CMDL
interface.
-}
module CMDL.DataTypes
( CmdlState (..)
, emptyCmdlState
, CmdlCmdDescription (..)
, cmdInput
, cmdName
, CmdlCmdPriority (..)
, CmdlCmdFnClasses (..)
, CmdlCmdRequirements (..)
, formatRequirement
, CmdlChannel (..)
, CmdlChannelType (..)
, CmdlChannelProperties (..)
, CmdlSocket (..)
, CmdlUseTranslation (..)
, CmdlProverConsChecker (..)
, CmdlPrompterState (..)
, CmdlMessage (..)
, emptyCmdlMessage
, CmdlListAction (..)
, CmdlGoalAxiom (..)
) where
import Interfaces.DataTypes
import Interfaces.Command
import Driver.Options
import Network
import System.IO (Handle)
data CmdlGoalAxiom =
ChangeGoals
| ChangeAxioms
data CmdlProverConsChecker =
Use_prover
| Use_consChecker
data CmdlUseTranslation =
Do_translate
| Dont_translate
-- * CMDL datatypes
{- | CMDLState contains all information the CMDL interface
might use at any time. -}
data CmdlState = CmdlState
{ intState :: IntState -- ^ common interface state
, prompter :: CmdlPrompterState -- ^ promter of the interface
, openComment :: Bool -- ^ open comment
, connections :: [CmdlChannel] -- ^ opened connections
, output :: CmdlMessage -- ^ output of interface
, hetsOpts :: HetcatsOpts -- ^ hets command options
}
-- | Creates an empty CmdlState
emptyCmdlState :: HetcatsOpts -> CmdlState
emptyCmdlState opts = CmdlState
{ intState = IntState
{ i_state = Nothing
, i_hist = IntHistory
{ undoList = []
, redoList = [] }
, filename = [] }
, prompter = CmdlPrompterState
{ fileLoaded = ""
, prompterHead = "> " }
, output = emptyCmdlMessage
, openComment = False
, connections = []
, hetsOpts = opts }
data CmdlPrompterState = CmdlPrompterState
{ fileLoaded :: String
, prompterHead :: String }
{- | Description of a command in order to have a uniform access to any of
the commands -}
data CmdlCmdDescription = CmdlCmdDescription
{ cmdDescription :: Command
, cmdPriority :: CmdlCmdPriority
, cmdFn :: CmdlCmdFnClasses
, cmdReq :: CmdlCmdRequirements }
cmdInput :: CmdlCmdDescription -> String
cmdInput = cmdInputStr . cmdDescription
cmdName :: CmdlCmdDescription -> String
cmdName = cmdNameStr . cmdDescription
{- | Some commands have different status, for example 'end-script'
needs to be processed even though the interface is in reading script
state. The same happens with '}%' even though the interface is in
multi line comment state. In order not to treat this few commands
separately from the other it is easy just to give to all commands
different priorities -}
data CmdlCmdPriority =
CmdNoPriority
| CmdGreaterThanComments
| CmdGreaterThanScriptAndComments
{- | Any command belongs to one of the following classes of functions,
a) f :: s -> IO s
b) f :: String -> s -> IO s -}
data CmdlCmdFnClasses =
CmdNoInput (CmdlState -> IO CmdlState)
| CmdWithInput (String -> CmdlState -> IO CmdlState)
{- | Datatype describing the types of commands according
to what they expect as input -}
data CmdlCmdRequirements =
ReqNodes
| ReqEdges
| ReqProvers
| ReqConsCheck
| ReqComorphism
| ReqFile
| ReqGNodes
| ReqGEdges
| ReqAxm
| ReqGoal
| ReqNumber
| ReqNothing
| ReqUnknown
deriving Show
formatRequirement :: CmdlCmdRequirements -> String
formatRequirement r = let s = showRequirement r in
if null s then "" else '<' : s ++ ">"
showRequirement :: CmdlCmdRequirements -> String
showRequirement cr = case cr of
ReqConsCheck -> "ConsChecker"
ReqProvers -> "Prover"
ReqGNodes -> "GoalNodes"
ReqGEdges -> "GoalEdges"
ReqAxm -> "Axiom"
ReqNothing -> ""
ReqUnknown -> ""
_ -> drop 3 $ show cr
-- Communication channel datatypes -----------------------------------------
{- | CMDLSocket takes care of opened sockets for comunication with other
application like the Broker in the case of PGIP -}
data CmdlChannel = CmdlChannel
{ chName :: String
, chType :: CmdlChannelType
, chHandler :: Handle
, chSocket :: Maybe CmdlSocket
, chProperties :: CmdlChannelProperties }
-- | Channel type describes different type of channel
data CmdlChannelType =
ChSocket
| ChFile
| ChStdin
| ChStdout
-- | Channel properties describes what a channel can do
data CmdlChannelProperties =
ChRead
| ChWrite
| ChReadWrite
-- | Describes a socket
data CmdlSocket = CmdlSocket
{ socketHandler :: Socket
, socketHostName :: HostName
, socketPortNumber :: PortNumber }
{- | Datatype describing the list of possible action on a list
of selected items -}
data CmdlListAction =
ActionSet
| ActionSetAll
| ActionDel
| ActionDelAll
| ActionAdd
-- | output message given by the interface
data CmdlMessage = CmdlMessage
{ outputMsg :: String
, warningMsg :: String
, errorMsg :: String }
emptyCmdlMessage :: CmdlMessage
emptyCmdlMessage = CmdlMessage
{ errorMsg = []
, outputMsg = []
, warningMsg = [] }
| nevrenato/Hets_Fork | CMDL/DataTypes.hs | gpl-2.0 | 5,317 | 0 | 11 | 1,131 | 862 | 534 | 328 | 138 | 8 |
import Control.Applicative
import System.Directory
import System.Environment
import System.Process
import qualified Text.StringTemplate as ST
render :: String -> [(String,String)] -> String
render tmpl attribs = (ST.render . ST.setManyAttrib attribs . ST.newSTMP) tmpl
strtmpl = "prospino {\n basedir = \"$basedir$\"\n resultFileName = \"$result$\"\n remoteDir = \"$remotedir$\"\n}\n"
minfty :: Double
minfty = 50000.0
createRdirBName procname (mq,mn) =
let rdir = "montecarlo/admproject/SimplifiedSUSYlep/8TeV/scan_" ++ procname
basename = "SimplifiedSUSYlepN" ++ show mn ++ "G"++show minfty ++ "QL" ++ show mq ++ "C"++show (0.5*(mn+mq))++ "L" ++ show minfty ++ "NN" ++ show minfty ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set1"
in (rdir,basename)
datalst :: [ (Double,Double) ]
datalst = [ (850.0,750.0) ]
-- datalst = [ (mg,mn) | mg <- [ 200,250..1500 ], mn <- [ 50,100..mg-50] ]
-- datalst = [ (mq,mn) | mq <- [ 200,250..1300], mn <- [ 50,100..mq-50 ] ]
-- datalst = [ (1300,300) ]
fst3 (a,_,_) = a
snd3 (_,a,_) = a
trd3 (_,_,a) = a
main :: IO ()
main = do
args <- getArgs
let cfgfile = args !! 0
dirname = args !! 1
n1 = read (args !! 2) :: Int
n2 = read (args !! 3) :: Int
datasublst = (zip [1..] . drop (n1-1) . take n2) datalst
filenames = map ((,,) <$> fst <*> snd <*> createRdirBName "1step_2sq" . snd) datasublst
makecfg rdirbname = render strtmpl [ ("basedir", dirname )
, ("result", (snd rdirbname) ++"_xsecKfactor.json" )
, ("remotedir", (fst rdirbname) )
]
cfglst = map ((,,) <$> (\x-> "runprospino"++show x++".conf") . fst3
<*> snd3
<*> makecfg . trd3)
filenames
-- (error . show) (length datalst)
-- mapM_ print cfglst
setCurrentDirectory dirname
mapM_ (\(x,_,y)->writeFile x y) cfglst
mapM_ (\(x,(g,n),y) -> let c = cmd cfgfile x (g,n) in print c >> system c) cfglst
cmd cfgfile jobfile (q,n) = "/home2/iankim/repo/src/lhc-analysis-collection/analysis/runProspino squarkpair " ++ cfgfile ++ " " ++ show q ++ " " ++ show minfty ++ " --config=" ++ jobfile
| wavewave/lhc-analysis-collection | analysis/2013-07-26_prospino_2sq.hs | gpl-3.0 | 2,307 | 0 | 23 | 627 | 732 | 394 | 338 | 39 | 1 |
{-# LANGUAGE PatternGuards #-}
module Lang.FreeTyCons (bindsTyCons) where
import CoreSyn
import CoreUtils (exprType)
import DataCon
import TyCon
import Id
import Type
import Var
import Data.Set (Set)
import qualified Data.Set as S
bindsTyCons :: [CoreBind] -> [TyCon]
bindsTyCons = S.toList . S.unions . map bindTyCons
bindTyCons :: CoreBind -> Set TyCon
bindTyCons = S.unions . map exprTyCons . rhssOfBind
tyTyCons :: Type -> Set TyCon
tyTyCons = go . expandTypeSynonyms
where
go t0
| Just (t1,t2) <- splitFunTy_maybe t0 = S.union (go t1) (go t2)
| Just (tc,ts) <- splitTyConApp_maybe t0 = S.insert tc (S.unions (map go ts))
| Just (_,t) <- splitForAllTy_maybe t0 = go t
| otherwise = S.empty
varTyCons :: Var -> Set TyCon
varTyCons = tyTyCons . varType
-- | For all used constructors in expressions and patterns,
-- return the TyCons they originate from
exprTyCons :: CoreExpr -> Set TyCon
exprTyCons e0 = case e0 of
Case e x t alts -> S.unions (varTyCons x:tyTyCons t:exprTyCons e:map altTyCons alts)
App e1 e2 -> S.union (exprTyCons e1) (exprTyCons e2)
Let bs e -> S.unions (exprTyCons e:map exprTyCons (rhssOfBind bs))
Lam _ e -> exprTyCons e
Cast e _ -> exprTyCons e
Tick _ e -> exprTyCons e
Var x -> varTyCons x
Type t -> tyTyCons t
Coercion{} -> S.empty
Lit{} -> tyTyCons (exprType e0)
altTyCons :: CoreAlt -> Set TyCon
altTyCons (alt,_,rhs) = patTyCons alt `S.union` exprTyCons rhs
patTyCons :: AltCon -> Set TyCon
patTyCons p = case p of
DataAlt c -> S.singleton (dataConTyCon c)
LitAlt{} -> S.empty
DEFAULT -> S.empty
| danr/tfp1 | Lang/FreeTyCons.hs | gpl-3.0 | 1,737 | 0 | 13 | 464 | 647 | 322 | 325 | 43 | 10 |
{-# LANGUAGE OverloadedStrings #-}
-- ghc --make EditDistViz.hs -main-is EditDistViz.main
module EditDistViz where
import Data.Array
import Data.List (intersperse)
import Control.Arrow ((***))
import qualified Data.Set as S
-- write file
import System.IO
data Cell a = Val {val::Int, reasons::[Reason a]}
deriving (Show)
data Reason a = Init | X a | Y a | Eq a | Neq a
deriving (Show)
data SVG = SVG {mainElement::XMLElement}
data XMLString = XMLString {unescaped::String}
data XMLAttribute = Attr {attrName::XMLString, attrValue::XMLString}
data XMLElement = Tag {tagName::XMLString, attributes::[XMLAttribute], content::[Either XMLElement XMLString]}
instance Show XMLString where
show (XMLString unescaped) = concatMap f unescaped
where f '<' = "<"
f '>' = ">"
f '&' = "&"
f '\'' = "'"
f '"' = """
f x = [x]
mkTag x a =
Tag
(XMLString x)
(map (uncurry Attr . (XMLString *** XMLString)) a)
rgb r g b =
"rgb(" ++ show (255 * r) ++
"," ++ show (255 * g) ++
"," ++ show (255 * b) ++ ")"
red = rgb 1 0 0
yello = rgb 1 1 0
green = rgb 0 1 0
cyan = rgb 0 1 1
blu = rgb 0 0 1
purpl = rgb 1 0 1
{- trace successful path back from (m,n) point to origin -}
successpath table =
let (_, (m,n)) = bounds table
aux' (0,0) = []
-- arbitrary preference? no, let's show all successful paths.
aux' (i,j) =
let diag = any (\x -> case x of (Eq _) -> True ; (Neq _) -> True ; _ -> False) (reasons (table ! (i,j)))
horz = any (\x -> case x of (X _) -> True ; _ -> False) (reasons (table ! (i,j)))
vert = any (\x -> case x of (Y _) -> True ; _ -> False) (reasons (table ! (i,j)))
in
[(i-1,j-1) | diag] ++ [(i-1,j) | horz] ++ [(i,j-1) | vert]
aux front accum =
case S.minView front of
Nothing -> accum
Just ((i,j), s) ->
let contributions = aux' (i,j)
in
aux (S.union s (S.fromList contributions))
(S.union accum (S.fromList (map (\x -> (x, (i,j))) contributions)))
in
aux (S.fromList [(m,n)]) (S.empty)
toSVG :: Array (Int,Int) (Cell Char) -> SVG
toSVG table =
let (_, (m,n)) = bounds table
-- square edge width
sqmeasure = 50.0 :: Float
rmeasure = 5.0
-- stroke line width:
smeasure = 1.0
width = sqmeasure * fromIntegral m
height = sqmeasure * fromIntegral n
valmaxf = fromIntegral $ maximum (map val (elems table))
palette = cycle [red, yello, green, cyan, blu, purpl]
s_path = S.toList (successpath table)
in
SVG $
mkTag "svg"
[("xmlns","http://www.w3.org/2000/svg"), ("width", show width), ("height", show height)
,("viewBox", show (-0.5*sqmeasure) ++ " " ++ show (-0.5*sqmeasure) ++ " " ++ show (width + 1*sqmeasure) ++ " " ++ show (height + 1*sqmeasure))
]
$
-- white background
[ Left (mkTag "rect" [("x", show $ -0.5*sqmeasure),
("y", show $ -0.5*sqmeasure),
("width", show $ width + 1*sqmeasure),
("height", show $ height + 1*sqmeasure),
("fill", "white")
] [])]
++
-- horizontal lettering
[ Left (mkTag "text"
[("x", show x), ("y", show (-sqmeasure/4)),
("fill", rgb 0.0 0.0 0.0)
]
[Right $ XMLString c])
| i <- [1..m]
, let c = case reasons (table ! (i, 0)) of [X c] -> [c] ; _ -> ""
, let x = fromIntegral i * sqmeasure - 0.5 * sqmeasure ]
++
-- vertical lettering
[ Left (mkTag "text"
[("y", show y), ("x", show (-sqmeasure/4)),
("fill", rgb 0.0 0.0 0.0)
]
[Right $ XMLString c])
| j <- [1..n]
, let c = case reasons (table ! (0, j)) of [Y c] -> [c] ; _ -> ""
, let y = fromIntegral j * sqmeasure - 0.5 * sqmeasure ]
++
-- little square tiles
[ Left (mkTag "rect"
[("x", show rx), ("y", show ry),
("width", show sqmeasure),
("height", show sqmeasure),
("fill", color),
("fill-opacity", show 1.0),
("stroke", color),
("stroke-width", show smeasure)
] [])
| i <- [0..m-1], j <- [0..n-1]
, let rx = fromIntegral i * sqmeasure
, let ry = fromIntegral j * sqmeasure
, let vf = fromIntegral $ val (table ! (i+1,j+1))
, let shade = vf / valmaxf
, let color = rgb shade shade shade ]
++
-- highlight successful path(s)
[ Left (mkTag "line"
[("x1", show x1)
,("y1", show y1)
,("x2", show x2)
,("y2", show y2)
,("stroke", color)
,("stroke-width", show s'measure)]
[])
| ((i',j'), (i,j)) <- s_path
-- a nice possibility: draw a thicker line first
, let s'measure = 5.0
, let x1 = fromIntegral i' * sqmeasure
, let y1 = fromIntegral j' * sqmeasure
, let x2 = fromIntegral i * sqmeasure
, let y2 = fromIntegral j * sqmeasure
, let color = rgb 0.0 0.0 1.0 ]
++
-- dashed lines for same letter
[ Left (mkTag "line"
[("x1", show x1)
,("y1", show y1)
,("x2", show x2)
,("y2", show y2)
,("stroke", color)
,("stroke-width", show s'measure)
,("stroke-dasharray", show 5)]
[])
| i <- [0..m-1], j <- [0..n-1]
, let s'measure = smeasure
, let x1 = fromIntegral i * sqmeasure
, let y1 = fromIntegral j * sqmeasure
, let x2 = fromIntegral (i+1) * sqmeasure
, let y2 = fromIntegral (j+1) * sqmeasure
, let rr = reasons (table ! (i+1,j+1))
, any (\x -> case x of (Eq _) -> True ; _ -> False) rr
, let color = palette !! val (table ! (i, j)) ]
++
-- horizontal
[ Left (mkTag "line"
[("x1", show x1)
,("y1", show y1)
,("x2", show x2)
,("y2", show y2)
,("stroke", color)
,("stroke-width", show s'measure)]
[])
| i <- [0..m-1], j <- [0..n-1]
, let s'measure = smeasure
, let x1 = fromIntegral i * sqmeasure
, let y1 = fromIntegral (j+1) * sqmeasure
, let x2 = fromIntegral (i+1) * sqmeasure
, let y2 = fromIntegral (j+1) * sqmeasure
, let rr = reasons (table ! (i+1,j+1))
, any (\x -> case x of (X _) -> True ; _ -> False) rr
, let color = palette !! val (table ! (i, j)) ]
++
-- vertical
[ Left (mkTag "line"
[("x1", show x1)
,("y1", show y1)
,("x2", show x2)
,("y2", show y2)
,("stroke", color)
,("stroke-width", show s'measure)]
[])
| i <- [0..m-1], j <- [0..n-1]
, let s'measure = smeasure
, let x1 = fromIntegral (i+1) * sqmeasure
, let y1 = fromIntegral j * sqmeasure
, let x2 = fromIntegral (i+1) * sqmeasure
, let y2 = fromIntegral (j+1) * sqmeasure
, let rr = reasons (table ! (i+1,j+1))
, any (\x -> case x of (Y _) -> True ; _ -> False) rr
, let color = palette !! val (table ! (i, j))]
++
-- diagonal, different letter
[ Left (mkTag "line"
[("x1", show x1)
,("y1", show y1)
,("x2", show x2)
,("y2", show y2)
,("stroke", color)
,("stroke-width", show s'measure)]
[])
| i <- [0..m-1], j <- [0..n-1]
, let s'measure = smeasure
, let x1 = fromIntegral i * sqmeasure
, let y1 = fromIntegral j * sqmeasure
, let x2 = fromIntegral (i+1) * sqmeasure
, let y2 = fromIntegral (j+1) * sqmeasure
, let rr = reasons (table ! (i+1,j+1))
, any (\x -> case x of (Neq _) -> True ; _ -> False) rr
, let color = palette !! val (table ! (i, j)) ]
++
[ Left (mkTag "circle"
[("cx", show cx), ("cy", show cy), ("r", show rmeasure),
("fill", rgb 0.0 0.0 (vf / valmaxf)),
("fill-opacity", show 1)
] [])
| i <- [0..m], j <- [0..n]
, let cx = fromIntegral i * sqmeasure
, let cy = fromIntegral j * sqmeasure
, let vf = fromIntegral $ val (table ! (i,j)) ]
instance Show SVG where
show (SVG elt) = show elt
instance Show XMLElement where
show (Tag name attrs content) =
concat $ ["<", show name] ++
[" "| not (null attrs)] ++
intersperse " " (map show attrs) ++ ["/>" | null content] ++
[">" | not (null content)] ++
[case c of
Left c -> show c
Right c -> show c | c <- content] ++
["</" ++ show name ++ ">" | not (null content)]
instance Show XMLAttribute where
show (Attr name value) =
concat [show name, "=\"", show value, "\""]
edtable :: (Eq a) => [a] -> [a] -> Array (Int, Int) (Cell a)
edtable v w =
let res = array ((0,0), (length v , length w)) $
[((0,0), Val 0 [Init])] ++
[((x,0), Val x [X vx]) | (x,vx) <- zip [1..] v] ++
[((0,y), Val y [Y wy]) | (y,wy) <- zip [1..] w] ++
[((x,y), k)
| (x,vx) <- zip [1..] v
, (y,wy) <- zip [1..] w
, let nx = 1 + val (res ! (x-1, y))
ny = 1 + val (res ! (x, y-1))
nd = (if vx == wy then 0 else 1) + val(res ! (x-1, y-1))
n = minimum [nx, ny, nd]
, let k = Val n $
[X vx | n == nx] ++
[Y wy | n == ny] ++
[Eq vx | n == nd, vx == wy] ++
[Neq vx | n == nd, vx /= wy]
]
in res
-- (s1,s2) = ("preternatural", "unintentional")
(s1,s2) = ("efghabcd", "abcdefgh")
main :: IO ()
main = do
(pathOfTempFile, h) <- openTempFile "/tmp" "edtable.svg"
putStrLn ("Writing to " ++ pathOfTempFile)
hPutStr h $ show $ toSVG (edtable s1 s2)
hClose h
| fnordomat/misc | haskell/editdistviz/EditDistViz.hs | gpl-3.0 | 10,585 | 3 | 31 | 4,101 | 4,542 | 2,436 | 2,106 | 247 | 7 |
class Functor' f where
fmap' :: (a -> b) -> f a -> f b
instance Functor' [] where
fmap' = map
instance Functor' Maybe where
fmap' f (Just x) = Just (f x)
fmap' f Nothing = Nothing
instance Functor' (Either a) where
fmap' f (Right x) = Right (f x)
fmap' f (Left x) = Left x
data Barry t k p = Barry { yabba :: p, dabba :: t k } deriving (Show)
instance Functor' (Barry a b) where
fmap' f (Barry {yabba = x, dabba = y}) = Barry {yabba = f x, dabba = y}
-- ghci functor.hs
-- fmap' (*3) (Barry {yabba = 2, dabba = Just 'a'})
instance Functor' IO where
fmap' f action = do
result <- action
return (f result)
instance Functor' ((->) r) where
fmap' f g = (\x -> f (g x))
| lamontu/learning_haskell | functor.hs | gpl-3.0 | 725 | 0 | 10 | 204 | 330 | 171 | 159 | 19 | 0 |
--
-- Copyright (c) 2004-2008 Don Stewart - http://www.cse.unsw.edu.au/~dons
--
-- 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.
--
--
-- | Color manipulation
--
module Style where
#include "config.h"
import qualified Curses
import Data.ByteString (ByteString)
import Data.Char (toLower)
import Data.Word (Word8)
import Data.Maybe (fromJust)
import Data.IORef (readIORef, writeIORef, newIORef, IORef)
import qualified Data.Map as M (fromList, empty, lookup, Map)
import System.IO.Unsafe (unsafePerformIO)
import Control.Exception
------------------------------------------------------------------------
-- | User-configurable colours
-- Each component of this structure corresponds to a fg\/bg colour pair
-- for an item in the ui
data UIStyle = UIStyle {
window :: !Style -- default window colour
, helpscreen :: !Style -- help screen
, titlebar :: !Style -- titlebar of window
, selected :: !Style -- currently playing track
, cursors :: !Style -- the scrolling cursor line
, combined :: !Style -- the style to use when the cursor is on the current track
, warnings :: !Style -- style for warnings
, blockcursor :: !Style -- style for the block cursor when typing text
, progress :: !Style -- style for the progress bar
}
------------------------------------------------------------------------
-- | Colors
data Color
= RGB !Word8 !Word8 !Word8
| Default
| Reverse
deriving (Eq,Ord)
-- | Foreground and background color pairs
data Style = Style !Color !Color
deriving (Eq,Ord)
-- | A list of such values (the representation is optimised)
data StringA
= Fast !ByteString !Style
| FancyS ![(ByteString,Style)] -- one line made up of segments
------------------------------------------------------------------------
--
-- | Some simple colours (derivied from proxima\/src\/common\/CommonTypes.hs)
--
-- But we don't have a light blue?
--
black, grey, darkred, red, darkgreen, green, brown, yellow :: Color
darkblue, blue, purple, magenta, darkcyan, cyan, white, brightwhite :: Color
black = RGB 0 0 0
grey = RGB 128 128 128
darkred = RGB 139 0 0
red = RGB 255 0 0
darkgreen = RGB 0 100 0
green = RGB 0 128 0
brown = RGB 165 42 42
yellow = RGB 255 255 0
darkblue = RGB 0 0 139
blue = RGB 0 0 255
purple = RGB 128 0 128
magenta = RGB 255 0 255
darkcyan = RGB 0 139 139
cyan = RGB 0 255 255
white = RGB 165 165 165
brightwhite = RGB 255 255 255
defaultfg, defaultbg, reversefg, reversebg :: Color
#if defined(HAVE_USE_DEFAULT_COLORS)
defaultfg = Default
defaultbg = Default
#else
defaultfg = white
defaultbg = black
#endif
reversefg = Reverse
reversebg = Reverse
--
-- | map strings to colors
--
stringToColor :: String -> Maybe Color
stringToColor s = case map toLower s of
"black" -> Just black
"grey" -> Just grey
"darkred" -> Just darkred
"red" -> Just red
"darkgreen" -> Just darkgreen
"green" -> Just green
"brown" -> Just brown
"yellow" -> Just yellow
"darkblue" -> Just darkblue
"blue" -> Just blue
"purple" -> Just purple
"magenta" -> Just magenta
"darkcyan" -> Just darkcyan
"cyan" -> Just cyan
"white" -> Just white
"brightwhite" -> Just brightwhite
"default" -> Just Default
"reverse" -> Just Reverse
_ -> Nothing
------------------------------------------------------------------------
--
-- | Set some colours, perform an action, and then reset the colours
--
withStyle :: Style -> (IO ()) -> IO ()
withStyle sty fn = uiAttr sty >>= setAttribute >> fn >> reset
{-# INLINE withStyle #-}
--
-- | manipulate the current attributes of the standard screen
-- Only set attr if it's different to the current one?
--
setAttribute :: (Curses.Attr, Curses.Pair) -> IO ()
setAttribute = uncurry Curses.attrSet
{-# INLINE setAttribute #-}
--
-- | Reset the screen to normal values
--
reset :: IO ()
reset = setAttribute (Curses.attr0, Curses.Pair 0)
{-# INLINE reset #-}
--
-- | And turn on the colours
--
initcolours :: UIStyle -> IO ()
initcolours sty = do
let ls = [helpscreen sty, warnings sty, window sty,
selected sty, titlebar sty, progress sty,
blockcursor sty, cursors sty, combined sty ]
(Style fg bg) = progress sty -- bonus style
pairs <- initUiColors (ls ++ [Style bg bg, Style fg fg])
writeIORef pairMap pairs
-- set the background
uiAttr (window sty) >>= \(_,p) -> Curses.bkgrndSet nullA p
------------------------------------------------------------------------
--
-- | Set up the ui attributes, given a ui style record
--
-- Returns an association list of pairs for foreground and bg colors,
-- associated with the terminal color pair that has been defined for
-- those colors.
--
initUiColors :: [Style] -> IO PairMap
initUiColors stys = do
ls <- sequence [ uncurry fn m | m <- zip stys [1..] ]
return (M.fromList ls)
where
fn :: Style -> Int -> IO (Style, (Curses.Attr,Curses.Pair))
fn sty p = do
let (CColor (a,fgc),CColor (b,bgc)) = style2curses sty
handle (\(SomeException _ ) -> return ()) $ Curses.initPair (Curses.Pair p) fgc bgc
return (sty, (a `Curses.attrPlus` b, Curses.Pair p))
------------------------------------------------------------------------
--
-- | Getting from nice abstract colours to ncurses-settable values
-- 20% of allocss occur here! But there's only 3 or 4 colours :/
-- Every call to uiAttr
--
uiAttr :: Style -> IO (Curses.Attr, Curses.Pair)
uiAttr sty = do
m <- readIORef pairMap
return $ lookupPair m sty
{-# INLINE uiAttr #-}
-- | Given a curses color pair, find the Curses.Pair (i.e. the pair
-- curses thinks these colors map to) from the state
lookupPair :: PairMap -> Style -> (Curses.Attr, Curses.Pair)
lookupPair m s = case M.lookup s m of
Nothing -> (Curses.attr0, Curses.Pair 0) -- default settings
Just v -> v
{-# INLINE lookupPair #-}
-- | Keep a map of nice style defs to underlying curses pairs, created at init time
type PairMap = M.Map Style (Curses.Attr, Curses.Pair)
-- | map of Curses.Color pairs to ncurses terminal Pair settings
pairMap :: IORef PairMap
pairMap = unsafePerformIO $ newIORef M.empty
{-# NOINLINE pairMap #-}
------------------------------------------------------------------------
--
-- Basic (ncurses) colours.
--
defaultColor :: Curses.Color
defaultColor = fromJust $ Curses.color "default"
cblack, cred, cgreen, cyellow, cblue, cmagenta, ccyan, cwhite :: Curses.Color
cblack = fromJust $ Curses.color "black"
cred = fromJust $ Curses.color "red"
cgreen = fromJust $ Curses.color "green"
cyellow = fromJust $ Curses.color "yellow"
cblue = fromJust $ Curses.color "blue"
cmagenta = fromJust $ Curses.color "magenta"
ccyan = fromJust $ Curses.color "cyan"
cwhite = fromJust $ Curses.color "white"
--
-- Combine attribute with another attribute
--
setBoldA, setReverseA :: Curses.Attr -> Curses.Attr
setBoldA = flip Curses.setBold True
setReverseA = flip Curses.setReverse True
--
-- | Some attribute constants
--
boldA, nullA, reverseA :: Curses.Attr
nullA = Curses.attr0
boldA = setBoldA nullA
reverseA = setReverseA nullA
------------------------------------------------------------------------
newtype CColor = CColor (Curses.Attr, Curses.Color)
--
-- | Map Style rgb rgb colours to ncurses pairs
-- TODO a generic way to turn an rgb into the nearest curses color
--
style2curses :: Style -> (CColor, CColor)
style2curses (Style fg bg) = (fgCursCol fg, bgCursCol bg)
{-# INLINE style2curses #-}
fgCursCol :: Color -> CColor
fgCursCol c = case c of
RGB 0 0 0 -> CColor (nullA, cblack)
RGB 128 128 128 -> CColor (boldA, cblack)
RGB 139 0 0 -> CColor (nullA, cred)
RGB 255 0 0 -> CColor (boldA, cred)
RGB 0 100 0 -> CColor (nullA, cgreen)
RGB 0 128 0 -> CColor (boldA, cgreen)
RGB 165 42 42 -> CColor (nullA, cyellow)
RGB 255 255 0 -> CColor (boldA, cyellow)
RGB 0 0 139 -> CColor (nullA, cblue)
RGB 0 0 255 -> CColor (boldA, cblue)
RGB 128 0 128 -> CColor (nullA, cmagenta)
RGB 255 0 255 -> CColor (boldA, cmagenta)
RGB 0 139 139 -> CColor (nullA, ccyan)
RGB 0 255 255 -> CColor (boldA, ccyan)
RGB 165 165 165 -> CColor (nullA, cwhite)
RGB 255 255 255 -> CColor (boldA, cwhite)
Default -> CColor (nullA, defaultColor)
Reverse -> CColor (reverseA, defaultColor)
_ -> CColor (nullA, cblack) -- NB
bgCursCol :: Color -> CColor
bgCursCol c = case c of
RGB 0 0 0 -> CColor (nullA, cblack)
RGB 128 128 128 -> CColor (nullA, cblack)
RGB 139 0 0 -> CColor (nullA, cred)
RGB 255 0 0 -> CColor (nullA, cred)
RGB 0 100 0 -> CColor (nullA, cgreen)
RGB 0 128 0 -> CColor (nullA, cgreen)
RGB 165 42 42 -> CColor (nullA, cyellow)
RGB 255 255 0 -> CColor (nullA, cyellow)
RGB 0 0 139 -> CColor (nullA, cblue)
RGB 0 0 255 -> CColor (nullA, cblue)
RGB 128 0 128 -> CColor (nullA, cmagenta)
RGB 255 0 255 -> CColor (nullA, cmagenta)
RGB 0 139 139 -> CColor (nullA, ccyan)
RGB 0 255 255 -> CColor (nullA, ccyan)
RGB 165 165 165 -> CColor (nullA, cwhite)
RGB 255 255 255 -> CColor (nullA, cwhite)
Default -> CColor (nullA, defaultColor)
Reverse -> CColor (reverseA, defaultColor)
_ -> CColor (nullA, cwhite) -- NB
defaultSty :: Style
defaultSty = Style Default Default
------------------------------------------------------------------------
--
-- Support for runtime configuration
-- We choose a simple strategy, read/showable record types, with strings
-- to represent colors
--
-- The fields must map to UIStyle
--
-- It is this data type that is stored in 'show' format in ~/.hmp3
--
data Config = Config {
hmp3_window :: (String,String)
, hmp3_helpscreen :: (String,String)
, hmp3_titlebar :: (String,String)
, hmp3_selected :: (String,String)
, hmp3_cursors :: (String,String)
, hmp3_combined :: (String,String)
, hmp3_warnings :: (String,String)
, hmp3_blockcursor :: (String,String)
, hmp3_progress :: (String,String)
} deriving (Show,Read)
--
-- | Read the ~/.hmp3 file, and construct a UIStyle from it, to insert
-- into
--
buildStyle :: Config -> UIStyle
buildStyle bs = UIStyle {
window = f $ hmp3_window bs
, helpscreen = f $ hmp3_helpscreen bs
, titlebar = f $ hmp3_titlebar bs
, selected = f $ hmp3_selected bs
, cursors = f $ hmp3_cursors bs
, combined = f $ hmp3_combined bs
, warnings = f $ hmp3_warnings bs
, blockcursor = f $ hmp3_blockcursor bs
, progress = f $ hmp3_progress bs
}
where
f (x,y) = Style (g x) (g y)
g x = case stringToColor x of
Nothing -> Default
Just y -> y
| danplubell/hmp3-phoenix | src/Style.hs | gpl-3.0 | 12,146 | 0 | 14 | 3,187 | 3,002 | 1,641 | 1,361 | 241 | 19 |
{-# 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.CloudHSM.DescribeHapg
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Retrieves information about a high-availability partition group.
--
-- <http://docs.aws.amazon.com/cloudhsm/latest/dg/API_DescribeHapg.html>
module Network.AWS.CloudHSM.DescribeHapg
(
-- * Request
DescribeHapg
-- ** Request constructor
, describeHapg
-- ** Request lenses
, dh1HapgArn
-- * Response
, DescribeHapgResponse
-- ** Response constructor
, describeHapgResponse
-- ** Response lenses
, dhrHapgArn
, dhrHapgSerial
, dhrHsmsLastActionFailed
, dhrHsmsPendingDeletion
, dhrHsmsPendingRegistration
, dhrLabel
, dhrLastModifiedTimestamp
, dhrPartitionSerialList
, dhrState
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CloudHSM.Types
import qualified GHC.Exts
newtype DescribeHapg = DescribeHapg
{ _dh1HapgArn :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DescribeHapg' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dh1HapgArn' @::@ 'Text'
--
describeHapg :: Text -- ^ 'dh1HapgArn'
-> DescribeHapg
describeHapg p1 = DescribeHapg
{ _dh1HapgArn = p1
}
-- | The ARN of the high-availability partition group to describe.
dh1HapgArn :: Lens' DescribeHapg Text
dh1HapgArn = lens _dh1HapgArn (\s a -> s { _dh1HapgArn = a })
data DescribeHapgResponse = DescribeHapgResponse
{ _dhrHapgArn :: Maybe Text
, _dhrHapgSerial :: Maybe Text
, _dhrHsmsLastActionFailed :: List "HsmsLastActionFailed" Text
, _dhrHsmsPendingDeletion :: List "HsmsPendingDeletion" Text
, _dhrHsmsPendingRegistration :: List "HsmsPendingRegistration" Text
, _dhrLabel :: Maybe Text
, _dhrLastModifiedTimestamp :: Maybe Text
, _dhrPartitionSerialList :: List "PartitionSerialList" Text
, _dhrState :: Maybe CloudHsmObjectState
} deriving (Eq, Read, Show)
-- | 'DescribeHapgResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dhrHapgArn' @::@ 'Maybe' 'Text'
--
-- * 'dhrHapgSerial' @::@ 'Maybe' 'Text'
--
-- * 'dhrHsmsLastActionFailed' @::@ ['Text']
--
-- * 'dhrHsmsPendingDeletion' @::@ ['Text']
--
-- * 'dhrHsmsPendingRegistration' @::@ ['Text']
--
-- * 'dhrLabel' @::@ 'Maybe' 'Text'
--
-- * 'dhrLastModifiedTimestamp' @::@ 'Maybe' 'Text'
--
-- * 'dhrPartitionSerialList' @::@ ['Text']
--
-- * 'dhrState' @::@ 'Maybe' 'CloudHsmObjectState'
--
describeHapgResponse :: DescribeHapgResponse
describeHapgResponse = DescribeHapgResponse
{ _dhrHapgArn = Nothing
, _dhrHapgSerial = Nothing
, _dhrHsmsLastActionFailed = mempty
, _dhrHsmsPendingDeletion = mempty
, _dhrHsmsPendingRegistration = mempty
, _dhrLabel = Nothing
, _dhrLastModifiedTimestamp = Nothing
, _dhrPartitionSerialList = mempty
, _dhrState = Nothing
}
-- | The ARN of the high-availability partition group.
dhrHapgArn :: Lens' DescribeHapgResponse (Maybe Text)
dhrHapgArn = lens _dhrHapgArn (\s a -> s { _dhrHapgArn = a })
-- | The serial number of the high-availability partition group.
dhrHapgSerial :: Lens' DescribeHapgResponse (Maybe Text)
dhrHapgSerial = lens _dhrHapgSerial (\s a -> s { _dhrHapgSerial = a })
dhrHsmsLastActionFailed :: Lens' DescribeHapgResponse [Text]
dhrHsmsLastActionFailed =
lens _dhrHsmsLastActionFailed (\s a -> s { _dhrHsmsLastActionFailed = a })
. _List
dhrHsmsPendingDeletion :: Lens' DescribeHapgResponse [Text]
dhrHsmsPendingDeletion =
lens _dhrHsmsPendingDeletion (\s a -> s { _dhrHsmsPendingDeletion = a })
. _List
dhrHsmsPendingRegistration :: Lens' DescribeHapgResponse [Text]
dhrHsmsPendingRegistration =
lens _dhrHsmsPendingRegistration
(\s a -> s { _dhrHsmsPendingRegistration = a })
. _List
-- | The label for the high-availability partition group.
dhrLabel :: Lens' DescribeHapgResponse (Maybe Text)
dhrLabel = lens _dhrLabel (\s a -> s { _dhrLabel = a })
-- | The date and time the high-availability partition group was last modified.
dhrLastModifiedTimestamp :: Lens' DescribeHapgResponse (Maybe Text)
dhrLastModifiedTimestamp =
lens _dhrLastModifiedTimestamp
(\s a -> s { _dhrLastModifiedTimestamp = a })
-- | The list of partition serial numbers that belong to the high-availability
-- partition group.
dhrPartitionSerialList :: Lens' DescribeHapgResponse [Text]
dhrPartitionSerialList =
lens _dhrPartitionSerialList (\s a -> s { _dhrPartitionSerialList = a })
. _List
-- | The state of the high-availability partition group.
dhrState :: Lens' DescribeHapgResponse (Maybe CloudHsmObjectState)
dhrState = lens _dhrState (\s a -> s { _dhrState = a })
instance ToPath DescribeHapg where
toPath = const "/"
instance ToQuery DescribeHapg where
toQuery = const mempty
instance ToHeaders DescribeHapg
instance ToJSON DescribeHapg where
toJSON DescribeHapg{..} = object
[ "HapgArn" .= _dh1HapgArn
]
instance AWSRequest DescribeHapg where
type Sv DescribeHapg = CloudHSM
type Rs DescribeHapg = DescribeHapgResponse
request = post "DescribeHapg"
response = jsonResponse
instance FromJSON DescribeHapgResponse where
parseJSON = withObject "DescribeHapgResponse" $ \o -> DescribeHapgResponse
<$> o .:? "HapgArn"
<*> o .:? "HapgSerial"
<*> o .:? "HsmsLastActionFailed" .!= mempty
<*> o .:? "HsmsPendingDeletion" .!= mempty
<*> o .:? "HsmsPendingRegistration" .!= mempty
<*> o .:? "Label"
<*> o .:? "LastModifiedTimestamp"
<*> o .:? "PartitionSerialList" .!= mempty
<*> o .:? "State"
| dysinger/amazonka | amazonka-cloudhsm/gen/Network/AWS/CloudHSM/DescribeHapg.hs | mpl-2.0 | 6,794 | 0 | 29 | 1,538 | 1,050 | 616 | 434 | 114 | 1 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
import qualified Data.List ()
| lspitzner/brittany | data/Test469.hs | agpl-3.0 | 144 | 0 | 4 | 15 | 11 | 7 | 4 | 1 | 0 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TupleSections #-}
module MicroLens where
import Prelude hiding (sum)
import Data.Monoid
import qualified Data.Traversable as T
---------------------------------------------------------
-- Some basic libraries
class Profunctor p where
dimap :: (a' -> a) -> (b -> b') -> p a b -> p a' b'
dimap f g = lmap f . rmap g
lmap :: (a' -> a) -> p a b -> p a' b
lmap f = dimap f id
rmap :: (b -> b') -> p a b -> p a b'
rmap = dimap id
--
class Profunctor p => Choice p where
left' :: p a b -> p (Either a c) (Either b c)
right' :: p a b -> p (Either c a) (Either c b)
--
instance Profunctor (->) where
dimap f g h = g . h . f
--
instance Choice (->) where
left' f = either (Left . f) Right
right' = fmap
--
class Contravariant f where
contramap :: (a' -> a) -> (f a -> f a')
--
-- Control.Applicative.Const replicated here for your
-- convenience
newtype K b a = K { getK :: b } deriving Functor
instance Monoid b => Applicative (K b) where
pure _ = K mempty
K e <*> K f = K $ e <> f
--
instance Contravariant (K b) where
contramap _ (K b) = K b
--
newtype Id a = Id { getId :: a } deriving Functor
instance Applicative Id where
pure = Id
Id f <*> Id x = Id (f x)
--
---------------------------------------------------------
-- The lens types you'll implement
-- | Optic is the general pattern for all other lens types.
type Optic p f s t a b =
p a (f b) -> p s (f t)
--
type Lens s t a b =
forall f . Functor f =>
Optic (->) f s t a b
--
type Traversal s t a b =
forall f . Applicative f =>
Optic (->) f s t a b
--
type Fold s a =
forall f . (Contravariant f, Applicative f) =>
Optic (->) f s s a a
--
type Prism s t a b =
forall p f . (Choice p, Applicative f) =>
Optic p f s t a b
--
type Iso s t a b =
forall p f . (Profunctor p, Functor f) =>
Optic p f s t a b
--
---------------------------------------------------------
---------------------------------------------------------
-- Todo
-- | A lens focusing on the first element in a pair
-- f :: a -> Functor b
-- g :: (a, x) -> Functor (b, x)
_1 :: Lens (a, x) (b, x) a b
_1 f (a, x) = (, x) <$> f a
-- | A lens focusing on the second element in a pair
_2 :: Lens (x, a) (x, b) a b
_2 f (x, a) = (x, ) <$> f a
-- | A function which takes a lens and looks through it.
-- The type given is specialized to provide a hint as to
-- how to write 'view'. The more intuitive type for its use
-- is
--
-- @_@
-- view :: Lens s t a b -> (s -> a)
-- @_@
-- >_> (a -> K a b) -> (s -> K a t)
view :: Optic (->) (K a) s t a b -> (s -> a)
view f = getK . f K
-- | A function which takes a lens and a transformation function
-- and applies that transformer at the focal point of the lens.
-- The type given is specialized to provide a hint as to how to
-- write 'over'. The more intuitive type for its use is
--
-- @_@
-- over :: Lens s t a b -> (a -> b) -> (s -> t)
-- @_@
over :: Optic (->) Id s t a b -> (a -> b) -> (s -> t)
over l f = getId . l (Id . f)
-- | A function from a lens and a value which sets the value
-- at the focal point of the lens. The type given has been
-- specialized to provide a hint as to how to write 'set'. The
-- more intuitive type for its use is
--
-- @_@
-- set :: Lens s t a b -> b -> (s -> t)
-- @_@
-- >_> (a -> Id b) -> (s -> Id t)
set :: Optic (->) Id s t a b -> b -> (s -> t)
--set f b = getId . f (const $ Id b)
set f = over f . const
-- | A traversal which focuses on each element in any
-- Traversable container.
-- >_> (a -> App b) -> (f a -> App $ f b)
elements :: T.Traversable f => Traversal (f a) (f b) a b
elements = traverse
-- | A function which takes a Traversal and pulls out each
-- element it focuses on in order. The type has been
-- specialized, as the others, but a more normal type might be
--
-- @_@
-- toListOf :: Traversal s s a a -> (s -> [a])
-- @_@
-- >_> (a -> f a) -> (s -> f s)
toListOf :: Optic (->) (K (Endo [a])) s s a a -> s -> [a]
toListOf f = (`appEndo` []) . getK . f (K . Endo . (:))
-- | A function which takes any kind of Optic which might
-- be focused on zero subparts and returns Just the first
-- subpart or else Nothing.
--
-- @_@
-- preview :: Traversal s s a a -> (s -> Maybe a)
-- @_@
preview :: Optic (->) (K (First a)) s s a a -> s -> Maybe a
preview f = getFirst . getK . f (K . First . Just)
-- | A helper function which witnesses the fact that any
-- container which is both a Functor and a Contravariant
-- must actually be empty.
coerce :: (Contravariant f, Functor f) => f a -> f b
coerce = contramap (const ()) . (const () <$>)
-- | A Fold which views the result of a function application
-- contramap f :: (f b -> f a)
-- return type: (b -> f b) -> (a -> f a)
to :: (a -> b) -> Fold a b
to f g = coerce . g . f
-- | A prism which focuses on the left branch of an Either
_Left :: Prism (Either a x) (Either b x) a b
_Left = rmap (either (Left <$>) $ pure . Right) . left'
-- | A prism which focuses on the right branch of an Either
_Right :: Prism (Either x a) (Either x b) a b
_Right = rmap (either (pure . Left) (Right <$>)) . right'
-- | An iso which witnesses that tuples can be flipped without
-- losing any information
-- dimap :: (a1 -> a) -> (b -> b1) -> (a -> b) -> (a1 -> b1)
-- >_> (ba -> f ba) ->> (ab -> f ab)
_flip :: Iso (a, b) (a, b) (b, a) (b, a)
_flip = dimap flipT (flipT <$>)
where flipT (a, b) = (b, a)
--
| ice1000/OI-codes | codewars/301-400/lensmaker.hs | agpl-3.0 | 5,433 | 0 | 11 | 1,352 | 1,638 | 914 | 724 | 78 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Tetris.Block.Dir where
import GHC.Prim (Constraint)
data Right = Right
data Down = Down
data RightUp = RightUp
class Dir d
instance Dir Right
instance Dir Down
instance Dir RightUp
class (Dir d) => CanBeFirst d
instance CanBeFirst Right
instance CanBeFirst Down
class CanGo from to
instance CanGo Right Right
instance CanGo Right Down
instance CanGo Down Right
instance CanGo Down Down
instance CanGo Down RightUp
instance CanGo RightUp Right
instance CanGo RightUp Down
class DirToFun dir ctx x where
toF :: dir -> ctx -> x -> Maybe x
| melrief/tetris | src/Tetris/Block/Dir.hs | apache-2.0 | 653 | 0 | 10 | 165 | 202 | 98 | 104 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Test.Grenade.Layers.PadCrop where
import Grenade
import Hedgehog
import Numeric.LinearAlgebra.Static ( norm_Inf )
import Test.Hedgehog.Hmatrix
prop_pad_crop :: Property
prop_pad_crop =
let net :: Network '[Pad 2 3 4 6, Crop 2 3 4 6] '[ 'D3 7 9 5, 'D3 16 15 5, 'D3 7 9 5 ]
net = Pad :~> Crop :~> NNil
in property $
forAll genOfShape >>= \(d :: S ('D3 7 9 5)) ->
let (tapes, res) = runForwards net d
(_ , grad) = runBackwards net tapes d
in do assert $ d ~~~ res
assert $ grad ~~~ d
prop_pad_crop_2d :: Property
prop_pad_crop_2d =
let net :: Network '[Pad 2 3 4 6, Crop 2 3 4 6] '[ 'D2 7 9, 'D2 16 15, 'D2 7 9 ]
net = Pad :~> Crop :~> NNil
in property $
forAll genOfShape >>= \(d :: S ('D2 7 9)) ->
let (tapes, res) = runForwards net d
(_ , grad) = runBackwards net tapes d
in do assert $ d ~~~ res
assert $ grad ~~~ d
(~~~) :: S x -> S x -> Bool
(S1D x) ~~~ (S1D y) = norm_Inf (x - y) < 0.00001
(S2D x) ~~~ (S2D y) = norm_Inf (x - y) < 0.00001
(S3D x) ~~~ (S3D y) = norm_Inf (x - y) < 0.00001
tests :: IO Bool
tests = checkParallel $$(discover)
| HuwCampbell/grenade | test/Test/Grenade/Layers/PadCrop.hs | bsd-2-clause | 1,521 | 0 | 14 | 475 | 593 | 304 | 289 | 39 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-| Helpers for creating various kinds of 'Field's.
They aren't directly needed for the Template Haskell code in Ganeti.THH,
so better keep them in a separate module.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.THH.Field
( specialNumericalField
, timeAsDoubleField
, timeStampFields
, uuidFields
, serialFields
, TagSet
, tagsFields
, fileModeAsIntField
, processIdField
) where
import Control.Monad
import qualified Data.ByteString as BS
import qualified Data.Set as Set
import Language.Haskell.TH
import qualified Text.JSON as JSON
import System.Posix.Types (FileMode, ProcessID)
import System.Time (ClockTime(..))
import Ganeti.JSON
import Ganeti.THH
-- * Internal functions
-- | Wrapper around a special parse function, suitable as field-parsing
-- function.
numericalReadFn :: JSON.JSON a => (String -> JSON.Result a)
-> [(String, JSON.JSValue)] -> JSON.JSValue -> JSON.Result a
numericalReadFn _ _ v@(JSON.JSRational _ _) = JSON.readJSON v
numericalReadFn f _ (JSON.JSString x) = f $ JSON.fromJSString x
numericalReadFn _ _ _ = JSON.Error "A numerical field has to be a number or\
\ a string."
-- | Sets the read function to also accept string parsable by the given
-- function.
specialNumericalField :: Name -> Field -> Field
specialNumericalField f field =
field { fieldRead = Just (appE (varE 'numericalReadFn) (varE f)) }
-- | Creates a new mandatory field that reads time as the (floating point)
-- number of seconds since the standard UNIX epoch, and represents it in
-- Haskell as 'ClockTime'.
timeAsDoubleField :: String -> Field
timeAsDoubleField fname =
(simpleField fname [t| ClockTime |])
{ fieldRead = Just $ [| \_ -> liftM unTimeAsDoubleJSON . JSON.readJSON |]
, fieldShow = Just $ [| \c -> (JSON.showJSON $ TimeAsDoubleJSON c, []) |]
}
-- | A helper function for creating fields whose Haskell representation is
-- 'Integral' and which are serialized as numbers.
integralField :: Q Type -> String -> Field
integralField typq fname =
let (~->) = appT . appT arrowT -- constructs an arrow type
(~::) = sigE . varE -- (f ~:: t) constructs (f :: t)
in (simpleField fname typq)
{ fieldRead = Just $
[| \_ -> liftM $('fromInteger ~:: (conT ''Integer ~-> typq))
. JSON.readJSON |]
, fieldShow = Just $
[| \c -> (JSON.showJSON
. $('toInteger ~:: (typq ~-> conT ''Integer))
$ c, []) |]
}
-- * External functions and data types
-- | Timestamp fields description.
timeStampFields :: [Field]
timeStampFields = map (defaultField [| TOD 0 0 |] . timeAsDoubleField)
["ctime", "mtime"]
-- | Serial number fields description.
serialFields :: [Field]
serialFields =
[ presentInForthcoming . renameField "Serial"
$ simpleField "serial_no" [t| Int |] ]
-- | UUID fields description.
uuidFields :: [Field]
uuidFields = [ presentInForthcoming $ simpleField "uuid" [t| BS.ByteString |] ]
-- | Tag set type alias.
type TagSet = Set.Set String
-- | Tag field description.
tagsFields :: [Field]
tagsFields = [ defaultField [| Set.empty |] $
simpleField "tags" [t| TagSet |] ]
-- ** Fields related to POSIX data types
-- | Creates a new mandatory field that reads a file mode in the standard
-- POSIX file mode representation. The Haskell type of the field is 'FileMode'.
fileModeAsIntField :: String -> Field
fileModeAsIntField = integralField [t| FileMode |]
-- | Creates a new mandatory field that contains a POSIX process ID.
processIdField :: String -> Field
processIdField = integralField [t| ProcessID |]
| leshchevds/ganeti | src/Ganeti/THH/Field.hs | bsd-2-clause | 4,987 | 0 | 11 | 1,019 | 661 | 397 | 264 | 62 | 1 |
--
-- Copyright 2014, NICTA
--
-- This software may be distributed and modified according to the terms of
-- the BSD 2-Clause license. Note that NO WARRANTY is provided.
-- See "LICENSE_BSD2.txt" for details.
--
-- @TAG(NICTA_BSD)
--
-- Functions for generating domain schedule from an input specification.
module OutputConfig (showConfig) where
import Data.List (elemIndex)
import Data.Maybe (fromJust)
import Objects
import Utils
-- |Configuration schedule to be compiled into the kernel. Note that the
-- generated schedule intentionally ignored the initial (booter) thread that
-- shares its domain with the first cell. This can cause some quirks in the
-- boot process if this cell has a low schedule rate.
showConfig :: Double -> Double -> [SpecObject] -> String
showConfig factor total cells =
unlines ["#include <object/structures.h>",
"#include <model/statedata.h>",
"",
"const dschedule_t ksDomSchedule[] = {",
schedules,
"};",
"",
"const unsigned int ksDomScheduleLength = sizeof(ksDomSchedule) / sizeof(dschedule_t);"]
where
schedules = indent 1 $ unlines $ map (\c ->
"{ .domain = " ++
(show $ fromJust $ elemIndex c cells) ++
", .length = " ++
-- NB: total is in µs, factor is Hz and we want time slices.
(show $ round $ total * (fromIntegral $ cell_rate c) / 100 / (10 ^ 6 / factor)) ++
"},") cells
| NICTA/sk-config | src/OutputConfig.hs | bsd-2-clause | 1,462 | 0 | 19 | 358 | 216 | 126 | 90 | 21 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Default
import qualified Network.HTTPMultiplexer.Config as MITM
import qualified Network.HTTPMultiplexer.Tee as MITM
import qualified Network.Wai as Wai
import qualified Network.Wai.Middleware.RequestLogger as Wai
import qualified Network.Wai.Handler.Warp as Warp
import Options.Applicative
import qualified System.Log.FastLogger as LOG
main :: IO ()
main = do
configFilePath <- execParser options
MITM.withConfigFile configFilePath $ \config -> do
let backends = MITM.cfgBackendAddress config
log_filepath = MITM.cfgLogFilePath config
fileLoggerSet <- LOG.newFileLoggerSet LOG.defaultBufSize log_filepath
requestLogger <- Wai.mkRequestLogger def
Warp.run 8000 (requestLogger (MITM.teeProxy backends fileLoggerSet))
where
parser = strOption (
long "config"
<> noArgError ShowHelpText
<> metavar "CONFIG"
<> value "config/mitmproxy.yaml"
<> help "configuration filepath"
)
options = info parser (fullDesc <> progDesc "http-multiplexer: http request mutiplexer")
| BrandKarma/http-multiplexer | src/Main.hs | bsd-3-clause | 1,113 | 0 | 16 | 201 | 254 | 138 | 116 | 26 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] he
[@ISO639-2@] heb
[@ISO639-3@] heb
[@Native name@] עִבְרִית
[@English name@] Modern Hebrew
-}
module Text.Numeral.Language.HEB
( -- * Language entry
entry
-- * Conversions
, cardinal
-- * Structure
, struct
-- * Bounds
, bounds
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Data.Bool ( otherwise )
import "base" Data.Function ( ($), fix )
import "base" Data.List ( concat )
import "base" Data.Maybe ( Maybe(Just) )
import "base" Prelude ( Integral, (+), div, negate )
import "base-unicode-symbols" Data.Function.Unicode ( (∘) )
import "base-unicode-symbols" Data.Monoid.Unicode ( (⊕) )
import "base-unicode-symbols" Data.Ord.Unicode ( (≤) )
import qualified "containers" Data.Map as M ( fromList, lookup )
import "this" Text.Numeral
import qualified "this" Text.Numeral.Exp as E
import "this" Text.Numeral.Grammar as G
import "this" Text.Numeral.Entry
import "text" Data.Text ( Text )
--------------------------------------------------------------------------------
-- HEB
--------------------------------------------------------------------------------
entry ∷ Entry
entry = emptyEntry
{ entIso639_1 = Just "he"
, entIso639_2 = ["heb"]
, entIso639_3 = Just "heb"
, entNativeNames = ["עִבְרִית"]
, entEnglishName = Just "Modern Hebrew"
, entCardinal = Just Conversion
{ toNumeral = cardinal
, toStructure = struct
}
}
cardinal ∷ (G.Plural i, G.Dual i, Integral α)
⇒ i → α → Maybe Text
cardinal inf = cardinalRepr inf ∘ struct
struct ∷ ( Integral α
, E.Unknown β, E.Lit β, E.Neg β, E.Add β, E.Mul β
, E.Inflection β, G.Plural (E.Inf β), G.Dual (E.Inf β)
)
⇒ α → β
struct = pos
$ fix
$ findRule ( 0, lit)
( [ (11, add 10 L)
, (20, inflection G.dual ∘ mapRule (`div` 10) lit)
, (21, add 20 R)
]
⊕ concat [ [ (n, inflection G.plural ∘ mapRule (`div` 10) lit)
, (n+1, add n R)
]
| n ← [20,30..90]
]
⊕ [ (100, step 100 10 R L)
, (200, inflection G.dual ∘ mapRule (`div` 2) lit)
, (201, add 200 R)
, (300, step 100 10 R L)
]
)
1000
bounds ∷ (Integral α) ⇒ (α, α)
bounds = let x = 1000 in (negate x, x)
-- TODO: Handle inflection, mainly masculine and feminine
-- gender. Maybe get rid of Dual and Plural in the expression language
-- and use grammatical number for that.
cardinalRepr ∷ (G.Plural i, G.Dual i) ⇒ i → Exp i → Maybe Text
cardinalRepr = render defaultRepr
{ reprValue = \i n → M.lookup n (syms i)
, reprAdd = Just (⊞)
, reprMul = Just (⊡)
, reprNeg = Just $ \_ _ → "מינוס "
, reprAddCombine = Just addCombine
}
where
(_ ⊞ Lit 10) _ = "ה"
(Inflection _ _ ⊞ _) _ = " ו"
(_ ⊞ _) _ = " "
(_ ⊡ Lit 10) _ = ""
(_ ⊡ _ ) _ = " "
addCombine a x _ y (Lit 10) = x ⊕ " " ⊕ y ⊕ a
addCombine a x _ y _ = x ⊕ a ⊕ y
syms inf =
M.fromList
[ (0, \c → case c of
_ → "אפס"
)
, (1, \c → case c of
_ → "אחת"
)
, (2, \c → case c of
CtxAdd _ (Lit 10) _ → "שתים"
_ | G.isDual inf → "עשרים"
| otherwise → "שתיים"
)
, (3, \c → case c of
_ | G.isPlural inf → "שלושים"
| otherwise → "שלוש"
)
, (4, \c → case c of
_ | G.isPlural inf → "ארבעים"
| otherwise → "ארבע"
)
, (5, \c → case c of
_ | G.isPlural inf → "חמישים"
| otherwise → "חמש"
)
, (6, \c → case c of
_ | G.isPlural inf → "ששים"
| otherwise → "שש"
)
, (7, \c → case c of
_ | G.isPlural inf → "שבעים"
| otherwise → "שבע"
)
, (8, \c → case c of
_ | G.isPlural inf → "שמונים"
| otherwise → "שמונה"
)
, (9, \c → case c of
_ | G.isPlural inf → "תשעים"
| otherwise → "תשע"
)
, (10, \c → case c of
CtxMul _ (Lit n) _ | n ≤ 9 → ""
_ → "עשר"
)
, (100, \c → case c of
_ | G.isDual inf → "מאתיים"
| G.isPlural inf → "מאות"
| otherwise → "מאה"
)
, (1000, \c → case c of
_ → "אלף"
)
]
| telser/numerals | src/Text/Numeral/Language/HEB.hs | bsd-3-clause | 5,941 | 15 | 18 | 2,541 | 1,557 | 871 | 686 | 112 | 7 |
module Block
(
doit
) where
import DumpLevelDB
import Blockchain.Format
--import Debug.Trace
doit::String->String->IO ()
--doit dbtype h = showKeyVal (formatBlock . rlpDecode . rlpDeserialize) dbtype "blocks" (if h == "-" then Nothing else Just h)
doit dbtype h = showKeyVal format dbtype "blockchain" (if h == "-" then Nothing else Just h)
| jamshidh/ethereum-query | src/Block.hs | bsd-3-clause | 366 | 0 | 8 | 77 | 74 | 41 | 33 | 7 | 2 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Extra functions for optparse-applicative.
module Options.Applicative.Builder.Extra
(boolFlags
,boolFlagsNoDefault
,maybeBoolFlags
,firstBoolFlags
,enableDisableFlags
,enableDisableFlagsNoDefault
,extraHelpOption
,execExtraHelp
,textOption
,textArgument
,optionalFirst
,absFileOption
,relFileOption
,absDirOption
,relDirOption
,eitherReader'
,fileCompleter
,fileExtCompleter
,dirCompleter
,PathCompleterOpts(..)
,defaultPathCompleterOpts
,pathCompleterWith
,unescapeBashArg
) where
import Control.Monad (when, forM)
import Control.Monad.IO.Unlift
import Data.Either.Combinators
import Data.List (isPrefixOf)
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Options.Applicative
import Options.Applicative.Types (readerAsk)
import Path hiding ((</>))
import System.Directory (getCurrentDirectory, getDirectoryContents, doesDirectoryExist)
import System.Environment (withArgs)
import System.FilePath (takeBaseName, (</>), splitFileName, isRelative, takeExtension)
-- | Enable/disable flags for a 'Bool'.
boolFlags :: Bool -- ^ Default value
-> String -- ^ Flag name
-> String -- ^ Help suffix
-> Mod FlagFields Bool
-> Parser Bool
boolFlags defaultValue = enableDisableFlags defaultValue True False
-- | Enable/disable flags for a 'Bool', without a default case (to allow chaining with '<|>').
boolFlagsNoDefault :: String -- ^ Flag name
-> String -- ^ Help suffix
-> Mod FlagFields Bool
-> Parser Bool
boolFlagsNoDefault = enableDisableFlagsNoDefault True False
-- | Enable/disable flags for a @('Maybe' 'Bool')@.
maybeBoolFlags :: String -- ^ Flag name
-> String -- ^ Help suffix
-> Mod FlagFields (Maybe Bool)
-> Parser (Maybe Bool)
maybeBoolFlags = enableDisableFlags Nothing (Just True) (Just False)
-- | Like 'maybeBoolFlags', but parsing a 'First'.
firstBoolFlags :: String -> String -> Mod FlagFields (Maybe Bool) -> Parser (First Bool)
firstBoolFlags long0 help0 mod0 = First <$> maybeBoolFlags long0 help0 mod0
-- | Enable/disable flags for any type.
enableDisableFlags :: a -- ^ Default value
-> a -- ^ Enabled value
-> a -- ^ Disabled value
-> String -- ^ Name
-> String -- ^ Help suffix
-> Mod FlagFields a
-> Parser a
enableDisableFlags defaultValue enabledValue disabledValue name helpSuffix mods =
enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods <|>
pure defaultValue
-- | Enable/disable flags for any type, without a default (to allow chaining with '<|>')
enableDisableFlagsNoDefault :: a -- ^ Enabled value
-> a -- ^ Disabled value
-> String -- ^ Name
-> String -- ^ Help suffix
-> Mod FlagFields a
-> Parser a
enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods =
last <$> some
((flag'
enabledValue
(hidden <>
internal <>
long name <>
help helpSuffix <>
mods) <|>
flag'
disabledValue
(hidden <>
internal <>
long ("no-" ++ name) <>
help helpSuffix <>
mods)) <|>
flag'
disabledValue
(long ("[no-]" ++ name) <>
help ("Enable/disable " ++ helpSuffix) <>
mods))
-- | Show an extra help option (e.g. @--docker-help@ shows help for all @--docker*@ args).
--
-- To actually have that help appear, use 'execExtraHelp' before executing the main parser.
extraHelpOption :: Bool -- ^ Hide from the brief description?
-> String -- ^ Program name, e.g. @"stack"@
-> String -- ^ Option glob expression, e.g. @"docker*"@
-> String -- ^ Help option name, e.g. @"docker-help"@
-> Parser (a -> a)
extraHelpOption hide progName fakeName helpName =
infoOption (optDesc' ++ ".") (long helpName <> hidden <> internal) <*>
infoOption (optDesc' ++ ".") (long fakeName <>
help optDesc' <>
(if hide then hidden <> internal else idm))
where optDesc' = concat ["Run '", takeBaseName progName, " --", helpName, "' for details"]
-- | Display extra help if extra help option passed in arguments.
--
-- Since optparse-applicative doesn't allow an arbitrary IO action for an 'abortOption', this
-- was the best way I found that doesn't require manually formatting the help.
execExtraHelp :: [String] -- ^ Command line arguments
-> String -- ^ Extra help option name, e.g. @"docker-help"@
-> Parser a -- ^ Option parser for the relevant command
-> String -- ^ Option description
-> IO ()
execExtraHelp args helpOpt parser pd =
when (args == ["--" ++ helpOpt]) $
withArgs ["--help"] $ do
_ <- execParser (info (hiddenHelper <*>
((,) <$>
parser <*>
some (strArgument (metavar "OTHER ARGUMENTS"))))
(fullDesc <> progDesc pd))
return ()
where hiddenHelper = abortOption ShowHelpText (long "help" <> hidden <> internal)
-- | 'option', specialized to 'Text'.
textOption :: Mod OptionFields Text -> Parser Text
textOption = option (T.pack <$> readerAsk)
-- | 'argument', specialized to 'Text'.
textArgument :: Mod ArgumentFields Text -> Parser Text
textArgument = argument (T.pack <$> readerAsk)
-- | Like 'optional', but returning a 'First'.
optionalFirst :: Alternative f => f a -> f (First a)
optionalFirst = fmap First . optional
absFileOption :: Mod OptionFields (Path Abs File) -> Parser (Path Abs File)
absFileOption mods = option (eitherReader' parseAbsFile) $
completer (pathCompleterWith defaultPathCompleterOpts { pcoRelative = False }) <> mods
relFileOption :: Mod OptionFields (Path Rel File) -> Parser (Path Rel File)
relFileOption mods = option (eitherReader' parseRelFile) $
completer (pathCompleterWith defaultPathCompleterOpts { pcoAbsolute = False }) <> mods
absDirOption :: Mod OptionFields (Path Abs Dir) -> Parser (Path Abs Dir)
absDirOption mods = option (eitherReader' parseAbsDir) $
completer (pathCompleterWith defaultPathCompleterOpts { pcoRelative = False, pcoFileFilter = const False }) <> mods
relDirOption :: Mod OptionFields (Path Rel Dir) -> Parser (Path Rel Dir)
relDirOption mods = option (eitherReader' parseRelDir) $
completer (pathCompleterWith defaultPathCompleterOpts { pcoAbsolute = False, pcoFileFilter = const False }) <> mods
-- | Like 'eitherReader', but accepting any @'Show' e@ on the 'Left'.
eitherReader' :: Show e => (String -> Either e a) -> ReadM a
eitherReader' f = eitherReader (mapLeft show . f)
data PathCompleterOpts = PathCompleterOpts
{ pcoAbsolute :: Bool
, pcoRelative :: Bool
, pcoRootDir :: Maybe FilePath
, pcoFileFilter :: FilePath -> Bool
, pcoDirFilter :: FilePath -> Bool
}
defaultPathCompleterOpts :: PathCompleterOpts
defaultPathCompleterOpts = PathCompleterOpts
{ pcoAbsolute = True
, pcoRelative = True
, pcoRootDir = Nothing
, pcoFileFilter = const True
, pcoDirFilter = const True
}
fileCompleter :: Completer
fileCompleter = pathCompleterWith defaultPathCompleterOpts
fileExtCompleter :: [String] -> Completer
fileExtCompleter exts = pathCompleterWith defaultPathCompleterOpts { pcoFileFilter = (`elem` exts) . takeExtension }
dirCompleter :: Completer
dirCompleter = pathCompleterWith defaultPathCompleterOpts { pcoFileFilter = const False }
pathCompleterWith :: PathCompleterOpts -> Completer
pathCompleterWith PathCompleterOpts {..} = mkCompleter $ \inputRaw -> do
-- Unescape input, to handle single and double quotes. Note that the
-- results do not need to be re-escaped, due to some fiddly bash
-- magic.
let input = unescapeBashArg inputRaw
let (inputSearchDir0, searchPrefix) = splitFileName input
inputSearchDir = if inputSearchDir0 == "./" then "" else inputSearchDir0
msearchDir <-
case (isRelative inputSearchDir, pcoAbsolute, pcoRelative) of
(True, _, True) -> do
rootDir <- maybe getCurrentDirectory return pcoRootDir
return $ Just (rootDir </> inputSearchDir)
(False, True, _) -> return $ Just inputSearchDir
_ -> return Nothing
case msearchDir of
Nothing
| input == "" && pcoAbsolute -> return ["/"]
| otherwise -> return []
Just searchDir -> do
entries <- getDirectoryContents searchDir `catch` \(_ :: IOException) -> return []
fmap catMaybes $ forM entries $ \entry ->
-- Skip . and .. unless user is typing . or ..
if entry `elem` ["..", "."] && searchPrefix `notElem` ["..", "."] then return Nothing else
if searchPrefix `isPrefixOf` entry
then do
let path = searchDir </> entry
case (pcoFileFilter path, pcoDirFilter path) of
(True, True) -> return $ Just (inputSearchDir </> entry)
(fileAllowed, dirAllowed) -> do
isDir <- doesDirectoryExist path
if (if isDir then dirAllowed else fileAllowed)
then return $ Just (inputSearchDir </> entry)
else return Nothing
else return Nothing
unescapeBashArg :: String -> String
unescapeBashArg ('\'' : rest) = rest
unescapeBashArg ('\"' : rest) = go rest
where
go [] = []
go ('\\' : x : xs)
| x `elem` "$`\"\\\n" = x : xs
| otherwise = '\\' : x : go xs
go (x : xs) = x : go xs
unescapeBashArg input = go input
where
go [] = []
go ('\\' : x : xs) = x : go xs
go (x : xs) = x : go xs
| martin-kolinek/stack | src/Options/Applicative/Builder/Extra.hs | bsd-3-clause | 10,634 | 2 | 29 | 3,238 | 2,360 | 1,256 | 1,104 | 203 | 10 |
module Main where
import Bookkeeper
import Criterion.Main
type PersonB = Book '[ "name" :=> String, "age" :=> Int ]
data PersonR = PersonR { name :: String, age :: {-# NOUNPACK #-} Int } deriving (Eq, Show)
pb :: PersonB
pb = emptyBook
& #name =: ""
& #age =: 0
pr :: PersonR
pr = PersonR
{ name = ""
, age = 0
}
modB :: Int -> PersonB
modB 0 = pb
modB n = modB (n - 1) & #age %: (+ n)
modR :: Int -> PersonR
modR 0 = pr
modR n = let p = modR (n - 1) in p { age = age p + n }
main :: IO ()
main = defaultMain
[ bgroup "modB" [ bench "10" $ nf (\x -> get #age $ modB x) 10
, bench "100" $ nf (\x -> get #age $ modB x) 100
]
, bgroup "modR" [ bench "10" $ nf (\x -> age $ modR x) 10
, bench "100" $ nf (\x -> age $ modR x) 100
]
]
| turingjump/bookkeeper | bench/Main.hs | bsd-3-clause | 830 | 0 | 14 | 283 | 388 | 206 | 182 | -1 | -1 |
{-
This module contains definitions for HaCoTeB types: AST nodes and other
intermediate data structures
-}
module HaCoTeB.Types where
newtype AST = AST [Section] deriving (Eq, Show, Read)
data Section
= TextSection Content
| CodeSection Content
| DecoratedSection [Decoration] Content
deriving (Eq, Show, Read)
data Decoration
= Alignment Align
| ColorDec String
| PreformattedDec
| Heading Int
deriving (Eq, Show, Read)
data Align
= Center
| Full
| RightAllign
| LeftAllign
deriving (Eq, Show, Read)
data Content
= SimpleContent String
| FormattedContent [Format] String
| MixedContent [Content]
deriving (Eq, Show, Read)
data Format
= Bold
| Italic
| Underline
| Strikeout
| Preformatted
| Color String
deriving (Eq, Show, Read)
| mihaimaruseac/HaCoTeB | src/HaCoTeB/Types.hs | bsd-3-clause | 789 | 0 | 7 | 168 | 221 | 128 | 93 | 32 | 0 |
module Zero.Crypto.Client
(
generateInteger
, generateBytes
) where
import Control.Monad.IO.Class (liftIO)
import Data.Typeable
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.JSString as JSS
import Data.JSString (JSString)
import GHCJS.Types (JSVal, IsJSVal)
import Reflex.Dom.Core
import System.Random
------------------------------------------------------------------------------
newtype UInt8Array = UInt8Array JSVal
deriving (Typeable)
instance IsJSVal UInt8Array
generateInteger :: MonadWidget t m => Event t () -> m (Event t Integer)
generateInteger e =
performEvent (fmap (\_ -> liftIO $ getStdRandom (randomR ((2^512), (2^1024)))) e)
generateBytes :: Int -> IO Text
generateBytes size = do
arr <- js_newUInt8Array size
js_getRandomValues arr
str <- js_bufferFromAsHex arr
return $ T.pack $ JSS.unpack str
------------------------------------------------------------------------------
foreign import javascript unsafe "$r = new Uint8Array($1);"
js_newUInt8Array :: Int -> IO UInt8Array
foreign import javascript unsafe "window.crypto.getRandomValues($1);"
js_getRandomValues :: UInt8Array -> IO ()
foreign import javascript unsafe "$r = zero.buffer.Buffer.from($1).toString('hex').toUpperCase();"
js_bufferFromAsHex :: UInt8Array -> IO JSString
| et4te/zero | src/Zero/Crypto/Client.hs | bsd-3-clause | 1,392 | 8 | 17 | 250 | 342 | 185 | 157 | 31 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Language.GDL.Syntax
( Sexp (..)
, Identifier, Term (..), Query (..), Clause, Database
, State, Role, Move
, escape, unescape
, sexpToInt, termToInt
, (|+|)
) where
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Word
import Data.Data
import Data.Function (on)
import Data.List
import qualified Data.Map as M
import Data.String
data Sexp = SAtom ByteString | SList [Sexp]
deriving (Eq, Show, Data, Typeable)
instance IsString Sexp where
fromString = SAtom . B8.pack
type Identifier = ByteString
data Term = Atom ByteString
| Var Identifier
| Compound [Term]
| AntiVar Identifier
| Wild
deriving (Eq, Ord, Show, Data, Typeable)
instance IsString Term where
fromString = Atom . B8.pack
data Query = Query Term
| And [Query]
| Or [Query]
| Not Query
| Distinct Term Term
| Pass
deriving (Eq, Ord, Show, Data, Typeable)
type Clause = (Term, Query)
type Database = M.Map ByteString [Clause]
type Role = Term
type Move = Term
type State = [Clause]
-- | Escape @"@ and @\@ in the given string. This needs to be done
-- for double-quoted atoms (e.g. @"\"Hello\", he said"@).
escape :: String -> String
escape = concatMap escapeChar
where
escapeChar '\\' = "\\\\"
escapeChar '"' = "\\\""
escapeChar c = [c]
-- | The inverse of 'escape'.
unescape :: ByteString -> ByteString
unescape = B.reverse . B.pack . snd .
(foldl' unescapeChar (False, [])) . B.unpack
where
unescapeChar :: (Bool, [Word8]) -> Word8 -> (Bool, [Word8])
unescapeChar (False, cs) c = if c == fromIntegral (ord '\\')
then (True, cs)
else (False, c : cs)
unescapeChar (_, cs) c = (False, c : cs)
sexpToInt :: Sexp -> Maybe Int
sexpToInt (SAtom s) = case B8.readInt s of
Nothing -> Nothing
Just (i, rest) -> if B.null rest then Just i else Nothing
sexpToInt _ = Nothing
termToInt :: Term -> Maybe Int
termToInt (Atom s) = case B8.readInt s of
Nothing -> Nothing
Just (i, rest) -> if B.null rest then Just i else Nothing
termToInt _ = Nothing
(|+|) :: Database -> [Clause] -> Database
db |+| sts = db `M.union` stdb
where stdb = M.fromList $
map (\cs -> (fst $ head cs, map snd cs)) $
groupBy ((==) `on` fst) $
sortBy (compare `on` fst) $
map convert sts
convert c = (termName c, c)
termName (Atom s, _) = s
termName (Compound ((Atom s) : _), _) = s
termName _ = error "termName!"
| ian-ross/ggp | Language/GDL/Syntax.hs | bsd-3-clause | 2,791 | 0 | 16 | 824 | 951 | 539 | 412 | 77 | 3 |
module Main where
import qualified Data.Map
import Data.List (intercalate)
import System.Random
import System.Random.Shuffle
import System.IO.Strict as St
-- | String partitions
partitionAll :: Int -> Int -> [a] -> [[a]]
partitionAll a b [] = []
partitionAll a b xs = take a xs : (partitionAll a b (drop b xs))
-- | Create a chain using a Map
wordChain :: [[String]] -> Data.Map.Map [String] [String]
wordChain [] = Data.Map.empty
wordChain xs = calcWordChain xs Data.Map.empty (length (head xs))
-- | Calculate Word Chain
calcWordChain :: [[String]] -> Data.Map.Map [String] [String] -> Int -> Data.Map.Map [String] [String]
calcWordChain [] m n = m
calcWordChain (x:xs) m n | length x == ( n - 1 ) = calcWordChain xs ev n
| length x == 1 = calcWordChain xs ek n
| Data.Map.member (init x) m = calcWordChain xs cm n
| otherwise = calcWordChain xs nm n
where nm = Data.Map.insert (init x) [last x] m
cm = Data.Map.insert (init x) (( m Data.Map.! (init x) ) ++ [last x]) m
ev = Data.Map.insert x [] m
ek = Data.Map.insert ( x ++ [""] ) [] m
-- | Convert text to word chain
textToWordChain x = wordChain (partitionAll 3 1 ( words x))
-- | Convert chain to text
chainToText :: [String] -> String
chainToText= intercalate " "
-- | walkChain
walkChain :: [String] -> Data.Map.Map [String] [String] -> [String] -> IO [String]
walkChain p c r | null suffixes = return r
| otherwise = do
ncc <- newResCharCount
if ncc >= 140 then
return r
else do
np <- newPref
suf <- suffix
walkChain np c ( r ++ [suf] )
where suffixes | p `elem` (Data.Map.keys c) = c Data.Map.! p
| otherwise = []
suffix :: IO String
suffix = do
g <- newStdGen
let rndSuf = shuffle' suffixes (length suffixes) g
return $ head rndSuf
newPref = do
suf <- suffix
return $ (last p) : suf : []
resultWithSpaces = chainToText r
resultCharCount = length resultWithSpaces
suffixCharCount = do
suf <- suffix
return $ (length suf ) + 1
newResCharCount = do
sc <- suffixCharCount
return $ resultCharCount + sc
-- | Generate text
generateText st wc = do
rs <- resChain
return $ chainToText rs
where prefix = words st
resChain = walkChain prefix wc prefix
-- | Process file NOT USED
processFile fname = do
contents <- St.readFile fname
return $ textToWordChain contents
-- | Files
files = ["resources/quangle-wangle.txt",
"resources/functional.txt",
"resources/haskell.txt",
"resources/quixote.txt"]
-- | Merge file contents into one string
getFilesContent xs = appendConts "" xs
where appendConts st [] = return st
appendConts st (y:ys) = do
conts <- St.readFile y
let new = st ++ " " ++ conts
appendConts new ys
-- | Get a prefix list
prefixList = do
conts <- St.readFile "resources/prefix_list.txt"
return (lines conts)
-- | Replace char in string
replace st c w = map (\x -> if x == c then w else x) st
-- | End punctuation
endLastPunct st = replace ct '"' '\''
where rt = trimToLastPunct st
ct = if last rt == ',' ||
last rt == ' '
then (init rt) ++ ['.']
else rt ++ ['.']
trimToLastPunct st | elem ',' st || elem '.' st = trimPunct (reverse st)
| otherwise = st
where trimPunct (x:xs) | x == ',' || x == '.' = reverse xs
| otherwise = trimPunct xs
-- | Generate Tweet
tweetText = do
g <- newStdGen
prefLst <- prefixList
let rndSuf = shuffle' prefLst (length prefLst) g
let prefix = head rndSuf
conts <- getFilesContent files
let chain = textToWordChain conts
text <- generateText prefix chain
let res = endLastPunct text
putStrLn res
main :: IO ()
main = tweetText
| hugo-dc/hsmarkov | src/Main.hs | bsd-3-clause | 4,322 | 0 | 14 | 1,525 | 1,430 | 718 | 712 | 97 | 2 |
module Teste2 where
class Mult a b c where
(.*.) :: a -> b -> c
instance Mult a b c => Mult a [b] [c]
f :: (Mult a [b] b) => Bool -> a -> b -> b
f b x y = if b then x .*. [y] else y
| emcardoso/CTi | src/Tests/Teste2.hs | bsd-3-clause | 195 | 0 | 8 | 66 | 120 | 65 | 55 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeOperators #-}
module Data.InvertibleGrammar.Combinators
( iso
, osi
, partialIso
, partialOsi
, push
, pair
, swap
, cons
, nil
, insert
, insertMay
, toDefault
, coproduct
, onHead
, onTail
, traversed
, flipped
, sealed
, coerced
, annotated
) where
import Control.Category ((>>>))
import Data.Coerce
import Data.Maybe
import Data.Void
import Data.Text (Text)
import Data.InvertibleGrammar.Base
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup
#endif
-- | Isomorphism on the stack head.
iso :: (a -> b) -> (b -> a) -> Grammar p (a :- t) (b :- t)
iso f' g' = Iso f g
where
f (a :- t) = f' a :- t
g (b :- t) = g' b :- t
-- | Flipped isomorphism on the stack head.
osi :: (b -> a) -> (a -> b) -> Grammar p (a :- t) (b :- t)
osi f' g' = Iso g f
where
f (a :- t) = f' a :- t
g (b :- t) = g' b :- t
-- | Partial isomorphism (for backward run) on the stack head.
partialIso :: (a -> b) -> (b -> Either Mismatch a) -> Grammar p (a :- t) (b :- t)
partialIso f' g' = PartialIso f g
where
f (a :- t) = f' a :- t
g (b :- t) = (:- t) <$> g' b
-- | Partial isomorphism (for forward run) on the stack head.
partialOsi :: (a -> Either Mismatch b) -> (b -> a) -> Grammar p (a :- t) (b :- t)
partialOsi g' f' = Flip $ PartialIso f g
where
f (a :- t) = f' a :- t
g (b :- t) = (:- t) <$> g' b
-- | Push an element to the stack on forward run, check if the element
-- satisfies predicate, otherwise report a mismatch.
push :: a -> (a -> Bool) -> (a -> Mismatch) -> Grammar p t (a :- t)
push a p e = PartialIso f g
where
f t = a :- t
g (a' :- t)
| p a' = Right t
| otherwise = Left $ e a'
-- | 2-tuple grammar. Construct on forward run, deconstruct on
-- backward run.
pair :: Grammar p (b :- a :- t) ((a, b) :- t)
pair = Iso
(\(b :- a :- t) -> (a, b) :- t)
(\((a, b) :- t) -> b :- a :- t)
-- | List cons-cell grammar. Construct on forward run, deconstruct on
-- backward run.
cons :: Grammar p ([a] :- a :- t) ([a] :- t)
cons = PartialIso
(\(lst :- el :- t) -> (el:lst) :- t)
(\(lst :- t) ->
case lst of
[] -> Left (expected "list element")
(el:rest) -> Right (rest :- el :- t))
-- | Empty list grammar. Construct empty list on forward run, check if
-- list is empty on backward run.
nil :: Grammar p t ([a] :- t)
nil = PartialIso
(\t -> [] :- t)
(\(lst :- t) ->
case lst of
[] -> Right t
(_el:_rest) -> Left (expected "end of list"))
-- | Swap two topmost stack elements.
swap :: Grammar p (a :- b :- t) (b :- a :- t)
swap = Iso
(\(a :- b :- t) -> (b :- a :- t))
(\(b :- a :- t) -> (a :- b :- t))
-- | Assoc-list element grammar. Inserts an element (with static key)
-- on forward run, look up an element on backward run.
insert :: (Eq k) => k -> Mismatch -> Grammar p (v :- [(k, v)] :- t) ([(k, v)] :- t)
insert k m = PartialIso
(\(v :- alist :- t) -> ((k, v) : alist) :- t)
(\(alist :- t) ->
case popKey k alist of
Nothing -> Left m
Just (v, alist') -> Right (v :- alist' :- t))
-- | Optional assoc-list element grammar. Like 'insert', but does not
-- report a mismatch on backward run. Instead takes and produces a
-- Maybe-value.
insertMay :: (Eq k) => k -> Grammar p (Maybe v :- [(k, v)] :- t) ([(k, v)] :- t)
insertMay k = PartialIso
(\(mv :- alist :- t) ->
case mv of
Just v -> ((k, v) : alist) :- t
Nothing -> alist :- t)
(\(alist :- t) ->
case popKey k alist of
Nothing -> Right (Nothing :- alist :- t)
Just (v, alist') -> Right (Just v :- alist' :- t))
popKey :: forall k v. Eq k => k -> [(k, v)] -> Maybe (v, [(k, v)])
popKey k' = go []
where
go :: [(k, v)] -> [(k, v)] -> Maybe (v, [(k, v)])
go acc (x@(k, v) : xs)
| k == k' = Just (v, reverse acc ++ xs)
| otherwise = go (x:acc) xs
go _ [] = Nothing
-- | Default value grammar. Replaces 'Nothing' with a default value on
-- forward run, an replaces a default value with 'Nothing' on backward
-- run.
toDefault :: (Eq a) => a -> Grammar p (Maybe a :- t) (a :- t)
toDefault def = iso
(fromMaybe def)
(\val -> if val == def then Nothing else Just val)
-- | Run a grammar operating on the stack head in a context where
-- there is no stack.
sealed :: Grammar p (a :- Void) (b :- Void) -> Grammar p a b
sealed g =
Iso (:- error "void") (\(a :- _) -> a) >>>
g >>>
Iso (\(a :- _) -> a) (:- error "void")
-- | Focus a given grammar to the stack head.
onHead :: Grammar p a b -> Grammar p (a :- t) (b :- t)
onHead = OnHead
-- | Focus a given grammar to the stack tail.
onTail :: Grammar p ta tb -> Grammar p (h :- ta) (h :- tb)
onTail = OnTail
-- | Traverse a structure with a given grammar.
traversed :: (Traversable f) => Grammar p a b -> Grammar p (f a) (f b)
traversed = Traverse
-- | Run a grammar with inputs and outputs flipped.
flipped :: Grammar p a b -> Grammar p b a
flipped = Flip
-- | Run a grammar with an annotation.
annotated :: Text -> Grammar p a b -> Grammar p a b
annotated = Annotate
-- | Run a grammar with the stack heads coerced to other ('Coercible')
-- types.
coerced
:: (Coercible a c, Coercible b d) =>
Grammar p (a :- t) (b :- t')
-> Grammar p (c :- t) (d :- t')
coerced g = iso coerce coerce >>> g >>> iso coerce coerce
-- | Join alternative grammars in parallel.
coproduct :: [Grammar p a b] -> Grammar p a b
coproduct = foldl1 (<>)
| esmolanka/sexp-grammar | invertible-grammar/src/Data/InvertibleGrammar/Combinators.hs | bsd-3-clause | 5,594 | 0 | 15 | 1,506 | 2,285 | 1,240 | 1,045 | 127 | 3 |
{-# OPTIONS_GHC -Wall #-}
module Classy.Utils ( lastCommonBases
, removeCommonList
) where
import Classy.Types
-- | Return the direct dependency of a frame
parentBases :: Bases -> Bases
parentBases NewtonianBases = NewtonianBases
parentBases (RotatedBases frame0 _ _) = frame0
-- | Return the lineage of frames, the last entry always being the newtonian frame
parentBasesChain :: Bases -> [Bases]
parentBasesChain NewtonianBases = [NewtonianBases]
parentBasesChain frame = frame : parentBasesChain (parentBases frame)
-- | Given two frames, finds the closest ancestor frame (in terms of dependency)
-- If all else fails, the newtonian reference frame is always a valid answer
lastCommonBases :: Bases -> Bases -> Bases
lastCommonBases frameA frameB = lastCommonList (reverse $ parentBasesChain frameA) (reverse $ parentBasesChain frameB) NewtonianBases
-- | Given two lists, traverses both lists as long as their entries are equal and returs the last equal entry
-- Example: lastCommonList [0,4,5] [0] 42 => 0
-- Example: lastCommonList [0,4,5] [4] 42 => 42 (nothing was common, outputing default )
-- Example: lastCommonList [0,4,5] [0,4,12] 42 => 4
-- Example: lastCommonList [0,4,5] [0,4,5] 42 => 5
lastCommonList :: Eq a => [a] -> [a] -> a -> a
lastCommonList [] _ n = n
lastCommonList _ [] n = n
lastCommonList (f1:t1) (f2:t2) last'
| f1 == f2 = lastCommonList t1 t2 f1
| otherwise = last'
-- | Given two lists, keeps chopping of the heads of these lists while entries compare to equal
-- removeCommonList [4,5] [1,2,3] => ([4,5],[1,2,3])
-- removeCommonList [1,4] [1,2,3] => ([5],[2,3])
-- removeCommonList [1,2] [1,2,3] => ([],[3])
removeCommonList :: Eq a => [a] -> [a] -> ([a],[a])
removeCommonList [] other = ([], other)
removeCommonList other [] = (other, [])
removeCommonList (f1:t1) (f2:t2)
| f1 == f2 = removeCommonList t1 t2
| otherwise = (f1:t1, f2:t2)
| ghorn/classy-dvda | src/Classy/Utils.hs | bsd-3-clause | 1,953 | 0 | 9 | 378 | 412 | 222 | 190 | 24 | 1 |
module Main where
import qualified PROJECT_NAMESPACE.Tests
import Test.Framework
main ::
IO ()
main =
defaultMain tests
tests ::
[Test]
tests =
[
testGroup "Tests"
[
PROJECT_NAMESPACE.Tests.test
]
]
| markhibberd/haskell.template | test/Main.hs | bsd-3-clause | 239 | 0 | 8 | 68 | 60 | 35 | 25 | 14 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Camera where
import Control.Lens.TH (makeLenses)
import Control.Lens.Getter (view)
import Control.Lens.Setter
import Linear.Conjugate
import Linear.Quaternion
import Linear.V3
import Linear.Vector
import Linear.Matrix hiding (translation)
import Linear.Metric
data Camera = Camera { _rotation :: Quaternion Float
, _translation :: V3 Float
, _velocity :: V3 Float
, _cameraUp :: V3 Float}
deriving Show
makeLenses ''Camera
-- |Create a human-readable text output of a camera's rotation and
-- translation.
writePose :: Camera -> String
writePose cam = show (_rotation cam) ++ "\n" ++ show (_translation cam) ++ "\n"
-- |Read back a camera pose saved in a format compatible with
-- 'writePose'.
readPose :: String -> Maybe Camera
readPose = aux . lines
where aux [r,t] = Just $ Camera (read r) (read t) 0 (V3 0 1 0)
aux _ = Nothing
-- |Axes identified in the camera's local coordinate frame expressed
-- as vectors in the global coordinate frame.
forward,right,up :: Camera -> V3 Float
forward = flip rotate (V3 0 0 (-1)) . conjugate . view rotation
right = flip rotate (V3 1 0 0) . conjugate . view rotation
up c = rotate (_rotation c) (_cameraUp c)
defaultCamera :: Camera
defaultCamera = Camera 1 0 0 (V3 0 1 0)
-- |A "first-person shooter"-style camera default for a right-handed
-- coordinate system with the positive Z axis extending up from the
-- ground, Y extending forward from the camera, and X off to the
-- right.
fpsDefault :: Camera
fpsDefault = tilt (-pi*0.5) . (cameraUp .~ (V3 0 0 1)) $ defaultCamera
toMatrix :: Camera -> M44 Float
toMatrix (Camera r t _ _) = mkTransformation r (rotate r (negate t))
-- The pan, tilt, roll controls are designed for FPS-style camera
-- control. The key idea is that panning is about a world-frame
-- up-axis, not the camera's local up axis. We record which world axis
-- to use as the up vector in the 'Camera' data structure.
pan :: Float -> Camera -> Camera
pan theta c = rotation *~ axisAngle (_cameraUp c) theta $ c
tilt :: Float -> Camera -> Camera
tilt theta c@(Camera r _ _ _) = rotation .~ r' $ c
where r' = axisAngle (V3 1 0 0) theta * r
roll :: Float -> Camera -> Camera
roll theta c@(Camera r _ _ _) = (rotation .~ r') $ c
where r' = axisAngle (V3 0 0 1) theta * r
-- |Add a vector to a 'Camera''s current velocity.
deltaV :: V3 Float -> Camera -> Camera
deltaV = (velocity +~)
clampSpeed :: Float -> Camera -> Camera
clampSpeed maxSpeed = velocity %~ aux
where aux v = let q = quadrance v
in if q >= maxSpeed*maxSpeed
then maxSpeed *^ fmap (/ sqrt q) v
else v
slow :: Float -> Camera -> Camera
slow rate = velocity %~ (rate *^)
-- Zero out velocity in a particular direction.
stopAxis :: V3 Float -> Camera -> Camera
stopAxis axis (Camera r t v u) = flip (Camera r t) u $
v ^-^ dot (rotate r axis) v *^ axis
-- Update a camera's position based on its velocity and a time step
-- (in seconds).
update :: Double -> Camera -> Camera
update dt (Camera r t v u) = Camera r (t + v ^* realToFrac dt) v u
| acowley/PointCloudViewer | src/Camera.hs | bsd-3-clause | 3,206 | 0 | 13 | 762 | 963 | 510 | 453 | 56 | 2 |
module OtherTests (otherTests) where
import TestHelpers
import Foreign.Storable (peek, poke)
import Foreign.Marshal (alloca)
import Foreign.C.Types (CInt)
import Control.Parallel.MPI.Base
import Data.Maybe (isJust)
otherTests :: ThreadSupport -> Rank -> [(String,TestRunnerTest)]
otherTests threadSupport _ =
[ testCase "Peeking/poking Status" statusPeekPoke
, testCase "Querying MPI implementation" getImplementationTest
, testCase "Universe size" universeSizeTest
, testCase "wtime/wtick" wtimeWtickTest
, testCase "commGetParent is null" commGetParentNullTest
, testCase "commRank, commSize, getProcessor name, version" rankSizeNameVersionTest
, testCase "initialized" initializedTest
, testCase "finalized" finalizedTest
, testCase "tag value upper bound" tagUpperBoundTest
, testCase "queryThread" $ queryThreadTest threadSupport
, testCase "test requestNull" $ testRequestNull
, testCase "Info objects" $ testInfoObjects
, testCase "anySource/anySize values" anySourceTagTest
, testCase "openClosePort" openClosePortTest
]
queryThreadTest :: ThreadSupport -> IO ()
queryThreadTest threadSupport = do
newThreadSupport <- queryThread
threadSupport == newThreadSupport @?
("Result from queryThread: " ++ show newThreadSupport ++
", differs from result from initThread: " ++ show threadSupport)
statusPeekPoke :: IO ()
statusPeekPoke = do
alloca $ \statusPtr -> do
let s0 = Status (fromIntegral (maxBound::CInt)) 2 3
poke statusPtr s0
s1 <- peek statusPtr
s0 == s1 @? ("Poked " ++ show s0 ++ ", but peeked " ++ show s1)
getImplementationTest :: IO ()
getImplementationTest = do
putStrLn $ "Using " ++ show (getImplementation)
wtimeWtickTest :: IO ()
wtimeWtickTest = do
t <- wtime
tick <- wtick
tick < t @? "Timer resolution is greater than current time"
putStrLn $ "Current time is " ++ show t ++ ", timer resolution is " ++ show tick
putStrLn $ "Wtime is global: " ++ show wtimeIsGlobal
universeSizeTest :: IO ()
universeSizeTest = do
us <- universeSize commWorld
putStrLn $ "Universe size is " ++ show us
rankSizeNameVersionTest :: IO ()
rankSizeNameVersionTest = do
r <- commRank commWorld
s <- commSize commWorld
p <- getProcessorName
v <- getVersion
putStrLn $ "I am process " ++ show r ++ " out of " ++ show s ++ ", running on " ++ p ++ ", MPI version " ++ show v
initializedTest :: IO ()
initializedTest = do
isInit <- initialized
isInit == True @? "initialized return False, but was expected to return True"
finalizedTest :: IO ()
finalizedTest = do
isFinal <- finalized
isFinal == False @? "finalized return True, but was expected to return False"
tagUpperBoundTest :: IO ()
tagUpperBoundTest = do
putStrLn $ "Maximum tag value is " ++ show tagUpperBound
tagUpperBound /= (-1) @? "tagUpperBound has no value"
testRequestNull :: IO ()
testRequestNull = do
status <- test requestNull
isJust status @? "test requestNull does not return status"
let (Just s) = status
status_source s == anySource @? "status returned from (test requestNull) does not have source set to anySource"
status_tag s == anyTag @? "status returned from (test requestNull) does not have tag set to anyTag"
status_error s == 0 @? "status returned from (test requestNull) does not have error set to success"
commGetParentNullTest :: IO ()
commGetParentNullTest = do
comm <- commGetParent
comm == commNull @? "commGetParent did not return commNull, yet this is not dynamically-spawned process"
testInfoObjects :: IO ()
testInfoObjects = do
i <- infoCreate
v <- infoGet i "foo"
v == Nothing @? "Key 'foo' found in freshly-created Info object"
infoSet i "foo" "bar"
v' <- infoGet i "foo"
v' == (Just "bar") @? ("Key 'foo' was not set to 'bar', check retrieved " ++ show v')
infoDelete i "foo"
v'' <- infoGet i "foo"
v'' == Nothing @? "Key 'foo' was not deleted"
anySourceTagTest :: IO ()
anySourceTagTest = do
if (anySource) == (toEnum (-1)) then return ()
else putStrLn ("anySource is not -1, but rather " ++ show anySource)
if (anyTag) == (toEnum (-1)) then return ()
else putStrLn ("anyTag is not -1, but rather " ++ show anyTag)
openClosePortTest :: IO ()
openClosePortTest = do
port <- openPort infoNull
closePort port
| bjpop/haskell-mpi | test/OtherTests.hs | bsd-3-clause | 4,291 | 0 | 17 | 819 | 1,127 | 546 | 581 | 102 | 3 |
module Main where
import Output
import Parser
import FromID
import System.Environment
import Control.Applicative
import Data.Time
main :: IO ()
main = do
d <- localDay . zonedTimeToLocalTime <$> getZonedTime
args <- getArgs
let (_, "--" : fps) = span (/= "--") args
items <- mapM (fmap parse . readFile) fps
putStrLn "start\t2014-04-17"
putStr $ evrOutputs $ fromItemN (read "2014-04-17") items
| YoshikuniJujo/forest | subprojects/schedevr/src/mkschd/marge-schedule-evr.hs | bsd-3-clause | 403 | 0 | 11 | 68 | 144 | 73 | 71 | 15 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans -fsimpl-tick-factor=500 #-}
module Real.PkgBinary where
import Real.Types
import Data.Binary as Binary
import Data.Binary.Get as Binary
import Data.ByteString.Lazy as BS
serialise :: [GenericPackageDescription] -> BS.ByteString
serialise pkgs = Binary.encode pkgs
deserialise :: BS.ByteString -> [GenericPackageDescription]
deserialise = Binary.decode
deserialiseNull :: BS.ByteString -> ()
deserialiseNull =
Binary.runGet $ do
n <- get :: Get Int
go n
where
go 0 = return ()
go i = do x <- get :: Get GenericPackageDescription
x `seq` go (i-1)
instance Binary Version
instance Binary PackageName
instance Binary PackageId
instance Binary VersionRange
instance Binary Dependency
instance Binary CompilerFlavor
instance Binary License
instance Binary SourceRepo
instance Binary RepoKind
instance Binary RepoType
instance Binary BuildType
instance Binary Library
instance Binary Executable
instance Binary TestSuite
instance Binary TestSuiteInterface
instance Binary TestType
instance Binary Benchmark
instance Binary BenchmarkInterface
instance Binary BenchmarkType
instance Binary BuildInfo
instance Binary ModuleName
instance Binary Language
instance Binary Extension
instance Binary KnownExtension
instance Binary PackageDescription
instance Binary OS
instance Binary Arch
instance Binary Flag
instance Binary FlagName
instance (Binary a, Binary b, Binary c) => Binary (CondTree a b c)
instance Binary ConfVar
instance Binary a => Binary (Condition a)
instance Binary GenericPackageDescription
| thoughtpolice/binary-serialise-cbor | bench/Real/PkgBinary.hs | bsd-3-clause | 1,575 | 0 | 12 | 236 | 456 | 220 | 236 | 51 | 2 |
-- | This module provides the /Empty Processor/.
-- If the given condition is fulfilled, the tree is closed with a constant certificate.
module Tct.Core.Processor.Empty (empty) where
import qualified Tct.Core.Common.Pretty as PP
import Tct.Core.Common.SemiRing (zero)
import qualified Tct.Core.Common.Xml as Xml
import qualified Tct.Core.Data as T
data Empty prob = Empty (prob -> Bool)
instance Show (Empty prob) where
show _ = "EmptyProcessor"
data EmptyProof
= EmptyProblem
| OpenProblem
deriving Show
instance PP.Pretty EmptyProof where
pretty EmptyProblem = PP.text "The problem is already closed. The intended complexity is O(1)."
pretty OpenProblem = PP.text "The problem is still open."
instance Xml.Xml EmptyProof where
toXml EmptyProblem = Xml.elt "closed" []
toXml OpenProblem = Xml.elt "open" []
toCeTA EmptyProblem = Xml.elt "rIsEmpty" []
toCeTA _ = Xml.unsupported
instance T.ProofData prob => T.Processor (Empty prob) where
type ProofObject (Empty prob) = EmptyProof
type In (Empty prob) = prob
type Out (Empty prob) = prob
type Forking (Empty prob) = T.Judgement
execute (Empty f) prob
| f prob = T.succeedWith0 EmptyProblem (T.judgement zero)
| otherwise = T.abortWith OpenProblem
empty :: T.ProofData i => (i -> Bool) -> T.Strategy i i
empty = T.processor . Empty
| ComputationWithBoundedResources/tct-core | src/Tct/Core/Processor/Empty.hs | bsd-3-clause | 1,400 | 0 | 10 | 307 | 399 | 213 | 186 | -1 | -1 |
-- | This library provides functions to SMSDirect API.
--
-- Simple usage:
--
-- @
-- -- Get DB list
-- r <- smsdirect \"test\" \"test\" getDB
--
-- -- Make url for tracing purposes
-- let cmd = url \"test\" \"test\" getDB
-- @
--
module SMSDirect (
module SMSDirect.Command
) where
import SMSDirect.Command
| mvoidex/smsdirect | src/SMSDirect.hs | bsd-3-clause | 317 | 0 | 5 | 65 | 29 | 23 | 6 | 3 | 0 |
-- | Util to work with bit representation of number
module Toy.Util.Bits where
import Data.Bits (Bits (..), FiniteBits (..))
import Universum
setHBit :: FiniteBits x => x -> x
setHBit = flip setBit =<< subtract 1 . finiteBitSize
clearHBit :: FiniteBits x => x -> x
clearHBit = flip clearBit =<< subtract 1 . finiteBitSize
setPHBit :: FiniteBits x => x -> x
setPHBit = flip setBit =<< subtract 2 . finiteBitSize
clearPHBit :: FiniteBits x => x -> x
clearPHBit = flip clearBit =<< subtract 2 . finiteBitSize
| Martoon-00/toy-compiler | src/Toy/Util/Bits.hs | bsd-3-clause | 533 | 0 | 7 | 116 | 172 | 90 | 82 | 11 | 1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, TypeFamilies, FlexibleContexts, FlexibleInstances #-}
module Main
( main )
where
import Prelude hiding (null)
import Data.Maybe (fromJust)
import Control.Applicative
import System.Random
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit (testCase)
import Test.QuickCheck hiding (ranges, Result)
import Data.RangeSet
import Data.FiniteStateMachine
import Data.FiniteStateMachine.Deterministic
import Data.FiniteStateMachine.RegexpDerivatives
import Layout
import LayoutHUnit
--------------------------------------------------------------------------------
-- from http://www.cubiclemuses.com/cm/articles/2011/07/14/quickchecking-type-class-laws/
asFunctionOf :: (a -> b) -> a -> (a -> b)
asFunctionOf f _ = f
--------------------------------------------------------------------------------
type TypeIndexedTest a = a -> Test
typeIndexedTest :: forall a. TypeIndexedTest a -> Test
typeIndexedTest t = t (undefined :: a)
--------------------------------------------------------------------------------
test_BooleanAlgebra :: forall a.
(BooleanAlgebra a, Eq a, Arbitrary a, Show a) =>
TypeIndexedTest a
test_BooleanAlgebra t
= testGroup "Boolean algebra laws"
[ testProperty "or is associative" (prop_or_assoc `asFunctionOf` t)
, testProperty "or is commutative" (prop_or_commutative `asFunctionOf` t)
, testProperty "and is associative" (prop_and_assoc `asFunctionOf` t)
, testProperty "and is commutative" (prop_and_commutative `asFunctionOf` t)
, testProperty "or/and distribute on the left" (prop_distrib1 `asFunctionOf` t)
, testProperty "or/and distribute on the right" (prop_distrib2 `asFunctionOf` t)
, testProperty "absorbtion law 1" (prop_absorb1 `asFunctionOf` t)
, testProperty "absorbtion law 2" (prop_absorb2 `asFunctionOf` t)
, testProperty "a and not a is zero" (prop_complement1 `asFunctionOf` t)
, testProperty "a or not a is one" (prop_complement2 `asFunctionOf` t)
]
--------------------------------------------------------------------------------
instance (Ord a, Bounded a, Enum a, Arbitrary a) => Arbitrary (Set a) where
arbitrary = foldl (.|.) zero <$> (map (uncurry interval) <$> arbitrary)
prop_interval :: (Random a, Ord a) => a -> a -> Property
prop_interval a b = do
c <- choose (a,b)
property (c `member` (interval a b))
prop_ranges :: (Bounded a, Enum a, Ord a) =>
Set a ->
Bool
prop_ranges a =
(foldl (.|.) zero . map (uncurry interval) . ranges) a == a
prop_singleton :: Ord a => a -> Bool
prop_singleton a = a `member` (singleton a)
prop_representative :: Ord a => Set a -> Property
prop_representative s =
not (null s) ==>
(fromJust $ getRepresentative s) `member` s
--------------------------------------------------------------------------------
{-
compareFSAs :: ( FiniteStateAcceptor a
, FiniteStateAcceptor b
, Alphabet a ~ Alphabet b
, Result a ~ Result b
, Arbitrary (Alphabet a)
, Show (Alphabet a)
, Eq (Result a)) =>
a ->
b ->
Property
compareFSAs a b = property $ \input -> runFiniteStateAcceptor a input == runFiniteStateAcceptor b input
-}
-- based on:
-- https://github.com/sebfisch/haskell-regexp/blob/master/src/quickcheck.lhs
instance Arbitrary (Regexp Char) where
arbitrary = sized regexp
regexp :: Int -> Gen (Regexp Char)
regexp 0 = frequency [ (1, return one)
, (8, tok <$> (singleton <$> elements "abcdef"))
]
regexp n = frequency [ (3, regexp 0)
, (1, (.|.) <$> subexp <*> subexp)
, (2, (.>>.) <$> subexp <*> subexp)
, (1, zeroOrMore <$> regexp (n-1))
]
where subexp = regexp (n `div` 2)
newtype RegexpInput = RegexpInput String
deriving Show
instance Arbitrary RegexpInput where
arbitrary = RegexpInput <$> listOf1 (elements "abcdef")
-- FIXME: problem with this is that it spends most of its not matching
-- anything, so we only test part of the specification.
prop_regexp :: Regexp Char -> RegexpInput -> Bool
prop_regexp (r :: Regexp Char) (RegexpInput i) =
runFSM r i == runFSM (toDFA $ fromFSM r) i
--------------------------------------------------------------------------------
main :: IO ()
main = defaultMain
[ testGroup "Data.RangeSet"
[ typeIndexedTest (test_BooleanAlgebra :: TypeIndexedTest (Set Char))
, testProperty "interval" (prop_interval `asFunctionOf` (undefined :: Char))
, testProperty "ranges" (prop_ranges `asFunctionOf` (undefined :: Set Char))
, testProperty "singleton" (prop_singleton `asFunctionOf` (undefined :: Char))
, testProperty "representative" (prop_representative `asFunctionOf` (undefined :: Set Char))
]
, testGroup "Data.Regexp"
[ testProperty "regexp" prop_regexp
]
, testGroup "Language.Forvie.Layout"
[ testProperty "layout" prop_layout
, testCase "layout-hunit" layoutTestCases
]
]
| bobatkey/Forvie | tests/Properties.hs | bsd-3-clause | 5,452 | 0 | 13 | 1,317 | 1,232 | 684 | 548 | 84 | 1 |
module Lab2 where
------------------------------------------------------------------------------------------------------------------------------
-- Lab 2: Validating Credit Card Numbers
------------------------------------------------------------------------------------------------------------------------------
-- ===================================
-- Ex. 0
-- ===================================
toDigits :: Integer -> [Integer]
toDigits n
| n >= 0 && n < 10 = [n]
| n >= 10 = toDigits (n `div` 10) ++ [n `mod` 10]
| otherwise = error "n >= 0"
-- ===================================
-- Ex. 1
-- ===================================
toDigitsRev :: Integer -> [Integer]
toDigitsRev n
| n >= 0 && n < 10 = [n]
| n >= 10 = (n `mod` 10) : toDigitsRev (n `div` 10)
| otherwise = error "n >= 0"
-- ===================================
-- Ex. 2
-- ===================================
doubleSecond :: [Integer] -> [Integer]
doubleSecond xs = ds xs 0
where
ds :: [Integer] -> Integer -> [Integer]
ds [] n = []
ds (y:ys) n
| odd n = (y*2) : (ds ys (n+1))
| otherwise = y : (ds ys (n+1))
-- ===================================
-- Ex. 3
-- ===================================
sumDigits :: [Integer] -> Integer
sumDigits xs = foldr (\x y -> y + sum (toDigits x)) 0 xs
-- ===================================
-- Ex. 4
-- ===================================
isValid :: Integer -> Bool
isValid n = suma `mod` 10 == 0
where
suma = (sumDigits . doubleSecond . toDigitsRev) n
-- ===================================
-- Ex. 5
-- ===================================
numValid :: [Integer] -> Integer
numValid xs = sum . map (\_ -> 1) $ filter isValid xs
creditcards :: [Integer]
creditcards = [ 4716347184862961,
4532899082537349,
4485429517622493,
4320635998241421,
4929778869082405,
5256283618614517,
5507514403575522,
5191806267524120,
5396452857080331,
5567798501168013,
6011798764103720,
6011970953092861,
6011486447384806,
6011337752144550,
6011442159205994,
4916188093226163,
4916699537435624,
4024607115319476,
4556945538735693,
4532818294886666,
5349308918130507,
5156469512589415,
5210896944802939,
5442782486960998,
5385907818416901,
6011920409800508,
6011978316213975,
6011221666280064,
6011285399268094,
6011111757787451,
4024007106747875,
4916148692391990,
4916918116659358,
4024007109091313,
4716815014741522,
5370975221279675,
5586822747605880,
5446122675080587,
5361718970369004,
5543878863367027,
6011996932510178,
6011475323876084,
6011358905586117,
6011672107152563,
6011660634944997,
4532917110736356,
4485548499291791,
4532098581822262,
4018626753711468,
4454290525773941,
5593710059099297,
5275213041261476,
5244162726358685,
5583726743957726,
5108718020905086,
6011887079002610,
6011119104045333,
6011296087222376,
6011183539053619,
6011067418196187,
4532462702719400,
4420029044272063,
4716494048062261,
4916853817750471,
4327554795485824,
5138477489321723,
5452898762612993,
5246310677063212,
5211257116158320,
5230793016257272,
6011265295282522,
6011034443437754,
6011582769987164,
6011821695998586,
6011420220198992,
4716625186530516,
4485290399115271,
4556449305907296,
4532036228186543,
4916950537496300,
5188481717181072,
5535021441100707,
5331217916806887,
5212754109160056,
5580039541241472,
6011450326200252,
6011141461689343,
6011886911067144,
6011835735645726,
6011063209139742,
379517444387209,
377250784667541,
347171902952673,
379852678889749,
345449316207827,
349968440887576,
347727987370269,
370147776002793,
374465794689268,
340860752032008,
349569393937707,
379610201376008,
346590844560212,
376638943222680,
378753384029375,
348159548355291,
345714137642682,
347556554119626,
370919740116903,
375059255910682,
373129538038460,
346734548488728,
370697814213115,
377968192654740,
379127496780069,
375213257576161,
379055805946370,
345835454524671,
377851536227201,
345763240913232
]
| javier-alvarez/myhaskell | lab2.hs | bsd-3-clause | 5,884 | 0 | 12 | 2,439 | 865 | 515 | 350 | 146 | 2 |
import Data.Word
-- Gain a lot of speed here using Word32 type and `mod` for parity checking
-- instead of `even`. This is all since it keeps the values unboxed.
collatzLen :: Int -> Word32 -> Int
collatzLen c 1 = c
collatzLen c n = collatzLen (c+1) $ if n `mod` 2 == 0 then n `div` 2 else 3*n+1
pmax x n = x `max` (collatzLen 1 n, n)
main = print . solve $ 1000000
where solve xs = foldl pmax (1,1) [2..xs-1]
| dterei/Scraps | euler/p14/p14.hs | bsd-3-clause | 417 | 0 | 9 | 93 | 159 | 87 | 72 | 7 | 2 |
--
--
--
------------------
-- Exercise 10.35.
------------------
--
--
--
module E'10'35 where
-- It depends. There are many things that might be important:
--
-- - readability ( length and precision )
-- - future changes/extensions
-- - standard problems
-- - (efficient) algorithms
-- - (future) optimisations
-- - ...
--
-- The solutions to the exercises from chapter 5 in comparison to
-- ex. 10.32 and 10.33 show the first two things just mentioned.
-- But in general its hard to predict what would be the better
-- choice. In computer science people always argue about that ...
--
-- In the case that I know that the code or problem might change in the future,
-- I would avoid using standard functions and write adaptive definitions using
-- list comprehensions and recursion directly and where it is changeable.
--
-- If it is a standard or small (sub-)problem, library functions come in handy.
| pascal-knodel/haskell-craft | _/links/E'10'35.hs | mit | 925 | 0 | 2 | 179 | 32 | 31 | 1 | 1 | 0 |
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI, OverloadedStrings, ScopedTypeVariables #-}
{-
Copyright 2019 The CodeWorld Authors. All Rights Reserved.
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 Blocks.CodeGen (workspaceToCode)
where
import Blocks.Parser
import Blockly.Workspace hiding (workspaceToCode)
import qualified Data.Map as M
import qualified Data.Text as T
import Prelude hiding ((<>), show)
import qualified Prelude as P
import Blockly.Block
import Data.JSString.Text
import Control.Monad.State.Lazy (get,put)
import qualified Control.Monad.State.Lazy as S
import qualified Blocks.Printer as PR
import Control.Monad
import Data.Monoid ((<>))
pack = textToJSString
unpack = textFromJSString
show :: Show a => a -> T.Text
show = T.pack . P.show
errc :: T.Text -> Block -> SaveErr Expr
errc msg block = SE Comment $ Just $ Error msg block
type Code = T.Text
class Pretty a where
pretty :: a -> PR.Printer
-- instance Pretty Product where
-- pretty (Product s tps) = s <> " " <> T.concat (map pretty tps)
instance Pretty Type where
pretty (Type s) = PR.write_ s
pretty (Sum typeName [] ) = PR.write_ $ "data " <> typeName -- Empty data declaration
pretty (Sum typeName (tp:tps) ) = do
PR.write_ $ "data " <> typeName <> " ="
c <- PR.getCol
PR.write_ " "
pretty tp
mapM_ (\t -> PR.setCol (c-1) >> PR.writeLine "" >> PR.write "|" >> pretty t) tps
pretty (Product s tps) = do PR.write_ s
when (length tps > 0) $ do
PR.write_ "("
PR.intercalation "," tps pretty
PR.write_ ")"
PR.write_ " "
pretty (ListType t) = do
PR.write_ "["
pretty t
PR.write_ "]"
instance Pretty Expr where
pretty (LiteralS s) = PR.write_ s
pretty (LiteralN d) = PR.write_ $ if d == fromInteger (truncate d)
then show $ truncate d
else show d
pretty (LocalVar name) = PR.write_ $ name
pretty (CallFunc name vars_) = do
PR.write_ name
case vars_ of
[] -> return ()
_ -> do
PR.write_ "("
PR.intercalation "," vars_ pretty
PR.write_ ")"
pretty (CallConstr name vars_) = do
PR.write name
case vars_ of
[] -> return ()
_ -> do
PR.write_ "("
PR.intercalation "," vars_ pretty
PR.write_ ")"
pretty (CallFuncInfix name left right) = do shouldParenth left
PR.makeSpace
PR.write name -- SPACES between?
PR.makeSpace
shouldParenth right
where
getPrec (CallFuncInfix name _ _) = infixP name
getPrec _ = 9
cur = infixP name
shouldParenth expr = let prec = getPrec expr in
if prec < cur then parenthesize expr else pretty expr
parenthesize expr = do
PR.write_ "("
pretty expr
PR.write_ ")"
pretty (FuncDef name vars expr) = do
let varCode = if not $ null vars
then "(" <> T.intercalate "," vars <> ")"
else ""
PR.write_ name
if null vars then return () else PR.write_ varCode
PR.write_ " = "
pretty expr
pretty (If cond th el) = do
PR.push
PR.write "if"
pretty cond
PR.reset
PR.write "then"
pretty th
PR.reset
PR.write "else"
pretty el
PR.pop
pretty (Case expr rows) = do
col <- PR.getCol
PR.write "case"
PR.makeSpace
pretty expr
PR.makeSpace
PR.write "of"
mapM_ (\(con, vars, expr) -> do PR.setCol (col+4)
PR.writeLine ""
PR.write con
PR.makeSpace
when (length vars > 0) $ do
PR.write_ "("
PR.write_ $ T.intercalate "," vars
PR.write_ ")"
PR.write "->"
pretty expr) rows
PR.pop
pretty (UserType tp) = pretty tp
pretty (Tuple exprs) = do
PR.write_ "("
PR.intercalation "," exprs pretty
PR.write_ ")"
pretty (ListCreate exprs) = do
PR.write_ "["
PR.intercalation "," exprs pretty
PR.write_ "]"
pretty (ListSpec left right) = do
PR.write_ "["
pretty left
PR.write_ " .. "
pretty right
PR.write_ "]"
pretty (ListSpecStep left next right) = do
PR.write_ "["
pretty left
PR.write_ ", "
pretty next
PR.write_ " .. "
pretty right
PR.write_ "]"
pretty (ListComp act vars_ guards) = do
PR.write_ "["
pretty act
PR.write_ " | "
PR.intercalation ", " vars_ (\(var,expr) -> PR.write_ var >> PR.write_ " <- " >> pretty expr)
when (length guards > 0) $ do PR.write_ ","
PR.makeSpace
PR.intercalation ", " guards pretty
PR.write_ "]"
pretty Comment = PR.write_ ""
infixP "-" = 6
infixP "+" = 6
infixP "*" = 7
infixP "/" = 7
infixP "^" = 8
infixP "&" = 8
infixP "<>" = 8
infixP _ = 9
workspaceToCode :: Workspace -> IO (Code,[Error])
workspaceToCode workspace = do
topBlocks <- getTopBlocksTrue workspace >>= return . filter (not . isDisabled)
let exprs = map blockToCode topBlocks
let errors = map (\(SE code (Just e)) -> e) $
filter (\c -> case c of SE code Nothing -> False; _ -> True) exprs
let code = T.intercalate "\n\n" $ map (\(SE expr _) -> PR.run $ pretty expr) exprs
return (code,errors)
where
blockToCode :: Block -> SaveErr Expr
blockToCode block = do
let blockType = getBlockType block
case M.lookup blockType blockCodeMap of
Just func -> let (SE code err) = func block
in SE code err
Nothing -> errc "No such block in CodeGen" block
| alphalambda/codeworld | funblocks-client/src/Blocks/CodeGen.hs | apache-2.0 | 8,966 | 0 | 18 | 4,645 | 2,051 | 963 | 1,088 | 172 | 3 |
-- | This is a very simple promise system, for promises that can fail.
module STM.Promise ( newPromise
, PubFP
, SubFP
, fulfillPromise
, failPromise
, getResult
) where
import Control.Concurrent.STM
import Control.Monad (void)
-- | The publising part of the promise.
newtype PubFP e a = PubFP (Either e a -> STM ())
-- | The subscribing part of the promise.
newtype SubFP e a = SubFP (STM (Either e a))
newPromise :: STM (PubFP e a, SubFP e a)
newPromise = do
n <- newEmptyTMVar
return (PubFP (void . tryPutTMVar n), SubFP (readTMVar n))
fulfillPromise :: PubFP e a -> a -> STM ()
fulfillPromise (PubFP o) a = o (Right a)
failPromise :: PubFP e a -> e -> STM ()
failPromise (PubFP o) e = o (Left e)
getResult :: SubFP e a -> STM (Either e a)
getResult (SubFP o) = o
| bitemyapp/7startups | STM/Promise.hs | bsd-3-clause | 896 | 0 | 12 | 277 | 301 | 158 | 143 | 20 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.Bitcoin.BitX.Private.Fees
-- Copyright : 2017 Tebello Thejane
-- License : BSD3
--
-- Maintainer : Tebello Thejane <[email protected]>
-- Stability : Experimental
-- Portability : non-portable (GHC Extensions)
--
-- Retrieving fee information.
--
-- The BitX fee structure is cummulative-volume-based. The sole endpoint in
-- this package returns the user's current fee structure and 30-day volume.
--
-----------------------------------------------------------------------------
module Network.Bitcoin.BitX.Private.Fees
(
getFeeInfo
) where
import Network.Bitcoin.BitX.Internal
import Network.Bitcoin.BitX.Types
import Data.Text as Txt
import Network.Bitcoin.BitX.Response
import Data.Monoid ((<>))
{- | Get fee structure and 30-day volume (as of midnight) for a currency pair
@Perm_R_Orders@ permission required.
-}
getFeeInfo :: BitXAuth -> CcyPair -> IO (BitXAPIResponse FeeInfo)
getFeeInfo auth cpair = simpleBitXGetAuth_ auth ("fee_info?pair=" <> Txt.pack (show cpair))
| tebello-thejane/bitx-haskell | src/Network/Bitcoin/BitX/Private/Fees.hs | bsd-3-clause | 1,159 | 0 | 10 | 165 | 127 | 83 | 44 | 11 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
module PlaceHolder where
import Type ( Type )
import Outputable
import Name
import NameSet
import RdrName
import Var
import Coercion
import {-# SOURCE #-} ConLike (ConLike)
import TcEvidence (HsWrapper)
import FieldLabel
import Data.Data hiding ( Fixity )
import BasicTypes (Fixity)
{-
%************************************************************************
%* *
\subsection{Annotating the syntax}
%* *
%************************************************************************
-}
-- | used as place holder in PostTc and PostRn values
data PlaceHolder = PlaceHolder
deriving (Data,Typeable)
-- | Types that are not defined until after type checking
type family PostTc it ty :: * -- Note [Pass sensitive types]
type instance PostTc Id ty = ty
type instance PostTc Name ty = PlaceHolder
type instance PostTc RdrName ty = PlaceHolder
-- | Types that are not defined until after renaming
type family PostRn id ty :: * -- Note [Pass sensitive types]
type instance PostRn Id ty = ty
type instance PostRn Name ty = ty
type instance PostRn RdrName ty = PlaceHolder
placeHolderKind :: PlaceHolder
placeHolderKind = PlaceHolder
placeHolderFixity :: PlaceHolder
placeHolderFixity = PlaceHolder
placeHolderType :: PlaceHolder
placeHolderType = PlaceHolder
placeHolderTypeTc :: Type
placeHolderTypeTc = panic "Evaluated the place holder for a PostTcType"
placeHolderNames :: PlaceHolder
placeHolderNames = PlaceHolder
placeHolderNamesTc :: NameSet
placeHolderNamesTc = emptyNameSet
{-
Note [Pass sensitive types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since the same AST types are re-used through parsing,renaming and type
checking there are naturally some places in the AST that do not have
any meaningful value prior to the pass they are assigned a value.
Historically these have been filled in with place holder values of the form
panic "error message"
This has meant the AST is difficult to traverse using standard generic
programming techniques. The problem is addressed by introducing
pass-specific data types, implemented as a pair of open type families,
one for PostTc and one for PostRn. These are then explicitly populated
with a PlaceHolder value when they do not yet have meaning.
Since the required bootstrap compiler at this stage does not have
closed type families, an open type family had to be used, which
unfortunately forces the requirement for UndecidableInstances.
In terms of actual usage, we have the following
PostTc id Kind
PostTc id Type
PostRn id Fixity
PostRn id NameSet
TcId and Var are synonyms for Id
-}
type DataId id =
( Data id
, Data (PostRn id NameSet)
, Data (PostRn id Fixity)
, Data (PostRn id Bool)
, Data (PostRn id Name)
, Data (PostRn id [Name])
-- , Data (PostRn id [id])
, Data (PostRn id id)
, Data (PostTc id Type)
, Data (PostTc id Coercion)
, Data (PostTc id id)
, Data (PostTc id [Type])
, Data (PostTc id [ConLike])
, Data (PostTc id HsWrapper)
, Data (PostTc id [FieldLabel])
)
| da-x/ghc | compiler/hsSyn/PlaceHolder.hs | bsd-3-clause | 3,349 | 0 | 9 | 705 | 463 | 269 | 194 | 56 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module : Numeric.Tools.Mesh
-- Copyright : (c) 2011 Aleksey Khudyakov
-- License : BSD3
--
-- Maintainer : Aleksey Khudyakov <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-- 1-dimensional meshes. Used by 'Numeric.Tools.Interpolation'.
--
module Numeric.Tools.Mesh (
-- * Meshes
Mesh(..)
-- ** Uniform mesh
, UniformMesh
, uniformMeshStep
-- *** Constructors
, uniformMesh
, uniformMeshN
) where
import Data.Data (Data,Typeable)
import Numeric.Classes.Indexing
----------------------------------------------------------------
-- Type class
----------------------------------------------------------------
-- | Class for 1-dimensional meshes. Mesh is ordered set of
-- points. Each instance must guarantee that every next point is
-- greater that previous and there is at least 2 points in mesh.
--
-- Every mesh is instance of 'Indexable' and indexing should get n'th
-- mesh node.
class Indexable a => Mesh a where
-- | Low bound of mesh
meshLowerBound :: a -> Double
-- | Upper bound of mesh
meshUpperBound :: a -> Double
-- | Find such index for value that
--
-- > mesh ! i <= x && mesh ! i+1 > x
--
-- Will return invalid index if value is out of range.
meshFindIndex :: a -> Double -> Int
----------------------------------------------------------------
-- Uniform mesh
----------------------------------------------------------------
-- | Uniform mesh
data UniformMesh = UniformMesh { uniformMeshFrom :: Double
, uniformMeshStep :: Double
-- ^ Distance between points
, uniformMeshSize :: Int
}
deriving (Eq,Show,Data,Typeable)
-- | Create uniform mesh
uniformMesh :: (Double,Double) -- ^ Lower and upper bound
-> Int -- ^ Number of points
-> UniformMesh
uniformMesh (a,b) n
| b <= a = error "Numeric.Tool.Interpolation.Mesh.uniformMesh: bad range"
| n < 2 = error "Numeric.Tool.Interpolation.Mesh.uniformMesh: too few points"
| otherwise = UniformMesh a ((b - a) / fromIntegral (n - 1)) n
-- | Create uniform mesh
uniformMeshN :: Double -- ^ Lower bound
-> Double -- ^ Mesh step
-> Int -- ^ Number of points
-> UniformMesh
uniformMeshN a dx n
| n < 2 = error "Numeric.Tool.Interpolation.Mesh.uniformMeshStep: too few points"
| dx <= 0 = error "Numeric.Tool.Interpolation.Mesh.uniformMeshStep: nonpositive step"
| otherwise = UniformMesh a dx n
instance Indexable UniformMesh where
type IndexVal UniformMesh = Double
size = uniformMeshSize
unsafeIndex (UniformMesh a da _) i = a + fromIntegral i * da
instance Mesh UniformMesh where
meshLowerBound = uniformMeshFrom
meshUpperBound (UniformMesh a da n) = a + da * fromIntegral (n - 1)
meshFindIndex (UniformMesh a da _) x = truncate $ (x - a) / da
| KevinCotrone/numeric-tools | Numeric/Tools/Mesh.hs | bsd-3-clause | 3,116 | 0 | 11 | 813 | 499 | 282 | 217 | 41 | 1 |
-- |
-- Binary Communicator
--
-- This module provides the datatype BinaryCom, which enables you
-- to easily send and receive data to and from a binary source.
-- The transmitted data can be an instance of the 'Binary' class,
-- or you can provide your own Put and Get actions to serialize
-- and parse the binary stream.
module Data.BinaryCom
(BinaryCom,
binaryCom, binaryCom2H, binaryComBS,
send, flushAfter, receive,
sendPut, receiveGet,
(+|))
where
import System.IO
import Data.IORef
import Control.Monad (when)
import Control.Monad.Trans
import qualified Data.ByteString.Lazy as L
import qualified Data.Binary as B
import qualified Data.Binary.Get as B
import qualified Data.Binary.Put as B
-- | 'BinaryCom' type
data BinaryCom = BinaryCom (IORef L.ByteString) -- For reading
Handle -- For writing
Bool -- Auto-flush when 'send' called
-- | Creates a 'BinaryCom' from a 'Handle' opened for both reading and writing.
-- Be careful not to use the handle afterwards
binaryCom :: (MonadIO m) => Handle -> m BinaryCom
binaryCom h = binaryCom2H h h
-- | Creates a 'BinaryCom' from two 'Handle's: one for reading, one for writing
binaryCom2H :: (MonadIO m) =>
Handle -- ^ For reading
-> Handle -- ^ For writing
-> m BinaryCom -- ^ New 'BinaryCom'
binaryCom2H hR hW = do
inp <- liftIO $ L.hGetContents hR
binaryComBS inp hW
-- | Creates a 'BinaryCom' from a lazy 'L.ByteString' (for reading) and a 'Handle' (for writing)
binaryComBS :: (MonadIO m) =>
L.ByteString -- ^ For reading
-> Handle -- ^ For writing
-> m BinaryCom -- ^ New 'BinaryCom'
binaryComBS inp hW = liftIO $ do
ref <- newIORef inp
return $ BinaryCom ref hW True
-- | Sends a serializable value through a 'BinaryCom'
send :: (B.Binary a, MonadIO m) => BinaryCom -> a -> m ()
send b@(BinaryCom _ _ doFlush) val = do
sendPut b . B.put $ val
when doFlush $ flush b
-- | Runs a continuation, passing it a binary com with auto-flush deactivated.
-- Flushes when the continuation is finished.
-- It permits not to flush at each call to 'send'.
flushAfter :: (MonadIO m) => BinaryCom -> (BinaryCom -> m ()) -> m ()
flushAfter b@(BinaryCom ref hW _) cont = do
cont $ BinaryCom ref hW False
flush b
flush :: (MonadIO m) => BinaryCom -> m ()
flush (BinaryCom _ hW _) = liftIO $ hFlush hW
-- | Receives a serializable value through a 'BinaryCom'
receive :: (B.Binary a, MonadIO m) => BinaryCom -> m a
receive b = receiveGet b B.get
-- | Runs a 'B.Put' monad and sends its result
sendPut :: (MonadIO m) => BinaryCom -> B.Put -> m ()
sendPut (BinaryCom _ hW _) putAction = liftIO $
L.hPut hW $ B.runPut putAction
-- | Receives a value. Runs a 'B.Get' monad to parse it
receiveGet :: (MonadIO m) => BinaryCom -> B.Get a -> m a
receiveGet (BinaryCom ref _ _) getAction = liftIO $ do
inp <- readIORef ref
let (val, inpRest, _) = B.runGetState getAction inp 0
writeIORef ref inpRest
return val
-- | A if-then-else, but with the condition as last argument
(+|) :: a -> a -> Bool -> a
(+|) t e c = if c then t else e
| objectx/BinaryCommunicator | Data/BinaryCom.hs | bsd-3-clause | 3,200 | 0 | 12 | 774 | 785 | 422 | 363 | 56 | 2 |
Subsets and Splits