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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- The definition of Maybe is a mapping from type a to type Maybe a:
data Maybe a = Nothing | Just a
-- Heres an important subtlety: Maybe itself is not a type, its a type constructor.
-- You have to give it a type argument, like Int or Bool, in order to turn it into a type.
-- Maybe without any argument represents a function on types.
-- But can we turn Maybe into a functor?
-- NOTE: when I speak of functors in the context of programming, I will almost always mean endofunctors
-- endofunctor is a functor that maps from one category back to same category.
-- We often say that fmap lifts a function. The lifted function acts on Maybe values.
fmap' :: (a -> b) -> (Maybe a -> Maybe b)
fmap' _ Nothing = Nothing
fmap' f (Just x) = Just (f x)
-- Applying the Functor type constructor from Prelude to Maybe
--
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just x) = Just (f x)
-- Functor laws
-- preserves Category ... composition
-- ... 1. preserves identity
prop_maybe_preserves_identity_Nothing :: () -> Bool
prop_maybe_preserves_identity_Nothing
= fmap' id Nothing == id Nothing
-- = fmap' id Nothing
-- = Nothing
-- = id Nothing
prop_maybe_preserves_identity_Just :: a -> Bool
prop_maybe_preserves_identity_Just x
= fmap' id (Just x) == Just (id x)
-- = fmap' id (Just x)
-- = Just (id x)
-- = Just x
-- = id (Just x)
-- ... 2. preserves composition ... proved by Equational Reasoning
-- fmap' (g. f) Nothing
-- = Nothing
-- = fmap' g Nothing
-- = fmap' g (fmap' f Nothing)
--
-- fmap' (g . f) Just x
-- = Just (g . f) x
-- = Just g ( f x )
-- = fmap g Just (f x)
-- = fmap g (fmap' f (Just x))
-- = (fmap g . fmap' f) (Just x)
--
|
sujeet4github/MyLangUtils
|
CategoryTheory_BartoszMilewsky/PI_07_Functors/Maybe_Functor.hs
|
gpl-3.0
| 1,712 | 0 | 8 | 386 | 226 | 128 | 98 | 13 | 1 |
-- | Utility functions for working with tuples.
module Util.Tuple (fst3,
snd3,
trd3,
pair) where
-- | Look-up the first item in a 3-tuple.
fst3 :: (a, b, c) -> a
fst3 (a, _, _) = a
-- | Look-up the second item in a 3-tuple.
snd3 :: (a, b, c) -> b
snd3 (_, b, _) = b
-- | Look-up the third item in a 3-tuple.
trd3 :: (a, b, c) -> c
trd3 (_, _, c) = c
-- | Create a tuple from a single value by applying two separate functions to the value.
pair :: (a -> b) -> (a -> c) -> a -> (b, c)
pair f g x = (f x, g x)
|
dwdyer/anorak
|
src/haskell/Util/Tuple.hs
|
gpl-3.0
| 568 | 0 | 8 | 182 | 191 | 114 | 77 | 12 | 1 |
import HMeans
import Debug.Trace
import Data.Foldable
import System.Random
import Algorithms.Hungarian
import qualified Data.Vector.Unboxed as UV
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
lineToDoubleVector :: Int -> [String] -> DoubleVector
lineToDoubleVector n s = UV.fromList $ map read $ take n s
----------------------------------------------------------------------------------------------------
lineToLabel :: Int -> [String] -> Int
lineToLabel n s = read $ head $ drop n s
where
dropLast :: [a] -> [a]
dropLast [_] = []
dropLast (x:xs) = x : dropLast xs
----------------------------------------------------------------------------------------------------
readALOI :: IO [BasicData DoubleVector]
readALOI = do
let dimension = 2
csv_input <- readFile "aloi_input.csv"
return $ toBasicData $ map (lineToDoubleVector dimension . words) $ lines csv_input
----------------------------------------------------------------------------------------------------
readLabels :: IO [Int]
readLabels = do
let dimension = 2
csv_input <- readFile "aloi_input.csv"
return $ map (lineToLabel dimension . words) $ lines csv_input
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
runHungarian :: Int -> [Int] -> [Int] -> ([(Int, Int)], Double)
runHungarian d x y = hungarian m d d
where
m = foldr' ($) (take (d*d) $ repeat 0) $ fmap addAllExcept $ zip x y
----------------------------------------------------------------------------------------------------
addAllExcept :: (Int, Int) -> [Double] -> [Double]
addAllExcept (i, j) = addAllExcept' (10 * i) (10 * (i + 1)) (10*i + j) 0
where
addAllExcept' :: Int -> Int -> Int -> Int -> [Double] -> [Double]
addAllExcept' _ _ _ _ [] = []
addAllExcept' fr to n i (x:xs) | fr <= i && i <= to && i /= n = x + 1 : addAllExcept' fr to n (i+1) xs
| otherwise = x : addAllExcept' fr to n (i+1) xs
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
main = do
let nImages = 500
let dimension = 2
let aloiParams = Params 8 4 nImages dimension (KMeansParams 1000)
putStrLn $ "HMeans test script:"
aloiData <- readALOI
randomGen <- getStdGen
let microclusters = randomInitialize aloiParams randomGen aloiData
putStrLn $ "Base partition selected:"
putStrLn $ show microclusters
putStrLn $ "---------------------------------------------------------------------------------"
aloiData' <- readALOI
let traind = train $ map (trainDataPoint microclusters) aloiData'
putStrLn $ "Resulting partition:"
putStrLn $ show traind
putStrLn $ "---------------------------------------------------------------------------------"
let clusters = runHMeans aloiParams traind
putStrLn $ "Clusters found:"
putStrLn $ show clusters
putStrLn $ "---------------------------------------------------------------------------------"
aloiLabels <- readLabels
let cLabels = partitionToLabelList clusters
let (hungarianPairs, hungarianScore) = runHungarian dimension cLabels aloiLabels
putStrLn $ "Label list: "
putStrLn $ show $ zip aloiLabels cLabels
putStrLn $ "---------------------------------------------------------------------------------"
putStrLn $ "Score:"
putStrLn $ "\t" ++ show hungarianScore ++ " points mislabeled (" ++ (show $ 100 * hungarianScore / (toSomething nImages)) ++ "%)"
putStrLn $ "---------------------------------------------------------------------------------"
-- putStrLn $ "KMeans Score:"
-- putStrLn $ "\t" ++ show hungarianScore' ++ " points mislabeled (" ++ (show $ 100 * hungarianScore' / (toSomething nImages)) ++ "%)"
putStrLn $ "Done"
|
ehlemur/HMeans
|
Test/ALOI/test.hs
|
gpl-3.0
| 4,159 | 0 | 13 | 668 | 1,003 | 499 | 504 | 62 | 2 |
{-# 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.Games.Rooms.ReportStatus
-- 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)
--
-- Updates sent by a client reporting the status of peers in a room. For
-- internal use by the Games SDK only. Calling this method directly is
-- unsupported.
--
-- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.rooms.reportStatus@.
module Network.Google.Resource.Games.Rooms.ReportStatus
(
-- * REST Resource
RoomsReportStatusResource
-- * Creating a Request
, roomsReportStatus
, RoomsReportStatus
-- * Request Lenses
, rrsPayload
, rrsRoomId
, rrsLanguage
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.rooms.reportStatus@ method which the
-- 'RoomsReportStatus' request conforms to.
type RoomsReportStatusResource =
"games" :>
"v1" :>
"rooms" :>
Capture "roomId" Text :>
"reportstatus" :>
QueryParam "language" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] RoomP2PStatuses :>
Post '[JSON] RoomStatus
-- | Updates sent by a client reporting the status of peers in a room. For
-- internal use by the Games SDK only. Calling this method directly is
-- unsupported.
--
-- /See:/ 'roomsReportStatus' smart constructor.
data RoomsReportStatus =
RoomsReportStatus'
{ _rrsPayload :: !RoomP2PStatuses
, _rrsRoomId :: !Text
, _rrsLanguage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RoomsReportStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rrsPayload'
--
-- * 'rrsRoomId'
--
-- * 'rrsLanguage'
roomsReportStatus
:: RoomP2PStatuses -- ^ 'rrsPayload'
-> Text -- ^ 'rrsRoomId'
-> RoomsReportStatus
roomsReportStatus pRrsPayload_ pRrsRoomId_ =
RoomsReportStatus'
{ _rrsPayload = pRrsPayload_
, _rrsRoomId = pRrsRoomId_
, _rrsLanguage = Nothing
}
-- | Multipart request metadata.
rrsPayload :: Lens' RoomsReportStatus RoomP2PStatuses
rrsPayload
= lens _rrsPayload (\ s a -> s{_rrsPayload = a})
-- | The ID of the room.
rrsRoomId :: Lens' RoomsReportStatus Text
rrsRoomId
= lens _rrsRoomId (\ s a -> s{_rrsRoomId = a})
-- | The preferred language to use for strings returned by this method.
rrsLanguage :: Lens' RoomsReportStatus (Maybe Text)
rrsLanguage
= lens _rrsLanguage (\ s a -> s{_rrsLanguage = a})
instance GoogleRequest RoomsReportStatus where
type Rs RoomsReportStatus = RoomStatus
type Scopes RoomsReportStatus =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.me"]
requestClient RoomsReportStatus'{..}
= go _rrsRoomId _rrsLanguage (Just AltJSON)
_rrsPayload
gamesService
where go
= buildClient
(Proxy :: Proxy RoomsReportStatusResource)
mempty
|
brendanhay/gogol
|
gogol-games/gen/Network/Google/Resource/Games/Rooms/ReportStatus.hs
|
mpl-2.0
| 3,828 | 0 | 15 | 919 | 473 | 283 | 190 | 75 | 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.Healthcare.Projects.Locations.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists information about the supported locations for this service.
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.list@.
module Network.Google.Resource.Healthcare.Projects.Locations.List
(
-- * REST Resource
ProjectsLocationsListResource
-- * Creating a Request
, projectsLocationsList
, ProjectsLocationsList
-- * Request Lenses
, pllXgafv
, pllUploadProtocol
, pllAccessToken
, pllUploadType
, pllName
, pllFilter
, pllPageToken
, pllPageSize
, pllCallback
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.list@ method which the
-- 'ProjectsLocationsList' request conforms to.
type ProjectsLocationsListResource =
"v1" :>
Capture "name" Text :>
"locations" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListLocationsResponse
-- | Lists information about the supported locations for this service.
--
-- /See:/ 'projectsLocationsList' smart constructor.
data ProjectsLocationsList =
ProjectsLocationsList'
{ _pllXgafv :: !(Maybe Xgafv)
, _pllUploadProtocol :: !(Maybe Text)
, _pllAccessToken :: !(Maybe Text)
, _pllUploadType :: !(Maybe Text)
, _pllName :: !Text
, _pllFilter :: !(Maybe Text)
, _pllPageToken :: !(Maybe Text)
, _pllPageSize :: !(Maybe (Textual Int32))
, _pllCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pllXgafv'
--
-- * 'pllUploadProtocol'
--
-- * 'pllAccessToken'
--
-- * 'pllUploadType'
--
-- * 'pllName'
--
-- * 'pllFilter'
--
-- * 'pllPageToken'
--
-- * 'pllPageSize'
--
-- * 'pllCallback'
projectsLocationsList
:: Text -- ^ 'pllName'
-> ProjectsLocationsList
projectsLocationsList pPllName_ =
ProjectsLocationsList'
{ _pllXgafv = Nothing
, _pllUploadProtocol = Nothing
, _pllAccessToken = Nothing
, _pllUploadType = Nothing
, _pllName = pPllName_
, _pllFilter = Nothing
, _pllPageToken = Nothing
, _pllPageSize = Nothing
, _pllCallback = Nothing
}
-- | V1 error format.
pllXgafv :: Lens' ProjectsLocationsList (Maybe Xgafv)
pllXgafv = lens _pllXgafv (\ s a -> s{_pllXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pllUploadProtocol :: Lens' ProjectsLocationsList (Maybe Text)
pllUploadProtocol
= lens _pllUploadProtocol
(\ s a -> s{_pllUploadProtocol = a})
-- | OAuth access token.
pllAccessToken :: Lens' ProjectsLocationsList (Maybe Text)
pllAccessToken
= lens _pllAccessToken
(\ s a -> s{_pllAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pllUploadType :: Lens' ProjectsLocationsList (Maybe Text)
pllUploadType
= lens _pllUploadType
(\ s a -> s{_pllUploadType = a})
-- | The resource that owns the locations collection, if applicable.
pllName :: Lens' ProjectsLocationsList Text
pllName = lens _pllName (\ s a -> s{_pllName = a})
-- | A filter to narrow down results to a preferred subset. The filtering
-- language accepts strings like \"displayName=tokyo\", and is documented
-- in more detail in [AIP-160](https:\/\/google.aip.dev\/160).
pllFilter :: Lens' ProjectsLocationsList (Maybe Text)
pllFilter
= lens _pllFilter (\ s a -> s{_pllFilter = a})
-- | A page token received from the \`next_page_token\` field in the
-- response. Send that page token to receive the subsequent page.
pllPageToken :: Lens' ProjectsLocationsList (Maybe Text)
pllPageToken
= lens _pllPageToken (\ s a -> s{_pllPageToken = a})
-- | The maximum number of results to return. If not set, the service selects
-- a default.
pllPageSize :: Lens' ProjectsLocationsList (Maybe Int32)
pllPageSize
= lens _pllPageSize (\ s a -> s{_pllPageSize = a}) .
mapping _Coerce
-- | JSONP
pllCallback :: Lens' ProjectsLocationsList (Maybe Text)
pllCallback
= lens _pllCallback (\ s a -> s{_pllCallback = a})
instance GoogleRequest ProjectsLocationsList where
type Rs ProjectsLocationsList = ListLocationsResponse
type Scopes ProjectsLocationsList =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsList'{..}
= go _pllName _pllXgafv _pllUploadProtocol
_pllAccessToken
_pllUploadType
_pllFilter
_pllPageToken
_pllPageSize
_pllCallback
(Just AltJSON)
healthcareService
where go
= buildClient
(Proxy :: Proxy ProjectsLocationsListResource)
mempty
|
brendanhay/gogol
|
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/List.hs
|
mpl-2.0
| 6,112 | 0 | 19 | 1,439 | 962 | 556 | 406 | 133 | 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.SQL.Databases.Delete
-- 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)
--
-- Deletes a database from a Cloud SQL instance.
--
-- /See:/ <https://developers.google.com/cloud-sql/ Cloud SQL Admin API Reference> for @sql.databases.delete@.
module Network.Google.Resource.SQL.Databases.Delete
(
-- * REST Resource
DatabasesDeleteResource
-- * Creating a Request
, databasesDelete
, DatabasesDelete
-- * Request Lenses
, ddXgafv
, ddUploadProtocol
, ddProject
, ddDatabase
, ddAccessToken
, ddUploadType
, ddCallback
, ddInstance
) where
import Network.Google.Prelude
import Network.Google.SQLAdmin.Types
-- | A resource alias for @sql.databases.delete@ method which the
-- 'DatabasesDelete' request conforms to.
type DatabasesDeleteResource =
"v1" :>
"projects" :>
Capture "project" Text :>
"instances" :>
Capture "instance" Text :>
"databases" :>
Capture "database" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] Operation
-- | Deletes a database from a Cloud SQL instance.
--
-- /See:/ 'databasesDelete' smart constructor.
data DatabasesDelete =
DatabasesDelete'
{ _ddXgafv :: !(Maybe Xgafv)
, _ddUploadProtocol :: !(Maybe Text)
, _ddProject :: !Text
, _ddDatabase :: !Text
, _ddAccessToken :: !(Maybe Text)
, _ddUploadType :: !(Maybe Text)
, _ddCallback :: !(Maybe Text)
, _ddInstance :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DatabasesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ddXgafv'
--
-- * 'ddUploadProtocol'
--
-- * 'ddProject'
--
-- * 'ddDatabase'
--
-- * 'ddAccessToken'
--
-- * 'ddUploadType'
--
-- * 'ddCallback'
--
-- * 'ddInstance'
databasesDelete
:: Text -- ^ 'ddProject'
-> Text -- ^ 'ddDatabase'
-> Text -- ^ 'ddInstance'
-> DatabasesDelete
databasesDelete pDdProject_ pDdDatabase_ pDdInstance_ =
DatabasesDelete'
{ _ddXgafv = Nothing
, _ddUploadProtocol = Nothing
, _ddProject = pDdProject_
, _ddDatabase = pDdDatabase_
, _ddAccessToken = Nothing
, _ddUploadType = Nothing
, _ddCallback = Nothing
, _ddInstance = pDdInstance_
}
-- | V1 error format.
ddXgafv :: Lens' DatabasesDelete (Maybe Xgafv)
ddXgafv = lens _ddXgafv (\ s a -> s{_ddXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ddUploadProtocol :: Lens' DatabasesDelete (Maybe Text)
ddUploadProtocol
= lens _ddUploadProtocol
(\ s a -> s{_ddUploadProtocol = a})
-- | Project ID of the project that contains the instance.
ddProject :: Lens' DatabasesDelete Text
ddProject
= lens _ddProject (\ s a -> s{_ddProject = a})
-- | Name of the database to be deleted in the instance.
ddDatabase :: Lens' DatabasesDelete Text
ddDatabase
= lens _ddDatabase (\ s a -> s{_ddDatabase = a})
-- | OAuth access token.
ddAccessToken :: Lens' DatabasesDelete (Maybe Text)
ddAccessToken
= lens _ddAccessToken
(\ s a -> s{_ddAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ddUploadType :: Lens' DatabasesDelete (Maybe Text)
ddUploadType
= lens _ddUploadType (\ s a -> s{_ddUploadType = a})
-- | JSONP
ddCallback :: Lens' DatabasesDelete (Maybe Text)
ddCallback
= lens _ddCallback (\ s a -> s{_ddCallback = a})
-- | Database instance ID. This does not include the project ID.
ddInstance :: Lens' DatabasesDelete Text
ddInstance
= lens _ddInstance (\ s a -> s{_ddInstance = a})
instance GoogleRequest DatabasesDelete where
type Rs DatabasesDelete = Operation
type Scopes DatabasesDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/sqlservice.admin"]
requestClient DatabasesDelete'{..}
= go _ddProject _ddInstance _ddDatabase _ddXgafv
_ddUploadProtocol
_ddAccessToken
_ddUploadType
_ddCallback
(Just AltJSON)
sQLAdminService
where go
= buildClient
(Proxy :: Proxy DatabasesDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-sqladmin/gen/Network/Google/Resource/SQL/Databases/Delete.hs
|
mpl-2.0
| 5,323 | 0 | 20 | 1,364 | 859 | 499 | 360 | 126 | 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.Ml.Projects.Operations.Delete
-- 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)
--
-- Deletes a long-running operation. This method indicates that the client
-- is no longer interested in the operation result. It does not cancel the
-- operation. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`.
--
-- /See:/ <https://cloud.google.com/ml/ Google Cloud Machine Learning Reference> for @ml.projects.operations.delete@.
module Network.Google.Resource.Ml.Projects.Operations.Delete
(
-- * REST Resource
ProjectsOperationsDeleteResource
-- * Creating a Request
, projectsOperationsDelete
, ProjectsOperationsDelete
-- * Request Lenses
, podXgafv
, podUploadProtocol
, podPp
, podAccessToken
, podUploadType
, podBearerToken
, podName
, podCallback
) where
import Network.Google.MachineLearning.Types
import Network.Google.Prelude
-- | A resource alias for @ml.projects.operations.delete@ method which the
-- 'ProjectsOperationsDelete' request conforms to.
type ProjectsOperationsDeleteResource =
"v1beta1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] GoogleProtobuf__Empty
-- | Deletes a long-running operation. This method indicates that the client
-- is no longer interested in the operation result. It does not cancel the
-- operation. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`.
--
-- /See:/ 'projectsOperationsDelete' smart constructor.
data ProjectsOperationsDelete = ProjectsOperationsDelete'
{ _podXgafv :: !(Maybe Xgafv)
, _podUploadProtocol :: !(Maybe Text)
, _podPp :: !Bool
, _podAccessToken :: !(Maybe Text)
, _podUploadType :: !(Maybe Text)
, _podBearerToken :: !(Maybe Text)
, _podName :: !Text
, _podCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProjectsOperationsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'podXgafv'
--
-- * 'podUploadProtocol'
--
-- * 'podPp'
--
-- * 'podAccessToken'
--
-- * 'podUploadType'
--
-- * 'podBearerToken'
--
-- * 'podName'
--
-- * 'podCallback'
projectsOperationsDelete
:: Text -- ^ 'podName'
-> ProjectsOperationsDelete
projectsOperationsDelete pPodName_ =
ProjectsOperationsDelete'
{ _podXgafv = Nothing
, _podUploadProtocol = Nothing
, _podPp = True
, _podAccessToken = Nothing
, _podUploadType = Nothing
, _podBearerToken = Nothing
, _podName = pPodName_
, _podCallback = Nothing
}
-- | V1 error format.
podXgafv :: Lens' ProjectsOperationsDelete (Maybe Xgafv)
podXgafv = lens _podXgafv (\ s a -> s{_podXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
podUploadProtocol :: Lens' ProjectsOperationsDelete (Maybe Text)
podUploadProtocol
= lens _podUploadProtocol
(\ s a -> s{_podUploadProtocol = a})
-- | Pretty-print response.
podPp :: Lens' ProjectsOperationsDelete Bool
podPp = lens _podPp (\ s a -> s{_podPp = a})
-- | OAuth access token.
podAccessToken :: Lens' ProjectsOperationsDelete (Maybe Text)
podAccessToken
= lens _podAccessToken
(\ s a -> s{_podAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
podUploadType :: Lens' ProjectsOperationsDelete (Maybe Text)
podUploadType
= lens _podUploadType
(\ s a -> s{_podUploadType = a})
-- | OAuth bearer token.
podBearerToken :: Lens' ProjectsOperationsDelete (Maybe Text)
podBearerToken
= lens _podBearerToken
(\ s a -> s{_podBearerToken = a})
-- | The name of the operation resource to be deleted.
podName :: Lens' ProjectsOperationsDelete Text
podName = lens _podName (\ s a -> s{_podName = a})
-- | JSONP
podCallback :: Lens' ProjectsOperationsDelete (Maybe Text)
podCallback
= lens _podCallback (\ s a -> s{_podCallback = a})
instance GoogleRequest ProjectsOperationsDelete where
type Rs ProjectsOperationsDelete =
GoogleProtobuf__Empty
type Scopes ProjectsOperationsDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsOperationsDelete'{..}
= go _podName _podXgafv _podUploadProtocol
(Just _podPp)
_podAccessToken
_podUploadType
_podBearerToken
_podCallback
(Just AltJSON)
machineLearningService
where go
= buildClient
(Proxy :: Proxy ProjectsOperationsDeleteResource)
mempty
|
rueshyna/gogol
|
gogol-ml/gen/Network/Google/Resource/Ml/Projects/Operations/Delete.hs
|
mpl-2.0
| 5,810 | 0 | 17 | 1,375 | 855 | 499 | 356 | 121 | 1 |
module Main where
import Control.Monad
import qualified System.Environment as SystemEnvironment
import System.IO (stdout)
import System.Console.Haskeline (runInputT)
import System.Directory (doesPathExist, getHomeDirectory)
import ColorText
import Obj
import Types
import Repl
import StartingEnv
import Eval
import Util
defaultProject :: Project
defaultProject =
Project { projectTitle = "Untitled"
, projectIncludes = [SystemInclude "core.h"]
, projectCFlags = [""]
, projectLibFlags = [""]
, projectFiles = []
, projectAlreadyLoaded = []
, projectEchoC = False
, projectLibDir = ".carp/libs/"
, projectCarpDir = "./"
, projectOutDir = "./out/"
, projectDocsDir = "./docs/"
, projectDocsLogo = ""
, projectDocsPrelude = ""
, projectDocsURL = ""
, projectDocsStyling = "carp_style.css"
, projectPrompt = case platform of
MacOS -> "鲮 "
_ -> "> "
, projectCarpSearchPaths = []
, projectPrintTypedAST = False
, projectCompiler = case platform of
Windows -> "cl.exe -lm"
_ -> "clang -fPIC -lm"
, projectCore = True
, projectEchoCompilationCommand = False
, projectCanExecute = False
, projectFilePathPrintLength = FullPath
}
-- | Starting point of the application.
main :: IO ()
main = do args <- SystemEnvironment.getArgs
sysEnv <- SystemEnvironment.getEnvironment
let (argFilesToLoad, execMode, otherOptions) = parseArgs args
logMemory = LogMemory `elem` otherOptions
noCore = NoCore `elem` otherOptions
optimize = Optimize `elem` otherOptions
projectWithFiles = defaultProject { projectCFlags = (if logMemory then ["-D LOG_MEMORY"] else []) ++
(if optimize then ["-O3 -D OPTIMIZE"] else []) ++
(projectCFlags defaultProject),
projectCore = not noCore}
noArray = False
coreModulesToLoad = if noCore then [] else (coreModules (projectCarpDir projectWithCarpDir))
projectWithCarpDir = case lookup "CARP_DIR" sysEnv of
Just carpDir -> projectWithFiles { projectCarpDir = carpDir }
Nothing -> projectWithFiles
projectWithCustomPrompt = setCustomPromptFromOptions projectWithCarpDir otherOptions
startingContext = (Context
(startingGlobalEnv noArray)
(TypeEnv startingTypeEnv)
[]
projectWithCustomPrompt
""
execMode)
context <- loadFiles startingContext coreModulesToLoad
home <- getHomeDirectory
let carpProfile = home ++ "/.carp/profile.carp"
hasProfile <- doesPathExist carpProfile
context' <- if hasProfile
then loadFiles context [carpProfile]
else do --putStrLn ("No '" ++ carpProfile ++ "' found.")
return context
finalContext <- loadFiles context' argFilesToLoad
settings <- readlineSettings
case execMode of
Repl -> do putStrLn "Welcome to Carp 0.2.0"
putStrLn "This is free software with ABSOLUTELY NO WARRANTY."
putStrLn "Evaluate (help) for more information."
runInputT settings (repl finalContext "")
Build -> do _ <- executeString True finalContext ":b" "Compiler (Build)"
return ()
Install thing ->
do _ <- executeString True finalContext
("(load \"" ++ thing ++ "\")")
"Installation"
return ()
BuildAndRun -> do _ <- executeString True finalContext ":bx" "Compiler (Build & Run)"
-- TODO: Handle the return value from executeString and return that one to the shell
return ()
Check -> do return ()
-- | Options for how to run the compiler.
data OtherOptions = NoCore
| LogMemory
| Optimize
| SetPrompt String
deriving (Show, Eq)
-- | Parse the arguments sent to the compiler from the terminal.
-- | TODO: Switch to 'cmdargs' library for parsing these!
parseArgs :: [String] -> ([FilePath], ExecutionMode, [OtherOptions])
parseArgs args = parseArgsInternal [] Repl [] args
where parseArgsInternal filesToLoad execMode otherOptions [] =
(filesToLoad, execMode, otherOptions)
parseArgsInternal filesToLoad execMode otherOptions (arg:restArgs) =
case arg of
"-b" -> parseArgsInternal filesToLoad Build otherOptions restArgs
"-x" -> parseArgsInternal filesToLoad BuildAndRun otherOptions restArgs
"-i" -> parseArgsInternal filesToLoad (Install (head restArgs)) otherOptions (tail restArgs)
"--check" -> parseArgsInternal filesToLoad Check otherOptions restArgs
"--no-core" -> parseArgsInternal filesToLoad execMode (NoCore : otherOptions) restArgs
"--log-memory" -> parseArgsInternal filesToLoad execMode (LogMemory : otherOptions) restArgs
"--optimize" -> parseArgsInternal filesToLoad execMode (Optimize : otherOptions) restArgs
"--prompt" -> case restArgs of
newPrompt : restRestArgs ->
parseArgsInternal filesToLoad execMode (SetPrompt newPrompt : otherOptions) restRestArgs
_ ->
error "No prompt given after --prompt"
file -> parseArgsInternal (filesToLoad ++ [file]) execMode otherOptions restArgs
setCustomPromptFromOptions :: Project -> [OtherOptions] -> Project
setCustomPromptFromOptions project (o:os) =
case o of
SetPrompt newPrompt -> setCustomPromptFromOptions (project { projectPrompt = newPrompt }) os
_ -> setCustomPromptFromOptions project os
setCustomPromptFromOptions project _ =
project
|
eriksvedang/Carp
|
app/Main.hs
|
mpl-2.0
| 6,573 | 0 | 16 | 2,384 | 1,232 | 658 | 574 | 122 | 11 |
{-# 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.Healthcare.Projects.Locations.DataSets.DicomStores.Patch
-- 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)
--
-- Updates the specified DICOM store.
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.dicomStores.patch@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.DicomStores.Patch
(
-- * REST Resource
ProjectsLocationsDataSetsDicomStoresPatchResource
-- * Creating a Request
, projectsLocationsDataSetsDicomStoresPatch
, ProjectsLocationsDataSetsDicomStoresPatch
-- * Request Lenses
, pldsdspXgafv
, pldsdspUploadProtocol
, pldsdspUpdateMask
, pldsdspAccessToken
, pldsdspUploadType
, pldsdspPayload
, pldsdspName
, pldsdspCallback
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.dicomStores.patch@ method which the
-- 'ProjectsLocationsDataSetsDicomStoresPatch' request conforms to.
type ProjectsLocationsDataSetsDicomStoresPatchResource
=
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] DicomStore :>
Patch '[JSON] DicomStore
-- | Updates the specified DICOM store.
--
-- /See:/ 'projectsLocationsDataSetsDicomStoresPatch' smart constructor.
data ProjectsLocationsDataSetsDicomStoresPatch =
ProjectsLocationsDataSetsDicomStoresPatch'
{ _pldsdspXgafv :: !(Maybe Xgafv)
, _pldsdspUploadProtocol :: !(Maybe Text)
, _pldsdspUpdateMask :: !(Maybe GFieldMask)
, _pldsdspAccessToken :: !(Maybe Text)
, _pldsdspUploadType :: !(Maybe Text)
, _pldsdspPayload :: !DicomStore
, _pldsdspName :: !Text
, _pldsdspCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsDicomStoresPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldsdspXgafv'
--
-- * 'pldsdspUploadProtocol'
--
-- * 'pldsdspUpdateMask'
--
-- * 'pldsdspAccessToken'
--
-- * 'pldsdspUploadType'
--
-- * 'pldsdspPayload'
--
-- * 'pldsdspName'
--
-- * 'pldsdspCallback'
projectsLocationsDataSetsDicomStoresPatch
:: DicomStore -- ^ 'pldsdspPayload'
-> Text -- ^ 'pldsdspName'
-> ProjectsLocationsDataSetsDicomStoresPatch
projectsLocationsDataSetsDicomStoresPatch pPldsdspPayload_ pPldsdspName_ =
ProjectsLocationsDataSetsDicomStoresPatch'
{ _pldsdspXgafv = Nothing
, _pldsdspUploadProtocol = Nothing
, _pldsdspUpdateMask = Nothing
, _pldsdspAccessToken = Nothing
, _pldsdspUploadType = Nothing
, _pldsdspPayload = pPldsdspPayload_
, _pldsdspName = pPldsdspName_
, _pldsdspCallback = Nothing
}
-- | V1 error format.
pldsdspXgafv :: Lens' ProjectsLocationsDataSetsDicomStoresPatch (Maybe Xgafv)
pldsdspXgafv
= lens _pldsdspXgafv (\ s a -> s{_pldsdspXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldsdspUploadProtocol :: Lens' ProjectsLocationsDataSetsDicomStoresPatch (Maybe Text)
pldsdspUploadProtocol
= lens _pldsdspUploadProtocol
(\ s a -> s{_pldsdspUploadProtocol = a})
-- | The update mask applies to the resource. For the \`FieldMask\`
-- definition, see
-- https:\/\/developers.google.com\/protocol-buffers\/docs\/reference\/google.protobuf#fieldmask
pldsdspUpdateMask :: Lens' ProjectsLocationsDataSetsDicomStoresPatch (Maybe GFieldMask)
pldsdspUpdateMask
= lens _pldsdspUpdateMask
(\ s a -> s{_pldsdspUpdateMask = a})
-- | OAuth access token.
pldsdspAccessToken :: Lens' ProjectsLocationsDataSetsDicomStoresPatch (Maybe Text)
pldsdspAccessToken
= lens _pldsdspAccessToken
(\ s a -> s{_pldsdspAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldsdspUploadType :: Lens' ProjectsLocationsDataSetsDicomStoresPatch (Maybe Text)
pldsdspUploadType
= lens _pldsdspUploadType
(\ s a -> s{_pldsdspUploadType = a})
-- | Multipart request metadata.
pldsdspPayload :: Lens' ProjectsLocationsDataSetsDicomStoresPatch DicomStore
pldsdspPayload
= lens _pldsdspPayload
(\ s a -> s{_pldsdspPayload = a})
-- | Resource name of the DICOM store, of the form
-- \`projects\/{project_id}\/locations\/{location_id}\/datasets\/{dataset_id}\/dicomStores\/{dicom_store_id}\`.
pldsdspName :: Lens' ProjectsLocationsDataSetsDicomStoresPatch Text
pldsdspName
= lens _pldsdspName (\ s a -> s{_pldsdspName = a})
-- | JSONP
pldsdspCallback :: Lens' ProjectsLocationsDataSetsDicomStoresPatch (Maybe Text)
pldsdspCallback
= lens _pldsdspCallback
(\ s a -> s{_pldsdspCallback = a})
instance GoogleRequest
ProjectsLocationsDataSetsDicomStoresPatch
where
type Rs ProjectsLocationsDataSetsDicomStoresPatch =
DicomStore
type Scopes ProjectsLocationsDataSetsDicomStoresPatch
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsDicomStoresPatch'{..}
= go _pldsdspName _pldsdspXgafv
_pldsdspUploadProtocol
_pldsdspUpdateMask
_pldsdspAccessToken
_pldsdspUploadType
_pldsdspCallback
(Just AltJSON)
_pldsdspPayload
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsDicomStoresPatchResource)
mempty
|
brendanhay/gogol
|
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/DicomStores/Patch.hs
|
mpl-2.0
| 6,646 | 0 | 17 | 1,394 | 860 | 502 | 358 | 133 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.CreateGroup
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new group.
--
-- For information about the number of groups you can create, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities>
-- in the /Using IAM/ guide.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateGroup.html AWS API Reference> for CreateGroup.
module Network.AWS.IAM.CreateGroup
(
-- * Creating a Request
createGroup
, CreateGroup
-- * Request Lenses
, cgPath
, cgGroupName
-- * Destructuring the Response
, createGroupResponse
, CreateGroupResponse
-- * Response Lenses
, cgrsResponseStatus
, cgrsGroup
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createGroup' smart constructor.
data CreateGroup = CreateGroup'
{ _cgPath :: !(Maybe Text)
, _cgGroupName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cgPath'
--
-- * 'cgGroupName'
createGroup
:: Text -- ^ 'cgGroupName'
-> CreateGroup
createGroup pGroupName_ =
CreateGroup'
{ _cgPath = Nothing
, _cgGroupName = pGroupName_
}
-- | The path to the group. For more information about paths, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers>
-- in the /Using IAM/ guide.
--
-- This parameter is optional. If it is not included, it defaults to a
-- slash (\/).
cgPath :: Lens' CreateGroup (Maybe Text)
cgPath = lens _cgPath (\ s a -> s{_cgPath = a});
-- | The name of the group to create. Do not include the path in this value.
cgGroupName :: Lens' CreateGroup Text
cgGroupName = lens _cgGroupName (\ s a -> s{_cgGroupName = a});
instance AWSRequest CreateGroup where
type Rs CreateGroup = CreateGroupResponse
request = postQuery iAM
response
= receiveXMLWrapper "CreateGroupResult"
(\ s h x ->
CreateGroupResponse' <$>
(pure (fromEnum s)) <*> (x .@ "Group"))
instance ToHeaders CreateGroup where
toHeaders = const mempty
instance ToPath CreateGroup where
toPath = const "/"
instance ToQuery CreateGroup where
toQuery CreateGroup'{..}
= mconcat
["Action" =: ("CreateGroup" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"Path" =: _cgPath, "GroupName" =: _cgGroupName]
-- | Contains the response to a successful CreateGroup request.
--
-- /See:/ 'createGroupResponse' smart constructor.
data CreateGroupResponse = CreateGroupResponse'
{ _cgrsResponseStatus :: !Int
, _cgrsGroup :: !Group
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateGroupResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cgrsResponseStatus'
--
-- * 'cgrsGroup'
createGroupResponse
:: Int -- ^ 'cgrsResponseStatus'
-> Group -- ^ 'cgrsGroup'
-> CreateGroupResponse
createGroupResponse pResponseStatus_ pGroup_ =
CreateGroupResponse'
{ _cgrsResponseStatus = pResponseStatus_
, _cgrsGroup = pGroup_
}
-- | The response status code.
cgrsResponseStatus :: Lens' CreateGroupResponse Int
cgrsResponseStatus = lens _cgrsResponseStatus (\ s a -> s{_cgrsResponseStatus = a});
-- | Information about the group.
cgrsGroup :: Lens' CreateGroupResponse Group
cgrsGroup = lens _cgrsGroup (\ s a -> s{_cgrsGroup = a});
|
fmapfmapfmap/amazonka
|
amazonka-iam/gen/Network/AWS/IAM/CreateGroup.hs
|
mpl-2.0
| 4,453 | 0 | 14 | 958 | 632 | 382 | 250 | 80 | 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.BinaryAuthorization.Projects.UpdatePolicy
-- 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)
--
-- Creates or updates a project\'s policy, and returns a copy of the new
-- policy. A policy is always updated as a whole, to avoid race conditions
-- with concurrent policy enforcement (or management!) requests. Returns
-- NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the request
-- is malformed.
--
-- /See:/ <https://cloud.google.com/binary-authorization/ Binary Authorization API Reference> for @binaryauthorization.projects.updatePolicy@.
module Network.Google.Resource.BinaryAuthorization.Projects.UpdatePolicy
(
-- * REST Resource
ProjectsUpdatePolicyResource
-- * Creating a Request
, projectsUpdatePolicy
, ProjectsUpdatePolicy
-- * Request Lenses
, pupXgafv
, pupUploadProtocol
, pupAccessToken
, pupUploadType
, pupPayload
, pupName
, pupCallback
) where
import Network.Google.BinaryAuthorization.Types
import Network.Google.Prelude
-- | A resource alias for @binaryauthorization.projects.updatePolicy@ method which the
-- 'ProjectsUpdatePolicy' request conforms to.
type ProjectsUpdatePolicyResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Policy :> Put '[JSON] Policy
-- | Creates or updates a project\'s policy, and returns a copy of the new
-- policy. A policy is always updated as a whole, to avoid race conditions
-- with concurrent policy enforcement (or management!) requests. Returns
-- NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the request
-- is malformed.
--
-- /See:/ 'projectsUpdatePolicy' smart constructor.
data ProjectsUpdatePolicy =
ProjectsUpdatePolicy'
{ _pupXgafv :: !(Maybe Xgafv)
, _pupUploadProtocol :: !(Maybe Text)
, _pupAccessToken :: !(Maybe Text)
, _pupUploadType :: !(Maybe Text)
, _pupPayload :: !Policy
, _pupName :: !Text
, _pupCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsUpdatePolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pupXgafv'
--
-- * 'pupUploadProtocol'
--
-- * 'pupAccessToken'
--
-- * 'pupUploadType'
--
-- * 'pupPayload'
--
-- * 'pupName'
--
-- * 'pupCallback'
projectsUpdatePolicy
:: Policy -- ^ 'pupPayload'
-> Text -- ^ 'pupName'
-> ProjectsUpdatePolicy
projectsUpdatePolicy pPupPayload_ pPupName_ =
ProjectsUpdatePolicy'
{ _pupXgafv = Nothing
, _pupUploadProtocol = Nothing
, _pupAccessToken = Nothing
, _pupUploadType = Nothing
, _pupPayload = pPupPayload_
, _pupName = pPupName_
, _pupCallback = Nothing
}
-- | V1 error format.
pupXgafv :: Lens' ProjectsUpdatePolicy (Maybe Xgafv)
pupXgafv = lens _pupXgafv (\ s a -> s{_pupXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pupUploadProtocol :: Lens' ProjectsUpdatePolicy (Maybe Text)
pupUploadProtocol
= lens _pupUploadProtocol
(\ s a -> s{_pupUploadProtocol = a})
-- | OAuth access token.
pupAccessToken :: Lens' ProjectsUpdatePolicy (Maybe Text)
pupAccessToken
= lens _pupAccessToken
(\ s a -> s{_pupAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pupUploadType :: Lens' ProjectsUpdatePolicy (Maybe Text)
pupUploadType
= lens _pupUploadType
(\ s a -> s{_pupUploadType = a})
-- | Multipart request metadata.
pupPayload :: Lens' ProjectsUpdatePolicy Policy
pupPayload
= lens _pupPayload (\ s a -> s{_pupPayload = a})
-- | Output only. The resource name, in the format \`projects\/*\/policy\`.
-- There is at most one policy per project.
pupName :: Lens' ProjectsUpdatePolicy Text
pupName = lens _pupName (\ s a -> s{_pupName = a})
-- | JSONP
pupCallback :: Lens' ProjectsUpdatePolicy (Maybe Text)
pupCallback
= lens _pupCallback (\ s a -> s{_pupCallback = a})
instance GoogleRequest ProjectsUpdatePolicy where
type Rs ProjectsUpdatePolicy = Policy
type Scopes ProjectsUpdatePolicy =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsUpdatePolicy'{..}
= go _pupName _pupXgafv _pupUploadProtocol
_pupAccessToken
_pupUploadType
_pupCallback
(Just AltJSON)
_pupPayload
binaryAuthorizationService
where go
= buildClient
(Proxy :: Proxy ProjectsUpdatePolicyResource)
mempty
|
brendanhay/gogol
|
gogol-binaryauthorization/gen/Network/Google/Resource/BinaryAuthorization/Projects/UpdatePolicy.hs
|
mpl-2.0
| 5,555 | 0 | 16 | 1,226 | 783 | 460 | 323 | 111 | 1 |
module Network.Crazyflie.CRTP.Constants
( CRTPPort (..)
, LogChannel (..)
, AllChannel (..)
, ConsoleChannel (..)
, ParamChannel (..)
, CommanderChannel (..)
, DebugdriverChannel (..)
, LinkctrlChannel (..)
) where
import ClassyPrelude
import Data.Word
import Data.Binary
import Data.Bits
data LogChannel = LogTOC | LogSettings | LogData deriving (Show, Eq)
data AllChannel = AllChannel | AllBroadcast deriving (Show, Eq)
data ConsoleChannel = ConsoleChannel deriving (Show, Eq)
data ParamChannel = ParamChannel deriving (Show, Eq)
data CommanderChannel = CommanderChannel deriving (Show, Eq)
data DebugdriverChannel = DebugdriverChannel deriving (Show, Eq)
data LinkctrlChannel = LinkctrlChannel deriving (Show, Eq)
data CRTPPort = Console ConsoleChannel | Param ParamChannel | Commander CommanderChannel
| Logging LogChannel | Debugdriver DebugdriverChannel
| Linkctrl LinkctrlChannel | All AllChannel deriving (Show, Eq)
instance Binary CRTPPort where
put (Console _) = putWord8 $ encodePortAndChannel 0x00 0x00
put (Param _) = putWord8 $ encodePortAndChannel 0x02 0x00
put (Commander _) = putWord8 $ encodePortAndChannel 0x03 0x00
put (Logging c) = putWord8 $ encodePortAndChannel 0x05 chan
where chan = case c of
LogTOC -> 0x00
LogSettings -> 0x01
LogData -> 0x02
put (Debugdriver _) = putWord8 $ encodePortAndChannel 0x0e 0x00
put (Linkctrl _) = putWord8 $ encodePortAndChannel 0x0f 0x00
put (All c) = putWord8 $ encodePortAndChannel 0xff chan
where chan = case c of
AllChannel -> 0x00
AllBroadcast -> 0xff
get = do
p <- getWord8
case shiftR (p .&. 0xF0) 4 of
0x00 -> return (Console ConsoleChannel)
0x02 -> return (Param ParamChannel)
0x03 -> return (Commander CommanderChannel)
0x05 -> case (p .&. 0x03) of
0x00 -> return (Logging LogTOC)
0x01 -> return (Logging LogSettings)
0x02 -> return (Logging LogData)
0x0e -> return (Debugdriver DebugdriverChannel)
0x0f -> return (Linkctrl LinkctrlChannel)
0xff -> case (p .&. 0x03) of
0x00 -> return (All AllChannel)
0xff -> return (All AllBroadcast)
otherwise -> return (All AllChannel)
encodePortAndChannel :: Word8 -> Word8 -> Word8
encodePortAndChannel port channel = portBits .|. channelBits
where
portBits = (shiftL port 4) .&. 0xF0
channelBits = channel .&. 0x03
|
orclev/crazyflie-haskell
|
src/Network/Crazyflie/CRTP/Constants.hs
|
lgpl-3.0
| 2,608 | 0 | 16 | 707 | 775 | 410 | 365 | 58 | 1 |
module Strava (repl, initialStravaContext, getToken) where
import System.Exit
import System.Directory
import System.Locale
import System.IO.Error
import System.IO
import Network.Curl
import Text.JSON
import Control.Monad()
import Control.Monad.State
import Data.Functor
import Control.Applicative
import Data.Foldable (traverse_)
import Data.Time
appName :: String
appName = "strava-cli"
stravaUserTokenFile :: String
stravaUserTokenFile = ".strava-token"
clientSecretFile :: String
clientSecretFile = ".client-secret"
clientIdFile :: String
clientIdFile = ".client-id"
data StravaApp = StravaApp
{ clientId :: String
, clientSecret :: String
}
data StravaAuth = StravaAuth
{ accessToken :: String }
instance JSON StravaAuth where
readJSON (JSObject o) =
StravaAuth <$> valFromObj "access_token" o
readJSON _ = mzero
showJSON = undefined
data StravaAthlete = StravaAthlete
{ firstname :: String
, lastname :: String
} deriving (Eq)
instance JSON StravaAthlete where
readJSON (JSObject o) =
StravaAthlete <$>
valFromObj "firstname" o <*>
valFromObj "lastname" o
readJSON _ = mzero
showJSON = undefined
instance Show StravaAthlete where
show a = firstname a ++ " " ++ lastname a
data StravaActivity = StravaActivity
{ name :: Maybe String
, athlete :: Maybe StravaAthlete
, distance :: Maybe Double
, movingTime :: Maybe Double
, totalElevationGain :: Maybe Double
, startDate :: Maybe UTCTime
, elapsedTime :: Maybe Double
, averageHeartrate :: Maybe Double
, maxHeartrate :: Maybe Double
} deriving (Eq, Show)
instance JSON StravaActivity where
readJSON (JSObject o) =
StravaActivity <$>
queryObj "name" <*>
queryObj "athlete" <*>
queryObj "distance" <*>
queryObj "moving_time" <*>
queryObj "total_elevation_gain" <*>
queryTime "start_date" <*>
queryObj "elapsed_time" <*>
queryObj "average_heartrate" <*>
queryObj "max_heartrate"
where
queryObj str = case valFromObj str o of
(Ok a) -> return $ Just a
_ -> return Nothing
queryTime str = case valFromObj str o of
(Ok a) -> return $ parseTime defaultTimeLocale "%FT%TZ" a
_ -> return Nothing
readJSON _ = mzero
showJSON = undefined
data StravaAPI = StravaAPI
{ listUserActivities :: String
, listFriendActivities :: String
}
stravaAPI :: StravaAPI
stravaAPI = StravaAPI
"https://www.strava.com/api/v3/athlete/activities"
"https://www.strava.com/api/v3/activities/following"
readStravaAppID :: IO (String, String)
readStravaAppID = do
i <- readFile clientIdFile
s <- readFile clientSecretFile
return (i, s)
authorize :: IO (Maybe StravaAuth)
authorize = do
checkStravaApp <- tryIOError readStravaAppID
(appId, secret) <- case checkStravaApp of
Right c -> return c
Left _ -> do
putStrLn "Could not read application application id and secret"
putStrLn "Register your application (http://www.strava.com/developers)"
putStr "and provide your `application id': "
hFlush stdout
i <- getLine
writeFile clientIdFile i
putStr "and your `client secret': "
hFlush stdout
s <- getLine
writeFile clientSecretFile s
return (i, s)
let app = StravaApp appId secret
putStrLn $ "Visit: https://www.strava.com/oauth/authorize?client_id=" ++ clientId app ++ "&response_type=code&redirect_uri=http://putigny.net/strava&approval_prompt=force"
putStrLn "and authorize this application to access your strava data"
putStr "provide you code: "
hFlush stdout
code <- getLine
(_, curlResp) <- curlGetString
("https://www.strava.com/oauth/token?client_id=" ++ clientId app ++ "&client_secret=" ++ clientSecret app ++ "&code=" ++ code) [CurlPost True]
let stravaAuth = decode curlResp :: Result StravaAuth
case stravaAuth of
Ok a -> writeFile stravaUserTokenFile (accessToken a) >>
return (Just $ StravaAuth $ accessToken a)
_ -> return Nothing
getToken :: IO StravaAuth
getToken = do
token <- tryIOError $ readFile stravaUserTokenFile -- try to read previous token
case token of
Right t -> return $ StravaAuth t
Left _ -> do
putStrLn "Could not read previous strava auth token, requesting new token..."
stravaAuth <- authorize
case stravaAuth of
Just auth -> return auth
Nothing -> getToken
printActivity :: StravaActivity -> IO ()
printActivity a = do
ctz <- getCurrentTimeZone
printer $ (++ "\n") <$> show <$> athlete a
printer $ formatTime defaultTimeLocale "%F %T: " <$> utcToLocalTime ctz <$> startDate a
printer $ (\x -> "`" ++ x ++ "'\n") <$> name a
printer $ (\x -> " " ++ x ++ " km\n") <$> show <$> (round :: Double -> Int) <$> (/1000) <$> distance a
printer $ (\x -> " " ++ x ++ " mD+\n") <$> show <$> (round :: Double -> Int) <$> totalElevationGain a
printer $ (\x -> " HR: " ++ x ++ " (avg)\n") <$> show <$> (round :: Double -> Int) <$> averageHeartrate a
printer $ (\x -> " HR: " ++ x ++ " (max)\n") <$> show <$> (round :: Double -> Int) <$> maxHeartrate a
putStr "\n"
where
printer = traverse_ putStr
lsStrava :: StravaContext ()
lsStrava = do
aList <- userActivities <$> get
liftIO $ mapM_ printActivity $ reverse aList
lsFriend :: StravaContext ()
lsFriend = do
aList <- friendActivities <$> get
liftIO $ mapM_ printActivity $ reverse aList
data StravaData = StravaData {
userActivities :: [StravaActivity],
friendActivities :: [StravaActivity]
}
initialStravaContext :: StravaData
initialStravaContext = StravaData [] []
type StravaContext a = StateT StravaData IO a
loadStravaContext :: StravaAuth -> StravaContext ()
loadStravaContext sa = do
(c0, ownJson) <- liftIO $
curlGetString (listUserActivities stravaAPI) [CurlHttpHeaders [stravaAuth]]
when (c0 /= CurlOK) $ liftIO $ print c0
(c1, friendJson) <- liftIO $
curlGetString (listFriendActivities stravaAPI) [CurlHttpHeaders [stravaAuth]]
when (c1 /= CurlOK && c1 /= c0) $ liftIO $ print c1
let aList = decode ownJson :: Result [StravaActivity]
let a2List = decode friendJson :: Result [StravaActivity]
let ownAct = case aList of
Ok a -> a
_ -> []
let friendAct = case a2List of
Ok a -> a
_ -> []
put $ StravaData ownAct friendAct
where stravaAuth = "Authorization: Bearer " ++ accessToken sa
repl :: StravaAuth -> StravaContext ()
repl sa = do
liftIO $ putStrLn "Loading data from strava"
loadStravaContext sa
liftIO $ putStrLn "Done"
forever $ do
liftIO $ putStr "> " >> hFlush stdout
cmd <- liftIO $ tryIOError getLine
case cmd of
Right "ls" -> lsStrava
Right "lf" -> lsFriend
Right "up" -> loadStravaContext sa
Right "help" -> liftIO $ do
putStrLn "Supported commands are:"
putStrLn " ls: list user's activities"
putStrLn " lf: list friends activities"
putStrLn " up: update strava data"
Right str -> liftIO $ putStrLn $ str ++ " is not a valid command (use help)"
Left e -> liftIO $ if isEOFError e
then putStrLn "quit" >> exitSuccess
else print e
|
bputigny/strava-cli
|
src/Strava.hs
|
lgpl-3.0
| 8,041 | 0 | 16 | 2,478 | 2,095 | 1,028 | 1,067 | 194 | 7 |
module Miscellaneous.A259439 (a259439) where
import HelperSequences.A143482 (a143482)
a259439 :: Integral a => a -> a
a259439 n = a143482 n `div` n
|
peterokagey/haskellOEIS
|
src/Miscellaneous/A259439.hs
|
apache-2.0
| 149 | 0 | 6 | 23 | 54 | 30 | 24 | 4 | 1 |
{-# LANGUAGE TemplateHaskell, NoMonomorphismRestriction, FlexibleContexts,
RankNTypes #-}
{-| The WConfd functions for direct configuration manipulation
This module contains the client functions exported by WConfD for
specific configuration manipulation.
-}
{-
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.WConfd.ConfigModifications where
import Control.Applicative ((<$>))
import Control.Lens (_2)
import Control.Lens.Getter ((^.))
import Control.Lens.Setter (Setter, (.~), (%~), (+~), over)
import Control.Lens.Traversal (mapMOf)
import Control.Lens.Type (Simple)
import Control.Monad (unless, when, forM_, foldM, liftM, liftM2)
import Control.Monad.Error (throwError, MonadError)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.State (StateT, get, put, modify,
runStateT, execStateT)
import Data.Foldable (fold, foldMap)
import Data.List (elemIndex)
import Data.Maybe (isJust, maybeToList, fromMaybe, fromJust)
import Language.Haskell.TH (Name)
import System.Time (getClockTime, ClockTime)
import Text.Printf (printf)
import qualified Data.Map as M
import qualified Data.Set as S
import Ganeti.BasicTypes (GenericResult(..), genericResult, toError)
import Ganeti.Constants (lastDrbdPort)
import Ganeti.Errors (GanetiException(..))
import Ganeti.JSON (Container, GenericContainer(..), alterContainerL
, lookupContainer, MaybeForJSON(..), TimeAsDoubleJSON(..))
import Ganeti.Locking.Locks (ClientId, ciIdentifier)
import Ganeti.Logging.Lifted (logDebug, logInfo)
import Ganeti.Objects
import Ganeti.Objects.Lens
import Ganeti.Types (AdminState, AdminStateSource, JobId)
import Ganeti.Utils (ordNub)
import Ganeti.WConfd.ConfigState (ConfigState, csConfigData, csConfigDataL)
import Ganeti.WConfd.Monad (WConfdMonad, modifyConfigWithLock
, modifyConfigAndReturnWithLock)
import qualified Ganeti.WConfd.TempRes as T
type DiskUUID = String
type InstanceUUID = String
type NodeUUID = String
-- * accessor functions
getInstanceByUUID :: ConfigState
-> InstanceUUID
-> GenericResult GanetiException Instance
getInstanceByUUID cs uuid = lookupContainer
(Bad . ConfigurationError $
printf "Could not find instance with UUID %s" uuid)
uuid
(configInstances . csConfigData $ cs)
-- * getters
-- | Gets all logical volumes in the cluster
getAllLVs :: ConfigState -> S.Set String
getAllLVs = S.fromList . concatMap getLVsOfDisk . M.elems
. fromContainer . configDisks . csConfigData
where convert (LogicalVolume lvG lvV) = lvG ++ "/" ++ lvV
getDiskLV :: Disk -> Maybe String
getDiskLV disk = case diskLogicalId disk of
Just (LIDPlain lv) -> Just (convert lv)
_ -> Nothing
getLVsOfDisk :: Disk -> [String]
getLVsOfDisk disk = maybeToList (getDiskLV disk)
++ concatMap getLVsOfDisk (diskChildren disk)
-- | Gets the ids of nodes, instances, node groups,
-- networks, disks, nics, and the custer itself.
getAllIDs :: ConfigState -> S.Set String
getAllIDs cs =
let lvs = getAllLVs cs
keysFromC :: GenericContainer a b -> [a]
keysFromC = M.keys . fromContainer
valuesFromC :: GenericContainer a b -> [b]
valuesFromC = M.elems . fromContainer
instKeys = keysFromC . configInstances . csConfigData $ cs
nodeKeys = keysFromC . configNodes . csConfigData $ cs
instValues = map uuidOf . valuesFromC
. configInstances . csConfigData $ cs
nodeValues = map uuidOf . valuesFromC . configNodes . csConfigData $ cs
nodeGroupValues = map uuidOf . valuesFromC
. configNodegroups . csConfigData $ cs
networkValues = map uuidOf . valuesFromC
. configNetworks . csConfigData $ cs
disksValues = map uuidOf . valuesFromC . configDisks . csConfigData $ cs
nics = map nicUuid . concatMap instNics
. valuesFromC . configInstances . csConfigData $ cs
cluster = uuidOf . configCluster . csConfigData $ cs
in S.union lvs . S.fromList $ instKeys ++ nodeKeys ++ instValues ++ nodeValues
++ nodeGroupValues ++ networkValues ++ disksValues ++ nics ++ [cluster]
getAllMACs :: ConfigState -> S.Set String
getAllMACs = S.fromList . map nicMac . concatMap instNics . M.elems
. fromContainer . configInstances . csConfigData
-- | Checks if the two objects are equal,
-- excluding timestamps. The serial number of
-- current must be one greater than that of target.
--
-- If this is true, it implies that the update RPC
-- updated the config, but did not successfully return.
isIdentical :: (Eq a, SerialNoObjectL a, TimeStampObjectL a)
=> ClockTime
-> a
-> a
-> Bool
isIdentical now target current = (mTimeL .~ now $ current) ==
((serialL %~ (+1)) . (mTimeL .~ now) $ target)
-- | Checks if the two objects given have the same serial number
checkSerial :: SerialNoObject a => a -> a -> GenericResult GanetiException ()
checkSerial target current = if serialOf target == serialOf current
then Ok ()
else Bad . ConfigurationError $ printf
"Configuration object updated since it has been read: %d != %d"
(serialOf current) (serialOf target)
-- | Updates an object present in a container.
-- The presence of the object in the container
-- is determined by the uuid of the object.
--
-- A check that serial number of the
-- object is consistent with the serial number
-- of the object in the container is performed.
--
-- If the check passes, the object's serial number
-- is incremented, and modification time is updated,
-- and then is inserted into the container.
replaceIn :: (UuidObject a, TimeStampObjectL a, SerialNoObjectL a)
=> ClockTime
-> a
-> Container a
-> GenericResult GanetiException (Container a)
replaceIn now target = alterContainerL (uuidOf target) extract
where extract Nothing = Bad $ ConfigurationError
"Configuration object unknown"
extract (Just current) = do
checkSerial target current
return . Just . (serialL %~ (+1)) . (mTimeL .~ now) $ target
-- | Utility fuction that combines the two
-- possible actions that could be taken when
-- given a target.
--
-- If the target is identical to the current
-- value, we return the modification time of
-- the current value, and not change the config.
--
-- If not, we update the config.
updateConfigIfNecessary :: (Monad m, MonadError GanetiException m, Eq a,
UuidObject a, SerialNoObjectL a, TimeStampObjectL a)
=> ClockTime
-> a
-> (ConfigState -> Container a)
-> (ConfigState
-> m ((Int, ClockTime), ConfigState))
-> ConfigState
-> m ((Int, ClockTime), ConfigState)
updateConfigIfNecessary now target getContainer f cs = do
let container = getContainer cs
current <- lookupContainer (toError . Bad . ConfigurationError $
"Configuraton object unknown")
(uuidOf target)
container
if isIdentical now target current
then return ((serialOf current, mTimeOf current), cs)
else f cs
-- * UUID config checks
-- | Checks if the config has the given UUID
checkUUIDpresent :: UuidObject a
=> ConfigState
-> a
-> Bool
checkUUIDpresent cs a = uuidOf a `S.member` getAllIDs cs
-- | Checks if the given UUID is new (i.e., no in the config)
checkUniqueUUID :: UuidObject a
=> ConfigState
-> a
-> Bool
checkUniqueUUID cs a = not $ checkUUIDpresent cs a
-- * RPC checks
-- | Verifications done before adding an instance.
-- Currently confirms that the instance's macs are not
-- in use, and that the instance's UUID being
-- present (or not present) in the config based on
-- weather the instance is being replaced (or not).
--
-- TODO: add more verifications to this call;
-- the client should have a lock on the name of the instance.
addInstanceChecks :: Instance
-> Bool
-> ConfigState
-> GenericResult GanetiException ()
addInstanceChecks inst replace cs = do
let macsInUse = S.fromList (map nicMac (instNics inst))
`S.intersection` getAllMACs cs
unless (S.null macsInUse) . Bad . ConfigurationError $ printf
"Cannot add instance %s; MAC addresses %s already in use"
(show $ instName inst) (show macsInUse)
if replace
then do
let check = checkUUIDpresent cs inst
unless check . Bad . ConfigurationError $ printf
"Cannot add %s: UUID %s already in use"
(show $ instName inst) (instUuid inst)
else do
let check = checkUniqueUUID cs inst
unless check . Bad . ConfigurationError $ printf
"Cannot replace %s: UUID %s not present"
(show $ instName inst) (instUuid inst)
addDiskChecks :: Disk
-> Bool
-> ConfigState
-> GenericResult GanetiException ()
addDiskChecks disk replace cs =
if replace
then
unless (checkUUIDpresent cs disk) . Bad . ConfigurationError $ printf
"Cannot add %s: UUID %s already in use"
(show $ diskName disk) (diskUuid disk)
else
unless (checkUniqueUUID cs disk) . Bad . ConfigurationError $ printf
"Cannot replace %s: UUID %s not present"
(show $ diskName disk) (diskUuid disk)
attachInstanceDiskChecks :: InstanceUUID
-> DiskUUID
-> MaybeForJSON Int
-> ConfigState
-> GenericResult GanetiException ()
attachInstanceDiskChecks uuidInst uuidDisk idx' cs = do
let diskPresent = elem uuidDisk . map diskUuid . M.elems
. fromContainer . configDisks . csConfigData $ cs
unless diskPresent . Bad . ConfigurationError $ printf
"Disk %s doesn't exist" uuidDisk
inst <- getInstanceByUUID cs uuidInst
let numDisks = length $ instDisks inst
idx = fromMaybe numDisks (unMaybeForJSON idx')
when (idx < 0) . Bad . GenericError $
"Not accepting negative indices"
when (idx > numDisks) . Bad . GenericError $ printf
"Got disk index %d, but there are only %d" idx numDisks
let insts = M.elems . fromContainer . configInstances . csConfigData $ cs
forM_ insts (\inst' -> when (uuidDisk `elem` instDisks inst') . Bad
. ReservationError $ printf "Disk %s already attached to instance %s"
uuidDisk (show $ instName inst))
-- * Pure config modifications functions
attachInstanceDisk' :: InstanceUUID
-> DiskUUID
-> MaybeForJSON Int
-> ClockTime
-> ConfigState
-> ConfigState
attachInstanceDisk' iUuid dUuid idx' ct cs =
let inst = genericResult (error "impossible") id (getInstanceByUUID cs iUuid)
numDisks = length $ instDisks inst
idx = fromMaybe numDisks (unMaybeForJSON idx')
insert = instDisksL %~ (\ds -> take idx ds ++ [dUuid] ++ drop idx ds)
incr = instSerialL %~ (+ 1)
time = instMtimeL .~ ct
inst' = time . incr . insert $ inst
disks = updateIvNames idx inst' (configDisks . csConfigData $ cs)
ri = csConfigDataL . configInstancesL
. alterContainerL iUuid .~ Just inst'
rds = csConfigDataL . configDisksL .~ disks
in rds . ri $ cs
where updateIvNames :: Int -> Instance -> Container Disk -> Container Disk
updateIvNames idx inst (GenericContainer m) =
let dUuids = drop idx (instDisks inst)
upgradeIv m' (idx'', dUuid') =
M.adjust (diskIvNameL .~ "disk/" ++ show idx'') dUuid' m'
in GenericContainer $ foldl upgradeIv m (zip [idx..] dUuids)
-- * Monadic config modification functions which can return errors
detachInstanceDisk' :: MonadError GanetiException m
=> InstanceUUID
-> DiskUUID
-> ClockTime
-> ConfigState
-> m ConfigState
detachInstanceDisk' iUuid dUuid ct cs =
let resetIv :: MonadError GanetiException m
=> Int
-> [DiskUUID]
-> ConfigState
-> m ConfigState
resetIv startIdx disks = mapMOf (csConfigDataL . configDisksL)
(\cd -> foldM (\c (idx, dUuid') -> mapMOf (alterContainerL dUuid')
(\md -> case md of
Nothing -> throwError . ConfigurationError $
printf "Could not find disk with UUID %s" dUuid'
Just disk -> return
. Just
. (diskIvNameL .~ ("disk/" ++ show idx))
$ disk) c)
cd (zip [startIdx..] disks))
iL = csConfigDataL . configInstancesL . alterContainerL iUuid
in case cs ^. iL of
Nothing -> throwError . ConfigurationError $
printf "Could not find instance with UUID %s" iUuid
Just ist -> case elemIndex dUuid (instDisks ist) of
Nothing -> return cs
Just idx ->
let ist' = (instDisksL %~ filter (/= dUuid))
. (instSerialL %~ (+1))
. (instMtimeL .~ ct)
$ ist
cs' = iL .~ Just ist' $ cs
dks = drop (idx + 1) (instDisks ist)
in resetIv idx dks cs'
removeInstanceDisk' :: MonadError GanetiException m
=> InstanceUUID
-> DiskUUID
-> ClockTime
-> ConfigState
-> m ConfigState
removeInstanceDisk' iUuid dUuid ct =
let f cs
| elem dUuid
. fold
. fmap instDisks
. configInstances
. csConfigData
$ cs
= throwError . ProgrammerError $
printf "Cannot remove disk %s. Disk is attached to an instance" dUuid
| elem dUuid
. foldMap (:[])
. fmap diskUuid
. configDisks
. csConfigData
$ cs
= return
. ((csConfigDataL . configDisksL . alterContainerL dUuid) .~ Nothing)
. ((csConfigDataL . configClusterL . clusterSerialL) %~ (+1))
. ((csConfigDataL . configClusterL . clusterMtimeL) .~ ct)
$ cs
| otherwise = return cs
in (f =<<) . detachInstanceDisk' iUuid dUuid ct
-- * RPCs
-- | Add a new instance to the configuration, release DRBD minors,
-- and commit temporary IPs, all while temporarily holding the config
-- lock. Return True upon success and False if the config lock was not
-- available and the client should retry.
addInstance :: Instance -> ClientId -> Bool -> WConfdMonad Bool
addInstance inst cid replace = do
ct <- liftIO getClockTime
logDebug $ "AddInstance: client " ++ show (ciIdentifier cid)
++ " adding instance " ++ uuidOf inst
++ " with name " ++ show (instName inst)
let setCtime = instCtimeL .~ ct
setMtime = instMtimeL .~ ct
addInst i = csConfigDataL . configInstancesL . alterContainerL (uuidOf i)
.~ Just i
commitRes tr = mapMOf csConfigDataL $ T.commitReservedIps cid tr
r <- modifyConfigWithLock
(\tr cs -> do
toError $ addInstanceChecks inst replace cs
commitRes tr $ addInst (setMtime . setCtime $ inst) cs)
. T.releaseDRBDMinors $ uuidOf inst
logDebug $ "AddInstance: result of config modification is " ++ show r
return $ isJust r
addInstanceDisk :: InstanceUUID
-> Disk
-> MaybeForJSON Int
-> Bool
-> WConfdMonad Bool
addInstanceDisk iUuid disk idx replace = do
logInfo $ printf "Adding disk %s to configuration" (diskUuid disk)
ct <- liftIO getClockTime
let addD = csConfigDataL . configDisksL . alterContainerL (uuidOf disk)
.~ Just disk
incrSerialNo = csConfigDataL . configSerialL %~ (+1)
r <- modifyConfigWithLock (\_ cs -> do
toError $ addDiskChecks disk replace cs
let cs' = incrSerialNo . addD $ cs
toError $ attachInstanceDiskChecks iUuid (diskUuid disk) idx cs'
return $ attachInstanceDisk' iUuid (diskUuid disk) idx ct cs')
. T.releaseDRBDMinors $ uuidOf disk
return $ isJust r
attachInstanceDisk :: InstanceUUID
-> DiskUUID
-> MaybeForJSON Int
-> WConfdMonad Bool
attachInstanceDisk iUuid dUuid idx = do
ct <- liftIO getClockTime
r <- modifyConfigWithLock (\_ cs -> do
toError $ attachInstanceDiskChecks iUuid dUuid idx cs
return $ attachInstanceDisk' iUuid dUuid idx ct cs)
(return ())
return $ isJust r
-- | Detach a disk from an instance.
detachInstanceDisk :: InstanceUUID -> DiskUUID -> WConfdMonad Bool
detachInstanceDisk iUuid dUuid = do
ct <- liftIO getClockTime
isJust <$> modifyConfigWithLock
(const $ detachInstanceDisk' iUuid dUuid ct) (return ())
-- | Detach a disk from an instance and
-- remove it from the config.
removeInstanceDisk :: InstanceUUID -> DiskUUID -> WConfdMonad Bool
removeInstanceDisk iUuid dUuid = do
ct <- liftIO getClockTime
isJust <$> modifyConfigWithLock
(const $ removeInstanceDisk' iUuid dUuid ct) (return ())
-- | Remove the instance from the configuration.
removeInstance :: InstanceUUID -> WConfdMonad Bool
removeInstance iUuid = do
ct <- liftIO getClockTime
let iL = csConfigDataL . configInstancesL . alterContainerL iUuid
pL = csConfigDataL . configClusterL . clusterTcpudpPortPoolL
sL = csConfigDataL . configClusterL . clusterSerialL
mL = csConfigDataL . configClusterL . clusterMtimeL
-- Add the instances' network port to the cluster pool
f :: Monad m => StateT ConfigState m ()
f = get >>= (maybe
(return ())
(maybe
(return ())
(modify . (pL %~) . (:))
. instNetworkPort)
. (^. iL))
-- Release all IP addresses to the pool
g :: (MonadError GanetiException m, Functor m) => StateT ConfigState m ()
g = get >>= (maybe
(return ())
(mapM_ (\nic ->
when ((isJust . nicNetwork $ nic) && (isJust . nicIp $ nic)) $ do
let network = fromJust . nicNetwork $ nic
ip <- readIp4Address (fromJust . nicIp $ nic)
get >>= mapMOf csConfigDataL (T.commitReleaseIp network ip) >>= put)
. instNics)
. (^. iL))
-- Remove the instance and update cluster serial num, and mtime
h :: Monad m => StateT ConfigState m ()
h = modify $ (iL .~ Nothing) . (sL %~ (+1)) . (mL .~ ct)
isJust <$> modifyConfigWithLock (const $ execStateT (f >> g >> h)) (return ())
-- | Allocate a port.
-- The port will be taken from the available port pool or from the
-- default port range (and in this case we increase
-- highest_used_port).
allocatePort :: WConfdMonad (MaybeForJSON Int)
allocatePort = do
maybePort <- modifyConfigAndReturnWithLock (\_ cs ->
let portPoolL = csConfigDataL . configClusterL . clusterTcpudpPortPoolL
hupL = csConfigDataL . configClusterL . clusterHighestUsedPortL
in case cs ^. portPoolL of
[] -> if cs ^. hupL >= lastDrbdPort
then throwError . ConfigurationError $ printf
"The highest used port is greater than %s. Aborting." lastDrbdPort
else return (cs ^. hupL + 1, hupL %~ (+1) $ cs)
(p:ps) -> return (p, portPoolL .~ ps $ cs))
(return ())
return . MaybeForJSON $ maybePort
-- | Adds a new port to the available port pool.
addTcpUdpPort :: Int -> WConfdMonad Bool
addTcpUdpPort port =
let pL = csConfigDataL . configClusterL . clusterTcpudpPortPoolL
f :: Monad m => ConfigState -> m ConfigState
f = mapMOf pL (return . (port:) . filter (/= port))
in isJust <$> modifyConfigWithLock (const f) (return ())
-- | Set the instances' status to a given value.
setInstanceStatus :: InstanceUUID
-> MaybeForJSON AdminState
-> MaybeForJSON Bool
-> MaybeForJSON AdminStateSource
-> WConfdMonad (MaybeForJSON Instance)
setInstanceStatus iUuid m1 m2 m3 = do
ct <- liftIO getClockTime
let modifyInstance = maybe id (instAdminStateL .~) (unMaybeForJSON m1)
. maybe id (instDisksActiveL .~) (unMaybeForJSON m2)
. maybe id (instAdminStateSourceL .~) (unMaybeForJSON m3)
reviseInstance = (instSerialL %~ (+1))
. (instMtimeL .~ ct)
g :: Instance -> Instance
g i = if modifyInstance i == i
then i
else reviseInstance . modifyInstance $ i
iL = csConfigDataL . configInstancesL . alterContainerL iUuid
f :: MonadError GanetiException m => StateT ConfigState m Instance
f = get >>= (maybe
(throwError . ConfigurationError $
printf "Could not find instance with UUID %s" iUuid)
(liftM2 (>>)
(modify . (iL .~) . Just)
return . g)
. (^. iL))
MaybeForJSON <$> modifyConfigAndReturnWithLock
(const $ runStateT f) (return ())
-- | Sets the primary node of an existing instance
setInstancePrimaryNode :: InstanceUUID -> NodeUUID -> WConfdMonad Bool
setInstancePrimaryNode iUuid nUuid = isJust <$> modifyConfigWithLock
(\_ -> mapMOf (csConfigDataL . configInstancesL . alterContainerL iUuid)
(\mi -> case mi of
Nothing -> throwError . ConfigurationError $
printf "Could not find instance with UUID %s" iUuid
Just ist -> return . Just $ (instPrimaryNodeL .~ nUuid) ist))
(return ())
-- | The configuration is updated by the provided cluster
updateCluster :: Cluster -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateCluster cluster = do
ct <- liftIO getClockTime
r <- modifyConfigAndReturnWithLock (\_ cs -> do
let currentCluster = configCluster . csConfigData $ cs
if isIdentical ct cluster currentCluster
then return ((serialOf currentCluster, mTimeOf currentCluster), cs)
else do
toError $ checkSerial cluster currentCluster
let updateC = (clusterSerialL %~ (+1)) . (clusterMtimeL .~ ct)
return ((serialOf cluster + 1, ct)
, csConfigDataL . configClusterL .~ updateC cluster $ cs))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided node
updateNode :: Node -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateNode node = do
ct <- liftIO getClockTime
let nL = csConfigDataL . configNodesL
updateC = (clusterSerialL %~ (+1)) . (clusterMtimeL .~ ct)
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct node
(^. nL) (\cs -> do
nC <- toError $ replaceIn ct node (cs ^. nL)
return ((serialOf node + 1, ct), (nL .~ nC)
. (csConfigDataL . configClusterL %~ updateC)
$ cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided instance
updateInstance :: Instance -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateInstance inst = do
ct <- liftIO getClockTime
let iL = csConfigDataL . configInstancesL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct inst
(^. iL) (\cs -> do
iC <- toError $ replaceIn ct inst (cs ^. iL)
return ((serialOf inst + 1, ct), (iL .~ iC) cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided nodegroup
updateNodeGroup :: NodeGroup
-> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateNodeGroup ng = do
ct <- liftIO getClockTime
let ngL = csConfigDataL . configNodegroupsL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct ng
(^. ngL) (\cs -> do
ngC <- toError $ replaceIn ct ng (cs ^. ngL)
return ((serialOf ng + 1, ct), (ngL .~ ngC) cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided network
updateNetwork :: Network -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateNetwork net = do
ct <- liftIO getClockTime
let nL = csConfigDataL . configNetworksL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct net
(^. nL) (\cs -> do
nC <- toError $ replaceIn ct net (cs ^. nL)
return ((serialOf net + 1, ct), (nL .~ nC) cs)))
(return ())
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | The configuration is updated by the provided disk
updateDisk :: Disk -> WConfdMonad (MaybeForJSON (Int, TimeAsDoubleJSON))
updateDisk disk = do
ct <- liftIO getClockTime
let dL = csConfigDataL . configDisksL
r <- modifyConfigAndReturnWithLock (\_ -> updateConfigIfNecessary ct disk
(^. dL) (\cs -> do
dC <- toError $ replaceIn ct disk (cs ^. dL)
return ((serialOf disk + 1, ct), (dL .~ dC) cs)))
. T.releaseDRBDMinors $ uuidOf disk
return . MaybeForJSON $ fmap (_2 %~ TimeAsDoubleJSON) r
-- | Set a particular value and bump serial in the hosting
-- structure. Arguments are a setter to focus on the part
-- of the configuration that gets serial-bumped, and a modification
-- of that part. The function will do the change and bump the serial
-- in the WConfdMonad temporarily acquiring the configuration lock.
-- Return True if that succeeded and False if the configuration lock
-- was not available; no change is done in the latter case.
changeAndBump :: (SerialNoObjectL a, TimeStampObjectL a)
=> Simple Setter ConfigState a
-> (a -> a)
-> WConfdMonad Bool
changeAndBump focus change = do
now <- liftIO getClockTime
let operation = over focus $ (serialL +~ 1) . (mTimeL .~ now) . change
liftM isJust $ modifyConfigWithLock
(\_ cs -> return . operation $ cs)
(return ())
-- | Change and bump part of the maintenance part of the configuration.
changeAndBumpMaint :: (MaintenanceData -> MaintenanceData) -> WConfdMonad Bool
changeAndBumpMaint = changeAndBump $ csConfigDataL . configMaintenanceL
-- | Set the maintenance intervall.
setMaintdRoundDelay :: Int -> WConfdMonad Bool
setMaintdRoundDelay delay = changeAndBumpMaint $ maintRoundDelayL .~ delay
-- | Clear the list of current maintenance jobs.
clearMaintdJobs :: WConfdMonad Bool
clearMaintdJobs = changeAndBumpMaint $ maintJobsL .~ []
-- | Append new jobs to the list of current maintenace jobs, if
-- not alread present.
appendMaintdJobs :: [JobId] -> WConfdMonad Bool
appendMaintdJobs jobs = changeAndBumpMaint . over maintJobsL
$ ordNub . (++ jobs)
-- | Set the autobalance flag.
setMaintdBalance :: Bool -> WConfdMonad Bool
setMaintdBalance value = changeAndBumpMaint $ maintBalanceL .~ value
-- | Set the auto-balance threshold.
setMaintdBalanceThreshold :: Double -> WConfdMonad Bool
setMaintdBalanceThreshold value = changeAndBumpMaint
$ maintBalanceThresholdL .~ value
-- | Add a name to the list of recently evacuated instances.
addMaintdEvacuated :: [String] -> WConfdMonad Bool
addMaintdEvacuated names = changeAndBumpMaint . over maintEvacuatedL
$ ordNub . (++ names)
-- | Remove a name from the list of recently evacuated instances.
rmMaintdEvacuated :: String -> WConfdMonad Bool
rmMaintdEvacuated name = changeAndBumpMaint . over maintEvacuatedL
$ filter (/= name)
-- | Update an incident to the list of known incidents; if the incident,
-- as identified by the UUID, is not present, it is added.
updateMaintdIncident :: Incident -> WConfdMonad Bool
updateMaintdIncident incident =
changeAndBumpMaint . over maintIncidentsL
$ (incident :) . filter ((/= uuidOf incident) . uuidOf)
-- | Remove an incident from the list of known incidents.
rmMaintdIncident :: String -> WConfdMonad Bool
rmMaintdIncident uuid =
changeAndBumpMaint . over maintIncidentsL
$ filter ((/= uuid) . uuidOf)
-- * The list of functions exported to RPC.
exportedFunctions :: [Name]
exportedFunctions = [ 'addInstance
, 'addInstanceDisk
, 'addTcpUdpPort
, 'allocatePort
, 'attachInstanceDisk
, 'detachInstanceDisk
, 'removeInstance
, 'removeInstanceDisk
, 'setInstancePrimaryNode
, 'setInstanceStatus
, 'updateCluster
, 'updateDisk
, 'updateInstance
, 'updateNetwork
, 'updateNode
, 'updateNodeGroup
, 'setMaintdRoundDelay
, 'clearMaintdJobs
, 'appendMaintdJobs
, 'setMaintdBalance
, 'setMaintdBalanceThreshold
, 'addMaintdEvacuated
, 'rmMaintdEvacuated
, 'updateMaintdIncident
, 'rmMaintdIncident
]
|
bitemyapp/ganeti
|
src/Ganeti/WConfd/ConfigModifications.hs
|
bsd-2-clause
| 30,541 | 0 | 27 | 8,269 | 7,383 | 3,828 | 3,555 | -1 | -1 |
module Exercises181 where
import Control.Monad (join)
bind :: Monad m => (a -> m b) -> m a -> m b
bind f x = join $ fmap f x
|
pdmurray/haskell-book-ex
|
src/ch18/Exercises181.hs
|
bsd-3-clause
| 126 | 0 | 9 | 31 | 69 | 35 | 34 | 4 | 1 |
module Module5.Task18 where
import Data.Monoid (Sum(..))
import Control.Monad.Writer (Writer, execWriter, writer)
-- system code
type Shopping = Writer (Sum Integer) ()
shopping1 :: Shopping
shopping1 = do
purchase "Jeans" 19200
purchase "Water" 180
purchase "Lettuce" 328
-- solution code
purchase :: String -> Integer -> Shopping
purchase _ cost = writer ((), Sum cost)
total :: Shopping -> Integer
total = getSum . execWriter
|
dstarcev/stepic-haskell
|
src/Module5/Task18.hs
|
bsd-3-clause
| 447 | 0 | 7 | 82 | 147 | 80 | 67 | 13 | 1 |
module Exercises.FindMissingNumbers (findMissingPair) where
findMissingPair :: [Integer] -> Maybe (Integer, Integer)
findMissingPair [] = Nothing
findMissingPair s = findMP (1, []) s
where
findMP (_, [a,b]) _ = Just (a,b)
findMP _ [] = Nothing
findMP (i, missings) (current:xs)
| i == current = findMP (nextI, missings) xs
| otherwise = if nextI == current
then findMP (succ nextI,
missings++[i]) xs
else Just (i, nextI)
where nextI = succ i
|
WarKnife/exercises
|
src/Exercises/FindMissingNumbers.hs
|
bsd-3-clause
| 629 | 0 | 12 | 257 | 213 | 115 | 98 | 13 | 4 |
{-# LANGUAGE OverloadedStrings #-}
-- | Bindings to the Docker Remote API.
-- TODO Should be Network.Docker.Remote.
module Network.Docker.Remote where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Data.Aeson (object, FromJSON(..), ToJSON(..), Value(..), (.=), (.:), (.:?))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Int (Int64)
import Network.Aeson.Client (apiGet)
getContainers :: GetContainers -> IO [Container]
getContainers query = do
mxs <- apiGet Nothing "unix:///var/run/docker.sock"
"/containers/json" params
case mxs of
Nothing -> error "Error in apiGet result, in getContainers."
Just xs -> return xs
where
-- Always include the size (that's what our Container data type
-- expects) -- I don't know if there is a serious performance cost
-- to always include it.
params = ("size", Just "true") : case query of
-- TODO Maybe it is possible to combine since/before/limit ?
RunningContainers -> []
AllContainers -> [("all", Just "true")]
LastContainers n -> [("limit", Just . B.pack $ show n)]
SinceContainer (ContainerId i) -> [("since", Just i)]
BeforeContainer (ContainerId i) -> [("before", Just i)]
newtype ContainerId = ContainerId ByteString
deriving Show
-- | Possible modifiers for the `getContainers` query.
data GetContainers =
RunningContainers
-- ^ Return running containers.
| AllContainers
-- ^ Return all containers, i.e. including non-running ones.
| LastContainers Int
-- ^ Return the n last containers, including non-running ones.
| SinceContainer ContainerId
-- ^ Return all containers created since the given ID, including
-- non-running ones.
| BeforeContainer ContainerId
-- ^ Return all containers created before the given ID, including
-- non-running ones.
-- | Result of `GET /containers/json`.
data Container = Container
{ containerId :: ContainerId
, containerImage :: String
, containerCommand :: String
, containerCreated :: Int64
, containerStatus :: String
-- , containerPorts :: String -- TODO
, containerSizeRw :: Int64
, containerSizeRootFs :: Int64
}
deriving Show
-- | Attempts to parse JSON into a Container.
instance FromJSON Container where
parseJSON (Object v) = Container
<$> (ContainerId <$> v .: "Id")
<*> v .: "Image"
<*> v .: "Command"
<*> v .: "Created"
<*> v .: "Status"
<*> v .: "SizeRw"
<*> v .: "SizeRootFs"
parseJSON _ = mzero
|
noteed/rescoyl-checks
|
Network/Docker/Remote.hs
|
bsd-3-clause
| 2,502 | 0 | 21 | 482 | 523 | 306 | 217 | 49 | 6 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Web.ISO.Murv where
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TQueue (TQueue, newTQueue, readTQueue, writeTQueue)
import Control.Monad.Trans (MonadIO(..))
import Data.Text (Text)
import Data.JSString.Text (textToJSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (asyncCallback1)
import GHCJS.Types (JSString(..))
import Web.ISO.Diff
import Web.ISO.Patch
import Web.ISO.Types
-- | Children [HTML action]
{-
flattenHTML :: HTML action -> HTML action
flattenHTML h@(CDATA _ _) = h
flattenHTML h@(Children _) = h
flattenHTML (Element t acts attrs children)
-}
{-
renderHTML :: forall action m. (MonadIO m) => (action -> IO ()) -> JSDocument -> HTML action -> m (Maybe JSNode)
renderHTML _ doc (CDATA _ t) = fmap (fmap toJSNode) $ createJSTextNode doc t
renderHTML handle doc (Element tag {- events -} attrs _ children) =
do me <- createJSElement doc tag
case me of
Nothing -> return Nothing
(Just e) ->
do mapM_ (\c -> appendJSChild e =<< renderHTML handle doc c) children
let events' = [ ev | Event ev <- attrs]
attrs' = [ (k,v) | Attr k v <- attrs]
liftIO $ mapM_ (\(k, v) -> setAttribute e k v) attrs'
liftIO $ mapM_ (handleEvent e) events'
return (Just $ toJSNode e)
where
handle' :: JSElement -> (Maybe JSString -> action) -> IO ()
handle' elem toAction =
do ms <- getValue elem
handle (toAction ms)
handleEvent :: JSElement -> (EventType, Maybe JSString -> action) -> IO ()
handleEvent elem (eventType, toAction) =
do cb <- asyncCallback AlwaysRetain (handle' elem toAction) -- FIXME: free ?
addEventListener elem eventType cb False
-}
{-
data MUV model action = MUV
{ model :: model
, update :: action -> model -> model
, view :: model -> HTML action
}
mainLoop :: JSDocument -> JSNode -> MUV model action -> IO ()
mainLoop document body (MUV model update view) =
do queue <- atomically newTQueue
html <- renderHTML (handleAction queue) document (view model)
removeChildren body
appendJSChild body html
loop queue model
where
handleAction queue = \action -> atomically $ writeTQueue queue action
loop queue model =
do action <- atomically $ readTQueue queue
let model' = update action model
html <- renderHTML (handleAction queue) document (view model')
removeChildren body
appendJSChild body html
loop queue model'
muv :: MUV model action -> IO ()
muv m =
do (Just document) <- currentDocument
(Just bodyList) <- getElementsByTagName document "body"
(Just body) <- item bodyList 0
mainLoop document body m
-}
data MURV model action remote = MURV
{ model :: model
, update :: action -> model -> (model, Maybe remote)
, view :: model -> (HTML action, [Canvas])
}
mainLoopRemote :: (Show action) => Text -> (Text -> action) -> JSDocument -> JSNode -> MURV model action Text -> Maybe action -> IO ()
mainLoopRemote url h document body (MURV model update view) mInitAction =
do queue <- atomically newTQueue
let (vdom, canvases) = view model
-- update HTML
html <- renderHTML (handleAction queue) document vdom
removeChildren body
appendChild body html
-- update Canvases
mapM_ drawCanvas canvases
-- xhr request
xhr <- newXMLHttpRequest
-- cb <- asyncCallback1 (\_ -> handleXHR queue xhr)
addEventListener xhr ReadyStateChange (\_ -> handleXHR queue xhr) False
-- remoteLoop queue xhr
case mInitAction of
(Just initAction) ->
handleAction queue initAction
Nothing -> return ()
loop xhr queue model vdom
where
handleXHR queue xhr =
do t <- getResponseText xhr
atomically $ writeTQueue queue (h t)
handleAction queue = \action -> atomically $ writeTQueue queue action
-- remoteLoop queue xhr = forkIO $
-- return ()
loop xhr queue model oldVDom =
do action <- atomically $ readTQueue queue
let (model', mremote') = update action model
let (vdom, canvases) = view model'
diffs = diff oldVDom (Just vdom)
-- putStrLn $ "action --> " ++ show action
-- putStrLn $ "diff --> " ++ show diffs
-- update HTML
apply (handleAction queue) document body oldVDom diffs
-- update Canvases
mapM_ drawCanvas canvases
-- html <- renderHTML (handleAction queue) document vdom
-- removeChildren body
-- appendJSChild body html
case mremote' of
Nothing -> return ()
(Just remote) ->
do open xhr "POST" url True
sendString xhr (textToJSString remote)
loop xhr queue model' vdom
murv :: (Show action) =>
Text -- ^ remote API URL
-> (Text -> action) -- ^ convert a remote response to an 'action'
-> MURV model action Text -- ^ model-update-remote-view record
-> (Maybe action) -- ^ initial action
-> IO ()
murv url h m initAction =
do (Just document) <- currentDocument
murv <- do mmurv <- getElementById document "murv"
case mmurv of
(Just murv) -> return (toJSNode murv)
Nothing ->
do (Just bodyList) <- getElementsByTagName document "body"
(Just body) <- item bodyList 0
return body
mainLoopRemote url h document murv m initAction
|
stepcut/isomaniac
|
Web/ISO/Murv.hs
|
bsd-3-clause
| 5,917 | 0 | 17 | 1,857 | 888 | 456 | 432 | 66 | 3 |
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, CPP #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
-- | Utilities for reading PBBS data files, etc.
-- TODO:
-- * It is probably a better strategy to shift the slices around to match number
-- boundaries than it is to deal with this whole fragments business. Try that.
module PBBS.FileReader
(
-- * PBBS specific
readAdjacencyGraph, parseAdjacencyGraph,
AdjacencyGraph(..), NodeID, nbrs,
-- * Generally useful utilities
readNumFile, parReadNats,
-- * Testing
t0,t1,t2,t3,t3B,t4,t5,
unitTests
) where
import Control.Monad (foldM, unless)
import Control.Monad.IO.Class (liftIO)
import Control.DeepSeq (NFData,rnf)
import Control.Exception (evaluate)
import Control.Concurrent (getNumCapabilities)
import Control.Monad.Par
import Control.Monad.Par.Unsafe (unsafeParIO)
import Data.Word
import Data.Char (isSpace)
import Data.Maybe (fromJust)
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as M
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Unsafe (unsafeTail, unsafeHead)
import Data.Time.Clock
import System.IO.Posix.MMap (unsafeMMapFile)
import Test.HUnit
import Prelude hiding (min,max,fst,last)
--------------------------------------------------------------------------------
-- PBBS specific:
data AdjacencyGraph =
AdjacencyGraph {
vertOffets :: U.Vector Word,
allEdges :: U.Vector Word
}
deriving (Read,Show,Eq,Ord)
nbrs :: AdjacencyGraph -> NodeID -> U.Vector NodeID
nbrs AdjacencyGraph{vertOffets, allEdges} nid =
let ind = vertOffets U.! (fromIntegral nid)
nxt = vertOffets U.! (fromIntegral (nid+1))
suff = U.drop (fromIntegral ind) allEdges in
if fromIntegral nid == U.length vertOffets - 1
then suff
else U.take (fromIntegral$ nxt-ind) suff
type NodeID = Word
-- | Read an PBBS AdjacencyGraph file into memory.
readAdjacencyGraph :: String -> IO AdjacencyGraph
readAdjacencyGraph path = do
bs <- fmap (B.dropWhile isSpace) $
unsafeMMapFile path
ncap <- getNumCapabilities
runParIO $ parseAdjacencyGraph (ncap * overPartition) bs
-- | Parse a PBBS AdjacencyGraph file from a ByteString, in parallel.
parseAdjacencyGraph :: Int -> B.ByteString -> Par AdjacencyGraph
parseAdjacencyGraph chunks bs =
case B.splitAt (B.length tag) bs of
(fst, rst) | fst /= tag -> error$ "readAdjacencyGraph: First word in file was not "++B.unpack tag
| otherwise -> do
ls <- parReadNats chunks rst
let vec = U.concat (sewEnds ls)
vec' = U.drop 2 vec
unless (U.length vec >= 2)$ error "readAdjacencyGraph: file ends prematurely."
let verts = fromIntegral$ vec U.! 0
edges = fromIntegral$ vec U.! 1
(v1,v2) = U.splitAt verts vec'
if U.length v1 == verts && U.length v2 == edges
then return (AdjacencyGraph v1 v2)
else error "readAdjacencyGraph: file doesn't contain as many entry as the header claims."
where
tag = "AdjacencyGraph"
--------------------------------------------------------------------------------
-- | How much should we partition a loop beyond what is necessary to have one task
-- per processor core.
overPartition :: Int
overPartition = 4
-- Overpartitioning definitely makes it faster... over 2X faster.
-- 8 doesn't gain anything over 4 however.. but it may reduce variance.
-- Hyperthreading shows some benefit!!
--------------------------------------------------------------------------------
#if 1
{-# INLINE readNumFile #-}
{-# INLINE parReadNats #-}
{-# INLINE readNatsPartial #-}
#else
{-# NOINLINE readNumFile #-}
{-# NOINLINE parReadNats #-}
{-# NOINLINE readNatsPartial #-}
#endif
-- | A simple front-end to 'parReadNats'. This @mmap@s the file as a byte string and
-- parses it in parallel. It returns a list of chunks of arbitrary size that may be
-- concattenated for a final result.
readNumFile :: forall nty . (U.Unbox nty, Integral nty, Eq nty, Show nty, Read nty) =>
FilePath -> IO [U.Vector nty]
readNumFile path = do
bs <- unsafeMMapFile path
ncpus <- getNumCapabilities
ls <- runParIO $ parReadNats (ncpus * overPartition) bs
return (sewEnds ls)
testReadNumFile :: forall nty . (U.Unbox nty, Integral nty, Eq nty, Show nty, Read nty) =>
FilePath -> IO [U.Vector nty]
testReadNumFile path = do
bs <- unsafeMMapFile path
ncpus <- getNumCapabilities
ls <- runParIO $ parReadNats (ncpus * overPartition) bs
consume ls
let ls' = sewEnds ls
putStrLn $ "Number of chunks after sewing: "++show (length ls')
putStrLn $ "Lengths: "++show (map U.length ls')++" sum "++ show(sum$ map U.length ls')
let flat = U.concat ls'
if (U.toList flat == map (read . B.unpack) (B.words bs))
then putStrLn "Sewed version matched expected!!"
else error "Did not match expected!"
return ls'
-- | Read all the decimal numbers from a Bytestring. They must be positive integers.
-- Be warned that this function is very permissive -- all non-digit characters are
-- treated as separators.
parReadNats :: forall nty f . (U.Unbox nty, Num nty, Eq nty) =>
Int -> S.ByteString -> Par [PartialNums nty]
parReadNats chunks bs = par
where
(each,left) = S.length bs `quotRem` chunks
mapper ind = do
let howmany = each + if ind==chunks-1 then left else 0
mychunk = S.take howmany $ S.drop (ind * each) bs
-- liftIO $ putStrLn$ "(monad-par/tree) Launching chunk of "++show howmany
partial <- unsafeParIO (readNatsPartial mychunk) -- TODO: move to ST.
return [partial]
reducer a b = return (a++b) -- Quadratic, but just at the chunk level.
par :: Par [PartialNums nty]
par = do _ <- new
parMapReduceRangeThresh 1 (InclusiveRange 0 (chunks - 1))
mapper reducer []
--------------------------------------------------------------------------------
-- Partially parsed number fragments
--------------------------------------------------------------------------------
-- | A sequence of parsed numbers with ragged edges.
data PartialNums n = Compound !(Maybe (RightFrag n)) ![U.Vector n] !(Maybe (LeftFrag n))
| Single !(MiddleFrag n)
deriving (Show,Eq,Ord,Read)
-- | This represents the rightmost portion of a decimal number that was interrupted
-- in the middle.
data RightFrag n = RightFrag {
numDigits :: {-# UNPACK #-} !Int,
partialParse :: !n
-- ^ The partialParse will need to be combined with the other half
-- through addition (shifting first if it represents a left-half).
}
deriving (Show,Eq,Ord,Read)
data LeftFrag n = LeftFrag !n
deriving (Show,Eq,Ord,Read)
-- | A fragment from the middle of a number, (potentially) missing pieces on both ends.
data MiddleFrag n = MiddleFrag {-# UNPACK #-} !Int !n
deriving (Show,Eq,Ord,Read)
instance NFData (RightFrag n) where
rnf (RightFrag _ _) = ()
instance NFData (LeftFrag n) where
rnf (LeftFrag _) = ()
instance NFData (MiddleFrag n) where
rnf (MiddleFrag _ _) = ()
instance NFData (PartialNums n) where
rnf (Compound a b c) = a `seq` b `seq` c `seq` ()
rnf (Single a) = rnf a
{-# INLINE sewEnds #-}
-- Sew up a list of ragged-edged fragments into a list of normal vector chunks.
sewEnds :: forall nty . (U.Unbox nty, Integral nty, Eq nty) => [PartialNums nty] -> [U.Vector nty]
sewEnds [] = []
sewEnds origls = loop Nothing origls
where
loop _mleft [] = error "Internal error."
loop mleft [last] =
case last of
Single _ -> error "sewEnds: Got a MiddleFrag at the END!"
Compound _ _ (Just _) -> error "sewEnds: Got a LeftFrag at the END!"
Compound rf ls Nothing -> sew mleft rf ls
loop mleft (Compound rf ls lf : rst) =
sew mleft rf ls ++ loop lf rst
-- TODO: Test this properly... doesn't occur in most files:
loop mleft (Single (MiddleFrag nd m) : rst) =
case mleft of
Nothing -> loop (Just (LeftFrag m)) rst
Just (LeftFrag n) -> loop (Just (LeftFrag (shiftCombine n m nd))) rst
sew mleft rf ls =
case (mleft, rf) of
(Just (LeftFrag n), Just (RightFrag nd m)) -> let num = shiftCombine n m nd in
U.singleton num : ls
(Just (LeftFrag n), Nothing) -> U.singleton n : ls
(Nothing, Just (RightFrag _ m)) -> U.singleton m : ls
(Nothing, Nothing) -> ls
shiftCombine n m nd = n * (10 ^ (fromIntegral nd :: nty)) + m
--------------------------------------------------------------------------------
-- Efficient sequential parsing
--------------------------------------------------------------------------------
-- {-# SPECIALIZE readNatsPartial :: S.ByteString -> IO [PartialNums Word] #-}
-- {-# SPECIALIZE readNatsPartial :: S.ByteString -> IO [PartialNums Word8] #-}
-- {-# SPECIALIZE readNatsPartial :: S.ByteString -> IO [PartialNums Word16] #-}
-- {-# SPECIALIZE readNatsPartial :: S.ByteString -> IO [PartialNums Word32] #-}
-- {-# SPECIALIZE readNatsPartial :: S.ByteString -> IO [PartialNums Word64] #-}
-- {-# SPECIALIZE readNatsPartial :: S.ByteString -> IO [PartialNums Int] #-}
-- | Sequentially reads all the unsigned decimal (ASCII) numbers within a a
-- bytestring, which is typically a slice of a larger bytestring. Extra complexity
-- is needed to deal with the cases where numbers are cut off at the boundaries.
-- readNatsPartial :: S.ByteString -> IO [PartialNums Word]
readNatsPartial :: forall nty . (U.Unbox nty, Num nty, Eq nty) => S.ByteString -> IO (PartialNums nty)
readNatsPartial bs
| bs == S.empty = return (Single (MiddleFrag 0 0))
| otherwise = do
let hd = S.head bs
charsTotal = S.length bs
initV <- M.new (vecSize charsTotal)
(vs,lfrg) <- scanfwd charsTotal 0 initV [] hd (S.tail bs)
-- putStrLn$ " Got back "++show(length vs)++" partial reads"
-- Once we are done looping we need some logic to figure out the corner cases:
----------------------------------------
let total = sum $ map U.length vs
if digit hd then
(let first = U.head $ head vs -- The first (possibly partial) number parsed.
rest = U.tail (head vs) : tail vs
-- If we start in the middle of a number, then the RightFrag goes till the first whitespace:
rfrag = Just (RightFrag (fromJust$ S.findIndex (not . digit) bs) first) in
if total == 0
then case lfrg of
Nothing -> return (Compound rfrag [] Nothing)
Just (LeftFrag w) -> return (Single$ MiddleFrag charsTotal w)
else return (Compound rfrag rest lfrg)) -- Rfrag gobbles first.
else return (Compound Nothing vs lfrg) -- May be completely empty (whitespace only).
----------------------------------------
where
-- Given the number of characters left, how big of a vector chunk shall we allocate?
-- vecSize n = min chunkSize ((n `quot` 2) + 1) -- At minimum numbers must be one character.
vecSize n = ((n `quot` 4) + 1) -- Assume at least 3 digit numbers... tunable parameter.
-- loop :: Int -> Int -> nty -> M.IOVector nty -> Word8 -> S.ByteString ->
-- IO (M.IOVector nty, Maybe (LeftFrag nty), Int)
loop !lmt !ind !acc !vec !vecacc !nxt !rst
-- Extend the currently accumulating number in 'acc':
| digit nxt =
let acc' = (10*acc + (fromIntegral nxt-48)) in
if lmt == 1
then closeOff vec vecacc ind (Just (LeftFrag acc'))
else loop (lmt-1) ind acc' vec vecacc (unsafeHead rst) (unsafeTail rst)
-- When we fill one chunk we move to the next:
| ind >= M.length vec = do
-- putStrLn$ " [!] Overflow at "++show ind++", next chunk!"
-- putStr$ show ind ++ " "
fresh <- M.new (vecSize$ S.length rst) :: IO (M.IOVector nty)
vec' <- U.unsafeFreeze vec
loop lmt 0 acc fresh (vec':vecacc) nxt rst
| otherwise =
do M.write vec ind acc
if lmt == 1
then closeOff vec vecacc (ind+1) Nothing
else scanfwd (lmt-1) (ind+1) vec vecacc (unsafeHead rst) (unsafeTail rst)
scanfwd !lmt !ind !vec !vecacc !nxt !rst
| digit nxt = loop lmt ind 0 vec vecacc nxt rst -- We've started a number.
| otherwise = if lmt == 1
then closeOff vec vecacc ind Nothing
else scanfwd (lmt-1) ind vec vecacc (unsafeHead rst) (unsafeTail rst)
digit nxt = nxt >= 48 && nxt <= 57
closeOff vec vecacc ind frag =
do vec' <- U.unsafeFreeze (M.take ind vec)
return (reverse (vec':vecacc), frag)
--------------------------------------------------------------------------------
-- Unit Tests
--------------------------------------------------------------------------------
unitTests :: [Test]
unitTests =
[ TestCase$ assertEqual "t1" (Compound (Just (RightFrag 3 (123::Word))) [U.fromList []] Nothing) =<<
readNatsPartial (S.take 4 "123 4")
, TestCase$ assertEqual "t1" (Compound (Just (RightFrag 3 (123::Word))) [U.fromList []] (Just (LeftFrag 4))) =<<
readNatsPartial (S.take 5 "123 4")
, TestCase$ assertEqual "t3" (Single (MiddleFrag 3 (123::Word))) =<<
readNatsPartial (S.take 3 "123")
, TestCase$ assertEqual "t4" (Single (MiddleFrag 2 (12::Word))) =<<
readNatsPartial (S.take 2 "123")
, TestCase$ assertEqual "t5" (Compound Nothing [] (Just (LeftFrag (12::Word32)))) =<<
readNatsPartial (S.take 3 " 123")
, TestCase$ assertEqual "t6"
(Compound (Just (RightFrag 3 23)) [U.fromList [456]] (Just (LeftFrag (78::Word64)))) =<<
readNatsPartial (S.take 10 "023 456 789")
]
---------------------------
-- Bigger, temporary tests:
---------------------------
t0 :: IO [U.Vector Word]
-- t0 = testReadNumFile "/tmp/grid_1000"
-- t0 = testReadNumFile "../../pbbs/breadthFirstSearch/graphData/data/3Dgrid_J_1000"
t0 = testReadNumFile "1000_nums"
t1 :: IO [U.Vector Word]
-- t1 = testReadNumFile "/tmp/grid_125000"
t1 = testReadNumFile "../../pbbs/breadthFirstSearch/graphData/data/3Dgrid_J_125000"
t2 :: IO ()
t2 = do t0_ <- getCurrentTime
ls <- readNumFile "../../pbbs/breadthFirstSearch/graphData/data/3Dgrid_J_10000000"
t1_ <- getCurrentTime
let v :: U.Vector Word
v = U.concat ls
putStrLn$ "Resulting vector has length: "++show (U.length v)
t2_ <- getCurrentTime
putStrLn$ "Time parsing/reading "++show (diffUTCTime t1_ t0_)++
" and coalescing "++show(diffUTCTime t2_ t1_)
-- This one is fast... but WHY? It should be the same as the hacked 1-chunk parallel versions.
t3 :: IO [PartialNums Word]
t3 = do bs <- unsafeMMapFile "../../pbbs/breadthFirstSearch/graphData/data/3Dgrid_J_10000000"
pn <- readNatsPartial bs
consume [pn]
return [pn]
-- | Try it with readFile...
t3B :: IO [PartialNums Word]
t3B = do putStrLn "Sequential version + readFile"
t0_ <- getCurrentTime
bs <- S.readFile "../../pbbs/breadthFirstSearch/graphData/data/3Dgrid_J_10000000"
t1_ <- getCurrentTime
putStrLn$ "Time to read file sequentially: "++show (diffUTCTime t1_ t0_)
pn <- readNatsPartial bs
consume [pn]
return [pn]
t4 :: IO [PartialNums Word]
t4 = do putStrLn$ "Using parReadNats + readFile"
t0_ <- getCurrentTime
bs <- S.readFile "../../pbbs/breadthFirstSearch/graphData/data/3Dgrid_J_10000000"
t1_ <- getCurrentTime
putStrLn$ "Time to read file sequentially: "++show (diffUTCTime t1_ t0_)
pns <- runParIO $ parReadNats 4 bs
consume pns
return pns
t5 :: IO ()
t5 = do t0_ <- getCurrentTime
AdjacencyGraph v1 v2 <- readAdjacencyGraph "../../pbbs/breadthFirstSearch/graphData/data/3Dgrid_J_10000000"
t1_ <- getCurrentTime
putStrLn$ "Read adjacency graph in: "++show (diffUTCTime t1_ t0_)
putStrLn$ " Edges and Verts: "++show (U.length v1, U.length v2)
return ()
-- Make sure everything is forced
consume :: (Show n, M.Unbox n) => [PartialNums n] -> IO ()
consume ox = do
evaluate (rnf ox)
putStrLn$ "Result: "++show (length ox)++" segments of output"
mapM_ fn ox
where
fn (Single (MiddleFrag c x)) = putStrLn$ " <middle frag "++ show (c,x)++">"
fn (Compound r uvs l) = putStrLn$ " <segment, lengths "++show (map U.length uvs)++", ends "++show(r,l)++">"
|
adk9/pbbs-haskell
|
PBBS/FileReader.hs
|
bsd-3-clause
| 16,918 | 0 | 21 | 4,091 | 4,428 | 2,253 | 2,175 | 274 | 10 |
{-# LANGUAGE OverloadedStrings #-}
module Buildsome.Print
( posText ) where
import Data.String (IsString(..))
import Text.Parsec (SourcePos)
posText :: (Monoid s, IsString s) => SourcePos -> s
posText _ = ""
|
da-x/buildsome-tst
|
app/Buildsome/Print.hs
|
bsd-3-clause
| 242 | 0 | 6 | 64 | 68 | 40 | 28 | 7 | 1 |
{-# LANGUAGE PackageImports #-}
module System.Exit (module M) where
import "base" System.Exit as M
|
silkapp/base-noprelude
|
src/System/Exit.hs
|
bsd-3-clause
| 104 | 0 | 4 | 18 | 21 | 15 | 6 | 3 | 0 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.ShaderBufferLoad
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.ShaderBufferLoad (
-- * Extension Support
glGetNVShaderBufferLoad,
gl_NV_shader_buffer_load,
-- * Enums
pattern GL_BUFFER_GPU_ADDRESS_NV,
pattern GL_GPU_ADDRESS_NV,
pattern GL_MAX_SHADER_BUFFER_ADDRESS_NV,
-- * Functions
glGetBufferParameterui64vNV,
glGetIntegerui64vNV,
glGetNamedBufferParameterui64vNV,
glGetUniformui64vNV,
glIsBufferResidentNV,
glIsNamedBufferResidentNV,
glMakeBufferNonResidentNV,
glMakeBufferResidentNV,
glMakeNamedBufferNonResidentNV,
glMakeNamedBufferResidentNV,
glProgramUniformui64NV,
glProgramUniformui64vNV,
glUniformui64NV,
glUniformui64vNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/NV/ShaderBufferLoad.hs
|
bsd-3-clause
| 1,160 | 0 | 5 | 148 | 106 | 75 | 31 | 24 | 0 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoRebindableSyntax #-}
module Duckling.Numeral.Rules
( rules
) where
import Prelude
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Regex.Types
import Duckling.Types
ruleIntegerNumeric :: Rule
ruleIntegerNumeric = Rule
{ name = "integer (numeric)"
, pattern =
[ regex "(\\d{1,18})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
toInteger <$> parseInt match >>= integer
_ -> Nothing
}
ruleFractions :: Rule
ruleFractions = Rule
{ name = "fractional number"
, pattern =
[ regex "(\\d+)/(\\d+)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (numerator:denominator:_)):_) -> do
n <- parseDecimal False numerator
d <- parseDecimal False denominator
divide n d >>= notOkForAnyTime
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleIntegerNumeric
, ruleFractions
]
|
facebookincubator/duckling
|
Duckling/Numeral/Rules.hs
|
bsd-3-clause
| 1,227 | 0 | 18 | 271 | 280 | 159 | 121 | 34 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | This module provides convenience functions for interfacing @io-streams@
-- with @HsOpenSSL@. It is intended to be imported @qualified@, e.g.:
--
-- @
-- import qualified "OpenSSL" as SSL
-- import qualified "OpenSSL.Session" as SSL
-- import qualified "System.IO.Streams.SSL" as SSLStreams
--
-- \ example :: IO ('InputStream' 'ByteString', 'OutputStream' 'ByteString')
-- example = SSL.'SSL.withOpenSSL' $ do
-- ctx <- SSL.'SSL.context'
-- SSL.'SSL.contextSetDefaultCiphers' ctx
--
-- \ \-\- Note: the location of the system certificates is system-dependent,
-- \-\- on Linux systems this is usually \"\/etc\/ssl\/certs\". This
-- \-\- step is optional if you choose to disable certificate verification
-- \-\- (not recommended!).
-- SSL.'SSL.contextSetCADirectory' ctx \"\/etc\/ssl\/certs\"
-- SSL.'SSL.contextSetVerificationMode' ctx $
-- SSL.'SSL.VerifyPeer' True True Nothing
-- SSLStreams.'connect' ctx "foo.com" 4444
-- @
--
module System.IO.Streams.SSL
( connect
, withConnection
, sslToStreams
) where
import qualified Control.Exception as E
import Control.Monad (void)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Network.Socket (HostName, PortNumber)
import qualified Network.Socket as N
import OpenSSL.Session (SSL, SSLContext)
import qualified OpenSSL.Session as SSL
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as Streams
------------------------------------------------------------------------------
bUFSIZ :: Int
bUFSIZ = 32752
------------------------------------------------------------------------------
-- | Given an existing HsOpenSSL 'SSL' connection, produces an 'InputStream' \/
-- 'OutputStream' pair.
sslToStreams :: SSL -- ^ SSL connection object
-> IO (InputStream ByteString, OutputStream ByteString)
sslToStreams ssl = do
is <- Streams.makeInputStream input
os <- Streams.makeOutputStream output
return $! (is, os)
where
input = do
s <- SSL.read ssl bUFSIZ
return $! if S.null s then Nothing else Just s
output Nothing = return $! ()
output (Just s) = SSL.write ssl s
------------------------------------------------------------------------------
-- | Convenience function for initiating an SSL connection to the given
-- @('HostName', 'PortNumber')@ combination.
--
-- Note that sending an end-of-file to the returned 'OutputStream' will not
-- close the underlying SSL connection; to do that, call:
--
-- @
-- SSL.'SSL.shutdown' ssl SSL.'SSL.Unidirectional'
-- maybe (return ()) 'N.close' $ SSL.'SSL.sslSocket' ssl
-- @
--
-- on the returned 'SSL' object.
connect :: SSLContext -- ^ SSL context. See the @HsOpenSSL@
-- documentation for information on creating
-- this.
-> HostName -- ^ hostname to connect to
-> PortNumber -- ^ port number to connect to
-> IO (InputStream ByteString, OutputStream ByteString, SSL)
connect ctx host port = do
-- Partial function here OK, network will throw an exception rather than
-- return the empty list here.
(addrInfo:_) <- N.getAddrInfo (Just hints) (Just host) (Just $ show port)
let family = N.addrFamily addrInfo
let socketType = N.addrSocketType addrInfo
let protocol = N.addrProtocol addrInfo
let address = N.addrAddress addrInfo
E.bracketOnError (N.socket family socketType protocol)
N.close
(\sock -> do N.connect sock address
ssl <- SSL.connection ctx sock
SSL.connect ssl
(is, os) <- sslToStreams ssl
return $! (is, os, ssl)
)
where
hints = N.defaultHints {
N.addrFlags = [N.AI_NUMERICSERV]
, N.addrSocketType = N.Stream
}
------------------------------------------------------------------------------
-- | Convenience function for initiating an SSL connection to the given
-- @('HostName', 'PortNumber')@ combination. The socket and SSL connection are
-- closed and deleted after the user handler runs.
--
-- /Since: 1.2.0.0./
withConnection ::
SSLContext -- ^ SSL context. See the @HsOpenSSL@
-- documentation for information on creating
-- this.
-> HostName -- ^ hostname to connect to
-> PortNumber -- ^ port number to connect to
-> (InputStream ByteString -> OutputStream ByteString -> SSL -> IO a)
-- ^ Action to run with the new connection
-> IO a
withConnection ctx host port action = do
(addrInfo:_) <- N.getAddrInfo (Just hints) (Just host) (Just $ show port)
E.bracket (connectTo addrInfo) cleanup go
where
go (is, os, ssl, _) = action is os ssl
connectTo addrInfo = do
let family = N.addrFamily addrInfo
let socketType = N.addrSocketType addrInfo
let protocol = N.addrProtocol addrInfo
let address = N.addrAddress addrInfo
E.bracketOnError (N.socket family socketType protocol)
N.close
(\sock -> do N.connect sock address
ssl <- SSL.connection ctx sock
SSL.connect ssl
(is, os) <- sslToStreams ssl
return $! (is, os, ssl, sock))
cleanup (_, os, ssl, sock) = E.mask_ $ do
eatException $! Streams.write Nothing os
eatException $! SSL.shutdown ssl $! SSL.Unidirectional
eatException $! N.close sock
hints = N.defaultHints {
N.addrFlags = [N.AI_NUMERICSERV]
, N.addrSocketType = N.Stream
}
eatException m = void m `E.catch` (\(_::E.SomeException) -> return $! ())
|
snapframework/openssl-streams
|
src/System/IO/Streams/SSL.hs
|
bsd-3-clause
| 6,187 | 0 | 16 | 1,801 | 1,084 | 587 | 497 | 78 | 3 |
module Snap.Snaplet.Environments
( module Data.Configurator
, lookupConfig
, lookupConfigDefault
, lookupEnv
, lookupEnvDefault
, module Snap.Snaplet.Environments.Instances )
where
import Control.Monad.Reader
import Data.Maybe (fromMaybe)
import Data.Configurator
import Data.Configurator.Types
import qualified Data.HashMap.Lazy as HM
import Data.List (find)
import qualified Data.Text as T
import Snap.Snaplet
import Snap.Snaplet.Environments.Instances
import System.Environment (getArgs)
import Text.Regex.TDFA
-----------------------------------------------------------
--
lookupConfig :: (MonadIO (m b v), MonadSnaplet m, Configured a) => Name -> m b v (Maybe a)
lookupConfig name = do
config <- getSnapletUserConfig
liftIO $ Data.Configurator.lookup config name
lookupConfigDefault :: (MonadIO (m b v), MonadSnaplet m, Configured a)
=> Name -- ^ Key
-> a -- ^ default value
-> m b v a
lookupConfigDefault name def = liftM (fromMaybe def) (lookupConfig name)
-----------------------------------------------------------
-- Look up value under environments sub group.
-- | Look up a given name without default value.
--
lookupEnv :: (Configured a, Monad (m b v), MonadSnaplet m, MonadIO (m b v)) => Name -> m b v (Maybe a)
lookupEnv name = do
mainConf <- getSnapletUserConfig
subName <- getNameForCurEnv name mainConf
liftIO $ Data.Configurator.lookup mainConf subName
-- | This function takes current env subconfig and at its base
-- looks up given name
--
lookupEnvDefault :: (Configured a, Monad (m b v), MonadSnaplet m, MonadIO (m b v)) => Name -> a -> m b v a
lookupEnvDefault name def = liftM (fromMaybe def) (lookupEnv name)
-----------------------------------------------------------
getNameForCurEnv :: (Monad (m b v), MonadSnaplet m, MonadIO (m b v)) => Name -> Config -> m b v Name
getNameForCurEnv name cfg = do
env <- getCurrentEnv cfg
return $ T.pack $ "app.environments." ++ env ++ "." ++ (T.unpack name)
getCurrentEnv :: (Monad (m b v), MonadSnaplet m, MonadIO (m b v)) => Config -> m b v String
getCurrentEnv cfg = do
mopt <- return . find (\a -> take 1 a == "@") =<< liftIO getArgs
case mopt of
Nothing -> do
hm <- liftIO $ getMap cfg
case filter (\k -> (T.unpack k) =~ ("app.environments." :: String)) $ HM.keys hm of
[] -> error "You have to put at least one env definition in your config file."
(x:_) -> return $ T.unpack $ (T.split (== '.') x) !! 2
Just opt -> do
hm <- liftIO $ getMap cfg
case length (filter (\k -> (T.unpack k) =~ ("app.environments." ++ (tail opt))) $ HM.keys hm) > 0 of
True -> return $ tail opt
False -> error $ "Given env name: " ++ opt ++ " wasn't found in your config file."
|
kamilc/Snaplet-Environments
|
src/Snap/Snaplet/Environments.hs
|
bsd-3-clause
| 3,002 | 0 | 24 | 789 | 932 | 486 | 446 | 52 | 4 |
{-
- Claq (c) 2013 NEC Laboratories America, Inc. All rights reserved.
-
- This file is part of Claq.
- Claq is distributed under the 3-clause BSD license.
- See the LICENSE file for more details.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Compile (prepareExprCoherent, prepareExprNoncoherent) where
import Data.Functor ((<$>))
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Traversable (traverse)
import Control.Monad.Quantum.Class
import Data.Quantum.Wire
import Data.ClassicalCircuit
import qualified Data.DAG as DAG
import Data.ExitF
prepareExprGraph :: MonadQuantum Wire m => ClaCircuit (Bit Wire) -> m (Seq (Bit Wire))
prepareExprGraph (ClaCircuit g) =
DAG.foldMapDAGM (exitF return prepareNode) g
where
prepareNode (GConst c) = return $ BitConst c
prepareNode (GNot b1) = return $ negateBit b1
prepareNode (GAnd (BitConst False) _) = return $ BitConst False
prepareNode (GAnd (BitConst True) b2) = return b2
prepareNode (GAnd _ (BitConst False)) = return $ BitConst False
prepareNode (GAnd b1 (BitConst True)) = return b1
prepareNode (GAnd b1@(BitWire inv1 w1) b2@(BitWire inv2 w2))
| w1 == w2 && inv1 == inv2 =
return b1
| w1 == w2 && inv1 /= inv2 =
return $ BitConst False
| otherwise = do
w <- ancilla
destructiveToffoli w b1 b2
return $ bit w
prepareNode (GOr b1 b2) = negateBit <$> prepareNode (GAnd (negateBit b1) (negateBit b2))
prepareNode (GXor (BitConst False) b2) = return b2
prepareNode (GXor (BitConst True) b2) = return $ negateBit b2
prepareNode (GXor b1 (BitConst False)) = return b1
prepareNode (GXor b1 (BitConst True)) = return $ negateBit b1
prepareNode (GXor b1@(BitWire inv1 w1) b2@(BitWire inv2 w2))
| w1 == w2 =
return $ BitConst $ inv1 /= inv2
| otherwise = do
w <- ancilla
control b1 $ applyX w
control b2 $ applyX w
return $ bit w
prepareExprCoherent :: MonadQuantum Wire m => ClaCircuit (Bit Wire) -> Seq Int -> m (Seq Wire)
prepareExprCoherent g vs =
with (prepareExprGraph g) $ \ws ->
traverse (prepareCopy ws) vs
prepareExprNoncoherent :: MonadQuantum Wire m => ClaCircuit (Bit Wire) -> Seq Int -> m (Seq Wire)
prepareExprNoncoherent g vs = do
ws <- prepareExprGraph g
traverse (prepareCopy ws) vs
prepareCopy :: MonadQuantum w m => Seq (Bit w) -> Int -> m w
prepareCopy ws v = do
w <- ancilla
cnotWire w (Seq.index ws v)
return w
|
ti1024/claq
|
src/Compile.hs
|
bsd-3-clause
| 2,573 | 0 | 12 | 613 | 929 | 454 | 475 | 56 | 13 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Test.Unit where
import Prelude (($), (.))
import Data.Foldable (mapM_)
import Data.Text hiding (toTitle)
import Data.Text.Titlecase
import Data.Text.Titlecase.Internal hiding (articles, conjunctions, prepositions)
import qualified Data.Text.Titlecase.Internal as Titlecase
import Test.Tasty
import Test.Tasty.HUnit
tests :: TestTree
tests = testGroup "Unit tests" [articles, conjunctions, prepositions]
articles :: TestTree
articles = testGroup "Articles" [articleFirst, articleLast, articleIgnored]
conjunctions :: TestTree
conjunctions = testGroup "Conjunctions" [conjunctionFirst, conjunctionLast, conjunctionIgnored]
prepositions :: TestTree
prepositions = testGroup "Prepositions" [prepositionFirst, prepositionLast, prepositionIgnored]
testTitlecase, testFirst, testLast, testIgnored :: Text -> Assertion
testTitlecase t = titlecase (toLower t) @?= Titlecase t
toTitleFirst :: Text -> Text
toTitleFirst t = unwords $ case words t of
[] -> []
(x:xs) -> toTitle x : xs
toTitleLast :: Text -> Text
toTitleLast t = unwords $ go $ words t
where
go [] = []
go [x] = [toTitle x]
go (x:xs) = x : go xs
testFirst t = testTitlecase $ toTitleFirst t <#> "Is First, so It Is Capitalized"
testLast t = testTitlecase $ "This Sentence Capitalizes" <#> toTitleLast t
testIgnored t = testTitlecase $ "This Sentence Keeps" <#> t <#> "As Is"
articleFirst, articleLast, articleIgnored :: TestTree
articleFirst = testCase "article is first" $ mapM_ (testFirst . unArticle) Titlecase.articles
articleLast = testCase "article is last" $ mapM_ (testLast . unArticle) Titlecase.articles
articleIgnored = testCase "article is ignored" $ mapM_ (testIgnored . unArticle) Titlecase.articles
conjunctionFirst, conjunctionLast, conjunctionIgnored :: TestTree
conjunctionFirst = testCase "conjunction is first" $ mapM_ (testFirst . unConjunction) Titlecase.conjunctions
conjunctionLast = testCase "conjunction is last" $ mapM_ (testLast . unConjunction) Titlecase.conjunctions
conjunctionIgnored = testCase "conjunction is ignored" $ mapM_ (testIgnored . unConjunction) Titlecase.conjunctions
prepositionFirst, prepositionLast, prepositionIgnored :: TestTree
prepositionFirst = testCase "preposition is first" $ mapM_ (testFirst . unPreposition) Titlecase.prepositions
prepositionLast = testCase "preposition is last" $ mapM_ (testLast . unPreposition) Titlecase.prepositions
prepositionIgnored = testCase "preposition is ignored" $ mapM_ (testIgnored . unPreposition) Titlecase.prepositions
|
nkaretnikov/titlecase
|
tests/Test/Unit.hs
|
bsd-3-clause
| 2,760 | 0 | 10 | 529 | 683 | 376 | 307 | 45 | 3 |
{-# LANGUAGE TemplateHaskell #-}
module NotCPP.Utils where
import Control.Applicative ((<$>))
import Language.Haskell.TH
-- | Turns 'Nothing' into an expression representing 'Nothing', and
-- @'Just' x@ into an expression representing 'Just' applied to the
-- expression in @x@.
liftMaybe :: Maybe Exp -> Exp
liftMaybe = maybe (ConE 'Nothing) (AppE (ConE 'Just))
-- | A useful variant of 'reify' that returns 'Nothing' instead of
-- halting compilation when an error occurs (e.g. because the given
-- name was not in scope).
maybeReify :: Name -> Q (Maybe Info)
maybeReify = recoverMaybe . reify
-- | Turns a possibly-failing 'Q' action into one returning a 'Maybe'
-- value.
recoverMaybe :: Q a -> Q (Maybe a)
recoverMaybe q = recover (return Nothing) (Just <$> q)
-- | Returns @'Just' ('VarE' n)@ if the info relates to a value called
-- @n@, or 'Nothing' if it relates to a different sort of thing.
infoToExp :: Info -> Maybe Exp
infoToExp (VarI n _ _ _) = Just (VarE n)
infoToExp (DataConI n _ _ _) = Just (ConE n)
infoToExp _ = Nothing
|
bmillwood/notcpp
|
NotCPP/Utils.hs
|
bsd-3-clause
| 1,046 | 0 | 9 | 185 | 229 | 124 | 105 | 14 | 1 |
import Data.STM.LinkedList (LinkedList)
import qualified Data.STM.LinkedList as LinkedList
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import Control.Monad (forM_, forever)
import Foreign.Marshal.Error (void)
type Event = String
type EventHandler = (Event -> IO ())
withEventHandler :: LinkedList EventHandler
-> EventHandler
-> IO a
-> IO a
withEventHandler list handler action =
bracket (atomically $ LinkedList.append handler list)
(atomically . LinkedList.delete)
(\_ -> action)
dispatchEvent :: LinkedList EventHandler
-> Event
-> IO ()
dispatchEvent list event = do
handlers <- atomically $ LinkedList.toList list
forM_ handlers $ \handler -> handler event
main :: IO ()
main = do
list <- LinkedList.emptyIO
let testThread listeningFor = void $ forkIO $ do
eventReceived <- atomically $ newTVar False
let handler ev = do
putStrLn $ listeningFor ++ ": Received " ++ ev
if ev == listeningFor
then atomically $ writeTVar eventReceived True
else return ()
withEventHandler list handler $ do
atomically $ do
r <- readTVar eventReceived
if r
then return ()
else retry
putStrLn $ listeningFor ++ ": Caught my event; leaving now"
testThread "brown"
testThread "chicken"
testThread "brown"
testThread "cow"
forever $ do
line <- getLine
dispatchEvent list line
|
joeyadams/haskell-stm-linkedlist
|
testing/event-handler.hs
|
bsd-3-clause
| 1,705 | 0 | 21 | 597 | 442 | 216 | 226 | 47 | 3 |
module Lucid.Foundation.Typography
( module Lucid.Foundation.Typography.Types
, module Lucid.Foundation.Typography.InlineList
, module Lucid.Foundation.Typography.Labels
) where
import Lucid.Foundation.Typography.Types
import Lucid.Foundation.Typography.InlineList
import Lucid.Foundation.Typography.Labels
|
athanclark/lucid-foundation
|
src/Lucid/Foundation/Typography.hs
|
bsd-3-clause
| 316 | 0 | 5 | 28 | 54 | 39 | 15 | 7 | 0 |
module Database.Hitcask(
get
, put
, delete
, Hitcask()
, connect
, connectWith
, close
, compact
, listKeys
, standardSettings
) where
import Control.Concurrent.STM
import System.IO
import System.Directory
import Database.Hitcask.Types
import Database.Hitcask.Restore
import Database.Hitcask.Get
import Database.Hitcask.Put
import Database.Hitcask.Delete
import Database.Hitcask.Compact
import Database.Hitcask.Logs
import Database.Hitcask.ListKeys
import qualified Data.HashMap.Strict as M
standardSettings :: HitcaskSettings
standardSettings = HitcaskSettings (2 * 1073741824)
connect :: FilePath -> IO Hitcask
connect dir = connectWith dir standardSettings
connectWith :: FilePath -> HitcaskSettings -> IO Hitcask
connectWith dir options = do
createDirectoryIfMissing True dir
m <- restoreFromLogDir dir
ls <- openLogFiles dir
h@(LogFile _ p) <- getOrCreateCurrent dir ls
let allLogs = if M.null ls then M.fromList [(p, h)] else ls
t <- newTVarIO $! m
l <- newTVarIO $! HitcaskLogs h allLogs
return $! Hitcask t l dir options
getOrCreateCurrent :: FilePath -> M.HashMap FilePath LogFile -> IO LogFile
getOrCreateCurrent dir ls
| M.null ls = createNewLog dir
| otherwise = return $! head (M.elems ls)
close :: Hitcask -> IO ()
close h = do
ls <- readTVarIO $ logs h
mapM_ (hClose . handle) $ M.elems (files ls)
|
tcrayford/hitcask
|
Database/Hitcask.hs
|
bsd-3-clause
| 1,366 | 0 | 13 | 236 | 450 | 234 | 216 | 47 | 2 |
module Internal.BitOps
(
fixedXOR
, repeatingKeyXOR
, hamming
) where
import qualified Data.ByteString as BS
import Data.Bits
import Internal.Uncons
import Data.Monoid
import Data.Word
import Debug.Trace
fixedXOR :: BS.ByteString -> BS.ByteString -> Maybe BS.ByteString
fixedXOR bs1 bs2
| BS.length bs1 /= BS.length bs2 = Nothing
| otherwise = Just . BS.pack $ BS.zipWith xor bs1 bs2
repeatingKeyXOR :: BS.ByteString -> BS.ByteString -> BS.ByteString
repeatingKeyXOR k bs =
let repeatingKey = cycle $ BS.unpack k
unpackedBS = BS.unpack bs
in
BS.pack $ zipWith xor repeatingKey unpackedBS
hamming :: BS.ByteString -> BS.ByteString -> Int
hamming bs1 bs2 =
sum $ zipWith ((.) popCount . xor) (BS.unpack bs1) (BS.unpack bs2)
|
caneroj1/Crypto-hs
|
src/Internal/BitOps.hs
|
bsd-3-clause
| 775 | 0 | 11 | 159 | 268 | 138 | 130 | 23 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.YAML.Snap (handleApi, handleApiPost) where
import qualified Data.ByteString as B
import qualified Data.Text.Encoding as TE
import Network.YAML
import qualified Data.Aeson as Json
import Snap
errorMsg :: Int -> B.ByteString -> Snap ()
errorMsg status msg = do
modifyResponse $ setResponseStatus status msg
writeBS msg
finishWith =<< getResponse
-- | Snap handler for POST method
handleApiPost :: Dispatcher IO -> Snap ()
handleApiPost dispatcher = method POST $ handleApi dispatcher
-- | Snap handler for any method
handleApi :: Dispatcher IO -> Snap ()
handleApi dispatcher = do
maybeMethod <- getParam "method"
case maybeMethod of
Nothing -> errorMsg 400 "No method name specified"
Just methodName -> case dispatcher (TE.decodeUtf8 methodName) of
Nothing -> errorMsg 404 "No such method"
Just method -> do
body <- readRequestBody 16384
case Json.decode body of
Nothing -> errorMsg 400 "Invalid JSON in request"
Just json -> do
result <- liftIO $ method json
writeLBS $ Json.encode result
|
portnov/yaml-rpc
|
yaml-rpc-snap/Network/YAML/Snap.hs
|
bsd-3-clause
| 1,280 | 0 | 22 | 396 | 306 | 151 | 155 | 28 | 4 |
module Options.Nested.Types where
import Options.Nested.Types.Parser
import Control.Applicative
import Data.Maybe (isJust)
import Data.Monoid
import Data.Tree
-- | A command tree is a rose tree of the command label and it's optional flag
-- parser.
type CommandTree a = Forest (String, Maybe a)
-- | A list of the acceptable sub-command invocations for a given rose-tree
-- schema.
executables :: CommandTree b -> [[String]]
executables =
map (map fst) . filter (isJust . snd . last) . concatMap steps
data LabelledArg a = LabelledArg Label a
deriving (Show, Eq)
data PositionedArg a = PositionedArg a
deriving (Show, Eq)
data Label = ShortLabel Char
| LongLabel String
| BothLabels Char String
deriving (Show, Eq)
|
athanclark/optparse-nested
|
src/Options/Nested/Types.hs
|
bsd-3-clause
| 804 | 0 | 10 | 200 | 195 | 112 | 83 | 18 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Lambdasim.Time where
import Data.Time hiding (utc)
import Data.Ratio ((%))
import Control.Monad (liftM)
import Control.Parallel.Strategies
import Prelude ()
import Lambdasim.Prelude
addTime :: Time -> UTCTime -> UTCTime
addTime x = addUTCTime (toNominalDiffTime x)
toNominalDiffTime :: Time -> NominalDiffTime
toNominalDiffTime t = fromRational (ps % 1000000000000)
where
ps = round (t /~ pico second)
toMicroseconds :: Time -> Int
toMicroseconds t = round (t /~ micro second)
toNearestSecond :: UTCTime -> UTCTime
toNearestSecond utc = utc { utctDayTime = rounded }
where
rounded = secondsToDiffTime seconds
seconds = round (toRational dayTime)
dayTime = utctDayTime utc
getRoundedTime :: IO UTCTime
getRoundedTime = liftM toNearestSecond getCurrentTime
instance NFData UTCTime where
rnf x = utctDay x `seq` utctDayTime x `seq` ()
|
jystic/lambdasim
|
src/Lambdasim/Time.hs
|
bsd-3-clause
| 911 | 0 | 10 | 155 | 275 | 149 | 126 | 24 | 1 |
module Ling.Rename where
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe (fromMaybe)
import Control.Applicative
import Control.Lens
import Ling.Abs (Name)
import Ling.Utils
import Ling.Norm
-- import Ling.Print.Instances ()
type Ren = Map Name Name
type E a = a -> a
class Rename a where
rename :: Ren -> E a
rename1 :: Rename a => (Name, Name) -> E a
rename1 = rename . l2m . pure
instance Rename Name where
rename f n = fromMaybe n (f ^. at n)
instance Rename Term where
rename f e0 = case e0 of
Def x es -> Def (rename f x) (rename f es)
Lam arg t -> Lam (rename f arg) (rename (hideArg arg f) t)
TFun arg t -> TFun (rename f arg) (rename (hideArg arg f) t)
TSig arg t -> TSig (rename f arg) (rename (hideArg arg f) t)
TTyp -> e0
Lit{} -> e0
Ann{} -> error "rename/Ann: impossible"
Proc{} -> error "rename/Proc: TODO"
TProto{} -> error "rename/TProto: TODO"
instance Rename a => Rename (Arg a) where
rename f (Arg x e) = Arg (rename f x) (rename f e)
instance Rename a => Rename [a] where
rename = map . rename
instance Rename a => Rename (Maybe a) where
rename = fmap . rename
hideArg :: Arg a -> E Ren
hideArg (Arg x _) = Map.delete x
hidePref :: Pref -> E Ren
hidePref (Recv _ arg) = hideArg arg
hidePref (NewSlice _ x) = Map.delete x
hidePref _ = id
hidePrefs :: [Pref] -> E Ren
hidePrefs = flip (foldr hidePref)
instance Rename Pref where
rename f pref = case pref of
TenSplit c ds -> TenSplit (rename f c) (rename f ds)
ParSplit c ds -> ParSplit (rename f c) (rename f ds)
Send c e -> Send (rename f c) (rename f e)
Recv c arg -> Recv (rename f c) (rename f arg)
Nu c d -> Nu (rename f c) (rename f d)
NewSlice t x -> NewSlice (rename f t) (rename f x)
instance Rename Proc where
rename f (Act prefs procs) = Act (rename f prefs) (rename (hidePrefs prefs f) procs)
rename f (Ax s c d es) = Ax (rename f s) (rename f c) (rename f d) (rename f es)
rename f (At t cs) = At (rename f t) (rename f cs)
instance Rename Session where
rename f s0 = case s0 of
Ten ss -> Ten (rename f ss)
Par ss -> Par (rename f ss)
Seq ss -> Seq (rename f ss)
Snd t s -> Snd (rename f t) (rename f s)
Rcv t s -> Rcv (rename f t) (rename f s)
Atm p n -> Atm p (rename f n)
End -> End
instance Rename RSession where
rename f (Repl s t) = Repl (rename f s) (rename f t)
|
jyp/ling
|
Ling/Rename.hs
|
bsd-3-clause
| 2,485 | 0 | 13 | 681 | 1,244 | 611 | 633 | 65 | 1 |
-- various desugaring routines
--
-- The general desugaring routine creates selectors for data
-- constructors with named fields, changes all pattern bindings
-- into 'simple' pattern bindings, and adds failure cases to lambda
-- expressions which have failable patterns
module FrontEnd.Desugar (doToExp, listCompToExp, desugarHsModule, desugarHsStmt) where
import Control.Monad.State
import FrontEnd.HsSyn
import FrontEnd.SrcLoc
import FrontEnd.Syn.Traverse
import Name.Name
import Name.Names
type PatState = Int
getUnique = do
n <- get
put (n + 1)
return n
type PatSM = State PatState
instance MonadSrcLoc PatSM where
instance MonadSetSrcLoc PatSM where
withSrcLoc _ a = a
-- a new (unique) name introduced in pattern selector functions
newPatVarName :: HsName
newPatVarName = nameName $ toName Val ("patvar@0"::String)
{-
this function replaces all constructor-pattern bindings in a module with
function calls
ie:
(x, y) = head $ zip "abc" [1,2,3]
becomes
x = (\(a, _) -> a) rhs1
y = (\(_, a) -> a) rhs1
rhs1 = head $ zip "abc" [1,2,3]
-}
-- first argument is imported synonyms
desugarHsModule :: HsModule -> HsModule
desugarHsModule m = hsModuleDecls_s ds' m where
(ds', _) = runState (dsm (hsModuleDecls m)) (0::Int)
dsm ds = fmap concat $ mapM desugarDecl ds
desugarHsStmt :: Monad m => HsStmt -> m HsStmt
desugarHsStmt s = return $ fst $ runState (desugarStmt s) (0::Int)
desugarDecl :: HsDecl -> PatSM [HsDecl]
desugarDecl (HsFunBind matches) = do
newMatches <- mapM desugarMatch matches
return [HsFunBind newMatches]
-- variable pattern bindings remain unchanged
desugarDecl pb@(HsPatBind sloc (HsPVar n) rhs wheres) = do
newRhs <- desugarRhs rhs
newWheres <- mapM desugarDecl wheres
return [HsPatBind sloc (HsPVar n) newRhs (concat newWheres)]
desugarDecl pb@(HsPatBind sloc pat rhs wheres) = do
rhs <- desugarRhs rhs
unique <- getUnique
let newRhsName = toName Val ("patrhs@" ++ show unique)
newWheres <- mapM desugarDecl wheres
let newTopDeclForRhs
= HsPatBind sloc (HsPVar newRhsName) rhs (concat newWheres)
let newBinds = genBindsForPat pat sloc newRhsName
newBinds <- mapM desugarDecl newBinds
return (newTopDeclForRhs : concat newBinds)
desugarDecl (HsClassDecl sloc qualtype decls) = do
newDecls <- mapM desugarDecl decls
return [HsClassDecl sloc qualtype (concat newDecls)]
desugarDecl (HsInstDecl sloc qualtype decls) = do
newDecls <- mapM desugarDecl decls
return [HsInstDecl sloc qualtype (concat newDecls)]
-- XXX we currently discard instance specializations
desugarDecl HsPragmaSpecialize { hsDeclName = n } | n == u_instance = return []
desugarDecl anyOtherDecl = return [anyOtherDecl]
desugarMatch :: (HsMatch) -> PatSM (HsMatch)
desugarMatch (HsMatch sloc funName pats rhs wheres) = do
newWheres <- mapM desugarDecl wheres
newRhs <- desugarRhs rhs
return (HsMatch sloc funName pats newRhs (concat newWheres))
-- generate the pattern bindings for each variable in a pattern
genBindsForPat :: HsPat -> SrcLoc -> HsName -> [HsDecl]
genBindsForPat pat sloc rhsName
= [HsPatBind sloc (HsPVar patName) (HsUnGuardedRhs (HsApp selector (HsVar rhsName))) [] | (patName, selector) <- selFuns]
where
selFuns = getPatSelFuns sloc pat
-- generate selector functions for each of the variables that
-- are bound in a pattern
getPatSelFuns :: SrcLoc -> HsPat -> [(HsName, (HsExp))]
getPatSelFuns sloc pat = [(varName, HsParen (HsLambda sloc [HsPVar newPatVarName] (kase (replaceVarNamesInPat varName pat)))) | varName <- getNamesFromHsPat pat] where
kase p = HsCase (HsVar newPatVarName) [a1, a2 ] where
a1 = HsAlt sloc p (HsUnGuardedRhs (HsVar newPatVarName)) []
a2 = HsAlt sloc HsPWildCard (HsUnGuardedRhs (HsError { hsExpSrcLoc = sloc, hsExpErrorType = HsErrorPatternFailure, hsExpString = show sloc ++ " failed pattern match" })) []
--a2 = HsAlt sloc HsPWildCard (HsUnGuardedRhs (HsApp (HsVar (toName Val ("error"::String))) (HsLit $ HsString $ show sloc ++ " failed pattern match"))) []
-- replaces all occurrences of a name with a new variable
-- and every other name with underscore
replaceVarNamesInPat :: HsName -> HsPat -> HsPat
replaceVarNamesInPat name p = f name p where
f name1 (HsPVar (toName Val -> name2))
| name1 == name2 = HsPVar $ newPatVarName
| otherwise = HsPWildCard
f _ p@(HsPLit _) = p
f name (HsPNeg pat) = HsPNeg $ f name pat
f name (HsPInfixApp pat1 conName pat2) = HsPInfixApp (f name pat1) conName (f name pat2)
f name (HsPApp conName pats) = HsPApp conName (map (f name) pats)
f name (HsPTuple pats) = HsPTuple (map (f name) pats)
f name (HsPUnboxedTuple pats) = HsPUnboxedTuple (map (f name) pats)
f name (HsPList pats) = HsPList (map (f name) pats)
f name (HsPParen pat) = HsPParen (f name pat)
f name (HsPRec conName fields) = HsPRec conName [ HsPFieldPat fname (f name pat)
| HsPFieldPat fname pat <- fields ]
f name (HsPAsPat asName pat)
| name == asName = HsPAsPat newPatVarName (f name pat)
| otherwise = f name pat
f name HsPWildCard = HsPWildCard
f name (HsPIrrPat pat) = HsPIrrPat $ fmap (f name) pat
f name (HsPBangPat pat) = HsPBangPat $ fmap (f name) pat
f name p = error $ "f: " ++ show (name,p)
desugarRhs :: (HsRhs) -> PatSM (HsRhs)
desugarRhs = traverseHsRhsHsExp desugarExp
desugarExp :: (HsExp) -> PatSM (HsExp)
desugarExp (HsLambda sloc pats e)
| all isSimplePat pats = do
newE <- desugarExp e
return (HsLambda sloc pats newE)
desugarExp (HsLambda sloc pats e) = z where
z = do
ps <- mapM f pats
let (xs,zs) = unzip ps
e' <- (ne e $ concat zs)
return (HsLambda sloc (map HsPVar xs) e')
ne e [] = desugarExp e
ne e ((n,p):zs) = do
e' <- ne e zs
let a1 = HsAlt sloc p (HsUnGuardedRhs e') []
a2 = HsAlt sloc HsPWildCard (HsUnGuardedRhs (HsError { hsExpSrcLoc = sloc, hsExpErrorType = HsErrorPatternFailure, hsExpString = show sloc ++ " failed pattern match in lambda" })) []
return $ HsCase (HsVar n) [a1, a2 ]
f (HsPVar x) = return (x,[])
f (HsPAsPat n p) = return (n,[(n,p)])
f p = do
unique <- getUnique
let n = nameName $ toName Val ("lambind@" ++ show unique)
return (n,[(n,p)])
desugarExp (HsLet decls e) = do
newDecls <- mapM desugarDecl decls
newE <- desugarExp e
return (HsLet (concat newDecls) newE)
desugarExp (HsCase e alts) = do
newE <- desugarExp e
newAlts <- mapM desugarAlt alts
return (HsCase newE newAlts)
desugarExp (HsDo stmts) = HsDo `liftM` mapM desugarStmt stmts
desugarExp (HsListComp e stmts) = do
e <- desugarExp e
stmts <- mapM desugarStmt stmts
return (HsListComp e stmts)
desugarExp e = traverseHsExp desugarExp e
desugarAlt :: (HsAlt) -> PatSM (HsAlt)
desugarAlt (HsAlt sloc pat gAlts wheres) = do
newGAlts <- desugarRhs gAlts
newWheres <- mapM desugarDecl wheres
return (HsAlt sloc pat newGAlts (concat newWheres))
desugarStmt :: (HsStmt) -> PatSM (HsStmt)
desugarStmt (HsGenerator srcLoc pat e) = do
newE <- desugarExp e
return (HsGenerator srcLoc pat newE)
desugarStmt (HsQualifier e) = do
newE <- desugarExp e
return (HsQualifier newE)
desugarStmt (HsLetStmt decls) = do
newDecls <- mapM desugarDecl decls
return (HsLetStmt $ concat newDecls)
doToExp :: Monad m
=> m HsName -- ^ name generator
-> HsName -- ^ bind (>>=) to use
-> HsName -- ^ bind_ (>>) to use
-> HsName -- ^ fail to use
-> [HsStmt]
-> m HsExp
doToExp newName f_bind f_bind_ f_fail ss = hsParen `liftM` f ss where
f [] = fail "doToExp: empty statements in do notation"
f [HsQualifier e] = return e
f [gen@(HsGenerator srcLoc _pat _e)] = fail $ "doToExp: last expression n do notation is a generator (srcLoc):" ++ show srcLoc
f [letst@(HsLetStmt _decls)] = fail $ "doToExp: last expression n do notation is a let statement"
f (HsQualifier e:ss) = do
ss <- f ss
return $ HsInfixApp (hsParen e) (HsVar f_bind_) (hsParen ss)
f ((HsGenerator _srcLoc pat e):ss) | isSimplePat pat = do
ss <- f ss
return $ HsInfixApp (hsParen e) (HsVar f_bind) (HsLambda _srcLoc [pat] ss)
f ((HsGenerator srcLoc pat e):ss) = do
npvar <- newName
ss <- f ss
let kase = HsCase (HsVar npvar) [a1, a2 ]
a1 = HsAlt srcLoc pat (HsUnGuardedRhs ss) []
a2 = HsAlt srcLoc HsPWildCard (HsUnGuardedRhs (HsApp (HsVar f_fail) (HsLit $ HsString $ show srcLoc ++ " failed pattern match in do"))) []
return $ HsInfixApp (hsParen e) (HsVar f_bind) (HsLambda srcLoc [HsPVar npvar] kase) where
f (HsLetStmt decls:ss) = do
ss <- f ss
return $ HsLet decls ss
hsApp e es = hsParen $ foldl HsApp (hsParen e) (map hsParen es)
hsIf e a b = hsParen $ HsIf e a b
listCompToExp :: Monad m => m HsName -> HsExp -> [HsStmt] -> m HsExp
listCompToExp newName exp ss = hsParen `liftM` f ss where
f [] = return $ HsList [exp]
f (gen:HsQualifier q1:HsQualifier q2:ss) = f (gen:HsQualifier (hsApp (HsVar v_and) [q1,q2]):ss)
f ((HsLetStmt ds):ss) = do ss' <- f ss; return $ hsParen (HsLet ds ss')
f (HsQualifier e:ss) = do ss' <- f ss; return $ hsParen (HsIf e ss' (HsList []))
f ((HsGenerator srcLoc pat e):ss) | isLazyPat pat, Just exp' <- g ss = do
return $ hsParen $ HsVar v_map `app` HsLambda srcLoc [pat] exp' `app` e
--f ((HsGenerator srcLoc pat e):[HsQualifier q]) | isHsPVar pat = hsParen $ HsApp (HsApp (HsVar f_filter) (hsParen $ HsLambda srcLoc [pat] q) ) e
f ((HsGenerator srcLoc pat e):HsQualifier q:ss) | isLazyPat pat, Just exp' <- g ss = do
npvar <- newName
return $ hsApp (HsVar v_foldr) [HsLambda srcLoc [pat,HsPVar npvar] $ hsIf q (hsApp (HsCon dc_Cons) [exp',HsVar npvar]) (HsVar npvar), HsList [],e]
f ((HsGenerator srcLoc pat e):ss) | isLazyPat pat = do
ss' <- f ss
return $ hsParen $ HsVar v_concatMap `app` HsLambda srcLoc [pat] ss' `app` e
f ((HsGenerator srcLoc pat e):HsQualifier q:ss) | isFailablePat pat || Nothing == g ss = do
npvar <- newName
ss' <- f ss
let kase = HsCase (HsVar npvar) [a1, a2 ]
a1 = HsAlt srcLoc pat (HsGuardedRhss [HsGuardedRhs srcLoc q ss']) []
a2 = HsAlt srcLoc HsPWildCard (HsUnGuardedRhs $ HsList []) []
return $ hsParen $ HsVar v_concatMap `app` HsLambda srcLoc [HsPVar npvar] kase `app` e
f ((HsGenerator srcLoc pat e):ss) | isFailablePat pat || Nothing == g ss = do
npvar <- newName
ss' <- f ss
let kase = HsCase (HsVar npvar) [a1, a2 ]
a1 = HsAlt srcLoc pat (HsUnGuardedRhs ss') []
a2 = HsAlt srcLoc HsPWildCard (HsUnGuardedRhs $ HsList []) []
return $ hsParen $ HsVar v_concatMap `app` HsLambda srcLoc [HsPVar npvar] kase `app` e
f ((HsGenerator srcLoc pat e):ss) = do
npvar <- newName
let Just exp' = g ss
kase = HsCase (HsVar npvar) [a1 ]
a1 = HsAlt srcLoc pat (HsUnGuardedRhs exp') []
return $ hsParen $ HsVar v_map `app` HsLambda srcLoc [HsPVar npvar] kase `app` e
g [] = return exp
g (HsLetStmt ds:ss) = do
e <- g ss
return (hsParen (HsLet ds e))
g _ = Nothing
app x y = HsApp x (hsParen y)
-- patterns are
-- failable - strict and may fail to match
-- refutable or strict - may bottom out
-- irrefutable or lazy - match no matter what
-- simple, a wildcard or variable
-- failable is a subset of refutable
isFailablePat p | isStrictPat p = f (openPat p) where
f (HsPTuple ps) = any isFailablePat ps
f (HsPUnboxedTuple ps) = any isFailablePat ps
f (HsPBangPat (Located _ p)) = isFailablePat p
f _ = True
isFailablePat _ = False
isSimplePat p = f (openPat p) where
f HsPVar {} = True
f HsPWildCard = True
f _ = False
isLazyPat pat = not (isStrictPat pat)
isStrictPat p = f (openPat p) where
f HsPVar {} = False
f HsPWildCard = False
f (HsPIrrPat p) = False -- isStrictPat p -- TODO irrefutable patterns
f _ = True
openPat (HsPParen p) = openPat p
openPat (HsPNeg p) = openPat p
openPat (HsPAsPat _ p) = openPat p
openPat (HsPTypeSig _ p _) = openPat p
openPat (HsPInfixApp a n b) = HsPApp n [a,b]
openPat p = p
|
dec9ue/jhc_copygc
|
src/FrontEnd/Desugar.hs
|
gpl-2.0
| 12,538 | 0 | 20 | 3,093 | 4,637 | 2,276 | 2,361 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-| Unittests for the KVM daemon.
-}
{-
Copyright (C) 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.Kvmd (testKvmd) where
import Control.Concurrent
import Control.Exception (try)
import qualified Network.Socket as Socket
import System.Directory
import System.FilePath
import System.IO
import qualified Ganeti.Kvmd as Kvmd
import qualified Ganeti.UDSServer as UDSServer
import Test.HUnit as HUnit
import qualified Test.Ganeti.TestHelper as TestHelper (testSuite)
import qualified Test.Ganeti.TestCommon as TestCommon (getTempFileName)
import qualified Ganeti.Logging as Logging
{-# ANN module "HLint: ignore Use camelCase" #-}
startKvmd :: FilePath -> IO ThreadId
startKvmd dir =
forkIO (do Logging.setupLogging Nothing "ganeti-kvmd" False False
False Logging.SyslogNo
Kvmd.startWith dir)
stopKvmd :: ThreadId -> IO ()
stopKvmd = killThread
delayKvmd :: IO ()
delayKvmd = threadDelay 1000000
detectShutdown :: (Handle -> IO ()) -> IO Bool
detectShutdown putFn =
do monitorDir <- TestCommon.getTempFileName "ganeti"
let monitor = "instance" <.> Kvmd.monitorExtension
monitorFile = monitorDir </> monitor
shutdownFile = Kvmd.shutdownPath monitorFile
-- ensure the KVM directory exists
createDirectoryIfMissing True monitorDir
-- ensure the shutdown file does not exist
(try (removeFile shutdownFile) :: IO (Either IOError ())) >> return ()
-- start KVM daemon
threadId <- startKvmd monitorDir
threadDelay 1000
-- create a Unix socket
sock <- UDSServer.openServerSocket monitorFile
Socket.listen sock 1
handle <- UDSServer.acceptSocket sock
-- read 'qmp_capabilities' message
res <- try . hGetLine $ handle :: IO (Either IOError String)
case res of
Left err ->
assertFailure $ "Expecting " ++ show Kvmd.monitorGreeting ++
", received " ++ show err
Right str -> Kvmd.monitorGreeting @=? str
-- send Qmp messages
putFn handle
hFlush handle
-- close the Unix socket
UDSServer.closeClientSocket handle
UDSServer.closeServerSocket sock monitorFile
-- KVM needs time to create the shutdown file
delayKvmd
-- stop the KVM daemon
stopKvmd threadId
-- check for shutdown file
doesFileExist shutdownFile
case_DetectAdminShutdown :: Assertion
case_DetectAdminShutdown =
do res <- detectShutdown putMessage
assertBool "Detected user shutdown instead of administrator shutdown" $
not res
where putMessage handle =
do hPrint handle "POWERDOWN"
hPrint handle "SHUTDOWN"
case_DetectUserShutdown :: Assertion
case_DetectUserShutdown =
do res <- detectShutdown putMessage
assertBool "Detected administrator shutdown instead of user shutdown" res
where putMessage handle =
hPrint handle "SHUTDOWN"
TestHelper.testSuite "Kvmd"
[ 'case_DetectAdminShutdown
, 'case_DetectUserShutdown
]
|
ribag/ganeti-experiments
|
test/hs/Test/Ganeti/Kvmd.hs
|
gpl-2.0
| 3,682 | 0 | 14 | 780 | 639 | 324 | 315 | 67 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : injective maps
Copyright : (c) Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Injective maps
-}
module Common.InjMap
( InjMap
, unsafeConstructInjMap
, getAToB
, getBToA
, empty
, member
, insert
, delete
, deleteA
, deleteB
, lookupWithA
, lookupWithB
, updateBWithA
, updateAWithB
) where
import Data.Data
import qualified Data.Map as Map
-- | the data type of injective maps
data InjMap a b = InjMap
{ getAToB :: Map.Map a b -- ^ the actual injective map
, getBToA :: Map.Map b a -- ^ the inverse map
} deriving (Show, Eq, Ord, Typeable, Data)
-- | for serialization only
unsafeConstructInjMap :: Map.Map a b -> Map.Map b a -> InjMap a b
unsafeConstructInjMap = InjMap
-- * the visible interface
-- | get an empty injective map
empty :: InjMap a b
empty = InjMap Map.empty Map.empty
{- | insert a pair into the given injective map. An existing key and the
corresponding content will be overridden. -}
insert :: (Ord a, Ord b) => a -> b -> InjMap a b -> InjMap a b
insert a b i = let InjMap m n = delete a b i in
InjMap (Map.insert a b m) (Map.insert b a n)
{- | delete the pair with the given key in the injective
map. Possibly two pairs may be deleted if the pair is not a member. -}
delete :: (Ord a, Ord b) => a -> b -> InjMap a b -> InjMap a b
delete a b (InjMap m n) =
InjMap (Map.delete (Map.findWithDefault a b n) $ Map.delete a m)
(Map.delete (Map.findWithDefault b a m) $ Map.delete b n)
-- | delete domain entry
deleteA :: (Ord a, Ord b) => a -> InjMap a b -> InjMap a b
deleteA a i@(InjMap m n) = case Map.lookup a m of
Just b -> case Map.lookup b n of
Just e -> if e == a then InjMap (Map.delete a m) $ Map.delete b n
else error "InjMap.deleteA1"
Nothing -> error "InjMap.deleteA2"
Nothing -> i
-- | delete codomain entry
deleteB :: (Ord a, Ord b) => b -> InjMap a b -> InjMap a b
deleteB b = transpose . deleteA b . transpose
-- | check membership of an injective pair
member :: (Ord a, Ord b) => a -> b -> InjMap a b -> Bool
member a b (InjMap m n) = case (Map.lookup a m, Map.lookup b n) of
(Just x, Just y) | x == b && y == a -> True
_ -> False
-- | transpose to avoid duplicate code
transpose :: InjMap a b -> InjMap b a
transpose (InjMap m n) = InjMap n m
-- | look up the content at domain
lookupWithA :: (Ord a, Ord b) => a -> InjMap a b -> Maybe b
lookupWithA a (InjMap m n) = case Map.lookup a m of
Just b -> case Map.lookup b n of
Just e -> if e == a then Just b
else error "InjMap.lookupWith1"
Nothing -> error "InjMap.lookupWith2"
Nothing -> Nothing
-- the errors indicate that the injectivity is destroyed
-- | look up the content at codomain
lookupWithB :: (Ord a, Ord b) => b -> InjMap a b -> Maybe a
lookupWithB y = lookupWithA y . transpose
-- | update codomain at domain value that must be defined
updateBWithA :: (Ord a, Ord b) => a -> b -> InjMap a b -> InjMap a b
updateBWithA a b m = case lookupWithA a m of
Nothing -> error "InjMap.updateBWithA"
_ -> insert a b m
-- | update domain at codomain value that must be defined
updateAWithB :: (Ord a, Ord b) => b -> a -> InjMap a b -> InjMap a b
updateAWithB b newA = transpose . updateBWithA b newA . transpose
|
keithodulaigh/Hets
|
Common/InjMap.hs
|
gpl-2.0
| 3,487 | 0 | 16 | 885 | 1,140 | 579 | 561 | 63 | 4 |
import Control.Monad.ST (runST)
import Criterion.Main
import Data.Complex
import Statistics.Sample
import Statistics.Transform
import Statistics.Correlation.Pearson
import System.Random.MWC
import qualified Data.Vector.Unboxed as U
-- Test sample
sample :: U.Vector Double
sample = runST $ flip uniformVector 10000 =<< create
-- Weighted test sample
sampleW :: U.Vector (Double,Double)
sampleW = U.zip sample (U.reverse sample)
-- Comlex vector for FFT tests
sampleC :: U.Vector (Complex Double)
sampleC = U.zipWith (:+) sample (U.reverse sample)
-- Simple benchmark for functions from Statistics.Sample
main :: IO ()
main =
defaultMain
[ bgroup "sample"
[ bench "range" $ nf (\x -> range x) sample
-- Mean
, bench "mean" $ nf (\x -> mean x) sample
, bench "meanWeighted" $ nf (\x -> meanWeighted x) sampleW
, bench "harmonicMean" $ nf (\x -> harmonicMean x) sample
, bench "geometricMean" $ nf (\x -> geometricMean x) sample
-- Variance
, bench "variance" $ nf (\x -> variance x) sample
, bench "varianceUnbiased" $ nf (\x -> varianceUnbiased x) sample
, bench "varianceWeighted" $ nf (\x -> varianceWeighted x) sampleW
-- Correlation
, bench "pearson" $ nf (\x -> pearson (U.reverse sample) x) sample
, bench "pearson'" $ nf (\x -> pearson' (U.reverse sample) x) sample
, bench "pearsonFast" $ nf (\x -> pearsonFast (U.reverse sample) x) sample
-- Other
, bench "stdDev" $ nf (\x -> stdDev x) sample
, bench "skewness" $ nf (\x -> skewness x) sample
, bench "kurtosis" $ nf (\x -> kurtosis x) sample
-- Central moments
, bench "C.M. 2" $ nf (\x -> centralMoment 2 x) sample
, bench "C.M. 3" $ nf (\x -> centralMoment 3 x) sample
, bench "C.M. 4" $ nf (\x -> centralMoment 4 x) sample
, bench "C.M. 5" $ nf (\x -> centralMoment 5 x) sample
]
, bgroup "FFT"
[ bgroup "fft"
[ bench (show n) $ whnf fft (U.take n sampleC) | n <- fftSizes ]
, bgroup "ifft"
[ bench (show n) $ whnf ifft (U.take n sampleC) | n <- fftSizes ]
, bgroup "dct"
[ bench (show n) $ whnf dct (U.take n sample) | n <- fftSizes ]
, bgroup "dct_"
[ bench (show n) $ whnf dct_ (U.take n sampleC) | n <- fftSizes ]
, bgroup "idct"
[ bench (show n) $ whnf idct (U.take n sample) | n <- fftSizes ]
, bgroup "idct_"
[ bench (show n) $ whnf idct_ (U.take n sampleC) | n <- fftSizes ]
]
]
fftSizes :: [Int]
fftSizes = [32,128,512,2048]
|
bos/statistics
|
benchmark/bench.hs
|
bsd-2-clause
| 2,701 | 0 | 16 | 814 | 1,013 | 521 | 492 | 51 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Distribution.Nixpkgs.Haskell.FromCabal.Name ( toNixName, libNixName, buildToolNixName ) where
import Data.String
import Distribution.Package
import Language.Nix
-- | Map Cabal names to Nix attribute names.
toNixName :: PackageName -> Identifier
toNixName (PackageName "") = error "toNixName: invalid empty package name"
toNixName (PackageName n) = fromString n
-- | Map libraries to Nix packages.
--
-- TODO: This list should not be hard-coded here; it belongs into the Nixpkgs
-- repository.
libNixName :: String -> [Identifier]
libNixName "" = []
libNixName "adns" = return "adns"
libNixName "alsa" = return "alsaLib"
libNixName "alut" = return "freealut"
libNixName "appindicator-0.1" = return "appindicator"
libNixName "appindicator3-0.1" = return "appindicator"
libNixName "asound" = return "alsaLib"
libNixName "awesomium-1.6.5" = return "awesomium"
libNixName "bz2" = return "bzip2"
libNixName "cairo-pdf" = return "cairo"
libNixName "cairo-ps" = return "cairo"
libNixName "cairo" = return "cairo"
libNixName "cairo-svg" = return "cairo"
libNixName "CEGUIBase-0.7.7" = return "CEGUIBase"
libNixName "CEGUIOgreRenderer-0.7.7" = return "CEGUIOgreRenderer"
libNixName "clutter-1.0" = return "clutter"
libNixName "crypto" = return "openssl"
libNixName "crypt" = [] -- provided by glibc
libNixName "curses" = return "ncurses"
libNixName "c++" = [] -- What is that?
libNixName "dl" = [] -- provided by glibc
libNixName "fftw3f" = return "fftwFloat"
libNixName "fftw3" = return "fftw"
libNixName "gconf-2.0" = return "GConf"
libNixName "gconf" = return "GConf"
libNixName "gdk-2.0" = return "gtk"
libNixName "gdk-pixbuf-2.0" = return "gdk_pixbuf"
libNixName "gdk-x11-2.0" = return "gdk_x11"
libNixName "gio-2.0" = return "glib"
libNixName "glib-2.0" = return "glib"
libNixName "GL" = return "mesa"
libNixName "GLU" = ["freeglut","mesa"]
libNixName "glut" = ["freeglut","mesa"]
libNixName "gmime-2.4" = return "gmime"
libNixName "gnome-keyring-1" = return "gnome_keyring"
libNixName "gnome-keyring" = return "gnome_keyring"
libNixName "gnome-vfs-2.0" = return "gnome_vfs"
libNixName "gnome-vfs-module-2.0" = return "gnome_vfs_module"
libNixName "gobject-2.0" = return "glib"
libNixName "gstreamer-0.10" = return "gstreamer"
libNixName "gstreamer-audio-0.10" = return "gst_plugins_base"
libNixName "gstreamer-base-0.10" = return "gst_plugins_base"
libNixName "gstreamer-controller-0.10" = return "gstreamer"
libNixName "gstreamer-dataprotocol-0.10" = return "gstreamer"
libNixName "gstreamer-net-0.10" = return "gst_plugins_base"
libNixName "gstreamer-plugins-base-0.10" = return "gst_plugins_base"
libNixName "gthread-2.0" = return "glib"
libNixName "gtk+-2.0" = return "gtk"
libNixName "gtk+-3.0" = return "gtk3"
libNixName "gtkglext-1.0" = return "gtkglext"
libNixName "gtksourceview-2.0" = return "gtksourceview"
libNixName "gtksourceview-3.0" = return "gtksourceview"
libNixName "gtk-x11-2.0" = return "gtk_x11"
libNixName "icudata" = return "icu"
libNixName "icui18n" = return "icu"
libNixName "icuuc" = return "icu"
libNixName "idn" = return "libidn"
libNixName "IL" = return "libdevil"
libNixName "ImageMagick" = return "imagemagick"
libNixName "Imlib2" = return "imlib2"
libNixName "iw" = return "wirelesstools"
libNixName "jack" = return "libjack2"
libNixName "jpeg" = return "libjpeg"
libNixName "ldap" = return "openldap"
libNixName "libavutil" = return "ffmpeg"
libNixName "libglade-2.0" = return "libglade"
libNixName "libgsasl" = return "gsasl"
libNixName "librsvg-2.0" = return "librsvg"
libNixName "libsoup-gnome-2.4" = return "libsoup"
libNixName "libsystemd" = return "systemd"
libNixName "libusb-1.0" = return "libusb"
libNixName "libxml-2.0" = return "libxml2"
libNixName "libzip" = return "libzip"
libNixName "libzmq" = return "zeromq"
libNixName "MagickWand" = return "imagemagick"
libNixName "magic" = return "file"
libNixName "m" = [] -- in stdenv
libNixName "mono-2.0" = return "mono"
libNixName "mpi" = return "openmpi"
libNixName "ncursesw" = return "ncurses"
libNixName "netsnmp" = return "net_snmp"
libNixName "notify" = return "libnotify"
libNixName "odbc" = return "unixODBC"
libNixName "panelw" = return "ncurses"
libNixName "pangocairo" = return "pango"
libNixName "pcap" = return "libpcap"
libNixName "pcre" = return "pcre"
libNixName "pfs-1.2" = return "pfstools"
libNixName "png" = return "libpng"
libNixName "poppler-glib" = return "poppler"
libNixName "portaudio-2.0" = return "portaudio"
libNixName "pq" = return "postgresql"
libNixName "pthread" = []
libNixName "pulse-simple" = return "libpulseaudio"
libNixName "python-3.3" = return "python3"
libNixName "Qt5Core" = return "qt5"
libNixName "Qt5Gui" = return "qt5"
libNixName "Qt5Qml" = return "qt5"
libNixName "Qt5Quick" = return "qt5"
libNixName "Qt5Widgets" = return "qt5"
libNixName "rtlsdr" = return "rtl-sdr"
libNixName "rt" = [] -- in glibc
libNixName "ruby1.8" = return "ruby"
libNixName "sass" = return "libsass"
libNixName "sane-backends" = return "saneBackends"
libNixName "SDL2-2.0" = return "SDL2"
libNixName "sdl2" = return "SDL2"
libNixName "sndfile" = return "libsndfile"
libNixName "sodium" = return "libsodium"
libNixName "sqlite3" = return "sqlite"
libNixName "ssl" = return "openssl"
libNixName "stdc++.dll" = [] -- What is that?
libNixName "stdc++" = [] -- What is that?
libNixName "systemd-journal" = return "systemd"
libNixName "tag_c" = return "taglib"
libNixName "taglib_c" = return "taglib"
libNixName "udev" = return "systemd";
libNixName "uuid" = return "libossp_uuid";
libNixName "vte-2.90" = return "vte"
libNixName "wayland-client" = return "wayland"
libNixName "wayland-cursor" = return "wayland"
libNixName "wayland-egl" = return "mesa"
libNixName "wayland-server" = return "wayland"
libNixName "webkit-1.0" = return "webkit"
libNixName "webkitgtk-3.0" = return "webkit"
libNixName "webkitgtk" = return "webkit"
libNixName "X11" = return "libX11"
libNixName "xau" = return "libXau"
libNixName "Xcursor" = return "libXcursor"
libNixName "xerces-c" = return "xercesc"
libNixName "Xext" = return "libXext"
libNixName "xft" = return "libXft"
libNixName "Xinerama" = return "libXinerama"
libNixName "Xi" = return "libXi"
libNixName "xkbcommon" = return "libxkbcommon"
libNixName "xml2" = return "libxml2"
libNixName "Xpm" = return "libXpm"
libNixName "Xrandr" = return "libXrandr"
libNixName "Xss" = return "libXScrnSaver"
libNixName "Xtst" = return "libXtst"
libNixName "Xxf86vm" = return "libXxf86vm"
libNixName "zmq" = return "zeromq"
libNixName "z" = return "zlib"
libNixName x = return (fromString x)
-- | Map build tool names to Nix attribute names.
buildToolNixName :: String -> [Identifier]
buildToolNixName "" = return (error "buildToolNixName: invalid empty dependency name")
buildToolNixName "cabal" = return "cabal-install"
buildToolNixName "ghc" = []
buildToolNixName "gtk2hsC2hs" = return "gtk2hs-buildtools"
buildToolNixName "gtk2hsHookGenerator" = return "gtk2hs-buildtools"
buildToolNixName "gtk2hsTypeGen" = return "gtk2hs-buildtools"
buildToolNixName "hsc2hs" = []
buildToolNixName x = return (fromString x)
|
psibi/cabal2nix
|
src/Distribution/Nixpkgs/Haskell/FromCabal/Name.hs
|
bsd-3-clause
| 10,974 | 0 | 7 | 4,759 | 1,803 | 849 | 954 | 162 | 1 |
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, LambdaCase, TupleSections, GeneralizedNewtypeDeriving #-}
module Sound.Pd.Internal where
import Foreign.C
import Foreign.Ptr
import Foreign.StablePtr
import Control.Concurrent
import Control.Monad
import Sound.Pd.OpenAL
data FileOpaque
type File = Ptr FileOpaque
data BindingOpaque
type Binding = Ptr BindingOpaque
data AtomOpaque
type AtomPtr = Ptr AtomOpaque
type PdChan = Chan (IO ())
-- Run a command on the Pd thread and block awaiting the result
pdRun :: PdChan -> IO a -> IO a
pdRun chan action = do
result <- newEmptyMVar
writeChan chan (action >>= putMVar result)
takeMVar result
foreign import ccall "startAudio"
startAudio :: CInt -> CInt -> StablePtr PdChan -> IO (Ptr OpenALSource)
foreign import ccall "stopAudio"
stopAudio :: IO ()
foreign import ccall "libpd_process_float"
libpd_process_float :: CInt -> Ptr CFloat -> Ptr CFloat -> IO CInt
foreign import ccall "libpd_process_double"
libpd_process_double :: CInt -> Ptr CDouble -> Ptr CDouble -> IO CInt
foreign import ccall "libpd_process_short"
libpd_process_short :: CInt -> Ptr CShort -> Ptr CShort -> IO CInt
foreign export ccall processFloat :: StablePtr PdChan -> CInt -> Ptr CFloat -> Ptr CFloat -> IO ()
processFloat :: StablePtr PdChan -> CInt -> Ptr CFloat -> Ptr CFloat -> IO ()
processFloat stablePdChan ticks inBuffer outBuffer = do
chan <- deRefStablePtr stablePdChan
pdRun chan $ void $ libpd_process_float ticks inBuffer outBuffer
foreign export ccall processDouble :: StablePtr PdChan -> CInt -> Ptr CDouble -> Ptr CDouble -> IO ()
processDouble :: StablePtr PdChan -> CInt -> Ptr CDouble -> Ptr CDouble -> IO ()
processDouble stablePdChan ticks inBuffer outBuffer = do
chan <- deRefStablePtr stablePdChan
pdRun chan $ void $ libpd_process_double ticks inBuffer outBuffer
foreign export ccall processShort :: StablePtr PdChan -> CInt -> Ptr CShort -> Ptr CShort -> IO ()
processShort :: StablePtr PdChan -> CInt -> Ptr CShort -> Ptr CShort -> IO ()
processShort stablePdChan ticks inBuffer outBuffer = do
chan <- deRefStablePtr stablePdChan
pdRun chan $ void $ libpd_process_short ticks inBuffer outBuffer
foreign import ccall "libpd_init" libpd_init :: IO ()
foreign import ccall "libpd_add_to_search_path" libpd_add_to_search_path :: CString -> IO ()
foreign import ccall "libpd_openfile" libpd_openfile :: CString -> CString -> IO File
foreign import ccall "libpd_closefile" libpd_closefile :: File -> IO ()
foreign import ccall "libpd_getdollarzero" libpd_getdollarzero :: File -> IO CInt
foreign import ccall "libpd_bang" libpd_bang :: CString -> IO CInt
foreign import ccall "libpd_float" libpd_float :: CString -> CFloat -> IO CInt
foreign import ccall "libpd_symbol" libpd_symbol :: CString -> CString -> IO CInt
foreign import ccall "libpd_start_message" libpd_start_message :: CInt -> IO CInt
foreign import ccall "libpd_finish_message" libpd_finish_message :: CString -> CString -> IO CInt
foreign import ccall "libpd_finish_list" libpd_finish_list :: CString -> IO CInt
foreign import ccall "libpd_add_float" libpd_add_float :: CFloat -> IO ()
foreign import ccall "libpd_add_symbol" libpd_add_symbol :: CString -> IO ()
type CPrintHook = CString -> IO ()
foreign import ccall "wrapper"
mkPrintHook :: CPrintHook -> IO (FunPtr CPrintHook)
foreign import ccall "libpd_set_printhook" libpd_set_printhook :: FunPtr CPrintHook -> IO ()
type CBangHook = CString -> IO ()
foreign import ccall "wrapper"
mkBangHook :: CBangHook -> IO (FunPtr CBangHook)
foreign import ccall "libpd_set_banghook" libpd_set_banghook :: FunPtr CBangHook -> IO ()
type CFloatHook = CString -> CFloat -> IO ()
foreign import ccall "wrapper"
mkFloatHook :: CFloatHook -> IO (FunPtr CFloatHook)
foreign import ccall "libpd_set_floathook" libpd_set_floathook :: FunPtr CFloatHook -> IO ()
type CSymbolHook = CString -> CString -> IO ()
foreign import ccall "wrapper"
mkSymbolHook :: CSymbolHook -> IO (FunPtr CSymbolHook)
foreign import ccall "libpd_set_symbolhook" libpd_set_symbolhook :: FunPtr CSymbolHook -> IO ()
type CListHook = CString -> CInt -> AtomPtr -> IO ()
foreign import ccall "wrapper"
mkListHook :: CListHook -> IO (FunPtr CListHook)
foreign import ccall "libpd_set_listhook" libpd_set_listhook :: FunPtr CListHook -> IO ()
type CMessageHook = CString -> CString -> CInt -> AtomPtr -> IO ()
foreign import ccall "wrapper"
mkMessageHook :: CMessageHook -> IO (FunPtr CMessageHook)
foreign import ccall "libpd_set_messagehook" libpd_set_messagehook :: FunPtr CMessageHook -> IO ()
foreign import ccall "libpd_get_symbol" libpd_get_symbol :: AtomPtr -> IO CString
foreign import ccall "libpd_get_float" libpd_get_float :: AtomPtr -> IO CFloat
foreign import ccall "libpd_is_symbol" libpd_is_symbol :: AtomPtr -> IO CInt
foreign import ccall "libpd_is_float" libpd_is_float :: AtomPtr -> IO CInt
foreign import ccall "libpd_next_atom" libpd_next_atom :: AtomPtr -> AtomPtr
foreign import ccall "libpd_exists" libpd_exists :: CString -> IO CInt
foreign import ccall "libpd_bind" libpd_bind :: CString -> IO Binding
foreign import ccall "libpd_unbind" libpd_unbind :: Binding -> IO ()
-- Arrays
foreign import ccall "libpd_arraysize" libpd_arraysize :: CString -> IO CInt
foreign import ccall "libpd_read_array" libpd_read_array :: Ptr CFloat -> CString -> CInt -> CInt -> IO CInt
foreign import ccall "libpd_write_array" libpd_write_array :: CString -> CInt -> Ptr CFloat -> CInt -> IO CInt
|
lukexi/pd-hs
|
src/Sound/Pd/Internal.hs
|
bsd-3-clause
| 5,558 | 0 | 11 | 903 | 1,585 | 801 | 784 | -1 | -1 |
import Data.List
isPossible :: [String] -> String -> (Int, Int) -> (Int, Int) -> Bool
isPossible _ [] _ _ = True
isPossible grid (w:ws) (x, y) (dx, dy)
| x < 10 && y < 10 && (grid !! x !! y == w || grid !! x !! y == '-') = isPossible grid ws (x + dx, y + dy) (dx, dy)
| otherwise = False
putWords :: [String] -> String -> (Int, Int) -> (Int, Int) -> [String]
putWords grid word (x, y) (dx, dy) = [[charAt r c | c <- [0..9]] | r <- [0..9]]
where len = length word
idx = [(x + dx * i, y + dy * i) | i <- [0..len - 1]]
charAt r c = case findIndex (==(r, c)) idx of
Nothing -> grid !! r !! c
Just i -> word !! i
solve :: [String] -> [String] -> String
solve grid [] = if (or . map (any (=='-')) $ grid) then ""
else intercalate "\n" $ grid
solve grid (word:ws)
| length ans1 > 0 = ans1 !! 0
| length ans2 > 0 = ans2 !! 0
| otherwise = ""
where
indices = [(r, c) | r <- [0..9], c <- [0..9]]
hi = filter (\idx -> isPossible grid word idx (0, 1)) indices
vi = filter (\idx -> isPossible grid word idx (1, 0)) indices
ans1 = filter (\sol -> length sol > 0) $ map (\idx -> solve (putWords grid word idx (0, 1)) ws) hi
ans2 = filter (\sol -> length sol > 0) $ map (\idx -> solve (putWords grid word idx (1, 0)) ws) vi
main :: IO ()
main = do
contents <- getContents
let
(grid, wordList':_) = splitAt 10 . words $ contents
wordList = getWords wordList'
putStrLn $ solve grid wordList
getWords :: String -> [String]
getWords wordList = pre : if null suc then [] else getWords $ tail suc
where (pre, suc) = break (\x -> x == ';') wordList
|
EdisonAlgorithms/HackerRank
|
practice/fp/recursion/crosswords-101/crosswords-101.hs
|
mit
| 1,691 | 0 | 16 | 503 | 912 | 483 | 429 | 35 | 2 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
--
-- Code generator utilities; mostly monadic
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmUtils (
cgLit, mkSimpleLit,
emitDataLits, mkDataLits,
emitRODataLits, mkRODataLits,
emitRtsCall, emitRtsCallWithResult, emitRtsCallGen,
assignTemp, newTemp,
newUnboxedTupleRegs,
emitMultiAssign, emitCmmLitSwitch, emitSwitch,
tagToClosure, mkTaggedObjectLoad,
callerSaves, callerSaveVolatileRegs, get_GlobalReg_addr,
cmmAndWord, cmmOrWord, cmmNegate, cmmEqWord, cmmNeWord,
cmmUGtWord, cmmSubWord, cmmMulWord, cmmAddWord, cmmUShrWord,
cmmOffsetExprW, cmmOffsetExprB,
cmmRegOffW, cmmRegOffB,
cmmLabelOffW, cmmLabelOffB,
cmmOffsetW, cmmOffsetB,
cmmOffsetLitW, cmmOffsetLitB,
cmmLoadIndexW,
cmmConstrTag1,
cmmUntag, cmmIsTagged,
addToMem, addToMemE, addToMemLblE, addToMemLbl,
mkWordCLit,
newStringCLit, newByteStringCLit,
blankWord
) where
#include "HsVersions.h"
import StgCmmMonad
import StgCmmClosure
import Cmm
import BlockId
import MkGraph
import CodeGen.Platform
import CLabel
import CmmUtils
import CmmSwitch
import ForeignCall
import IdInfo
import Type
import TyCon
import SMRep
import Module
import Literal
import Digraph
import Util
import Unique
import UniqSupply (MonadUnique(..))
import DynFlags
import FastString
import Outputable
import qualified Data.ByteString as BS
import qualified Data.Map as M
import Data.Char
import Data.List
import Data.Ord
import Data.Word
-------------------------------------------------------------------------
--
-- Literals
--
-------------------------------------------------------------------------
cgLit :: Literal -> FCode CmmLit
cgLit (MachStr s) = newByteStringCLit (BS.unpack s)
-- not unpackFS; we want the UTF-8 byte stream.
cgLit other_lit = do dflags <- getDynFlags
return (mkSimpleLit dflags other_lit)
mkSimpleLit :: DynFlags -> Literal -> CmmLit
mkSimpleLit dflags (MachChar c) = CmmInt (fromIntegral (ord c)) (wordWidth dflags)
mkSimpleLit dflags MachNullAddr = zeroCLit dflags
mkSimpleLit dflags (MachInt i) = CmmInt i (wordWidth dflags)
mkSimpleLit _ (MachInt64 i) = CmmInt i W64
mkSimpleLit dflags (MachWord i) = CmmInt i (wordWidth dflags)
mkSimpleLit _ (MachWord64 i) = CmmInt i W64
mkSimpleLit _ (MachFloat r) = CmmFloat r W32
mkSimpleLit _ (MachDouble r) = CmmFloat r W64
mkSimpleLit _ (MachLabel fs ms fod)
= CmmLabel (mkForeignLabel fs ms labelSrc fod)
where
-- TODO: Literal labels might not actually be in the current package...
labelSrc = ForeignLabelInThisPackage
mkSimpleLit _ other = pprPanic "mkSimpleLit" (ppr other)
--------------------------------------------------------------------------
--
-- Incrementing a memory location
--
--------------------------------------------------------------------------
addToMemLbl :: CmmType -> CLabel -> Int -> CmmAGraph
addToMemLbl rep lbl n = addToMem rep (CmmLit (CmmLabel lbl)) n
addToMemLblE :: CmmType -> CLabel -> CmmExpr -> CmmAGraph
addToMemLblE rep lbl = addToMemE rep (CmmLit (CmmLabel lbl))
addToMem :: CmmType -- rep of the counter
-> CmmExpr -- Address
-> Int -- What to add (a word)
-> CmmAGraph
addToMem rep ptr n = addToMemE rep ptr (CmmLit (CmmInt (toInteger n) (typeWidth rep)))
addToMemE :: CmmType -- rep of the counter
-> CmmExpr -- Address
-> CmmExpr -- What to add (a word-typed expression)
-> CmmAGraph
addToMemE rep ptr n
= mkStore ptr (CmmMachOp (MO_Add (typeWidth rep)) [CmmLoad ptr rep, n])
-------------------------------------------------------------------------
--
-- Loading a field from an object,
-- where the object pointer is itself tagged
--
-------------------------------------------------------------------------
mkTaggedObjectLoad
:: DynFlags -> LocalReg -> LocalReg -> ByteOff -> DynTag -> CmmAGraph
-- (loadTaggedObjectField reg base off tag) generates assignment
-- reg = bitsK[ base + off - tag ]
-- where K is fixed by 'reg'
mkTaggedObjectLoad dflags reg base offset tag
= mkAssign (CmmLocal reg)
(CmmLoad (cmmOffsetB dflags
(CmmReg (CmmLocal base))
(offset - tag))
(localRegType reg))
-------------------------------------------------------------------------
--
-- Converting a closure tag to a closure for enumeration types
-- (this is the implementation of tagToEnum#).
--
-------------------------------------------------------------------------
tagToClosure :: DynFlags -> TyCon -> CmmExpr -> CmmExpr
tagToClosure dflags tycon tag
= CmmLoad (cmmOffsetExprW dflags closure_tbl tag) (bWord dflags)
where closure_tbl = CmmLit (CmmLabel lbl)
lbl = mkClosureTableLabel (tyConName tycon) NoCafRefs
-------------------------------------------------------------------------
--
-- Conditionals and rts calls
--
-------------------------------------------------------------------------
emitRtsCall :: UnitId -> FastString -> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()
emitRtsCall pkg fun args safe = emitRtsCallGen [] (mkCmmCodeLabel pkg fun) args safe
emitRtsCallWithResult :: LocalReg -> ForeignHint -> UnitId -> FastString
-> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()
emitRtsCallWithResult res hint pkg fun args safe
= emitRtsCallGen [(res,hint)] (mkCmmCodeLabel pkg fun) args safe
-- Make a call to an RTS C procedure
emitRtsCallGen
:: [(LocalReg,ForeignHint)]
-> CLabel
-> [(CmmExpr,ForeignHint)]
-> Bool -- True <=> CmmSafe call
-> FCode ()
emitRtsCallGen res lbl args safe
= do { dflags <- getDynFlags
; updfr_off <- getUpdFrameOff
; let (caller_save, caller_load) = callerSaveVolatileRegs dflags
; emit caller_save
; call updfr_off
; emit caller_load }
where
call updfr_off =
if safe then
emit =<< mkCmmCall fun_expr res' args' updfr_off
else do
let conv = ForeignConvention CCallConv arg_hints res_hints CmmMayReturn
emit $ mkUnsafeCall (ForeignTarget fun_expr conv) res' args'
(args', arg_hints) = unzip args
(res', res_hints) = unzip res
fun_expr = mkLblExpr lbl
-----------------------------------------------------------------------------
--
-- Caller-Save Registers
--
-----------------------------------------------------------------------------
-- Here we generate the sequence of saves/restores required around a
-- foreign call instruction.
-- TODO: reconcile with includes/Regs.h
-- * Regs.h claims that BaseReg should be saved last and loaded first
-- * This might not have been tickled before since BaseReg is callee save
-- * Regs.h saves SparkHd, ParkT1, SparkBase and SparkLim
--
-- This code isn't actually used right now, because callerSaves
-- only ever returns true in the current universe for registers NOT in
-- system_regs (just do a grep for CALLER_SAVES in
-- includes/stg/MachRegs.h). It's all one giant no-op, and for
-- good reason: having to save system registers on every foreign call
-- would be very expensive, so we avoid assigning them to those
-- registers when we add support for an architecture.
--
-- Note that the old code generator actually does more work here: it
-- also saves other global registers. We can't (nor want) to do that
-- here, as we don't have liveness information. And really, we
-- shouldn't be doing the workaround at this point in the pipeline, see
-- Note [Register parameter passing] and the ToDo on CmmCall in
-- cmm/CmmNode.hs. Right now the workaround is to avoid inlining across
-- unsafe foreign calls in rewriteAssignments, but this is strictly
-- temporary.
callerSaveVolatileRegs :: DynFlags -> (CmmAGraph, CmmAGraph)
callerSaveVolatileRegs dflags = (caller_save, caller_load)
where
platform = targetPlatform dflags
caller_save = catAGraphs (map callerSaveGlobalReg regs_to_save)
caller_load = catAGraphs (map callerRestoreGlobalReg regs_to_save)
system_regs = [ Sp,SpLim,Hp,HpLim,CCCS,CurrentTSO,CurrentNursery
{- ,SparkHd,SparkTl,SparkBase,SparkLim -}
, BaseReg ]
regs_to_save = filter (callerSaves platform) system_regs
callerSaveGlobalReg reg
= mkStore (get_GlobalReg_addr dflags reg) (CmmReg (CmmGlobal reg))
callerRestoreGlobalReg reg
= mkAssign (CmmGlobal reg)
(CmmLoad (get_GlobalReg_addr dflags reg) (globalRegType dflags reg))
-- -----------------------------------------------------------------------------
-- Global registers
-- We map STG registers onto appropriate CmmExprs. Either they map
-- to real machine registers or stored as offsets from BaseReg. Given
-- a GlobalReg, get_GlobalReg_addr always produces the
-- register table address for it.
-- (See also get_GlobalReg_reg_or_addr in MachRegs)
get_GlobalReg_addr :: DynFlags -> GlobalReg -> CmmExpr
get_GlobalReg_addr dflags BaseReg = regTableOffset dflags 0
get_GlobalReg_addr dflags mid
= get_Regtable_addr_from_offset dflags
(globalRegType dflags mid) (baseRegOffset dflags mid)
-- Calculate a literal representing an offset into the register table.
-- Used when we don't have an actual BaseReg to offset from.
regTableOffset :: DynFlags -> Int -> CmmExpr
regTableOffset dflags n =
CmmLit (CmmLabelOff mkMainCapabilityLabel (oFFSET_Capability_r dflags + n))
get_Regtable_addr_from_offset :: DynFlags -> CmmType -> Int -> CmmExpr
get_Regtable_addr_from_offset dflags _rep offset =
if haveRegBase (targetPlatform dflags)
then CmmRegOff (CmmGlobal BaseReg) offset
else regTableOffset dflags offset
-- -----------------------------------------------------------------------------
-- Information about global registers
baseRegOffset :: DynFlags -> GlobalReg -> Int
baseRegOffset dflags Sp = oFFSET_StgRegTable_rSp dflags
baseRegOffset dflags SpLim = oFFSET_StgRegTable_rSpLim dflags
baseRegOffset dflags (LongReg 1) = oFFSET_StgRegTable_rL1 dflags
baseRegOffset dflags Hp = oFFSET_StgRegTable_rHp dflags
baseRegOffset dflags HpLim = oFFSET_StgRegTable_rHpLim dflags
baseRegOffset dflags CCCS = oFFSET_StgRegTable_rCCCS dflags
baseRegOffset dflags CurrentTSO = oFFSET_StgRegTable_rCurrentTSO dflags
baseRegOffset dflags CurrentNursery = oFFSET_StgRegTable_rCurrentNursery dflags
baseRegOffset dflags HpAlloc = oFFSET_StgRegTable_rHpAlloc dflags
baseRegOffset dflags GCEnter1 = oFFSET_stgGCEnter1 dflags
baseRegOffset dflags GCFun = oFFSET_stgGCFun dflags
baseRegOffset _ reg = pprPanic "baseRegOffset:" (ppr reg)
-------------------------------------------------------------------------
--
-- Strings generate a top-level data block
--
-------------------------------------------------------------------------
emitDataLits :: CLabel -> [CmmLit] -> FCode ()
-- Emit a data-segment data block
emitDataLits lbl lits = emitDecl (mkDataLits (Section Data lbl) lbl lits)
emitRODataLits :: CLabel -> [CmmLit] -> FCode ()
-- Emit a read-only data block
emitRODataLits lbl lits = emitDecl (mkRODataLits lbl lits)
newStringCLit :: String -> FCode CmmLit
-- Make a global definition for the string,
-- and return its label
newStringCLit str = newByteStringCLit (map (fromIntegral . ord) str)
newByteStringCLit :: [Word8] -> FCode CmmLit
newByteStringCLit bytes
= do { uniq <- newUnique
; let (lit, decl) = mkByteStringCLit uniq bytes
; emitDecl decl
; return lit }
-------------------------------------------------------------------------
--
-- Assigning expressions to temporaries
--
-------------------------------------------------------------------------
assignTemp :: CmmExpr -> FCode LocalReg
-- Make sure the argument is in a local register.
-- We don't bother being particularly aggressive with avoiding
-- unnecessary local registers, since we can rely on a later
-- optimization pass to inline as necessary (and skipping out
-- on things like global registers can be a little dangerous
-- due to them being trashed on foreign calls--though it means
-- the optimization pass doesn't have to do as much work)
assignTemp (CmmReg (CmmLocal reg)) = return reg
assignTemp e = do { dflags <- getDynFlags
; uniq <- newUnique
; let reg = LocalReg uniq (cmmExprType dflags e)
; emitAssign (CmmLocal reg) e
; return reg }
newTemp :: MonadUnique m => CmmType -> m LocalReg
newTemp rep = do { uniq <- getUniqueM
; return (LocalReg uniq rep) }
newUnboxedTupleRegs :: Type -> FCode ([LocalReg], [ForeignHint])
-- Choose suitable local regs to use for the components
-- of an unboxed tuple that we are about to return to
-- the Sequel. If the Sequel is a join point, using the
-- regs it wants will save later assignments.
newUnboxedTupleRegs res_ty
= ASSERT( isUnboxedTupleType res_ty )
do { dflags <- getDynFlags
; sequel <- getSequel
; regs <- choose_regs dflags sequel
; ASSERT( regs `equalLength` reps )
return (regs, map primRepForeignHint reps) }
where
UbxTupleRep ty_args = repType res_ty
reps = [ rep
| ty <- ty_args
, let rep = typePrimRep ty
, not (isVoidRep rep) ]
choose_regs _ (AssignTo regs _) = return regs
choose_regs dflags _ = mapM (newTemp . primRepCmmType dflags) reps
-------------------------------------------------------------------------
-- emitMultiAssign
-------------------------------------------------------------------------
emitMultiAssign :: [LocalReg] -> [CmmExpr] -> FCode ()
-- Emit code to perform the assignments in the
-- input simultaneously, using temporary variables when necessary.
type Key = Int
type Vrtx = (Key, Stmt) -- Give each vertex a unique number,
-- for fast comparison
type Stmt = (LocalReg, CmmExpr) -- r := e
-- We use the strongly-connected component algorithm, in which
-- * the vertices are the statements
-- * an edge goes from s1 to s2 iff
-- s1 assigns to something s2 uses
-- that is, if s1 should *follow* s2 in the final order
emitMultiAssign [] [] = return ()
emitMultiAssign [reg] [rhs] = emitAssign (CmmLocal reg) rhs
emitMultiAssign regs rhss = do
dflags <- getDynFlags
ASSERT( equalLength regs rhss )
unscramble dflags ([1..] `zip` (regs `zip` rhss))
unscramble :: DynFlags -> [Vrtx] -> FCode ()
unscramble dflags vertices = mapM_ do_component components
where
edges :: [ (Vrtx, Key, [Key]) ]
edges = [ (vertex, key1, edges_from stmt1)
| vertex@(key1, stmt1) <- vertices ]
edges_from :: Stmt -> [Key]
edges_from stmt1 = [ key2 | (key2, stmt2) <- vertices,
stmt1 `mustFollow` stmt2 ]
components :: [SCC Vrtx]
components = stronglyConnCompFromEdgedVertices edges
-- do_components deal with one strongly-connected component
-- Not cyclic, or singleton? Just do it
do_component :: SCC Vrtx -> FCode ()
do_component (AcyclicSCC (_,stmt)) = mk_graph stmt
do_component (CyclicSCC []) = panic "do_component"
do_component (CyclicSCC [(_,stmt)]) = mk_graph stmt
-- Cyclic? Then go via temporaries. Pick one to
-- break the loop and try again with the rest.
do_component (CyclicSCC ((_,first_stmt) : rest)) = do
dflags <- getDynFlags
u <- newUnique
let (to_tmp, from_tmp) = split dflags u first_stmt
mk_graph to_tmp
unscramble dflags rest
mk_graph from_tmp
split :: DynFlags -> Unique -> Stmt -> (Stmt, Stmt)
split dflags uniq (reg, rhs)
= ((tmp, rhs), (reg, CmmReg (CmmLocal tmp)))
where
rep = cmmExprType dflags rhs
tmp = LocalReg uniq rep
mk_graph :: Stmt -> FCode ()
mk_graph (reg, rhs) = emitAssign (CmmLocal reg) rhs
mustFollow :: Stmt -> Stmt -> Bool
(reg, _) `mustFollow` (_, rhs) = regUsedIn dflags (CmmLocal reg) rhs
-------------------------------------------------------------------------
-- mkSwitch
-------------------------------------------------------------------------
emitSwitch :: CmmExpr -- Tag to switch on
-> [(ConTagZ, CmmAGraphScoped)] -- Tagged branches
-> Maybe CmmAGraphScoped -- Default branch (if any)
-> ConTagZ -> ConTagZ -- Min and Max possible values;
-- behaviour outside this range is
-- undefined
-> FCode ()
-- First, two rather common cases in which there is no work to do
emitSwitch _ [] (Just code) _ _ = emit (fst code)
emitSwitch _ [(_,code)] Nothing _ _ = emit (fst code)
-- Right, off we go
emitSwitch tag_expr branches mb_deflt lo_tag hi_tag = do
join_lbl <- newLabelC
mb_deflt_lbl <- label_default join_lbl mb_deflt
branches_lbls <- label_branches join_lbl branches
tag_expr' <- assignTemp' tag_expr
-- Sort the branches before calling mk_discrete_switch
let branches_lbls' = [ (fromIntegral i, l) | (i,l) <- sortBy (comparing fst) branches_lbls ]
let range = (fromIntegral lo_tag, fromIntegral hi_tag)
emit $ mk_discrete_switch False tag_expr' branches_lbls' mb_deflt_lbl range
emitLabel join_lbl
mk_discrete_switch :: Bool -- ^ Use signed comparisons
-> CmmExpr
-> [(Integer, BlockId)]
-> Maybe BlockId
-> (Integer, Integer)
-> CmmAGraph
-- SINGLETON TAG RANGE: no case analysis to do
mk_discrete_switch _ _tag_expr [(tag, lbl)] _ (lo_tag, hi_tag)
| lo_tag == hi_tag
= ASSERT( tag == lo_tag )
mkBranch lbl
-- SINGLETON BRANCH, NO DEFAULT: no case analysis to do
mk_discrete_switch _ _tag_expr [(_tag,lbl)] Nothing _
= mkBranch lbl
-- The simplifier might have eliminated a case
-- so we may have e.g. case xs of
-- [] -> e
-- In that situation we can be sure the (:) case
-- can't happen, so no need to test
-- SOMETHING MORE COMPLICATED: defer to CmmImplementSwitchPlans
-- See Note [Cmm Switches, the general plan] in CmmSwitch
mk_discrete_switch signed tag_expr branches mb_deflt range
= mkSwitch tag_expr $ mkSwitchTargets signed range mb_deflt (M.fromList branches)
divideBranches :: Ord a => [(a,b)] -> ([(a,b)], a, [(a,b)])
divideBranches branches = (lo_branches, mid, hi_branches)
where
-- 2 branches => n_branches `div` 2 = 1
-- => branches !! 1 give the *second* tag
-- There are always at least 2 branches here
(mid,_) = branches !! (length branches `div` 2)
(lo_branches, hi_branches) = span is_lo branches
is_lo (t,_) = t < mid
--------------
emitCmmLitSwitch :: CmmExpr -- Tag to switch on
-> [(Literal, CmmAGraphScoped)] -- Tagged branches
-> CmmAGraphScoped -- Default branch (always)
-> FCode () -- Emit the code
emitCmmLitSwitch _scrut [] deflt = emit $ fst deflt
emitCmmLitSwitch scrut branches deflt = do
scrut' <- assignTemp' scrut
join_lbl <- newLabelC
deflt_lbl <- label_code join_lbl deflt
branches_lbls <- label_branches join_lbl branches
dflags <- getDynFlags
let cmm_ty = cmmExprType dflags scrut
rep = typeWidth cmm_ty
-- We find the necessary type information in the literals in the branches
let signed = case head branches of
(MachInt _, _) -> True
(MachInt64 _, _) -> True
_ -> False
let range | signed = (tARGET_MIN_INT dflags, tARGET_MAX_INT dflags)
| otherwise = (0, tARGET_MAX_WORD dflags)
if isFloatType cmm_ty
then emit =<< mk_float_switch rep scrut' deflt_lbl noBound branches_lbls
else emit $ mk_discrete_switch
signed
scrut'
[(litValue lit,l) | (lit,l) <- branches_lbls]
(Just deflt_lbl)
range
emitLabel join_lbl
-- | lower bound (inclusive), upper bound (exclusive)
type LitBound = (Maybe Literal, Maybe Literal)
noBound :: LitBound
noBound = (Nothing, Nothing)
mk_float_switch :: Width -> CmmExpr -> BlockId
-> LitBound
-> [(Literal,BlockId)]
-> FCode CmmAGraph
mk_float_switch rep scrut deflt _bounds [(lit,blk)]
= do dflags <- getDynFlags
return $ mkCbranch (cond dflags) deflt blk Nothing
where
cond dflags = CmmMachOp ne [scrut, CmmLit cmm_lit]
where
cmm_lit = mkSimpleLit dflags lit
ne = MO_F_Ne rep
mk_float_switch rep scrut deflt_blk_id (lo_bound, hi_bound) branches
= do dflags <- getDynFlags
lo_blk <- mk_float_switch rep scrut deflt_blk_id bounds_lo lo_branches
hi_blk <- mk_float_switch rep scrut deflt_blk_id bounds_hi hi_branches
mkCmmIfThenElse (cond dflags) lo_blk hi_blk
where
(lo_branches, mid_lit, hi_branches) = divideBranches branches
bounds_lo = (lo_bound, Just mid_lit)
bounds_hi = (Just mid_lit, hi_bound)
cond dflags = CmmMachOp lt [scrut, CmmLit cmm_lit]
where
cmm_lit = mkSimpleLit dflags mid_lit
lt = MO_F_Lt rep
--------------
label_default :: BlockId -> Maybe CmmAGraphScoped -> FCode (Maybe BlockId)
label_default _ Nothing
= return Nothing
label_default join_lbl (Just code)
= do lbl <- label_code join_lbl code
return (Just lbl)
--------------
label_branches :: BlockId -> [(a,CmmAGraphScoped)] -> FCode [(a,BlockId)]
label_branches _join_lbl []
= return []
label_branches join_lbl ((tag,code):branches)
= do lbl <- label_code join_lbl code
branches' <- label_branches join_lbl branches
return ((tag,lbl):branches')
--------------
label_code :: BlockId -> CmmAGraphScoped -> FCode BlockId
-- label_code J code
-- generates
-- [L: code; goto J]
-- and returns L
label_code join_lbl (code,tsc) = do
lbl <- newLabelC
emitOutOfLine lbl (code MkGraph.<*> mkBranch join_lbl, tsc)
return lbl
--------------
assignTemp' :: CmmExpr -> FCode CmmExpr
assignTemp' e
| isTrivialCmmExpr e = return e
| otherwise = do
dflags <- getDynFlags
lreg <- newTemp (cmmExprType dflags e)
let reg = CmmLocal lreg
emitAssign reg e
return (CmmReg reg)
|
oldmanmike/ghc
|
compiler/codeGen/StgCmmUtils.hs
|
bsd-3-clause
| 23,049 | 0 | 15 | 5,437 | 4,903 | 2,607 | 2,296 | -1 | -1 |
module C where
-- Test file
baz = 13
|
RefactoringTools/HaRe
|
test/testdata/C.hs
|
bsd-3-clause
| 39 | 0 | 4 | 11 | 10 | 7 | 3 | 2 | 1 |
module Meas () where
import Language.Haskell.Liquid.Prelude
mylen :: [a] -> Int
mylen [] = 0
mylen (_:xs) = 1 + mylen xs
mymap f [] = []
mymap f (x:xs) = (f x) : (mymap f xs)
zs :: [Int]
zs = [1..100]
prop2 = liquidAssertB (n1 == n2)
where n1 = mylen zs
n2 = mylen $ mymap (+ 1) zs
|
mightymoose/liquidhaskell
|
tests/pos/meas3.hs
|
bsd-3-clause
| 320 | 0 | 9 | 100 | 168 | 92 | 76 | 12 | 1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, RankNTypes #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.ST
-- Copyright : (c) The University of Glasgow, 1992-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The 'ST' Monad.
--
-----------------------------------------------------------------------------
module GHC.ST (
ST(..), STret(..), STRep,
fixST, runST,
-- * Unsafe functions
liftST, unsafeInterleaveST
) where
import GHC.Base
import GHC.Show
default ()
-- The state-transformer monad proper. By default the monad is strict;
-- too many people got bitten by space leaks when it was lazy.
-- | The strict state-transformer monad.
-- A computation of type @'ST' s a@ transforms an internal state indexed
-- by @s@, and returns a value of type @a@.
-- The @s@ parameter is either
--
-- * an uninstantiated type variable (inside invocations of 'runST'), or
--
-- * 'RealWorld' (inside invocations of 'Control.Monad.ST.stToIO').
--
-- It serves to keep the internal states of different invocations
-- of 'runST' separate from each other and from invocations of
-- 'Control.Monad.ST.stToIO'.
--
-- The '>>=' and '>>' operations are strict in the state (though not in
-- values stored in the state). For example,
--
-- @'runST' (writeSTRef _|_ v >>= f) = _|_@
newtype ST s a = ST (STRep s a)
type STRep s a = State# s -> (# State# s, a #)
instance Functor (ST s) where
fmap f (ST m) = ST $ \ s ->
case (m s) of { (# new_s, r #) ->
(# new_s, f r #) }
instance Applicative (ST s) where
{-# INLINE pure #-}
{-# INLINE (*>) #-}
pure x = ST (\ s -> (# s, x #))
m *> k = m >>= \ _ -> k
(<*>) = ap
instance Monad (ST s) where
{-# INLINE (>>=) #-}
(>>) = (*>)
(ST m) >>= k
= ST (\ s ->
case (m s) of { (# new_s, r #) ->
case (k r) of { ST k2 ->
(k2 new_s) }})
data STret s a = STret (State# s) a
-- liftST is useful when we want a lifted result from an ST computation. See
-- fixST below.
liftST :: ST s a -> State# s -> STret s a
liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
{-# NOINLINE unsafeInterleaveST #-}
unsafeInterleaveST :: ST s a -> ST s a
unsafeInterleaveST (ST m) = ST ( \ s ->
let
r = case m s of (# _, res #) -> res
in
(# s, r #)
)
-- | Allow the result of a state transformer computation to be used (lazily)
-- inside the computation.
-- Note that if @f@ is strict, @'fixST' f = _|_@.
fixST :: (a -> ST s a) -> ST s a
fixST k = ST $ \ s ->
let ans = liftST (k r) s
STret _ r = ans
in
case ans of STret s' x -> (# s', x #)
instance Show (ST s a) where
showsPrec _ _ = showString "<<ST action>>"
showList = showList__ (showsPrec 0)
{-# INLINE runST #-}
-- | Return the value computed by a state transformer computation.
-- The @forall@ ensures that the internal state used by the 'ST'
-- computation is inaccessible to the rest of the program.
runST :: (forall s. ST s a) -> a
runST (ST st_rep) = case runRW# st_rep of (# _, a #) -> a
-- See Note [Definition of runRW#] in GHC.Magic
|
tolysz/prepare-ghcjs
|
spec-lts8/base/GHC/ST.hs
|
bsd-3-clause
| 3,357 | 0 | 16 | 826 | 736 | 414 | 322 | 50 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Generate HPC (Haskell Program Coverage) reports
module Stack.Build.Coverage
( generateHpcReport
, generateHpcMarkupIndex
) where
import Control.Applicative
import Control.Exception.Lifted
import Control.Monad (liftM)
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as S8
import Data.Foldable (forM_)
import Data.Function
import Data.List
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as LT
import Data.Traversable (forM)
import Path
import Path.IO
import Prelude hiding (FilePath, writeFile)
import Stack.Constants
import Stack.Types
import System.Process.Read
import Text.Hastache (htmlEscape)
-- | Generates the HTML coverage report and shows a textual coverage
-- summary.
generateHpcReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env)
=> Path Abs Dir -> Text -> Text -> Text -> m ()
generateHpcReport pkgDir pkgName pkgId testName = do
let whichTest = pkgName <> "'s test-suite \"" <> testName <> "\""
-- Compute destination directory.
installDir <- installationRootLocal
testNamePath <- parseRelDir (T.unpack testName)
pkgIdPath <- parseRelDir (T.unpack pkgId)
let destDir = installDir </> hpcDirSuffix </> pkgIdPath </> testNamePath
-- Directories for .mix files.
hpcDir <- hpcDirFromDir pkgDir
hpcRelDir <- (</> dotHpc) <$> hpcRelativeDir
-- Compute arguments used for both "hpc markup" and "hpc report".
pkgDirs <- Map.keys . envConfigPackages <$> asks getEnvConfig
let args =
-- Use index files from all packages (allows cross-package
-- coverage results).
concatMap (\x -> ["--srcdir", toFilePath x]) pkgDirs ++
-- Look for index files in the correct dir (relative to
-- each pkgdir).
["--hpcdir", toFilePath hpcRelDir, "--reset-hpcdirs"
-- Restrict to just the current library code (see #634 -
-- this will likely be customizable in the future)
,"--include", T.unpack (pkgId <> ":")]
-- If a .tix file exists, generate an HPC report for it.
tixFile <- parseRelFile (T.unpack testName ++ ".tix")
let tixFileAbs = hpcDir </> tixFile
tixFileExists <- fileExists tixFileAbs
if not tixFileExists
then $logError $ T.concat
[ "Didn't find .tix coverage file for "
, whichTest
, " - expected to find it at "
, T.pack (toFilePath tixFileAbs)
, "."
]
else (`onException` $logError ("Error occurred while producing coverage report for " <> whichTest)) $ do
menv <- getMinimalEnvOverride
$logInfo $ "Generating HTML coverage report for " <> whichTest
_ <- readProcessStdout (Just hpcDir) menv "hpc"
("markup" : toFilePath tixFileAbs : ("--destdir=" ++ toFilePath destDir) : args)
output <- readProcessStdout (Just hpcDir) menv "hpc"
("report" : toFilePath tixFileAbs : args)
-- Print output, stripping @\r@ characters because
-- Windows.
forM_ (S8.lines output) ($logInfo . T.decodeUtf8 . S8.filter (not . (=='\r')))
$logInfo
("The HTML coverage report for " <> whichTest <> " is available at " <>
T.pack (toFilePath (destDir </> $(mkRelFile "hpc_index.html"))))
generateHpcMarkupIndex :: (MonadIO m,MonadReader env m,MonadLogger m,MonadCatch m,HasEnvConfig env)
=> m ()
generateHpcMarkupIndex = do
installDir <- installationRootLocal
let markupDir = installDir </> hpcDirSuffix
outputFile = markupDir </> $(mkRelFile "index.html")
(dirs, _) <- listDirectory markupDir
rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do
(subdirs, _) <- listDirectory dir
forM subdirs $ \subdir -> do
let indexPath = subdir </> $(mkRelFile "hpc_index.html")
exists <- fileExists indexPath
if not exists then return Nothing else do
relPath <- stripDir markupDir indexPath
let package = dirname dir
testsuite = dirname subdir
return $ Just $ T.concat
[ "<tr><td>"
, pathToHtml package
, "</td><td><a href=\""
, pathToHtml relPath
, "\">"
, pathToHtml testsuite
, "</a></td></tr>"
]
liftIO $ T.writeFile (toFilePath outputFile) $ T.concat $
[ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
-- Part of the css from HPC's output HTML
, "<style type=\"text/css\">"
, "table.dashboard { border-collapse: collapse; border: solid 1px black }"
, ".dashboard td { border: solid 1px black }"
, ".dashboard th { border: solid 1px black }"
, "</style>"
, "</head>"
, "<body>"
] ++
(if null rows
then
[ "<b>No hpc_index.html files found in \""
, pathToHtml markupDir
, "\".</b>"
]
else
[ "<table class=\"dashboard\" width=\"100%\" boder=\"1\"><tbody>"
, "<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>"
, "<tr><th>Package</th><th>TestSuite</th></tr>"
] ++
rows ++
["</tbody></table>"]) ++
["</body></html>"]
$logInfo $ "\nAn index of the generated HTML coverage reports is available at " <>
T.pack (toFilePath outputFile)
pathToHtml :: Path b t -> Text
pathToHtml = T.dropWhileEnd (=='/') . LT.toStrict . htmlEscape . LT.pack . toFilePath
|
akhileshs/stack
|
src/Stack/Build/Coverage.hs
|
bsd-3-clause
| 6,914 | 0 | 22 | 2,288 | 1,332 | 711 | 621 | 121 | 3 |
{-# LANGUAGE CPP, RecordWildCards #-}
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation:
--
-- The types LambdaFormInfo
-- ClosureInfo
--
-- Nothing monadic in here!
--
-----------------------------------------------------------------------------
module StgCmmClosure (
DynTag, tagForCon, isSmallFamily,
ConTagZ, dataConTagZ,
idPrimRep, isVoidRep, isGcPtrRep, addIdReps, addArgReps,
argPrimRep,
-- * LambdaFormInfo
LambdaFormInfo, -- Abstract
StandardFormInfo, -- ...ditto...
mkLFThunk, mkLFReEntrant, mkConLFInfo, mkSelectorLFInfo,
mkApLFInfo, mkLFImported, mkLFArgument, mkLFLetNoEscape,
lfDynTag,
maybeIsLFCon, isLFThunk, isLFReEntrant, lfUpdatable,
-- * Used by other modules
CgLoc(..), SelfLoopInfo, CallMethod(..),
nodeMustPointToIt, isKnownFun, funTag, tagForArity, getCallMethod,
-- * ClosureInfo
ClosureInfo,
mkClosureInfo,
mkCmmInfo,
-- ** Inspection
closureLFInfo, closureName,
-- ** Labels
-- These just need the info table label
closureInfoLabel, staticClosureLabel,
closureSlowEntryLabel, closureLocalEntryLabel,
-- ** Predicates
-- These are really just functions on LambdaFormInfo
closureUpdReqd, closureSingleEntry,
closureReEntrant, closureFunInfo,
isToplevClosure,
blackHoleOnEntry, -- Needs LambdaFormInfo and SMRep
isStaticClosure, -- Needs SMPre
-- * InfoTables
mkDataConInfoTable,
cafBlackHoleInfoTable,
indStaticInfoTable,
staticClosureNeedsLink,
) where
#include "../includes/MachDeps.h"
#define FAST_STRING_NOT_NEEDED
#include "HsVersions.h"
import StgSyn
import SMRep
import Cmm
import PprCmmExpr()
import BlockId
import CLabel
import Id
import IdInfo
import DataCon
import FastString
import Name
import Type
import TypeRep
import TcType
import TyCon
import BasicTypes
import Outputable
import DynFlags
import Util
-----------------------------------------------------------------------------
-- Data types and synonyms
-----------------------------------------------------------------------------
-- These data types are mostly used by other modules, especially StgCmmMonad,
-- but we define them here because some functions in this module need to
-- have access to them as well
data CgLoc
= CmmLoc CmmExpr -- A stable CmmExpr; that is, one not mentioning
-- Hp, so that it remains valid across calls
| LneLoc BlockId [LocalReg] -- A join point
-- A join point (= let-no-escape) should only
-- be tail-called, and in a saturated way.
-- To tail-call it, assign to these locals,
-- and branch to the block id
instance Outputable CgLoc where
ppr (CmmLoc e) = ptext (sLit "cmm") <+> ppr e
ppr (LneLoc b rs) = ptext (sLit "lne") <+> ppr b <+> ppr rs
type SelfLoopInfo = (Id, BlockId, [LocalReg])
-- used by ticky profiling
isKnownFun :: LambdaFormInfo -> Bool
isKnownFun (LFReEntrant _ _ _ _) = True
isKnownFun LFLetNoEscape = True
isKnownFun _ = False
-----------------------------------------------------------------------------
-- Representations
-----------------------------------------------------------------------------
-- Why are these here?
idPrimRep :: Id -> PrimRep
idPrimRep id = typePrimRep (idType id)
-- NB: typePrimRep fails on unboxed tuples,
-- but by StgCmm no Ids have unboxed tuple type
addIdReps :: [Id] -> [(PrimRep, Id)]
addIdReps ids = [(idPrimRep id, id) | id <- ids]
addArgReps :: [StgArg] -> [(PrimRep, StgArg)]
addArgReps args = [(argPrimRep arg, arg) | arg <- args]
argPrimRep :: StgArg -> PrimRep
argPrimRep arg = typePrimRep (stgArgType arg)
-----------------------------------------------------------------------------
-- LambdaFormInfo
-----------------------------------------------------------------------------
-- Information about an identifier, from the code generator's point of
-- view. Every identifier is bound to a LambdaFormInfo in the
-- environment, which gives the code generator enough info to be able to
-- tail call or return that identifier.
data LambdaFormInfo
= LFReEntrant -- Reentrant closure (a function)
TopLevelFlag -- True if top level
!RepArity -- Arity. Invariant: always > 0
!Bool -- True <=> no fvs
ArgDescr -- Argument descriptor (should really be in ClosureInfo)
| LFThunk -- Thunk (zero arity)
TopLevelFlag
!Bool -- True <=> no free vars
!Bool -- True <=> updatable (i.e., *not* single-entry)
StandardFormInfo
!Bool -- True <=> *might* be a function type
| LFCon -- A saturated constructor application
DataCon -- The constructor
| LFUnknown -- Used for function arguments and imported things.
-- We know nothing about this closure.
-- Treat like updatable "LFThunk"...
-- Imported things which we *do* know something about use
-- one of the other LF constructors (eg LFReEntrant for
-- known functions)
!Bool -- True <=> *might* be a function type
-- The False case is good when we want to enter it,
-- because then we know the entry code will do
-- For a function, the entry code is the fast entry point
| LFUnLifted -- A value of unboxed type;
-- always a value, needs evaluation
| LFLetNoEscape -- See LetNoEscape module for precise description
-------------------------
-- StandardFormInfo tells whether this thunk has one of
-- a small number of standard forms
data StandardFormInfo
= NonStandardThunk
-- The usual case: not of the standard forms
| SelectorThunk
-- A SelectorThunk is of form
-- case x of
-- con a1,..,an -> ak
-- and the constructor is from a single-constr type.
WordOff -- 0-origin offset of ak within the "goods" of
-- constructor (Recall that the a1,...,an may be laid
-- out in the heap in a non-obvious order.)
| ApThunk
-- An ApThunk is of form
-- x1 ... xn
-- The code for the thunk just pushes x2..xn on the stack and enters x1.
-- There are a few of these (for 1 <= n <= MAX_SPEC_AP_SIZE) pre-compiled
-- in the RTS to save space.
RepArity -- Arity, n
------------------------------------------------------
-- Building LambdaFormInfo
------------------------------------------------------
mkLFArgument :: Id -> LambdaFormInfo
mkLFArgument id
| isUnLiftedType ty = LFUnLifted
| might_be_a_function ty = LFUnknown True
| otherwise = LFUnknown False
where
ty = idType id
-------------
mkLFLetNoEscape :: LambdaFormInfo
mkLFLetNoEscape = LFLetNoEscape
-------------
mkLFReEntrant :: TopLevelFlag -- True of top level
-> [Id] -- Free vars
-> [Id] -- Args
-> ArgDescr -- Argument descriptor
-> LambdaFormInfo
mkLFReEntrant top fvs args arg_descr
= LFReEntrant top (length args) (null fvs) arg_descr
-------------
mkLFThunk :: Type -> TopLevelFlag -> [Id] -> UpdateFlag -> LambdaFormInfo
mkLFThunk thunk_ty top fvs upd_flag
= ASSERT( not (isUpdatable upd_flag) || not (isUnLiftedType thunk_ty) )
LFThunk top (null fvs)
(isUpdatable upd_flag)
NonStandardThunk
(might_be_a_function thunk_ty)
--------------
might_be_a_function :: Type -> Bool
-- Return False only if we are *sure* it's a data type
-- Look through newtypes etc as much as poss
might_be_a_function ty
| UnaryRep rep <- repType ty
, Just tc <- tyConAppTyCon_maybe rep
, isDataTyCon tc
= False
| otherwise
= True
-------------
mkConLFInfo :: DataCon -> LambdaFormInfo
mkConLFInfo con = LFCon con
-------------
mkSelectorLFInfo :: Id -> Int -> Bool -> LambdaFormInfo
mkSelectorLFInfo id offset updatable
= LFThunk NotTopLevel False updatable (SelectorThunk offset)
(might_be_a_function (idType id))
-------------
mkApLFInfo :: Id -> UpdateFlag -> Arity -> LambdaFormInfo
mkApLFInfo id upd_flag arity
= LFThunk NotTopLevel (arity == 0) (isUpdatable upd_flag) (ApThunk arity)
(might_be_a_function (idType id))
-------------
mkLFImported :: Id -> LambdaFormInfo
mkLFImported id
| Just con <- isDataConWorkId_maybe id
, isNullaryRepDataCon con
= LFCon con -- An imported nullary constructor
-- We assume that the constructor is evaluated so that
-- the id really does point directly to the constructor
| arity > 0
= LFReEntrant TopLevel arity True (panic "arg_descr")
| otherwise
= mkLFArgument id -- Not sure of exact arity
where
arity = idRepArity id
-----------------------------------------------------
-- Dynamic pointer tagging
-----------------------------------------------------
type ConTagZ = Int -- A *zero-indexed* contructor tag
type DynTag = Int -- The tag on a *pointer*
-- (from the dynamic-tagging paper)
-- Note [Data constructor dynamic tags]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- The family size of a data type (the number of constructors
-- or the arity of a function) can be either:
-- * small, if the family size < 2**tag_bits
-- * big, otherwise.
--
-- Small families can have the constructor tag in the tag bits.
-- Big families only use the tag value 1 to represent evaluatedness.
-- We don't have very many tag bits: for example, we have 2 bits on
-- x86-32 and 3 bits on x86-64.
isSmallFamily :: DynFlags -> Int -> Bool
isSmallFamily dflags fam_size = fam_size <= mAX_PTR_TAG dflags
-- We keep the *zero-indexed* tag in the srt_len field of the info
-- table of a data constructor.
dataConTagZ :: DataCon -> ConTagZ
dataConTagZ con = dataConTag con - fIRST_TAG
tagForCon :: DynFlags -> DataCon -> DynTag
tagForCon dflags con
| isSmallFamily dflags fam_size = con_tag + 1
| otherwise = 1
where
con_tag = dataConTagZ con
fam_size = tyConFamilySize (dataConTyCon con)
tagForArity :: DynFlags -> RepArity -> DynTag
tagForArity dflags arity
| isSmallFamily dflags arity = arity
| otherwise = 0
lfDynTag :: DynFlags -> LambdaFormInfo -> DynTag
-- Return the tag in the low order bits of a variable bound
-- to this LambdaForm
lfDynTag dflags (LFCon con) = tagForCon dflags con
lfDynTag dflags (LFReEntrant _ arity _ _) = tagForArity dflags arity
lfDynTag _ _other = 0
-----------------------------------------------------------------------------
-- Observing LambdaFormInfo
-----------------------------------------------------------------------------
-------------
maybeIsLFCon :: LambdaFormInfo -> Maybe DataCon
maybeIsLFCon (LFCon con) = Just con
maybeIsLFCon _ = Nothing
------------
isLFThunk :: LambdaFormInfo -> Bool
isLFThunk (LFThunk {}) = True
isLFThunk _ = False
isLFReEntrant :: LambdaFormInfo -> Bool
isLFReEntrant (LFReEntrant {}) = True
isLFReEntrant _ = False
-----------------------------------------------------------------------------
-- Choosing SM reps
-----------------------------------------------------------------------------
lfClosureType :: LambdaFormInfo -> ClosureTypeInfo
lfClosureType (LFReEntrant _ arity _ argd) = Fun arity argd
lfClosureType (LFCon con) = Constr (dataConTagZ con)
(dataConIdentity con)
lfClosureType (LFThunk _ _ _ is_sel _) = thunkClosureType is_sel
lfClosureType _ = panic "lfClosureType"
thunkClosureType :: StandardFormInfo -> ClosureTypeInfo
thunkClosureType (SelectorThunk off) = ThunkSelector off
thunkClosureType _ = Thunk
-- We *do* get non-updatable top-level thunks sometimes. eg. f = g
-- gets compiled to a jump to g (if g has non-zero arity), instead of
-- messing around with update frames and PAPs. We set the closure type
-- to FUN_STATIC in this case.
-----------------------------------------------------------------------------
-- nodeMustPointToIt
-----------------------------------------------------------------------------
nodeMustPointToIt :: DynFlags -> LambdaFormInfo -> Bool
-- If nodeMustPointToIt is true, then the entry convention for
-- this closure has R1 (the "Node" register) pointing to the
-- closure itself --- the "self" argument
nodeMustPointToIt _ (LFReEntrant top _ no_fvs _)
= not no_fvs -- Certainly if it has fvs we need to point to it
|| isNotTopLevel top -- See Note [GC recovery]
-- For lex_profiling we also access the cost centre for a
-- non-inherited (i.e. non-top-level) function.
-- The isNotTopLevel test above ensures this is ok.
nodeMustPointToIt dflags (LFThunk top no_fvs updatable NonStandardThunk _)
= not no_fvs -- Self parameter
|| isNotTopLevel top -- Note [GC recovery]
|| updatable -- Need to push update frame
|| gopt Opt_SccProfilingOn dflags
-- For the non-updatable (single-entry case):
--
-- True if has fvs (in which case we need access to them, and we
-- should black-hole it)
-- or profiling (in which case we need to recover the cost centre
-- from inside it) ToDo: do we need this even for
-- top-level thunks? If not,
-- isNotTopLevel subsumes this
nodeMustPointToIt _ (LFThunk {}) -- Node must point to a standard-form thunk
= True
nodeMustPointToIt _ (LFCon _) = True
-- Strictly speaking, the above two don't need Node to point
-- to it if the arity = 0. But this is a *really* unlikely
-- situation. If we know it's nil (say) and we are entering
-- it. Eg: let x = [] in x then we will certainly have inlined
-- x, since nil is a simple atom. So we gain little by not
-- having Node point to known zero-arity things. On the other
-- hand, we do lose something; Patrick's code for figuring out
-- when something has been updated but not entered relies on
-- having Node point to the result of an update. SLPJ
-- 27/11/92.
nodeMustPointToIt _ (LFUnknown _) = True
nodeMustPointToIt _ LFUnLifted = False
nodeMustPointToIt _ LFLetNoEscape = False
{- Note [GC recovery]
~~~~~~~~~~~~~~~~~~~~~
If we a have a local let-binding (function or thunk)
let f = <body> in ...
AND <body> allocates, then the heap-overflow check needs to know how
to re-start the evaluation. It uses the "self" pointer to do this.
So even if there are no free variables in <body>, we still make
nodeMustPointToIt be True for non-top-level bindings.
Why do any such bindings exist? After all, let-floating should have
floated them out. Well, a clever optimiser might leave one there to
avoid a space leak, deliberately recomputing a thunk. Also (and this
really does happen occasionally) let-floating may make a function f smaller
so it can be inlined, so now (f True) may generate a local no-fv closure.
This actually happened during bootsrapping GHC itself, with f=mkRdrFunBind
in TcGenDeriv.) -}
-----------------------------------------------------------------------------
-- getCallMethod
-----------------------------------------------------------------------------
{- The entry conventions depend on the type of closure being entered,
whether or not it has free variables, and whether we're running
sequentially or in parallel.
Closure Node Argument Enter
Characteristics Par Req'd Passing Via
---------------------------------------------------------------------------
Unknown & no & yes & stack & node
Known fun (>1 arg), no fvs & no & no & registers & fast entry (enough args)
& slow entry (otherwise)
Known fun (>1 arg), fvs & no & yes & registers & fast entry (enough args)
0 arg, no fvs \r,\s & no & no & n/a & direct entry
0 arg, no fvs \u & no & yes & n/a & node
0 arg, fvs \r,\s,selector & no & yes & n/a & node
0 arg, fvs \r,\s & no & yes & n/a & direct entry
0 arg, fvs \u & no & yes & n/a & node
Unknown & yes & yes & stack & node
Known fun (>1 arg), no fvs & yes & no & registers & fast entry (enough args)
& slow entry (otherwise)
Known fun (>1 arg), fvs & yes & yes & registers & node
0 arg, fvs \r,\s,selector & yes & yes & n/a & node
0 arg, no fvs \r,\s & yes & no & n/a & direct entry
0 arg, no fvs \u & yes & yes & n/a & node
0 arg, fvs \r,\s & yes & yes & n/a & node
0 arg, fvs \u & yes & yes & n/a & node
When black-holing, single-entry closures could also be entered via node
(rather than directly) to catch double-entry. -}
data CallMethod
= EnterIt -- No args, not a function
| JumpToIt BlockId [LocalReg] -- A join point or a header of a local loop
| ReturnIt -- It's a value (function, unboxed value,
-- or constructor), so just return it.
| SlowCall -- Unknown fun, or known fun with
-- too few args.
| DirectEntry -- Jump directly, with args in regs
CLabel -- The code label
RepArity -- Its arity
getCallMethod :: DynFlags
-> Name -- Function being applied
-> Id -- Function Id used to chech if it can refer to
-- CAF's and whether the function is tail-calling
-- itself
-> LambdaFormInfo -- Its info
-> RepArity -- Number of available arguments
-> CgLoc -- Passed in from cgIdApp so that we can
-- handle let-no-escape bindings and self-recursive
-- tail calls using the same data constructor,
-- JumpToIt. This saves us one case branch in
-- cgIdApp
-> Maybe SelfLoopInfo -- can we perform a self-recursive tail call?
-> CallMethod
getCallMethod dflags _ id _ n_args _cg_loc (Just (self_loop_id, block_id, args))
| gopt Opt_Loopification dflags, id == self_loop_id, n_args == length args
-- If these patterns match then we know that:
-- * loopification optimisation is turned on
-- * function is performing a self-recursive call in a tail position
-- * number of parameters of the function matches functions arity.
-- See Note [Self-recursive tail calls] in StgCmmExpr for more details
= JumpToIt block_id args
getCallMethod dflags _name _ lf_info _n_args _cg_loc _self_loop_info
| nodeMustPointToIt dflags lf_info && gopt Opt_Parallel dflags
= -- If we're parallel, then we must always enter via node.
-- The reason is that the closure may have been
-- fetched since we allocated it.
EnterIt
getCallMethod dflags name id (LFReEntrant _ arity _ _) n_args _cg_loc
_self_loop_info
| n_args == 0 = ASSERT( arity /= 0 )
ReturnIt -- No args at all
| n_args < arity = SlowCall -- Not enough args
| otherwise = DirectEntry (enterIdLabel dflags name (idCafInfo id)) arity
getCallMethod _ _name _ LFUnLifted n_args _cg_loc _self_loop_info
= ASSERT( n_args == 0 ) ReturnIt
getCallMethod _ _name _ (LFCon _) n_args _cg_loc _self_loop_info
= ASSERT( n_args == 0 ) ReturnIt
getCallMethod dflags name id (LFThunk _ _ updatable std_form_info is_fun)
n_args _cg_loc _self_loop_info
| is_fun -- it *might* be a function, so we must "call" it (which is always safe)
= SlowCall -- We cannot just enter it [in eval/apply, the entry code
-- is the fast-entry code]
-- Since is_fun is False, we are *definitely* looking at a data value
| updatable || gopt Opt_Ticky dflags -- to catch double entry
{- OLD: || opt_SMP
I decided to remove this, because in SMP mode it doesn't matter
if we enter the same thunk multiple times, so the optimisation
of jumping directly to the entry code is still valid. --SDM
-}
= EnterIt
-- even a non-updatable selector thunk can be updated by the garbage
-- collector, so we must enter it. (#8817)
| SelectorThunk{} <- std_form_info
= EnterIt
-- We used to have ASSERT( n_args == 0 ), but actually it is
-- possible for the optimiser to generate
-- let bot :: Int = error Int "urk"
-- in (bot `cast` unsafeCoerce Int (Int -> Int)) 3
-- This happens as a result of the case-of-error transformation
-- So the right thing to do is just to enter the thing
| otherwise -- Jump direct to code for single-entry thunks
= ASSERT( n_args == 0 )
DirectEntry (thunkEntryLabel dflags name (idCafInfo id) std_form_info
updatable) 0
getCallMethod _ _name _ (LFUnknown True) _n_arg _cg_locs _self_loop_info
= SlowCall -- might be a function
getCallMethod _ name _ (LFUnknown False) n_args _cg_loc _self_loop_info
= ASSERT2( n_args == 0, ppr name <+> ppr n_args )
EnterIt -- Not a function
getCallMethod _ _name _ LFLetNoEscape _n_args (LneLoc blk_id lne_regs)
_self_loop_info
= JumpToIt blk_id lne_regs
getCallMethod _ _ _ _ _ _ _ = panic "Unknown call method"
-----------------------------------------------------------------------------
-- staticClosureRequired
-----------------------------------------------------------------------------
{- staticClosureRequired is never called (hence commented out)
SimonMar writes (Sept 07) It's an optimisation we used to apply at
one time, I believe, but it got lost probably in the rewrite of
the RTS/code generator. I left that code there to remind me to
look into whether it was worth doing sometime
{- Avoiding generating entries and info tables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At present, for every function we generate all of the following,
just in case. But they aren't always all needed, as noted below:
[NB1: all of this applies only to *functions*. Thunks always
have closure, info table, and entry code.]
[NB2: All are needed if the function is *exported*, just to play safe.]
* Fast-entry code ALWAYS NEEDED
* Slow-entry code
Needed iff (a) we have any un-saturated calls to the function
OR (b) the function is passed as an arg
OR (c) we're in the parallel world and the function has free vars
[Reason: in parallel world, we always enter functions
with free vars via the closure.]
* The function closure
Needed iff (a) we have any un-saturated calls to the function
OR (b) the function is passed as an arg
OR (c) if the function has free vars (ie not top level)
Why case (a) here? Because if the arg-satis check fails,
UpdatePAP stuffs a pointer to the function closure in the PAP.
[Could be changed; UpdatePAP could stuff in a code ptr instead,
but doesn't seem worth it.]
[NB: these conditions imply that we might need the closure
without the slow-entry code. Here's how.
f x y = let g w = ...x..y..w...
in
...(g t)...
Here we need a closure for g which contains x and y,
but since the calls are all saturated we just jump to the
fast entry point for g, with R1 pointing to the closure for g.]
* Standard info table
Needed iff (a) we have any un-saturated calls to the function
OR (b) the function is passed as an arg
OR (c) the function has free vars (ie not top level)
NB. In the sequential world, (c) is only required so that the function closure has
an info table to point to, to keep the storage manager happy.
If (c) alone is true we could fake up an info table by choosing
one of a standard family of info tables, whose entry code just
bombs out.
[NB In the parallel world (c) is needed regardless because
we enter functions with free vars via the closure.]
If (c) is retained, then we'll sometimes generate an info table
(for storage mgr purposes) without slow-entry code. Then we need
to use an error label in the info table to substitute for the absent
slow entry code.
-}
staticClosureRequired
:: Name
-> StgBinderInfo
-> LambdaFormInfo
-> Bool
staticClosureRequired binder bndr_info
(LFReEntrant top_level _ _ _) -- It's a function
= ASSERT( isTopLevel top_level )
-- Assumption: it's a top-level, no-free-var binding
not (satCallsOnly bndr_info)
staticClosureRequired binder other_binder_info other_lf_info = True
-}
-----------------------------------------------------------------------------
-- Data types for closure information
-----------------------------------------------------------------------------
{- ClosureInfo: information about a binding
We make a ClosureInfo for each let binding (both top level and not),
but not bindings for data constructors: for those we build a CmmInfoTable
directly (see mkDataConInfoTable).
To a first approximation:
ClosureInfo = (LambdaFormInfo, CmmInfoTable)
A ClosureInfo has enough information
a) to construct the info table itself, and build other things
related to the binding (e.g. slow entry points for a function)
b) to allocate a closure containing that info pointer (i.e.
it knows the info table label)
-}
data ClosureInfo
= ClosureInfo {
closureName :: !Name, -- The thing bound to this closure
-- we don't really need this field: it's only used in generating
-- code for ticky and profiling, and we could pass the information
-- around separately, but it doesn't do much harm to keep it here.
closureLFInfo :: !LambdaFormInfo, -- NOTE: not an LFCon
-- this tells us about what the closure contains: it's right-hand-side.
-- the rest is just an unpacked CmmInfoTable.
closureInfoLabel :: !CLabel,
closureSMRep :: !SMRep, -- representation used by storage mgr
closureProf :: !ProfilingInfo
}
-- | Convert from 'ClosureInfo' to 'CmmInfoTable'.
mkCmmInfo :: ClosureInfo -> CmmInfoTable
mkCmmInfo ClosureInfo {..}
= CmmInfoTable { cit_lbl = closureInfoLabel
, cit_rep = closureSMRep
, cit_prof = closureProf
, cit_srt = NoC_SRT }
--------------------------------------
-- Building ClosureInfos
--------------------------------------
mkClosureInfo :: DynFlags
-> Bool -- Is static
-> Id
-> LambdaFormInfo
-> Int -> Int -- Total and pointer words
-> String -- String descriptor
-> ClosureInfo
mkClosureInfo dflags is_static id lf_info tot_wds ptr_wds val_descr
= ClosureInfo { closureName = name
, closureLFInfo = lf_info
, closureInfoLabel = info_lbl -- These three fields are
, closureSMRep = sm_rep -- (almost) an info table
, closureProf = prof } -- (we don't have an SRT yet)
where
name = idName id
sm_rep = mkHeapRep dflags is_static ptr_wds nonptr_wds (lfClosureType lf_info)
prof = mkProfilingInfo dflags id val_descr
nonptr_wds = tot_wds - ptr_wds
info_lbl = mkClosureInfoTableLabel id lf_info
--------------------------------------
-- Other functions over ClosureInfo
--------------------------------------
-- Eager blackholing is normally disabled, but can be turned on with
-- -feager-blackholing. When it is on, we replace the info pointer of
-- the thunk with stg_EAGER_BLACKHOLE_info on entry.
-- If we wanted to do eager blackholing with slop filling,
-- we'd need to do it at the *end* of a basic block, otherwise
-- we overwrite the free variables in the thunk that we still
-- need. We have a patch for this from Andy Cheadle, but not
-- incorporated yet. --SDM [6/2004]
--
--
-- Previously, eager blackholing was enabled when ticky-ticky
-- was on. But it didn't work, and it wasn't strictly necessary
-- to bring back minimal ticky-ticky, so now EAGER_BLACKHOLING
-- is unconditionally disabled. -- krc 1/2007
-- Static closures are never themselves black-holed.
blackHoleOnEntry :: ClosureInfo -> Bool
blackHoleOnEntry cl_info
| isStaticRep (closureSMRep cl_info)
= False -- Never black-hole a static closure
| otherwise
= case closureLFInfo cl_info of
LFReEntrant _ _ _ _ -> False
LFLetNoEscape -> False
LFThunk _ _no_fvs _updatable _ _ -> True
_other -> panic "blackHoleOnEntry" -- Should never happen
isStaticClosure :: ClosureInfo -> Bool
isStaticClosure cl_info = isStaticRep (closureSMRep cl_info)
closureUpdReqd :: ClosureInfo -> Bool
closureUpdReqd ClosureInfo{ closureLFInfo = lf_info } = lfUpdatable lf_info
lfUpdatable :: LambdaFormInfo -> Bool
lfUpdatable (LFThunk _ _ upd _ _) = upd
lfUpdatable _ = False
closureSingleEntry :: ClosureInfo -> Bool
closureSingleEntry (ClosureInfo { closureLFInfo = LFThunk _ _ upd _ _}) = not upd
closureSingleEntry _ = False
closureReEntrant :: ClosureInfo -> Bool
closureReEntrant (ClosureInfo { closureLFInfo = LFReEntrant _ _ _ _ }) = True
closureReEntrant _ = False
closureFunInfo :: ClosureInfo -> Maybe (RepArity, ArgDescr)
closureFunInfo (ClosureInfo { closureLFInfo = lf_info }) = lfFunInfo lf_info
lfFunInfo :: LambdaFormInfo -> Maybe (RepArity, ArgDescr)
lfFunInfo (LFReEntrant _ arity _ arg_desc) = Just (arity, arg_desc)
lfFunInfo _ = Nothing
funTag :: DynFlags -> ClosureInfo -> DynTag
funTag dflags (ClosureInfo { closureLFInfo = lf_info })
= lfDynTag dflags lf_info
isToplevClosure :: ClosureInfo -> Bool
isToplevClosure (ClosureInfo { closureLFInfo = lf_info })
= case lf_info of
LFReEntrant TopLevel _ _ _ -> True
LFThunk TopLevel _ _ _ _ -> True
_other -> False
--------------------------------------
-- Label generation
--------------------------------------
staticClosureLabel :: ClosureInfo -> CLabel
staticClosureLabel = toClosureLbl . closureInfoLabel
closureSlowEntryLabel :: ClosureInfo -> CLabel
closureSlowEntryLabel = toSlowEntryLbl . closureInfoLabel
closureLocalEntryLabel :: DynFlags -> ClosureInfo -> CLabel
closureLocalEntryLabel dflags
| tablesNextToCode dflags = toInfoLbl . closureInfoLabel
| otherwise = toEntryLbl . closureInfoLabel
mkClosureInfoTableLabel :: Id -> LambdaFormInfo -> CLabel
mkClosureInfoTableLabel id lf_info
= case lf_info of
LFThunk _ _ upd_flag (SelectorThunk offset) _
-> mkSelectorInfoLabel upd_flag offset
LFThunk _ _ upd_flag (ApThunk arity) _
-> mkApInfoTableLabel upd_flag arity
LFThunk{} -> std_mk_lbl name cafs
LFReEntrant{} -> std_mk_lbl name cafs
_other -> panic "closureInfoTableLabel"
where
name = idName id
std_mk_lbl | is_local = mkLocalInfoTableLabel
| otherwise = mkInfoTableLabel
cafs = idCafInfo id
is_local = isDataConWorkId id
-- Make the _info pointer for the implicit datacon worker
-- binding local. The reason we can do this is that importing
-- code always either uses the _closure or _con_info. By the
-- invariants in CorePrep anything else gets eta expanded.
thunkEntryLabel :: DynFlags -> Name -> CafInfo -> StandardFormInfo -> Bool -> CLabel
-- thunkEntryLabel is a local help function, not exported. It's used from
-- getCallMethod.
thunkEntryLabel dflags _thunk_id _ (ApThunk arity) upd_flag
= enterApLabel dflags upd_flag arity
thunkEntryLabel dflags _thunk_id _ (SelectorThunk offset) upd_flag
= enterSelectorLabel dflags upd_flag offset
thunkEntryLabel dflags thunk_id c _ _
= enterIdLabel dflags thunk_id c
enterApLabel :: DynFlags -> Bool -> Arity -> CLabel
enterApLabel dflags is_updatable arity
| tablesNextToCode dflags = mkApInfoTableLabel is_updatable arity
| otherwise = mkApEntryLabel is_updatable arity
enterSelectorLabel :: DynFlags -> Bool -> WordOff -> CLabel
enterSelectorLabel dflags upd_flag offset
| tablesNextToCode dflags = mkSelectorInfoLabel upd_flag offset
| otherwise = mkSelectorEntryLabel upd_flag offset
enterIdLabel :: DynFlags -> Name -> CafInfo -> CLabel
enterIdLabel dflags id c
| tablesNextToCode dflags = mkInfoTableLabel id c
| otherwise = mkEntryLabel id c
--------------------------------------
-- Profiling
--------------------------------------
-- Profiling requires two pieces of information to be determined for
-- each closure's info table --- description and type.
-- The description is stored directly in the @CClosureInfoTable@ when the
-- info table is built.
-- The type is determined from the type information stored with the @Id@
-- in the closure info using @closureTypeDescr@.
mkProfilingInfo :: DynFlags -> Id -> String -> ProfilingInfo
mkProfilingInfo dflags id val_descr
| not (gopt Opt_SccProfilingOn dflags) = NoProfilingInfo
| otherwise = ProfilingInfo ty_descr_w8 val_descr_w8
where
ty_descr_w8 = stringToWord8s (getTyDescription (idType id))
val_descr_w8 = stringToWord8s val_descr
getTyDescription :: Type -> String
getTyDescription ty
= case (tcSplitSigmaTy ty) of { (_, _, tau_ty) ->
case tau_ty of
TyVarTy _ -> "*"
AppTy fun _ -> getTyDescription fun
FunTy _ res -> '-' : '>' : fun_result res
TyConApp tycon _ -> getOccString tycon
ForAllTy _ ty -> getTyDescription ty
LitTy n -> getTyLitDescription n
}
where
fun_result (FunTy _ res) = '>' : fun_result res
fun_result other = getTyDescription other
getTyLitDescription :: TyLit -> String
getTyLitDescription l =
case l of
NumTyLit n -> show n
StrTyLit n -> show n
--------------------------------------
-- CmmInfoTable-related things
--------------------------------------
mkDataConInfoTable :: DynFlags -> DataCon -> Bool -> Int -> Int -> CmmInfoTable
mkDataConInfoTable dflags data_con is_static ptr_wds nonptr_wds
= CmmInfoTable { cit_lbl = info_lbl
, cit_rep = sm_rep
, cit_prof = prof
, cit_srt = NoC_SRT }
where
name = dataConName data_con
info_lbl | is_static = mkStaticInfoTableLabel name NoCafRefs
| otherwise = mkConInfoTableLabel name NoCafRefs
sm_rep = mkHeapRep dflags is_static ptr_wds nonptr_wds cl_type
cl_type = Constr (dataConTagZ data_con) (dataConIdentity data_con)
prof | not (gopt Opt_SccProfilingOn dflags) = NoProfilingInfo
| otherwise = ProfilingInfo ty_descr val_descr
ty_descr = stringToWord8s $ occNameString $ getOccName $ dataConTyCon data_con
val_descr = stringToWord8s $ occNameString $ getOccName data_con
-- We need a black-hole closure info to pass to @allocDynClosure@ when we
-- want to allocate the black hole on entry to a CAF.
cafBlackHoleInfoTable :: CmmInfoTable
cafBlackHoleInfoTable
= CmmInfoTable { cit_lbl = mkCAFBlackHoleInfoTableLabel
, cit_rep = blackHoleRep
, cit_prof = NoProfilingInfo
, cit_srt = NoC_SRT }
indStaticInfoTable :: CmmInfoTable
indStaticInfoTable
= CmmInfoTable { cit_lbl = mkIndStaticInfoLabel
, cit_rep = indStaticRep
, cit_prof = NoProfilingInfo
, cit_srt = NoC_SRT }
staticClosureNeedsLink :: Bool -> CmmInfoTable -> Bool
-- A static closure needs a link field to aid the GC when traversing
-- the static closure graph. But it only needs such a field if either
-- a) it has an SRT
-- b) it's a constructor with one or more pointer fields
-- In case (b), the constructor's fields themselves play the role
-- of the SRT.
--
-- At this point, the cit_srt field has not been calculated (that
-- happens right at the end of the Cmm pipeline), but we do have the
-- VarSet of CAFs that CoreToStg attached, and if that is empty there
-- will definitely not be an SRT.
--
staticClosureNeedsLink has_srt CmmInfoTable{ cit_rep = smrep }
| isConRep smrep = not (isStaticNoCafCon smrep)
| otherwise = has_srt -- needsSRT (cit_srt info_tbl)
|
green-haskell/ghc
|
compiler/codeGen/StgCmmClosure.hs
|
bsd-3-clause
| 37,881 | 0 | 12 | 10,224 | 4,625 | 2,511 | 2,114 | 433 | 7 |
module Kinding where
import qualified Data.Set as Set
import qualified Data.Map as Map
import Core
type KindSubst = Map.Map LowerName Kind
class Kinded
|
robertkleffner/gruit
|
src/Kinding.hs
|
mit
| 158 | 0 | 6 | 29 | 41 | 26 | 15 | -1 | -1 |
module Display (showColumns) where
import Data.List(intercalate)
showColumns :: Int -> Int -> ([String], [String]) -> String
showColumns wrapOne wrapTwo (as', bs') = intercalate "\n" $ map joinRow $ zip (map (pad wrapOne) colOneRows) (map (pad wrapTwo) colTwoRows)
where as = map (rmLineBreaks . rmLeadingWhitespace) $ concatMap (wrapText wrapOne) as'
bs = map (rmLineBreaks . rmLeadingWhitespace) $ concatMap (wrapText wrapTwo) bs'
rowCount = max (length as) (length bs)
colOneLen = 1 + (maximum $ map length as)
colTwoLen = maximum $ map length bs
colOneRows = as ++ take (max 0 $ rowCount - length as) (repeat "")
colTwoRows = bs ++ take (max 0 $ rowCount - length bs) (repeat "")
joinRow (a, b) = a ++ b
pad size s = s ++ take padding (repeat ' ')
where padding = max (size - length s) 0
wrapText width s | length s <= width = [s]
| otherwise = take width s : wrapText width (drop width s)
rmLeadingWhitespace s = dropWhile (\c -> c `elem` " \r\n\t") s
rmLineBreaks [] = []
rmLineBreaks ('\n':ss) = ' ' : rmLineBreaks ss
rmLineBreaks ('\r':ss) = ' ' : rmLineBreaks ss
rmLineBreaks (s:ss) = s : rmLineBreaks ss
|
MichaelBaker/zgy-cli
|
src/Display.hs
|
mit
| 1,215 | 0 | 12 | 299 | 533 | 270 | 263 | 21 | 1 |
module SFML.SFResource
where
class SFResource a where
-- | Destroy the given SFML resource.
destroy :: a -> IO ()
|
SFML-haskell/SFML
|
src/SFML/SFResource.hs
|
mit
| 130 | 0 | 9 | 36 | 30 | 16 | 14 | 3 | 0 |
module Y2016.M11.D08.Exercise where
import Data.Aeson
{--
So, last week we looked at a graph of twitter-users. NOICE! If you look at the
source code that generated the graph, it's a python script that makes a
request to the twitter API to get a list of the followers of the graphed
account.
Well. I happen to have a twitter API account and twitter application. Why don't
I just access these data myself and then we can work on the raw twitter (JSON)
data themselves.
Indeed!
So, today's Haskell exercise. In this directory, or at the URL:
https://github.com/geophf/1HaskellADay/blob/master/exercises/HAD/Y2016/M11/D08/1haskfollowersids.json.gz
is a gzipped list of twitter ids that follow 1HaskellADay as JSON.
I was able to get this JSON data with the following REST GET query:
https://api.twitter.com/1.1/followers/ids?screen_name=1HaskellADay
via my (o)authenticated twitter application.
Read in the JSON (after gunzipping it) and answer the below questions
--}
type TwitterId = Integer
data Tweeps = TIds { tweeps :: [TwitterId] } deriving Show
instance FromJSON Tweeps where
parseJSON = undefined
followers :: FilePath -> IO Tweeps
followers json = undefined
-- 1. How many followers does 1HaskellADay have?
-- 2. What is the max TwitterID? Is it an Int-value? (ooh, tricky)
-- 3. What is the min TwitterID?
-- Don't answer this:
-- 4. Trick question: what is 1HaskellADay's twitter ID?
{--
We'll be looking at how to get screen_name from twitter id and twitter id from
screen_name throughout this week, as well as looking at social networks of
followers who follow follwers who ...
How shall we do that? The Twitter API allows summary queries, as the JSON
examined here, as well as in-depth queries, given a screen_name (from which you
can obtain the twitter ID) or a twitter id (from which you can obtain the
screen_name) and followers, as you saw in today's query.
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2016/M11/D08/Exercise.hs
|
mit
| 1,902 | 0 | 9 | 325 | 80 | 50 | 30 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Lib (
withAuth
)
where
import Snap.Snaplet
import Snap.Core
import qualified Data.ByteString.Base64 as D
import qualified Data.ByteString.Char8 as B
import Control.Monad.Trans (liftIO)
import Data.Maybe
import Database.MongoDB (MongoContext(..), Database, connect, host, master)
import Services.AuthenticationService
import EncUtil (decryptMessage)
{- |
An Snap transparent handler to handle HTTP Basic authentication
-}
withAuth :: Handler a b () -> Handler a b ()
withAuth nextHandler = do
rq <- getRequest
let mh = getHeader "Authorization" rq
let ph = parseAuthorizationHeader mh
--liftIO $ print ph
if isNothing ph then
throwChallenge
else
do
isValid <- liftIO $ testAuth ph
if isValid then
nextHandler
else
throwAccessDenied
parseAuthorizationHeader :: Maybe B.ByteString -> Maybe (B.ByteString, B.ByteString)
parseAuthorizationHeader Nothing = Nothing
parseAuthorizationHeader (Just x) = case B.split ' ' x of
("Basic" : y : _) -> doParseBasicAuth y
("Token" : token : _) -> doParseAuthToken token
_ -> Nothing
doParseBasicAuth :: B.ByteString -> Maybe (B.ByteString, B.ByteString)
doParseBasicAuth y =
if B.length y == 0 then
Nothing
else
let decodedValue = D.decode y in
case decodedValue of
Left e -> Nothing
Right val ->
case B.split ':' val of
(user:pass:_) -> Just (user, pass)
_ -> Nothing
doParseAuthToken :: B.ByteString -> Maybe (B.ByteString, B.ByteString)
doParseAuthToken token =
if B.length token == 0 then
Nothing
else
let tVal = decryptMessage token in
case B.split ':' tVal of
(user:pass:_) -> Just (user, pass)
_ -> Nothing
testAuth :: Maybe (B.ByteString, B.ByteString) -> IO Bool
testAuth Nothing = return False
testAuth (Just (user,pass)) = validateUser dbConfig (B.unpack user) (B.unpack pass)
throwChallenge :: Handler a b ()
throwChallenge = do
modifyResponse $ setResponseCode 401
modifyResponse $ setHeader "WWW-Authenticate" "Basic releam=heub"
writeBS ""
throwAccessDenied :: Handler a b ()
throwAccessDenied = do
modifyResponse $ setResponseCode 403
writeText "Access Denied!"
dbName :: Database
dbName = "testAppDb"
dbConfig :: IO MongoContext
dbConfig = do
pipe <- connect $ host "localhost"
return $ MongoContext pipe master dbName
|
cackharot/heub
|
src/Lib.hs
|
mit
| 2,410 | 0 | 16 | 512 | 756 | 388 | 368 | 67 | 4 |
module Main where
import Lang.Cmn.Dict
main :: IO ()
main = do
dictEntries <- loadDict
let wdToEntry = dictToWdDict dictEntries
print $ length dictEntries
|
dancor/melang
|
src/Main/optimize-wubi.hs
|
mit
| 169 | 0 | 10 | 38 | 54 | 27 | 27 | 7 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Arguments
-- License : MIT (see the LICENSE file)
-- Maintainer : Felix Klein ([email protected])
--
-- Argument parser.
--
-----------------------------------------------------------------------------
{-# LANGUAGE
LambdaCase
, RecordWildCards
#-}
-----------------------------------------------------------------------------
module Arguments
( parseArguments
) where
-----------------------------------------------------------------------------
import Syfco
( Configuration(..)
, WriteMode(..)
, QuoteMode(..)
, defaultCfg
, verify
, update
)
import Data.Convertible
( safeConvert
)
import Info
( prError
)
import System.Directory
( doesFileExist
)
import Control.Monad
( void
, unless
)
import Text.Parsec.String
( Parser
)
import Text.Parsec
( parse
, letter
)
import Text.Parsec
( (<|>)
, char
, many1
, digit
, alphaNum
, eof
)
import Text.Parsec.Token
( GenLanguageDef(..)
, makeTokenParser
, identifier
)
import Text.Parsec.Language
( emptyDef
)
-----------------------------------------------------------------------------
data Args a = None a | Single a
-----------------------------------------------------------------------------
-- | Argument parser, which reads the given command line arguments to
-- the internal configuration and checks whether the given
-- combinations are realizable.
parseArguments
:: [String] -> IO Configuration
parseArguments args = do
c <- traverse defaultCfg args
case verify c of
Left err -> prError $ show err
_ -> return c
where
traverse c = \case
x:y:xr -> do
r <- parseArgument c x (Just y)
case r of
Single c'-> traverse c' xr
None c' -> traverse c' (y:xr)
[x] -> do
r <- parseArgument c x Nothing
case r of
None c' -> return c'
Single c' -> return c'
[] -> return c
parseArgument c arg next = case arg of
"-o" -> case next of
Just x -> return $ Single $ c { outputFile = Just x }
Nothing -> argsError "\"-o\": No output file"
"--output" -> case next of
Nothing -> argsError "\"--output\": No output file"
_ -> parseArgument c "-o" next
"-r" -> case next of
Just file -> do
exists <- doesFileExist file
unless exists $ argsError $ "File does not exist: " ++ file
fmap (update c) (readFile file) >>= \case
Left err -> prError $ show err
Right c' -> return $ Single c'
Nothing -> argsError "\"-r\": No configuration file"
"--read-config" -> case next of
Nothing -> argsError "\"--read-config\": No configuration file"
_ -> parseArgument c "-r" next
"-w" -> case next of
Just file ->
return $ Single $ c { saveConfig = file : saveConfig c }
Nothing -> argsError "\"-w\": Missing file path"
"--write-config" -> case next of
Nothing -> argsError "\"--write-config\": Missing file path"
_ -> parseArgument c "-w" next
"-f" -> case next of
Just x -> case safeConvert x of
Left err -> prError $ show err
Right y -> return $ Single $ c { outputFormat = y }
Nothing ->
argsError "\"-f\": No format given"
"--format" -> case next of
Nothing -> argsError "\"--format\": No format given"
_ -> parseArgument c "-f" next
"-m" -> case next of
Just "pretty" -> return $ Single $ c { outputMode = Pretty }
Just "fully" -> return $ Single $ c { outputMode = Fully }
Just x -> argsError ("Unknown mode: " ++ x)
Nothing -> argsError "\"-m\": No mode given"
"-q" -> case next of
Just "none" -> return $ Single $ c { quoteMode = NoQuotes }
Just "double" -> return $ Single $ c { quoteMode = DoubleQuotes }
Just x -> argsError ("Unknown quote mode: " ++ x)
Nothing -> argsError "\"-q\": No quote mode given"
"--mode" -> case next of
Nothing -> argsError "\"--mode\": no mode given"
_ -> parseArgument c "-m" next
"--quote" -> case next of
Nothing -> argsError "\"--quote\": no quote mode given"
_ -> parseArgument c "-q" next
"-pf" -> case next of
Just x -> return $ Single $ c { partFile = Just x }
Nothing -> argsError "\"-pf\": No partition file"
"-bd" -> case next of
Just x -> return $ Single $ c { busDelimiter = x }
Nothing -> argsError "\"-bd\": No delimiter given"
"--bus-delimiter" -> case next of
Nothing -> argsError "\"--bus-delimiter\": No delimiter given"
_ -> parseArgument c "-bd" next
"-ps" -> case next of
Just x -> return $ Single $ c { primeSymbol = x }
Nothing -> argsError "\"-ps\": No symbol replacement given"
"--prime-symbol" -> case next of
Just x -> return $ Single $ c { primeSymbol = x }
Nothing -> argsError "\"--prime-symbol\": No symbol replacement given"
"-as" -> case next of
Just x -> return $ Single $ c { atSymbol = x }
Nothing -> argsError "\"-as\": No symbol replacement given"
"--at-symbol" -> case next of
Just x -> return $ Single $ c { atSymbol = x }
Nothing -> argsError "\"--at-symbol\": No symbol replacement given"
"-in" -> return $ None $ c { fromStdin = True }
"-os" -> case next of
Just x -> case safeConvert x of
Left err -> prError $ show err
Right y -> return $ Single $ c { owSemantics = Just y }
Nothing -> argsError "\"-os\": No semantics given"
"--overwrite-semantics" -> case next of
Nothing -> argsError "\"--overwrite-semantics\": No semantics given"
_ -> parseArgument c "-os" next
"-ot" -> case next of
Just x -> case safeConvert x of
Left err -> prError $ show err
Right y -> return $ Single $ c { owTarget = Just y }
Nothing -> argsError "\"-ot\": No target given"
"--overwrite-target" -> case next of
Nothing -> argsError "\"--overwrite-target\": No target given"
_ -> parseArgument c "-ot" next
"-op" -> case next of
Just x -> case parse parameterParser "Overwrite Parameter Error" x of
Left err -> prError $ show err
Right y -> return $ Single $ c { owParameter = y : owParameter c }
Nothing -> argsError "\"-op\": No parameter given"
"--overwrite-parameter" -> case next of
Nothing -> argsError "\"--overwrite-parameter\": No parameter given"
_ -> parseArgument c "-op" next
"-s0" -> simple $ c { simplifyWeak = True }
"-s1" -> simple $ c { simplifyStrong = True }
"-nnf" -> simple $ c { negNormalForm = True }
"-pgi" -> simple $ c { pushGlobally = True }
"-pfi" -> simple $ c { pushFinally = True }
"-pxi" -> simple $ c { pushNext = True }
"-pgo" -> simple $ c { pullGlobally = True }
"-pfo" -> simple $ c { pullFinally = True }
"-pxo" -> simple $ c { pullNext = True }
"-nw" -> simple $ c { noWeak = True }
"-nr" -> simple $ c { noRelease = True }
"-nf" -> simple $ c { noFinally = True }
"-ng" -> simple $ c { noGlobally = True }
"-nd" -> simple $ c { noDerived = True }
"-gr" -> simple $ (clean c) { cGR = True }
"-c" -> simple $ (clean c) { check = True }
"-t" -> simple $ (clean c) { pTitle = True }
"-d" -> simple $ (clean c) { pDesc = True }
"-s" -> simple $ (clean c) { pSemantics = True }
"-g" -> simple $ (clean c) { pTarget = True }
"-a" -> simple $ (clean c) { pTags = True }
"-p" -> simple $ (clean c) { pParameters = True }
"-ins" -> simple $ (clean c) { pInputs = True }
"-outs" -> simple $ (clean c) { pOutputs = True }
"-i" -> simple $ (clean c) { pInfo = True }
"-v" -> simple $ (clean c) { pVersion = True }
"-h" -> simple $ (clean c) { pHelp = True }
"--readme" -> simple $ (clean c) { pReadme = True }
"--readme.md" -> simple $ (clean c) { pReadmeMd = True }
"--part-file" -> parseArgument c "-pf" next
"--stdin" -> parseArgument c "-in" next
"--weak-simplify" -> parseArgument c "-s0" next
"--strong-simplify" -> parseArgument c "-s1" next
"--negation-normal-form" -> parseArgument c "-nnf" next
"--push-globally-inwards" -> parseArgument c "-pgi" next
"--push-finally-inwards" -> parseArgument c "-pfi" next
"--push-next-inwards" -> parseArgument c "-pni" next
"--pull-globally-outwards" -> parseArgument c "-pgo" next
"--pull-finally-outwards" -> parseArgument c "-pfo" next
"--pull-next-outwards" -> parseArgument c "-pxo" next
"--no-weak-until" -> parseArgument c "-nw" next
"--no-realease" -> parseArgument c "-nr" next
"--no-finally" -> parseArgument c "-nf" next
"--no-globally" -> parseArgument c "-ng" next
"--no-derived" -> parseArgument c "-nd" next
"--generalized-reactivity" -> parseArgument c "-gr" next
"--check" -> parseArgument c "-c" next
"--print-title" -> parseArgument c "-t" next
"--print-description" -> parseArgument c "-d" next
"--print-semantics" -> parseArgument c "-s" next
"--print-target" -> parseArgument c "-g" next
"--print-tags" -> parseArgument c "-a" next
"--print-parameters" -> parseArgument c "-p" next
"--print-input-signals" -> parseArgument c "-ins" next
"--print-output-signals" -> parseArgument c "-outs" next
"--print-info" -> parseArgument c "-i" next
"--version" -> parseArgument c "-v" next
"--help" -> parseArgument c "-h" next
_ -> return $ None $ c {
inputFiles = arg : inputFiles c
}
argsError str = do
prError $ "\"Error\" " ++ str
clean a = a {
check = False,
pTitle = False,
pDesc = False,
pSemantics = False,
pTarget = False,
pParameters = False,
pInfo = False,
pVersion = False,
pHelp = False,
pReadme = False,
pReadmeMd = False
}
simple = return . None
-----------------------------------------------------------------------------
parameterParser
:: Parser (String, Int)
parameterParser = do
name <-
identifier $ makeTokenParser
emptyDef
{ identStart = letter <|> char '_' <|> char '@'
, identLetter = alphaNum <|> char '_' <|> char '@' <|> char '\''
}
void $ char '='
x <- many1 digit
eof
return (name, read x)
-----------------------------------------------------------------------------
|
reactive-systems/syfco
|
src/syfco/Arguments.hs
|
mit
| 12,225 | 0 | 20 | 4,523 | 3,001 | 1,524 | 1,477 | 242 | 124 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module BT.Polling where
import BT.ZMQ
import BT.Types
import Data.Pool (Pool)
import qualified System.ZMQ3 as ZMQ
import Data.IORef (IORef, writeIORef)
import Network.Bitcoin (BTC)
import Data.ByteString as B
import Data.ByteString.Char8 as BC
import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class (liftIO)
import BT.Mining
pollOnce :: Pool (ZMQ.Socket ZMQ.Req) -> IORef BTC -> B.ByteString -> IO ()
pollOnce conn store name = do
valueraw <- sendraw conn name
let !value = read . BC.unpack $ valueraw :: BTC
liftIO $ writeIORef store value
pollOnceHex :: Pool (ZMQ.Socket ZMQ.Req) -> IORef BTC -> B.ByteString -> IO ()
pollOnceHex conn store name = do
valueraw <- sendraw conn name
let !value = hexDiffToInt $ valueraw :: BTC
liftIO $ writeIORef store value
poll :: PersistentConns -> IO ()
poll conns = do
liftIO $ threadDelay 60000000 -- 60 seconds
pollOnce (pool conns) (curPayout conns) "payout"
pollOnceHex (pool conns) (curTarget conns) "target"
poll conns
|
c00w/BitToll
|
haskell/BT/Polling.hs
|
mit
| 1,097 | 0 | 12 | 206 | 378 | 193 | 185 | 30 | 1 |
{-|
Module: Y2015.Util
Description: Shared functions for Advent of Code Solutions.
License: MIT
Maintainer: @tylerjl
Shared functions that support solutions to problems for the
<adventofcode.com> challenges.
-}
module Y2015.Util
( (<&&>)
, regularParse
, intParser
) where
import Control.Monad (liftM2)
import qualified Text.Parsec as P
import Text.Parsec.Char (digit)
import Text.Parsec.String (Parser)
-- |Combinator operator for predicates
(<&&>) :: (a -> Bool) -- ^ Predicate 1
-> (a -> Bool) -- ^ Predicate 2
-> a -- ^ Predicate target
-> Bool -- ^ Logical and for predicates
(<&&>) = liftM2 (&&)
-- |Generic parsing wrapper
regularParse :: Parser a -> String -> Either P.ParseError a
regularParse p = P.parse p ""
-- |Generic 'Int' parser
intParser :: Parser Int -- ^ Parsec parser for 'Int' types
intParser = read <$> P.many1 digit
|
tylerjl/adventofcode
|
src/Y2015/Util.hs
|
mit
| 942 | 0 | 8 | 235 | 173 | 104 | 69 | 17 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Raw where
import qualified GHCJS.TypeScript as TS
import GHCJS.TypeScript (type (:|:), type (:::), type (::?))
import qualified GHCJS.Marshal as GHCJS
import qualified GHCJS.Types as GHCJS
import qualified Data.Typeable
newtype Event = Event (GHCJS.JSRef Event)
newtype HTMLElement = HTMLElement (GHCJS.JSRef HTMLElement)
newtype Function = Function (GHCJS.JSRef Function)
newtype HighchartsAnimation = HighchartsAnimation (GHCJS.JSRef (HighchartsAnimation))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAnimation =
('[ "duration" ::? TS.Number
, "easing" ::? TS.String
])
newtype HighchartsAreaChart = HighchartsAreaChart (GHCJS.JSRef (HighchartsAreaChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "color" ::? TS.String
, "connectEnds" ::? TS.Boolean
, "connectNulls" ::? TS.Boolean
, "cropThreshold" ::? TS.Number
, "cursor" ::? TS.String
, "dashStyle" ::? TS.String
, "dataLabels" ::? HighchartsDataLabels
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "fillColor" ::? (TS.String :|: HighchartsGradient)
, "fillOpacity" ::? TS.Number
, "linkedTo" ::? TS.String
, "lineColor" ::? TS.String
, "lineWidth" ::? TS.Number
, "marker" ::? HighchartsMarker
, "negativeColor" ::? TS.String
, "negativeFillColor" ::? TS.String
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPlacement" ::? (TS.String :|: TS.Number)
, "pointStart" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "stacking" ::? TS.String
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsAreaStates
])
, "step" ::? TS.String
, "stickyTracking" ::? TS.Boolean
, "threshold" ::? TS.Number
, "tooltip" ::? HighchartsTooltipOptions
, "trackByArea" ::? TS.Boolean
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
, "zIndex" ::? TS.Number
])
newtype HighchartsAreaChartSeriesOptions = HighchartsAreaChartSeriesOptions (GHCJS.JSRef (HighchartsAreaChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaChart]
('[ ])
newtype HighchartsAreaCheckboxEvent = HighchartsAreaCheckboxEvent (GHCJS.JSRef (HighchartsAreaCheckboxEvent))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaCheckboxEvent = TS.Extends '[Event]
('[ "checked" ::: TS.Boolean
])
newtype HighchartsAreaClickEvent = HighchartsAreaClickEvent (GHCJS.JSRef (HighchartsAreaClickEvent))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaClickEvent = TS.Extends '[Event]
('[ "point" ::: HighchartsPointObject
])
newtype HighchartsAreaRangeChart = HighchartsAreaRangeChart (GHCJS.JSRef (HighchartsAreaRangeChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaRangeChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "color" ::? TS.String
, "connectNulls" ::? TS.Boolean
, "cropThreshold" ::? TS.Number
, "cursor" ::? TS.String
, "dashStyle" ::? TS.String
, "dataLabels" ::? HighchartsRangeDataLabels
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "fillColor" ::? (TS.String :|: HighchartsGradient)
, "fillOpacity" ::? TS.Number
, "lineColor" ::? TS.String
, "lineWidth" ::? TS.Number
, "linkedTo" ::? TS.String
, "negativeColor" ::? TS.String
, "negativeFillColor" ::? TS.String
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPlacement" ::? (TS.String :|: TS.Number)
, "pointStart" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "stacking" ::? TS.String
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsAreaStates
])
, "step" ::? TS.String
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "threshold" ::? TS.Number
, "trackByArea" ::? TS.Boolean
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
])
newtype HighchartsAreaRangeChartSeriesOptions = HighchartsAreaRangeChartSeriesOptions (GHCJS.JSRef (HighchartsAreaRangeChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaRangeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaRangeChart]
('[ ])
newtype HighchartsAreaSplineChart = HighchartsAreaSplineChart (GHCJS.JSRef (HighchartsAreaSplineChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaSplineChart = TS.Extends '[HighchartsAreaChart]
('[ "connectEnds" ::? TS.Boolean
])
newtype HighchartsAreaSplineChartSeriesOptions = HighchartsAreaSplineChartSeriesOptions (GHCJS.JSRef (HighchartsAreaSplineChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaSplineChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaSplineChart]
('[ ])
newtype HighchartsAreaSplineRangeChart = HighchartsAreaSplineRangeChart (GHCJS.JSRef (HighchartsAreaSplineRangeChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaSplineRangeChart = TS.Extends '[HighchartsAreaRangeChart]
('[ ])
newtype HighchartsAreaSplineRangeChartSeriesOptions = HighchartsAreaSplineRangeChartSeriesOptions (GHCJS.JSRef (HighchartsAreaSplineRangeChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaSplineRangeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsAreaSplineRangeChart]
('[ ])
newtype HighchartsAreaStates = HighchartsAreaStates (GHCJS.JSRef (HighchartsAreaStates))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAreaStates =
('[ "enabled" ::? TS.Boolean
, "lineWidth" ::? TS.Number
, "marker" ::? HighchartsMarker
])
newtype HighchartsAxisEvent = HighchartsAxisEvent (GHCJS.JSRef (HighchartsAxisEvent))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAxisEvent = TS.Extends '[Event]
('[ "min" ::: TS.Number
, "max" ::: TS.Number
])
newtype HighchartsAxisLabels = HighchartsAxisLabels (GHCJS.JSRef (HighchartsAxisLabels))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAxisLabels =
('[ "align" ::? TS.String
, "enabled" ::? TS.Boolean
, "formatter" ::? (TS.String)
, "overflow" ::? TS.String
, "rotation" ::? TS.Number
, "staggerLines" ::? TS.Number
, "step" ::? TS.Number
, "style" ::? HighchartsCSSObject
, "useHTML" ::? TS.Boolean
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsAxisObject = HighchartsAxisObject (GHCJS.JSRef (HighchartsAxisObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAxisObject =
('[ "addPlotBand" ::: TS.Fun (HighchartsPlotBands -> TS.Void)
, "addPlotLine" ::: TS.Fun (HighchartsPlotLines -> TS.Void)
, "getExtremes" ::: TS.Fun (HighchartsExtremes)
, "remove" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Void)
, "removePlotBand" ::: TS.Fun (TS.String -> TS.Void)
, "removePlotLine" ::: TS.Fun (TS.String -> TS.Void)
, "setCategories" ::: TS.Fun ((TS.Array TS.String) -> TS.Void)
, "setCategories" ::: TS.Fun ((TS.Array TS.String) -> TS.Boolean -> TS.Void)
, "setExtremes" ::: TS.Fun (TS.Number -> TS.Number -> TS.Void)
, "setExtremes" ::: TS.Fun (TS.Number -> TS.Number -> TS.Boolean -> TS.Void)
, "setExtremes" ::: TS.Fun (TS.Number -> TS.Number -> TS.Boolean -> (TS.Boolean :|: HighchartsAnimation) -> TS.Void)
, "setTitle" ::: TS.Fun (HighchartsAxisTitle -> TS.Optional (TS.Boolean) -> TS.Void)
, "toPixels" ::: TS.Fun (TS.Number -> TS.Optional (TS.Boolean) -> TS.Number)
, "toValue" ::: TS.Fun (TS.Number -> TS.Optional (TS.Boolean) -> TS.Number)
, "update" ::: TS.Fun (HighchartsAxisOptions -> TS.Optional (TS.Boolean) -> TS.Void)
])
newtype HighchartsAxisOptions = HighchartsAxisOptions (GHCJS.JSRef (HighchartsAxisOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAxisOptions =
('[ "allowDecimals" ::? TS.Boolean
, "alternateGridColor" ::? TS.String
, "categories" ::? (TS.Array TS.String)
, "dateTimeLabelFormats" ::? HighchartsDateTimeFormats
, "endOnTick" ::? TS.Boolean
, "events" ::? TS.Obj
('[ "afterSetExtremes" ::? (HighchartsAxisEvent -> TS.Void)
, "setExtremes" ::? (HighchartsAxisEvent -> TS.Void)
])
, "gridLineColor" ::? TS.String
, "gridLineDashStyle" ::? TS.String
, "gridLineWidth" ::? TS.Number
, "id" ::? TS.String
, "labels" ::? HighchartsAxisLabels
, "lineColor" ::? TS.String
, "lineWidth" ::? TS.Number
, "linkedTo" ::? TS.Number
, "max" ::? TS.Number
, "maxPadding" ::? TS.Number
, "maxZoom" ::? TS.Number
, "min" ::? TS.Number
, "minPadding" ::? TS.Number
, "minRange" ::? TS.Number
, "minTickInterval" ::? TS.Number
, "minorTickColor" ::? TS.String
, "minorTickInterval" ::? (TS.Number :|: TS.String)
, "minorTickLength" ::? TS.Number
, "minorTickPosition" ::? TS.String
, "minorTickWidth" ::? TS.Number
, "offset" ::? TS.Number
, "opposite" ::? TS.Boolean
, "plotBands" ::? HighchartsPlotBands
, "plotLines" ::? HighchartsPlotLines
, "reversed" ::? TS.Boolean
, "showEmpty" ::? TS.Boolean
, "showFirstLabel" ::? TS.Boolean
, "showLastLabel" ::? TS.Boolean
, "startOfWeek" ::? TS.Number
, "startOnTick" ::? TS.Boolean
, "tickColor" ::? TS.String
, "tickInterval" ::? TS.Number
, "tickLength" ::? TS.Number
, "tickPixelInterval" ::? TS.Number
, "tickPosition" ::? TS.String
, "tickWidth" ::? TS.Number
, "tickmarkPlacement" ::? TS.String
, "title" ::? HighchartsAxisTitle
, "type" ::? TS.String
])
newtype HighchartsAxisTitle = HighchartsAxisTitle (GHCJS.JSRef (HighchartsAxisTitle))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsAxisTitle =
('[ "align" ::? TS.String
, "margin" ::? TS.Number
, "offset" ::? TS.Number
, "rotation" ::? TS.Number
, "style" ::? HighchartsCSSObject
, "text" ::? TS.String
])
newtype HighchartsBarChart = HighchartsBarChart (GHCJS.JSRef (HighchartsBarChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsBarChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "color" ::? TS.String
, "colorByPoint" ::? TS.Boolean
, "cropThreshold" ::? TS.Number
, "colors" ::? (TS.Array TS.String)
, "cursor" ::? TS.String
, "dataLabels" ::? HighchartsDataLabels
, "depth" ::? TS.Number
, "edgeColor" ::? TS.String
, "edgeWidth" ::? TS.Number
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "groupPadding" ::? TS.Number
, "groupZPadding" ::? TS.Number
, "grouping" ::? TS.Boolean
, "linkedTo" ::? TS.String
, "minPointLength" ::? TS.Number
, "negativeColor" ::? TS.String
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPadding" ::? TS.Number
, "pointPlacement" ::? TS.String
, "pointRange" ::? TS.Number
, "pointStart" ::? TS.Number
, "pointWidth" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "stacking" ::? TS.String
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsBarStates
])
, "stickyTracking" ::? TS.Boolean
, "threshold" ::? TS.Number
, "tooltip" ::? HighchartsTooltipOptions
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
])
newtype HighchartsBarChartSeriesOptions = HighchartsBarChartSeriesOptions (GHCJS.JSRef (HighchartsBarChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsBarChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsBarChart]
('[ ])
newtype HighchartsBarStates = HighchartsBarStates (GHCJS.JSRef (HighchartsBarStates))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsBarStates = TS.Extends '[HighchartsAreaStates]
('[ "brightness" ::? TS.Number
])
newtype HighchartsBoxPlotChart = HighchartsBoxPlotChart (GHCJS.JSRef (HighchartsBoxPlotChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsBoxPlotChart =
('[ "allowPointSelect" ::? TS.Boolean
, "color" ::? TS.String
, "colorByPoint" ::? TS.Boolean
, "colors" ::? (TS.Array TS.String)
, "cursor" ::? TS.String
, "depth" ::? TS.Number
, "edgecolor" ::? TS.String
, "edgewidth" ::? TS.Number
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "fillColor" ::? TS.String
, "groupPadding" ::? TS.Number
, "groupZPadding" ::? TS.Number
, "grouping" ::? TS.Boolean
, "lineWidth" ::? TS.Number
, "linkedTo" ::? TS.String
, "medianColor" ::? TS.String
, "negativeColor" ::? TS.String
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPadding" ::? TS.Number
, "pointPlacement" ::? (TS.String :|: TS.Number)
, "pointRange" ::? TS.Number
, "pointStart" ::? TS.Number
, "pointWidth" ::? TS.Number
, "selected" ::? TS.Boolean
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsBarStates
])
, "stemColor" ::? TS.String
, "stemDashStyle" ::? TS.String
, "stemWidth" ::? TS.Number
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
, "whiskerColor" ::? TS.String
, "whiskerLength" ::? (TS.Number :|: TS.String)
, "whiskerWidth" ::? TS.Number
])
newtype HighchartsBoxPlotChartSeriesOptions = HighchartsBoxPlotChartSeriesOptions (GHCJS.JSRef (HighchartsBoxPlotChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsBoxPlotChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsBoxPlotChart]
('[ ])
newtype HighchartsBubbleChart = HighchartsBubbleChart (GHCJS.JSRef (HighchartsBubbleChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsBubbleChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "color" ::? TS.String
, "cropThreshold" ::? TS.Number
, "cursor" ::? TS.String
, "dashStyle" ::? TS.String
, "dataLabels" ::? HighchartsRangeDataLabels
, "displayNegative" ::? TS.Boolean
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "lineWidth" ::? TS.Number
, "linkedTo" ::? TS.String
, "marker" ::? HighchartsMarker
, "maxSize" ::? TS.String
, "minSize" ::? TS.String
, "negativeColor" ::? TS.String
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointStart" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "sizeBy" ::? TS.String
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsBarStates
])
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
, "zMax" ::? TS.Number
, "zMin" ::? TS.Number
, "zThreshold" ::? TS.Number
])
newtype HighchartsBubbleChartSeriesOptions = HighchartsBubbleChartSeriesOptions (GHCJS.JSRef (HighchartsBubbleChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsBubbleChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsBubbleChart]
('[ ])
newtype HighchartsButton = HighchartsButton (GHCJS.JSRef (HighchartsButton))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsButton =
('[ "align" ::? TS.String
, "backgroundColor" ::? (TS.String :|: HighchartsGradient)
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "verticalAlign" ::? TS.String
, "enabled" ::? TS.Boolean
, "height" ::? TS.Number
, "hoverBorderColor" ::? TS.String
, "hoverSymbolFill" ::? TS.String
, "hoverSimbolStroke" ::? TS.String
, "menuItems" ::? (TS.Array HighchartsMenuItem)
, "onclick" ::? (TS.Void)
, "symbol" ::? TS.String
, "simbolFill" ::? TS.String
, "simbolSize" ::? TS.Number
, "symbolStroke" ::? TS.String
, "symbolStrokeWidth" ::? TS.Number
, "symbolX" ::? TS.Number
, "symbolY" ::? TS.Number
, "width" ::? TS.Number
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsCSSObject = HighchartsCSSObject (GHCJS.JSRef (HighchartsCSSObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsCSSObject =
('[ "background" ::? TS.String
, "border" ::? TS.String
, "color" ::? TS.String
, "cursor" ::? TS.String
, "font" ::? TS.String
, "fontSize" ::? TS.String
, "fontWeight" ::? TS.String
, "left" ::? TS.String
, "opacity" ::? TS.Number
, "padding" ::? TS.String
, "position" ::? TS.String
, "top" ::? TS.String
])
newtype HighchartsChart = HighchartsChart (GHCJS.JSRef (HighchartsChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsChart =
('[ TS.Constructor (HighchartsOptions -> HighchartsChartObject)
, TS.Constructor (HighchartsOptions -> (HighchartsChartObject -> TS.Void) -> HighchartsChartObject)
])
newtype HighchartsChartEvents = HighchartsChartEvents (GHCJS.JSRef (HighchartsChartEvents))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsChartEvents =
('[ "addSeries" ::? (TS.Optional (Event) -> TS.Boolean)
, "click" ::? (TS.Optional (Event) -> TS.Void)
, "load" ::? (TS.Optional (Event) -> TS.Void)
, "redraw" ::? (Event -> TS.Void)
, "selection" ::? (HighchartsSelectionEvent -> TS.Void)
])
newtype HighchartsChartObject = HighchartsChartObject (GHCJS.JSRef (HighchartsChartObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsChartObject =
('[ "addAxis" ::: TS.Fun (HighchartsAxisOptions -> TS.Optional (TS.Boolean) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> HighchartsAxisObject)
, "addSeries" ::: TS.Fun (TS.Any {- forall t. (t TS.:= HighchartsIndividualSeriesOptions) => t -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> t -})
, "addSeriesAsDrilldown" ::: TS.Fun (HighchartsPointObject -> HighchartsSeriesOptions -> TS.Void)
, "container" ::: HTMLElement
, "destroy" ::: TS.Fun (TS.Void)
, "drillUp" ::: TS.Fun (TS.Void)
, "exportChart" ::: TS.Fun (TS.Void)
, "exportChart" ::: TS.Fun (HighchartsExportingOptions -> TS.Void)
, "exportChart" ::: TS.Fun (HighchartsExportingOptions -> HighchartsChartOptions -> TS.Void)
, "get" ::: TS.Fun (TS.String -> (HighchartsAxisObject :|: (HighchartsSeriesObject :|: HighchartsPointObject)))
, "getSVG" ::: TS.Fun (TS.String)
, "getSVG" ::: TS.Fun (HighchartsChartOptions -> TS.String)
, "getSelectedPoints" ::: TS.Fun ((TS.Array HighchartsPointObject))
, "getSelectedSeries" ::: TS.Fun ((TS.Array HighchartsSeriesObject))
, "hideLoading" ::: TS.Fun (TS.Void)
, "options" ::: HighchartsChartOptions
, "print" ::: TS.Fun (TS.Void)
, "redraw" ::: TS.Fun (TS.Void)
, "reflow" ::: TS.Fun (TS.Void)
, "series" ::: (TS.Array HighchartsSeriesObject)
, "setSize" ::: TS.Fun (TS.Number -> TS.Number -> TS.Void)
, "setSize" ::: TS.Fun (TS.Number -> TS.Number -> TS.Boolean -> TS.Void)
, "setSize" ::: TS.Fun (TS.Number -> TS.Number -> HighchartsAnimation -> TS.Void)
, "setTitle" ::: TS.Fun (HighchartsTitleOptions -> TS.Void)
, "setTitle" ::: TS.Fun (HighchartsTitleOptions -> HighchartsSubtitleOptions -> TS.Void)
, "setTitle" ::: TS.Fun (HighchartsTitleOptions -> HighchartsSubtitleOptions -> TS.Boolean -> TS.Void)
, "showLoading" ::: TS.Fun (TS.Void)
, "showLoading" ::: TS.Fun (TS.String -> TS.Void)
, "xAxis" ::: (TS.Array HighchartsAxisObject)
, "yAxis" ::: (TS.Array HighchartsAxisObject)
, "renderer" ::: HighchartsRendererObject
])
newtype HighchartsChartOptions = HighchartsChartOptions (GHCJS.JSRef (HighchartsChartOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsChartOptions =
('[ "alignTicks" ::? TS.Boolean
, "animation" ::? (TS.Boolean :|: HighchartsAnimation)
, "backgroundColor" ::? (TS.String :|: HighchartsGradient)
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "className" ::? TS.String
, "defaultSeriesType" ::? TS.String
, "events" ::? HighchartsChartEvents
, "height" ::? TS.Number
, "ignoreHiddenSeries" ::? TS.Boolean
, "inverted" ::? TS.Boolean
, "margin" ::? (TS.Array TS.Number)
, "marginBottom" ::? TS.Number
, "marginLeft" ::? TS.Number
, "marginRight" ::? TS.Number
, "marginTop" ::? TS.Number
, "plotBackGroundColor" ::? (TS.String :|: HighchartsGradient)
, "plotBackGroundImage" ::? TS.String
, "plotBorderColor" ::? TS.String
, "plotBorderWidth" ::? TS.Number
, "plotShadow" ::? (TS.Boolean :|: HighchartsShadow)
, "polar" ::? TS.Boolean
, "reflow" ::? TS.Boolean
, "renderTo" ::? TS.Any
, "resetZoomButton" ::? HighchartsChartResetZoomButton
, "selectionMarkerFill" ::? TS.String
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showAxes" ::? TS.Boolean
, "spacingBottom" ::? TS.Number
, "spacingLeft" ::? TS.Number
, "spacingRight" ::? TS.Number
, "spacingTop" ::? TS.Number
, "style" ::? HighchartsCSSObject
, "type" ::? TS.String
, "width" ::? TS.Number
, "zoomType" ::? TS.String
])
newtype HighchartsChartResetZoomButton = HighchartsChartResetZoomButton (GHCJS.JSRef (HighchartsChartResetZoomButton))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsChartResetZoomButton =
('[ "position" ::: HighchartsPosition
, "relativeTo" ::? TS.String
, "theme" ::? HighchartsChartResetZoomButtonTheme
])
newtype HighchartsChartResetZoomButtonTheme = HighchartsChartResetZoomButtonTheme (GHCJS.JSRef (HighchartsChartResetZoomButtonTheme))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsChartResetZoomButtonTheme =
('[ "fill" ::? TS.String
, "stroke" ::? TS.String
, "r" ::? TS.Number
, "states" ::? TS.Any
, "display" ::? TS.String
])
newtype HighchartsColumnChart = HighchartsColumnChart (GHCJS.JSRef (HighchartsColumnChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsColumnChart = TS.Extends '[HighchartsBarChart]
('[ ])
newtype HighchartsColumnChartSeriesOptions = HighchartsColumnChartSeriesOptions (GHCJS.JSRef (HighchartsColumnChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsColumnChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsColumnChart]
('[ ])
newtype HighchartsColumnRangeChart = HighchartsColumnRangeChart (GHCJS.JSRef (HighchartsColumnRangeChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsColumnRangeChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "color" ::? TS.String
, "colorByPoint" ::? TS.Boolean
, "colors" ::? (TS.Array TS.String)
, "cropThreshold" ::? TS.Number
, "cursor" ::? TS.String
, "dataLabels" ::? HighchartsRangeDataLabels
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "groupPadding" ::? TS.Number
, "grouping" ::? TS.Boolean
, "linkedTo" ::? TS.String
, "minPointLength" ::? TS.Number
, "negativeColor" ::? TS.String
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPadding" ::? TS.Number
, "pointPlacement" ::? (TS.String :|: TS.Number)
, "pointRange" ::? TS.Number
, "pointStart" ::? TS.Number
, "pointWidth" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "stacking" ::? TS.String
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsBarStates
])
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
])
newtype HighchartsColumnRangeChartSeriesOptions = HighchartsColumnRangeChartSeriesOptions (GHCJS.JSRef (HighchartsColumnRangeChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsColumnRangeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsColumnRangeChart]
('[ ])
newtype HighchartsCreditsOptions = HighchartsCreditsOptions (GHCJS.JSRef (HighchartsCreditsOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsCreditsOptions =
('[ "enabled" ::? TS.Boolean
, "href" ::? TS.String
, "position" ::? HighchartsPosition
, "style" ::? HighchartsCSSObject
, "text" ::? TS.String
])
newtype HighchartsCrosshairObject = HighchartsCrosshairObject (GHCJS.JSRef (HighchartsCrosshairObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsCrosshairObject =
('[ "color" ::? TS.String
, "width" ::? TS.Number
, "dashStyle" ::? TS.String
, "zIndex" ::? TS.Number
])
newtype HighchartsDataLabels = HighchartsDataLabels (GHCJS.JSRef (HighchartsDataLabels))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsDataLabels =
('[ "align" ::? TS.String
, "backgroundColor" ::? (TS.String :|: HighchartsGradient)
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "color" ::? TS.String
, "crop" ::? TS.Boolean
, "enabled" ::? TS.Boolean
, "formatter" ::? (TS.Any)
, "overflow" ::? TS.String
, "padding" ::? TS.Number
, "rotation" ::? TS.Number
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "staggerLines" ::? TS.Any
, "step" ::? TS.Any
, "style" ::? HighchartsCSSObject
, "useHTML" ::? TS.Boolean
, "verticalAlign" ::? TS.String
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsDataPoint = HighchartsDataPoint (GHCJS.JSRef (HighchartsDataPoint))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsDataPoint =
('[ "color" ::? TS.String
, "dataLabels" ::? HighchartsDataLabels
, "events" ::? HighchartsPointEvents
, "id" ::? TS.String
, "legendIndex" ::? TS.Number
, "marker" ::? HighchartsMarker
, "name" ::? TS.String
, "sliced" ::? TS.Boolean
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsDateTimeFormats = HighchartsDateTimeFormats (GHCJS.JSRef (HighchartsDateTimeFormats))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsDateTimeFormats =
('[ "millisecond" ::? TS.String
, "second" ::? TS.String
, "minute" ::? TS.String
, "hour" ::? TS.String
, "day" ::? TS.String
, "week" ::? TS.String
, "month" ::? TS.String
, "year" ::? TS.String
])
newtype HighchartsDial = HighchartsDial (GHCJS.JSRef (HighchartsDial))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsDial =
('[ "backgroundColor" ::? TS.String
, "baseLength" ::? TS.String
, "baseWidth" ::? TS.Number
, "borderColor" ::? TS.String
, "borderWidth" ::? TS.Number
, "radius" ::? TS.String
, "rearLength" ::? TS.String
, "topWidth" ::? TS.Number
])
newtype HighchartsElementObject = HighchartsElementObject (GHCJS.JSRef (HighchartsElementObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsElementObject =
('[ "add" ::: TS.Fun (HighchartsElementObject)
, "add" ::: TS.Fun (HighchartsElementObject -> HighchartsElementObject)
, "animate" ::: TS.Fun (TS.Any -> TS.Optional (TS.Any) -> HighchartsElementObject)
, "attr" ::: TS.Fun (TS.Any -> HighchartsElementObject)
, "css" ::: TS.Fun (HighchartsCSSObject -> HighchartsElementObject)
, "destroy" ::: TS.Fun (TS.Void)
, "getBBox" ::: TS.Fun (TS.Obj
('[ "x" ::: TS.Number
, "y" ::: TS.Number
, "height" ::: TS.Number
, "width" ::: TS.Number
])
)
, "on" ::: TS.Fun (TS.String -> (TS.Void) -> HighchartsElementObject)
, "toFront" ::: TS.Fun (HighchartsElementObject)
])
newtype HighchartsErrorBarChart = HighchartsErrorBarChart (GHCJS.JSRef (HighchartsErrorBarChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsErrorBarChart =
('[ ])
newtype HighchartsErrorBarChartSeriesOptions = HighchartsErrorBarChartSeriesOptions (GHCJS.JSRef (HighchartsErrorBarChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsErrorBarChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsErrorBarChart]
('[ ])
newtype HighchartsExportingOptions = HighchartsExportingOptions (GHCJS.JSRef (HighchartsExportingOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsExportingOptions =
('[ "buttons" ::? TS.Obj
('[ "exportButton" ::? HighchartsButton
, "printButton" ::? HighchartsButton
])
, "enableImages" ::? TS.Boolean
, "enabled" ::? TS.Boolean
, "filename" ::? TS.String
, "type" ::? TS.String
, "url" ::? TS.String
, "width" ::? TS.Number
])
newtype HighchartsExtremes = HighchartsExtremes (GHCJS.JSRef (HighchartsExtremes))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsExtremes =
('[ "dataMax" ::: TS.Number
, "dataMin" ::: TS.Number
, "max" ::: TS.Number
, "min" ::: TS.Number
])
newtype HighchartsFunnelChart = HighchartsFunnelChart (GHCJS.JSRef (HighchartsFunnelChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsFunnelChart =
('[ ])
newtype HighchartsFunnelChartSeriesOptions = HighchartsFunnelChartSeriesOptions (GHCJS.JSRef (HighchartsFunnelChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsFunnelChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsFunnelChart]
('[ ])
newtype HighchartsGaugeChart = HighchartsGaugeChart (GHCJS.JSRef (HighchartsGaugeChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsGaugeChart =
('[ "animation" ::? TS.Boolean
, "color" ::? TS.String
, "cursor" ::? TS.String
, "datalabels" ::? HighchartsDataLabels
, "dial" ::? HighchartsDial
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "id" ::? TS.String
, "pivot" ::? HighchartsPivot
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "selected" ::? TS.Boolean
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsAreaStates
])
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "visible" ::? TS.Boolean
, "zIndex" ::? TS.Number
])
newtype HighchartsGaugeChartSeriesOptions = HighchartsGaugeChartSeriesOptions (GHCJS.JSRef (HighchartsGaugeChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsGaugeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsGaugeChart]
('[ ])
newtype HighchartsGlobalObject = HighchartsGlobalObject (GHCJS.JSRef (HighchartsGlobalObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsGlobalObject =
('[ "Date" ::? TS.Any
, "VMLRadialGradientURL" ::? TS.String
, "canvasToolsURL" ::? TS.String
, "timezoneOffset" ::? TS.Number
, "useUTC" ::? TS.Boolean
])
newtype HighchartsGlobalOptions = HighchartsGlobalOptions (GHCJS.JSRef (HighchartsGlobalOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsGlobalOptions = TS.Extends '[HighchartsOptions]
('[ "global" ::? HighchartsGlobalObject
, "lang" ::? HighchartsLangObject
])
newtype HighchartsGradient = HighchartsGradient (GHCJS.JSRef (HighchartsGradient))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsGradient =
('[ "linearGradient" ::? TS.Obj
('[ "x1" ::: TS.Number
, "y1" ::: TS.Number
, "x2" ::: TS.Number
, "y2" ::: TS.Number
])
, "radialGradient" ::? TS.Obj
('[ "cx" ::: TS.Number
, "cy" ::: TS.Number
, "r" ::: TS.Number
])
, "stops" ::? (TS.Array (TS.Array TS.Any))
, "brighten" ::? TS.Fun (TS.Number -> (TS.String :|: HighchartsGradient))
, "get" ::? TS.Fun (TS.String -> TS.String)
])
newtype HighchartsHeatMapChart = HighchartsHeatMapChart (GHCJS.JSRef (HighchartsHeatMapChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsHeatMapChart =
('[ ])
newtype HighchartsHeatMapSeriesOptions = HighchartsHeatMapSeriesOptions (GHCJS.JSRef (HighchartsHeatMapSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsHeatMapSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsHeatMapChart]
('[ ])
newtype HighchartsIndividualSeriesOptions = HighchartsIndividualSeriesOptions (GHCJS.JSRef (HighchartsIndividualSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsIndividualSeriesOptions =
('[ "data" ::? ((TS.Array TS.Number) :|: ((TS.Array (TS.Number, TS.Number)) :|: (TS.Array HighchartsDataPoint)))
, "id" ::? TS.String
, "index" ::? TS.Number
, "legendIndex" ::? TS.Number
, "name" ::? TS.String
, "stack" ::? TS.Any
, "type" ::? TS.String
, "xAxis" ::? (TS.String :|: TS.Number)
, "yAxis" ::? (TS.String :|: TS.Number)
])
newtype HighchartsLabelItem = HighchartsLabelItem (GHCJS.JSRef (HighchartsLabelItem))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLabelItem =
('[ "html" ::: TS.String
, "style" ::: HighchartsCSSObject
])
newtype HighchartsLabelsOptions = HighchartsLabelsOptions (GHCJS.JSRef (HighchartsLabelsOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLabelsOptions =
('[ "items" ::? (TS.Array HighchartsLabelItem)
, "style" ::? HighchartsCSSObject
])
newtype HighchartsLangObject = HighchartsLangObject (GHCJS.JSRef (HighchartsLangObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLangObject =
('[ "contextButtonTitle" ::? TS.String
, "decimalPoint" ::? TS.String
, "downloadJPEG" ::? TS.String
, "downloadPDF" ::? TS.String
, "downloadPNG" ::? TS.String
, "downloadSVG" ::? TS.String
, "drillUpText" ::? TS.String
, "loading" ::? TS.String
, "months" ::? (TS.Array TS.String)
, "noData" ::? TS.String
, "numericSymbols" ::? (TS.Array TS.String)
, "printChart" ::? TS.String
, "resetZoom" ::? TS.String
, "resetZoomTitle" ::? TS.String
, "shortMonths" ::? (TS.Array TS.String)
, "thousandsSep" ::? TS.String
, "weekdays" ::? (TS.Array TS.String)
])
newtype HighchartsLegendNavigationOptions = HighchartsLegendNavigationOptions (GHCJS.JSRef (HighchartsLegendNavigationOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLegendNavigationOptions =
('[ "activeColor" ::? TS.String
, "animation" ::? (TS.Boolean :|: HighchartsAnimation)
, "arrowSize" ::? TS.Number
, "inactiveColor" ::? TS.String
, "style" ::? HighchartsCSSObject
])
newtype HighchartsLegendOptions = HighchartsLegendOptions (GHCJS.JSRef (HighchartsLegendOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLegendOptions =
('[ "align" ::? TS.String
, "backgroundColor" ::? (TS.String :|: HighchartsGradient)
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "enabled" ::? TS.Boolean
, "floating" ::? TS.Boolean
, "itemHiddenStyle" ::? HighchartsCSSObject
, "itemHoverStyle" ::? HighchartsCSSObject
, "itemMarginBottom" ::? TS.Number
, "itemMarginTop" ::? TS.Number
, "itemStyle" ::? HighchartsCSSObject
, "itemWidth" ::? TS.Number
, "labelFormatter" ::? (TS.String)
, "layout" ::? TS.String
, "lineHeight" ::? TS.String
, "margin" ::? TS.Number
, "maxHeight" ::? TS.Number
, "navigation" ::? HighchartsLegendNavigationOptions
, "padding" ::? TS.Number
, "reversed" ::? TS.Boolean
, "rtl" ::? TS.Boolean
, "verticalAlign" ::? TS.String
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "style" ::? HighchartsCSSObject
, "symbolPadding" ::? TS.Number
, "symbolWidth" ::? TS.Number
, "useHTML" ::? TS.Boolean
, "width" ::? TS.Number
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsLineChart = HighchartsLineChart (GHCJS.JSRef (HighchartsLineChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLineChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "color" ::? TS.String
, "connectEnds" ::? TS.Boolean
, "connectNulls" ::? TS.Boolean
, "cropThreshold" ::? TS.Number
, "cursor" ::? TS.String
, "dashStyle" ::? TS.String
, "dataLabels" ::? HighchartsDataLabels
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "id" ::? TS.String
, "lineWidth" ::? TS.Number
, "marker" ::? HighchartsMarker
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPlacement" ::? TS.String
, "pointStart" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "stacking" ::? TS.String
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsAreaStates
])
, "step" ::? (TS.Boolean :|: TS.String)
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
, "zIndex" ::? TS.Number
])
newtype HighchartsLineChartSeriesOptions = HighchartsLineChartSeriesOptions (GHCJS.JSRef (HighchartsLineChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLineChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsLineChart]
('[ ])
newtype HighchartsLoadingOptions = HighchartsLoadingOptions (GHCJS.JSRef (HighchartsLoadingOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsLoadingOptions =
('[ "hideDuration" ::? TS.Number
, "labelStyle" ::? HighchartsCSSObject
, "showDuration" ::? TS.Number
, "style" ::? HighchartsCSSObject
])
newtype HighchartsMarker = HighchartsMarker (GHCJS.JSRef (HighchartsMarker))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsMarker = TS.Extends '[HighchartsMarkerState]
('[ "states" ::? TS.Obj
('[ "hover" ::? HighchartsMarkerState
, "select" ::? HighchartsMarkerState
])
, "symbol" ::? TS.String
])
newtype HighchartsMarkerState = HighchartsMarkerState (GHCJS.JSRef (HighchartsMarkerState))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsMarkerState =
('[ "enabled" ::? TS.Boolean
, "fillColor" ::? TS.String
, "lineColor" ::? TS.String
, "lineWidth" ::? TS.Number
, "radius" ::? TS.Number
])
newtype HighchartsMenuItem = HighchartsMenuItem (GHCJS.JSRef (HighchartsMenuItem))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsMenuItem =
('[ "text" ::: TS.String
, "onclick" ::: (TS.Void)
])
newtype HighchartsMousePlotEvents = HighchartsMousePlotEvents (GHCJS.JSRef (HighchartsMousePlotEvents))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsMousePlotEvents =
('[ "click" ::? (TS.Optional (Event) -> TS.Void)
, "mouseover" ::? (TS.Optional (Event) -> TS.Void)
, "mouseout" ::? (TS.Optional (Event) -> TS.Void)
, "mousemove" ::? (TS.Optional (Event) -> TS.Void)
])
newtype HighchartsNavigationOptions = HighchartsNavigationOptions (GHCJS.JSRef (HighchartsNavigationOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsNavigationOptions =
('[ "buttonOptions" ::? HighchartsButton
, "menuItemHoverStyle" ::? HighchartsCSSObject
, "menuItemStyle" ::? HighchartsCSSObject
, "menuStyle" ::? HighchartsCSSObject
])
newtype HighchartsOptions = HighchartsOptions (GHCJS.JSRef (HighchartsOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsOptions =
('[ "chart" ::? HighchartsChartOptions
, "colors" ::? (TS.Array TS.String)
, "credits" ::? HighchartsCreditsOptions
, "data" ::? TS.Any
, "drilldown" ::? TS.Any
, "exporting" ::? HighchartsExportingOptions
, "labels" ::? HighchartsLabelsOptions
, "legend" ::? HighchartsLegendOptions
, "loading" ::? HighchartsLoadingOptions
, "navigation" ::? HighchartsNavigationOptions
, "noData" ::? TS.Any
, "pane" ::? HighchartsPaneOptions
, "plotOptions" ::? HighchartsPlotOptions
, "series" ::? (TS.Array HighchartsIndividualSeriesOptions)
, "subtitle" ::? HighchartsSubtitleOptions
, "title" ::? HighchartsTitleOptions
, "tooltip" ::? HighchartsTooltipOptions
, "xAxis" ::? HighchartsAxisOptions
, "yAxis" ::? HighchartsAxisOptions
])
newtype HighchartsPaneBackground = HighchartsPaneBackground (GHCJS.JSRef (HighchartsPaneBackground))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPaneBackground =
('[ "backgroundColor" ::: (TS.String :|: HighchartsGradient)
, "borderColor" ::? TS.String
, "borderWidth" ::? TS.Number
, "innerRadius" ::? TS.String
, "outerRadius" ::? TS.String
])
newtype HighchartsPaneOptions = HighchartsPaneOptions (GHCJS.JSRef (HighchartsPaneOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPaneOptions =
('[ "background" ::? (TS.Array HighchartsPaneBackground)
, "center" ::? ((TS.Number :|: TS.String), (TS.Number :|: TS.String))
, "endAngle" ::? TS.Number
, "size" ::? (TS.Number :|: TS.String)
, "startAngle" ::? TS.Number
])
newtype HighchartsPieChart = HighchartsPieChart (GHCJS.JSRef (HighchartsPieChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPieChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "borderColor" ::? TS.String
, "borderWidth" ::? TS.Number
, "center" ::? (TS.Array TS.String)
, "color" ::? TS.String
, "cursor" ::? TS.String
, "dataLabels" ::? HighchartsDataLabels
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "id" ::? TS.String
, "ignoreHiddenPoint" ::? TS.Boolean
, "innerSize" ::? (TS.Number :|: TS.String)
, "lineWidth" ::? TS.Number
, "marker" ::? HighchartsMarker
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointPlacement" ::? TS.String
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showInLegend" ::? TS.Boolean
, "size" ::? (TS.Number :|: TS.String)
, "slicedOffset" ::? TS.Number
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsAreaStates
])
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "visible" ::? TS.Boolean
, "zIndex" ::? TS.Number
])
newtype HighchartsPieChartSeriesOptions = HighchartsPieChartSeriesOptions (GHCJS.JSRef (HighchartsPieChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPieChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsPieChart]
('[ ])
newtype HighchartsPivot = HighchartsPivot (GHCJS.JSRef (HighchartsPivot))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPivot =
('[ "backgroundColor" ::? TS.String
, "borderColor" ::? TS.String
, "borderWidth" ::? TS.Number
, "radius" ::? TS.Number
])
newtype HighchartsPlotBands = HighchartsPlotBands (GHCJS.JSRef (HighchartsPlotBands))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPlotBands =
('[ "color" ::? TS.String
, "events" ::? HighchartsMousePlotEvents
, "from" ::? TS.Number
, "id" ::? TS.String
, "label" ::? HighchartsPlotLabel
, "to" ::? TS.Number
, "zIndex" ::? TS.Number
])
newtype HighchartsPlotEvents = HighchartsPlotEvents (GHCJS.JSRef (HighchartsPlotEvents))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPlotEvents =
('[ "checkboxClick" ::? (HighchartsAreaCheckboxEvent -> TS.Boolean)
, "click" ::? (HighchartsAreaClickEvent -> TS.Void)
, "hide" ::? (TS.Void)
, "legendItemClick" ::? (Event -> TS.Boolean)
, "mouseOut" ::? (Event -> TS.Void)
, "mouseOver" ::? (Event -> TS.Void)
, "show" ::? (TS.Void)
])
newtype HighchartsPlotLabel = HighchartsPlotLabel (GHCJS.JSRef (HighchartsPlotLabel))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPlotLabel =
('[ "align" ::? TS.String
, "rotation" ::? TS.Number
, "style" ::? HighchartsCSSObject
, "text" ::? TS.String
, "textAlign" ::? TS.String
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsPlotLines = HighchartsPlotLines (GHCJS.JSRef (HighchartsPlotLines))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPlotLines =
('[ "color" ::? TS.String
, "dashStyle" ::? TS.String
, "events" ::? HighchartsMousePlotEvents
, "id" ::? TS.String
, "label" ::? HighchartsPlotLabel
, "value" ::? TS.Number
, "width" ::? TS.Number
, "zIndex" ::? TS.Number
])
newtype HighchartsPlotOptions = HighchartsPlotOptions (GHCJS.JSRef (HighchartsPlotOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPlotOptions =
('[ "area" ::? HighchartsAreaChart
, "arearange" ::? HighchartsAreaRangeChart
, "areaspline" ::? HighchartsAreaSplineChart
, "areasplinerange" ::? HighchartsAreaSplineRangeChart
, "bar" ::? HighchartsBarChart
, "boxplot" ::? HighchartsBoxPlotChart
, "bubble" ::? HighchartsBubbleChart
, "column" ::? HighchartsColumnChart
, "columnrange" ::? HighchartsColumnRangeChart
, "errorbar" ::? HighchartsErrorBarChart
, "funnel" ::? HighchartsFunnelChart
, "gauge" ::? HighchartsGaugeChart
, "heatmap" ::? HighchartsHeatMapChart
, "line" ::? HighchartsLineChart
, "pie" ::? HighchartsPieChart
, "polygon" ::? HighchartsPolygonChart
, "pyramid" ::? HighchartsPyramidChart
, "scatter" ::? HighchartsScatterChart
, "series" ::? HighchartsSeriesChart
, "solidgauge" ::? HighchartsSolidGaugeChart
, "spline" ::? HighchartsSplineChart
, "treemap" ::? HighchartsTreeMapChart
, "waterfall" ::? HighchartsWaterFallChart
])
newtype HighchartsPlotPoint = HighchartsPlotPoint (GHCJS.JSRef (HighchartsPlotPoint))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPlotPoint =
('[ "plotX" ::: TS.Number
, "plotY" ::: TS.Number
])
newtype HighchartsPointEvents = HighchartsPointEvents (GHCJS.JSRef (HighchartsPointEvents))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPointEvents =
('[ "click" ::? (Event -> TS.Boolean)
, "mouseOut" ::? (Event -> TS.Void)
, "mouseOver" ::? (Event -> TS.Void)
, "remove" ::? (Event -> TS.Boolean)
, "select" ::? (Event -> TS.Boolean)
, "unselect" ::? (Event -> TS.Boolean)
, "update" ::? (Event -> TS.Boolean)
])
newtype HighchartsPointObject = HighchartsPointObject (GHCJS.JSRef (HighchartsPointObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPointObject =
('[ "category" ::: (TS.String :|: TS.Number)
, "percentage" ::: TS.Number
, "remove" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void)
, "select" ::: TS.Fun (TS.Void)
, "select" ::: TS.Fun (TS.Boolean -> TS.Void)
, "select" ::: TS.Fun (TS.Boolean -> TS.Boolean -> TS.Void)
, "selected" ::: TS.Boolean
, "series" ::: HighchartsSeriesObject
, "slice" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void)
, "total" ::: TS.Number
, "update" ::: TS.Fun ((TS.Number :|: ((TS.Number, TS.Number) :|: HighchartsDataPoint)) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void)
, "x" ::: TS.Number
, "y" ::: TS.Number
])
newtype HighchartsPolygonChart = HighchartsPolygonChart (GHCJS.JSRef (HighchartsPolygonChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPolygonChart =
('[ ])
newtype HighchartsPolygonChartSeriesOptions = HighchartsPolygonChartSeriesOptions (GHCJS.JSRef (HighchartsPolygonChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPolygonChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsPolygonChart]
('[ ])
newtype HighchartsPosition = HighchartsPosition (GHCJS.JSRef (HighchartsPosition))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPosition =
('[ "align" ::? TS.String
, "verticalAlign" ::? TS.String
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsPyramidChart = HighchartsPyramidChart (GHCJS.JSRef (HighchartsPyramidChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPyramidChart =
('[ ])
newtype HighchartsPyramidChartSeriesOptions = HighchartsPyramidChartSeriesOptions (GHCJS.JSRef (HighchartsPyramidChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsPyramidChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsPyramidChart]
('[ ])
newtype HighchartsRangeDataLabels = HighchartsRangeDataLabels (GHCJS.JSRef (HighchartsRangeDataLabels))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsRangeDataLabels =
('[ "align" ::? TS.String
, "backgroundColor" ::? (TS.String :|: HighchartsGradient)
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "color" ::? TS.String
, "crop" ::? TS.Boolean
, "defer" ::? TS.Boolean
, "enabled" ::? TS.Boolean
, "format" ::? TS.String
, "formatter" ::? (TS.Any)
, "inside" ::? TS.Boolean
, "overflow" ::? TS.String
, "padding" ::? TS.Number
, "rotation" ::? TS.Number
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "style" ::? HighchartsCSSObject
, "useHTML" ::? TS.Boolean
, "verticalAlign" ::? TS.String
, "xHigh" ::? TS.Number
, "xLow" ::? TS.Number
, "yHigh" ::? TS.Number
, "yLow" ::? TS.Number
, "zIndex" ::? TS.Number
])
newtype HighchartsRenderer = HighchartsRenderer (GHCJS.JSRef (HighchartsRenderer))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsRenderer =
('[ TS.Constructor (HTMLElement -> TS.Number -> TS.Number -> HighchartsRendererObject)
])
newtype HighchartsRendererObject = HighchartsRendererObject (GHCJS.JSRef (HighchartsRendererObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsRendererObject =
('[ "arc" ::: TS.Fun (TS.Number -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject)
, "circle" ::: TS.Fun (TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject)
, "g" ::: TS.Fun (TS.String -> HighchartsElementObject)
, "image" ::: TS.Fun (TS.String -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject)
, "path" ::: TS.Fun ((TS.Array TS.Any) -> HighchartsElementObject)
, "rect" ::: TS.Fun (TS.Number -> TS.Number -> TS.Number -> TS.Number -> TS.Number -> HighchartsElementObject)
, "text" ::: TS.Fun (TS.String -> TS.Number -> TS.Number -> HighchartsElementObject)
])
newtype HighchartsScatterChart = HighchartsScatterChart (GHCJS.JSRef (HighchartsScatterChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsScatterChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "color" ::? TS.String
, "connectNulls" ::? TS.Boolean
, "cropThreshold" ::? TS.Number
, "cursor" ::? TS.String
, "dashStyle" ::? TS.String
, "dataLabels" ::? HighchartsDataLabels
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "id" ::? TS.String
, "lineWidth" ::? TS.Number
, "marker" ::? HighchartsMarker
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPlacement" ::? TS.String
, "pointStart" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsAreaStates
])
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
, "zIndex" ::? TS.Number
])
newtype HighchartsScatterChartSeriesOptions = HighchartsScatterChartSeriesOptions (GHCJS.JSRef (HighchartsScatterChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsScatterChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsScatterChart]
('[ ])
newtype HighchartsSelectionEvent = HighchartsSelectionEvent (GHCJS.JSRef (HighchartsSelectionEvent))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSelectionEvent = TS.Extends '[Event]
('[ "xAxis" ::: (TS.Array HighchartsAxisOptions)
, "yAxis" ::: (TS.Array HighchartsAxisOptions)
])
newtype HighchartsSeriesChart = HighchartsSeriesChart (GHCJS.JSRef (HighchartsSeriesChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSeriesChart =
('[ "allowPointSelect" ::? TS.Boolean
, "animation" ::? TS.Boolean
, "color" ::? TS.String
, "connectEnds" ::? TS.Boolean
, "connectNulls" ::? TS.Boolean
, "cropThreshold" ::? TS.Number
, "cursor" ::? TS.String
, "dashStyle" ::? TS.String
, "dataLabels" ::? HighchartsDataLabels
, "enableMouseTracking" ::? TS.Boolean
, "events" ::? HighchartsPlotEvents
, "lineWidth" ::? TS.Number
, "marker" ::? HighchartsMarker
, "point" ::? TS.Obj
('[ "events" ::: HighchartsPointEvents
])
, "pointInterval" ::? TS.Number
, "pointPlacement" ::? TS.String
, "pointStart" ::? TS.Number
, "selected" ::? TS.Boolean
, "shadow" ::? (TS.Boolean :|: HighchartsShadow)
, "showCheckbox" ::? TS.Boolean
, "showInLegend" ::? TS.Boolean
, "stacking" ::? TS.String
, "states" ::? TS.Obj
('[ "hover" ::: HighchartsAreaStates
])
, "stickyTracking" ::? TS.Boolean
, "tooltip" ::? HighchartsTooltipOptions
, "turboThreshold" ::? TS.Number
, "visible" ::? TS.Boolean
, "zIndex" ::? TS.Number
])
newtype HighchartsSeriesObject = HighchartsSeriesObject (GHCJS.JSRef (HighchartsSeriesObject))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSeriesObject =
('[ "addPoint" ::: TS.Fun ((TS.Number :|: ((TS.Number, TS.Number) :|: HighchartsDataPoint)) -> TS.Optional (TS.Boolean) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Void)
, "chart" ::: HighchartsChartObject
, "data" ::: (TS.Array HighchartsPointObject)
, "hide" ::: TS.Fun (TS.Void)
, "name" ::: TS.String
, "options" ::: HighchartsSeriesOptions
, "remove" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Void)
, "select" ::: TS.Fun (TS.Optional (TS.Boolean) -> TS.Void)
, "selected" ::: TS.Boolean
, "setData" ::: TS.Fun (((TS.Array TS.Number) :|: ((TS.Array (TS.Array TS.Number)) :|: (TS.Array HighchartsDataPoint))) -> TS.Optional (TS.Boolean) -> TS.Optional ((TS.Boolean :|: HighchartsAnimation)) -> TS.Optional (TS.Boolean) -> TS.Void)
, "setVisible" ::: TS.Fun (TS.Boolean -> TS.Optional (TS.Boolean) -> TS.Void)
, "show" ::: TS.Fun (TS.Void)
, "type" ::: TS.String
, "update" ::: TS.Fun (HighchartsSeriesOptions -> TS.Optional (TS.Boolean) -> TS.Void)
, "visible" ::: TS.Boolean
, "xAxis" ::: HighchartsAxisObject
, "yAxis" ::: HighchartsAxisObject
])
newtype HighchartsSeriesOptions = HighchartsSeriesOptions (GHCJS.JSRef (HighchartsSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSeriesOptions = TS.Extends '[HighchartsSeriesChart]
('[ "type" ::? TS.String
, "data" ::? ((TS.Array TS.Number) :|: ((TS.Array (TS.Array TS.Number)) :|: (TS.Array HighchartsDataPoint)))
, "index" ::? TS.Number
, "legendIndex" ::? TS.Number
, "name" ::? TS.String
, "stack" ::? (TS.String :|: TS.Number)
, "xAxis" ::? (TS.String :|: TS.Number)
, "yAxis" ::? (TS.String :|: TS.Number)
])
newtype HighchartsShadow = HighchartsShadow (GHCJS.JSRef (HighchartsShadow))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsShadow =
('[ "color" ::? TS.String
, "offsetX" ::? TS.Number
, "offsetY" ::? TS.Number
, "opacity" ::? TS.Number
, "width" ::? TS.Number
])
newtype HighchartsSolidGaugeChart = HighchartsSolidGaugeChart (GHCJS.JSRef (HighchartsSolidGaugeChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSolidGaugeChart =
('[ ])
newtype HighchartsSolidGaugeChartSeriesOptions = HighchartsSolidGaugeChartSeriesOptions (GHCJS.JSRef (HighchartsSolidGaugeChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSolidGaugeChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsSolidGaugeChart]
('[ ])
newtype HighchartsSplineChart = HighchartsSplineChart (GHCJS.JSRef (HighchartsSplineChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSplineChart = TS.Extends '[HighchartsSeriesChart]
('[ ])
newtype HighchartsSplineChartSeriesOptions = HighchartsSplineChartSeriesOptions (GHCJS.JSRef (HighchartsSplineChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSplineChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsSplineChart]
('[ ])
newtype HighchartsStatic = HighchartsStatic (GHCJS.JSRef (HighchartsStatic))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsStatic =
('[ "Chart" ::: HighchartsChart
, "Renderer" ::: HighchartsRenderer
, "Color" ::: TS.Fun ((TS.String :|: HighchartsGradient) -> (TS.String :|: HighchartsGradient))
, "dateFormat" ::: TS.Fun (TS.String -> TS.Optional (TS.Number) -> TS.Optional (TS.Boolean) -> TS.String)
, "numberFormat" ::: TS.Fun (TS.Number -> TS.Optional (TS.Number) -> TS.Optional (TS.String) -> TS.Optional (TS.String) -> TS.String)
, "setOptions" ::: TS.Fun (HighchartsGlobalOptions -> HighchartsOptions)
, "getOptions" ::: TS.Fun (HighchartsOptions)
, "map" ::: TS.Fun ((TS.Array TS.Any) -> Function -> (TS.Array TS.Any))
])
newtype HighchartsSubtitleOptions = HighchartsSubtitleOptions (GHCJS.JSRef (HighchartsSubtitleOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsSubtitleOptions =
('[ "align" ::? TS.String
, "verticalAlign" ::? TS.String
, "floating" ::? TS.Boolean
, "style" ::? HighchartsCSSObject
, "text" ::? TS.String
, "useHTML" ::? TS.Boolean
, "x" ::? TS.Number
, "y" ::? TS.Number
])
newtype HighchartsTitleOptions = HighchartsTitleOptions (GHCJS.JSRef (HighchartsTitleOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsTitleOptions = TS.Extends '[HighchartsSubtitleOptions]
('[ "margin" ::? TS.Number
])
newtype HighchartsTooltipOptions = HighchartsTooltipOptions (GHCJS.JSRef (HighchartsTooltipOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsTooltipOptions =
('[ "animation" ::? TS.Boolean
, "backgroundColor" ::? (TS.String :|: HighchartsGradient)
, "borderColor" ::? TS.String
, "borderRadius" ::? TS.Number
, "borderWidth" ::? TS.Number
, "crosshairs" ::? (TS.Boolean :|: ((TS.Boolean, TS.Boolean) :|: (HighchartsCrosshairObject :|: (HighchartsCrosshairObject, HighchartsCrosshairObject))))
, "enabled" ::? TS.Boolean
, "footerFormat" ::? TS.String
, "formatter" ::? (TS.Any)
, "pointFormat" ::? TS.String
, "positioner" ::? (TS.Number -> TS.Number -> HighchartsPlotPoint -> TS.Obj
('[ "x" ::: TS.Number
, "y" ::: TS.Number
])
)
, "shadow" ::? TS.Boolean
, "shared" ::? TS.Boolean
, "snap" ::? TS.Number
, "style" ::? HighchartsCSSObject
, "useHTML" ::? TS.Boolean
, "valueDecimals" ::? TS.Number
, "valuePrefix" ::? TS.String
, "valueSuffix" ::? TS.String
, "xDateFormat" ::? TS.String
])
newtype HighchartsTreeMapChart = HighchartsTreeMapChart (GHCJS.JSRef (HighchartsTreeMapChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsTreeMapChart =
('[ ])
newtype HighchartsTreeMapChartSeriesOptions = HighchartsTreeMapChartSeriesOptions (GHCJS.JSRef (HighchartsTreeMapChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsTreeMapChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsTreeMapChart]
('[ ])
newtype HighchartsWaterFallChart = HighchartsWaterFallChart (GHCJS.JSRef (HighchartsWaterFallChart))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsWaterFallChart =
('[ ])
newtype HighchartsWaterFallChartSeriesOptions = HighchartsWaterFallChartSeriesOptions (GHCJS.JSRef (HighchartsWaterFallChartSeriesOptions))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members HighchartsWaterFallChartSeriesOptions = TS.Extends '[HighchartsIndividualSeriesOptions, HighchartsWaterFallChart]
('[ ])
newtype JQuery = JQuery (GHCJS.JSRef (JQuery))
deriving (Data.Typeable.Typeable, GHCJS.ToJSRef, GHCJS.FromJSRef)
type instance TS.Members JQuery =
('[ "highcharts" ::: TS.Fun (HighchartsChartObject)
, "highcharts" ::: TS.Fun (HighchartsOptions -> JQuery)
, "highcharts" ::: TS.Fun (HighchartsOptions -> (HighchartsChartObject -> TS.Void) -> JQuery)
])
|
mgsloan/ghcjs-typescript
|
examples/highcharts/Raw.hs
|
mit
| 68,354 | 0 | 20 | 11,775 | 18,674 | 10,368 | 8,306 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.XMLHttpRequestUpload
(abort, error, load, loadEnd, loadStart, progress,
XMLHttpRequestUpload, castToXMLHttpRequestUpload,
gTypeXMLHttpRequestUpload)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onabort Mozilla XMLHttpRequestUpload.onabort documentation>
abort :: EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent
abort = unsafeEventName (toJSString "abort")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onerror Mozilla XMLHttpRequestUpload.onerror documentation>
error :: EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent
error = unsafeEventName (toJSString "error")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onload Mozilla XMLHttpRequestUpload.onload documentation>
load :: EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent
load = unsafeEventName (toJSString "load")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onloadend Mozilla XMLHttpRequestUpload.onloadend documentation>
loadEnd :: EventName XMLHttpRequestUpload ProgressEvent
loadEnd = unsafeEventName (toJSString "loadend")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onloadstart Mozilla XMLHttpRequestUpload.onloadstart documentation>
loadStart :: EventName XMLHttpRequestUpload ProgressEvent
loadStart = unsafeEventName (toJSString "loadstart")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestUpload.onprogress Mozilla XMLHttpRequestUpload.onprogress documentation>
progress ::
EventName XMLHttpRequestUpload XMLHttpRequestProgressEvent
progress = unsafeEventName (toJSString "progress")
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/XMLHttpRequestUpload.hs
|
mit
| 2,568 | 0 | 7 | 234 | 450 | 279 | 171 | 32 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeOperators #-}
module Api (app) where
import Control.Monad.Except (ExceptT)
import Control.Monad.Reader (ReaderT, runReaderT)
-- import Control.Monad.Reader.Class ()
import Data.Int (Int64)
import Database.Persist.Postgresql (Entity (..), fromSqlKey, insert,
selectFirst, selectList, (==.))
import Network.Wai (Application)
import Servant {- ((:<|>)((:<|>)), (:~>)(Nat)
, Proxy(Proxy) , Raw, Server
, ServantErr, enter, serve
, serveDirectory) -}
import Config (App (..), Config (..))
import Models
import Api.Aircraft
-- | This is the function we export to run our 'AircraftAPI'. Given
-- a 'Config', we return a WAI 'Application' which any WAI compliant server
-- can run.
aircraftApp :: Config -> Application
aircraftApp cfg = serve (Proxy :: Proxy AircraftAPI) (appToServer cfg)
-- | This functions tells Servant how to run the 'App' monad with our
-- 'server' function.
appToServer :: Config -> Server AircraftAPI
appToServer cfg = enter (convertApp cfg) aircraftServer
-- | This function converts our 'App' monad into the @ExceptT ServantErr
-- IO@ monad that Servant's 'enter' function needs in order to run the
-- application. The ':~>' type is a natural transformation, or, in
-- non-category theory terms, a function that converts two type
-- constructors without looking at the values in the types.
convertApp :: Config -> App :~> ExceptT ServantErr IO
convertApp cfg = Nat (flip runReaderT cfg . runApp)
-- | Since we also want to provide a minimal front end, we need to give
-- Servant a way to serve a directory with HTML and JavaScript. This
-- function creates a WAI application that just serves the files out of the
-- given directory.
files :: Application
files = serveDirectory "assets"
-- | Just like a normal API type, we can use the ':<|>' combinator to unify
-- two different APIs and applications. This is a powerful tool for code
-- reuse and abstraction! We need to put the 'Raw' endpoint last, since it
-- always succeeds.
type AppAPI = AircraftAPI :<|> Raw
appApi :: Proxy AppAPI
appApi = Proxy
-- | Finally, this function takes a configuration and runs our 'AircraftAPI'
-- alongside the 'Raw' endpoint that serves all of our files.
app :: Config -> Application
app cfg =
serve appApi (appToServer cfg :<|> files)
|
tdox/aircraft-service
|
src/Api.hs
|
mit
| 2,746 | 0 | 8 | 782 | 318 | 191 | 127 | 28 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
--------------------------------------------------
--------------------------------------------------
{-| Define (non-deriveable) 'Ix' instances
via a (deriveable) 'Enumerate' instance.
== Usage
@
data A = ...
instance 'Bounded' A where
minBound = 'minBound_Enumerable' array_A
maxBound = 'maxBound_Enumerable' array_A
instance 'Enum' A where
toEnum = 'toEnum_Enumerable' array_A
fromEnum = 'fromEnum_Enumerable' table_A
-- CAF
array_A :: 'Array' Int A
array_A = 'array_Enumerable'
-- CAF
table_A :: 'Map' A Int
table_A = 'table_Enumerable'
-- we must pass in <https://wiki.haskell.org/Constant_applicative_form CAF>s
-- (i.e. expressions that are top-level and unconstrained),
-- which will be shared between all calls to minBound/maxBound/toEnum/fromEnum.
-- TODO must we?
@
--TODO template-haskell
See, also, the source of "Enumerate.Example".
@
inRange (l,u) i == elem i (range (l,u))
range (l,u) !! index (l,u) i == i, when inRange (l,u) i
map (index (l,u)) (range (l,u))) == [0..rangeSize (l,u)-1]
rangeSize (l,u) == length (range (l,u))
@
-}
--------------------------------------------------
--------------------------------------------------
module Enumerate.Ix
(
-- * @Ix@ methods:
range_Enumerable
, unsafeIndex_Enumerable
, inRange_Enumerable
) where
--------------------------------------------------
--------------------------------------------------
import Enumerate.Prelude
import Enumerate.Types
import Enumerate.Enum
--------------------------------------------------
-- Imports ---------------------------------------
--------------------------------------------------
import qualified "containers" Data.Map as Map
import "containers" Data.Map (Map)
--------------------------------------------------
import qualified "containers" Data.Sequence as Seq
import "containers" Data.Sequence (Seq)
--------------------------------------------------
import qualified Prelude
--------------------------------------------------
-- Types -----------------------------------------
--------------------------------------------------
--type BinarySearchTree a = (Int,a) -- TODO
-- Data.Map
-- Data.IntMap
-- Data.Sequence
--------------------------------------------------
-- « Ix » ----------------------------------------
--------------------------------------------------
{- | A (`Seq`-based) `range` implementation for an 'Enumerable' type.
"The list of values in the subrange defined by a bounding pair."
-}
range_Enumerable
:: forall a. (Enumerable a, Ord a)
=> (a,a) -> [a]
range_Enumerable = range_Seq sequence_Enumerable
{-# INLINEABLE range_Enumerable #-}
--------------------------------------------------
{-
{- |
"Like 'index', but without checking that the value is in range."
-}
unsafeIndex_Enumerable
:: forall a. (Enumerable a, Ord a)
=> (a,a) -> a -> Int
unsafeIndex_Enumerable = _indexWith _enumerated
{-# INLINEABLE unsafeIndex_Enumerable #-}
--------------------------------------------------
{- |
"Returns @True@ if the given subscript lies in the range defined
by the bounding pair."
-}
inRange_Enumerable
:: forall a. (Enumerable a, Ord a)
=> (a,a) -> a -> Bool
inRange_Enumerable = _withinWith _enumerated
{-# INLINEABLE inRange_Enumerable #-}
--------------------------------------------------
-- Caching ---------------------------------------
--------------------------------------------------
{-| Binary Search Tree for all values in a type.
Efficiently find subsets of
Mapping from indices (@Int@) to values (@Enumerable a => @a@).
-}
tree_Enumerable
:: forall a. (Enumerable a)
=> BinarySearchTree a
tree_Enumerable = tree
where
tree :: Tree Int a
tree = Tree.listTree bounds enumerated
bounds :: (Int, Int)
bounds = (0, n - 1)
n = intCardinality ([] :: [a])
-}
--------------------------------------------------
-- Utilities -------------------------------------
--------------------------------------------------
{- | Return a `range` function, given a `Seq`uence.
i.e. @range_Seq xs@ asssumes the `Seq`uence @(xs :: 'Seq' a)@ is monotonically increasing,
w.r.t @('Ord' a)@ . You may call 'Seq.sort' on @xs@ to ensure this prerequisite.
-}
range_Seq
:: forall a. (Ord a)
=> Seq a
-> ((a,a) -> [a])
range_Seq xs = range_
where
range_ :: (a,a) -> [a]
range_ (i,k) =
if (i <= k)
then toList js
else []
where
js = xs &
( Seq.dropWhileL (`lessThan` i)
> Seq.takeWhileL (<= k)
)
{-# INLINEABLE range_Seq #-}
--------------------------------------------------
{- | Return an `inRange` function, given a `Seq`uence.
-}
inRange_Seq
:: forall a. (Ord a)
=> Seq a
-> ((a, a) -> a -> Bool)
inRange_Seq xs = inRange_
where
inRange_ :: (a, a) -> a -> Bool
inRange_ (i,j) x = ys
where
ys = _ xs
{-# INLINEABLE inRange_Seq #-}
--------------------------------------------------
-- Notes -----------------------------------------
--------------------------------------------------
{-
from <http://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Arr.html#range>:
{- ...
Note [Inlining index]
~~~~~~~~~~~~~~~~~~~~~
We inline the 'index' operation,
* Partly because it generates much faster code
(although bigger); see Trac #1216
* Partly because it exposes the bounds checks to the simplifier which
might help a big.
If you make a per-instance index method, you may consider inlining it.
Note [Double bounds-checking of index values]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you index an array, a!x, there are two possible bounds checks we might make:
(A) Check that (inRange (bounds a) x) holds.
(A) is checked in the method for 'index'
(B) Check that (index (bounds a) x) lies in the range 0..n,
where n is the size of the underlying array
(B) is checked in the top-level function (!), in safeIndex.
Of course it *should* be the case that (A) holds iff (B) holds, but that
is a property of the particular instances of index, bounds, and inRange,
so GHC cannot guarantee it.
* If you do (A) and not (B), then you might get a seg-fault,
by indexing at some bizarre location. Trac #1610
* If you do (B) but not (A), you may get no complaint when you index
an array out of its semantic bounds. Trac #2120
At various times we have had (A) and not (B), or (B) and not (A); both
led to complaints. So now we implement *both* checks (Trac #2669).
For 1-d, 2-d, and 3-d arrays of Int we have specialised instances to avoid this.
Note [Out-of-bounds error messages]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The default method for 'index' generates hoplelessIndexError, because
Ix doesn't have Show as a superclass. For particular base types we
can do better, so we override the default method for index.
-}
-- Abstract these errors from the relevant index functions so that
-- the guts of the function will be small enough to inline.
{-# NOINLINE indexError #-}
indexError :: Show a => (a,a) -> a -> String -> b
indexError rng i tp
= errorWithoutStackTrace (showString "Ix{" . showString tp . showString "}.index: Index " .
showParen True (showsPrec 0 i) .
showString " out of range " $
showParen True (showsPrec 0 rng) "")
hopelessIndexError :: Int -- Try to use 'indexError' instead!
hopelessIndexError = errorWithoutStackTrace "Error in array index"
-}
--------------------------------------------------
-- EOF -------------------------------------------
--------------------------------------------------
|
sboosali/enumerate
|
enumerate/sources/Enumerate/Ix.hs
|
mit
| 7,847 | 0 | 13 | 1,522 | 405 | 255 | 150 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-action.html
module Stratosphere.ResourceProperties.WAFRegionalWebACLAction where
import Stratosphere.ResourceImports
-- | Full data type definition for WAFRegionalWebACLAction. See
-- 'wafRegionalWebACLAction' for a more convenient constructor.
data WAFRegionalWebACLAction =
WAFRegionalWebACLAction
{ _wAFRegionalWebACLActionType :: Val Text
} deriving (Show, Eq)
instance ToJSON WAFRegionalWebACLAction where
toJSON WAFRegionalWebACLAction{..} =
object $
catMaybes
[ (Just . ("Type",) . toJSON) _wAFRegionalWebACLActionType
]
-- | Constructor for 'WAFRegionalWebACLAction' containing required fields as
-- arguments.
wafRegionalWebACLAction
:: Val Text -- ^ 'wafrwaclaType'
-> WAFRegionalWebACLAction
wafRegionalWebACLAction typearg =
WAFRegionalWebACLAction
{ _wAFRegionalWebACLActionType = typearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-action.html#cfn-wafregional-webacl-action-type
wafrwaclaType :: Lens' WAFRegionalWebACLAction (Val Text)
wafrwaclaType = lens _wAFRegionalWebACLActionType (\s a -> s { _wAFRegionalWebACLActionType = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/WAFRegionalWebACLAction.hs
|
mit
| 1,379 | 0 | 13 | 164 | 174 | 100 | 74 | 23 | 1 |
--file ch6/TypeClass.hs
module TypeClass
where
class BasicEq a where
isEqual :: a -> a -> Bool
isEqual x y = not (isNotEqual x y)
isNotEqual :: a -> a -> Bool
isNotEqual x y = not (isEqual x y)
data Color = Red | Blue | Green
deriving (Show, Read, Eq, Ord)
instance BasicEq Color where
isEqual Red Red = True
isEqual Blue Blue = True
isEqual Green Green = True
isEqual _ _ = True
type JSONError = String
class JSON a where
toJValue :: a -> JValue
fromJValue :: JValue -> Either JSONError a
instance JSON JValue where
toJValue = id
fromJValue = Right
|
Numberartificial/workflow
|
haskell-first-principles/src/RW/CH6/TypeClass.hs
|
mit
| 610 | 0 | 9 | 166 | 218 | 114 | 104 | 20 | 0 |
module Specify.Eval where
import Specify.Expression
import Specify.Definition
import Autolib.Set
import Autolib.ToDoc
import Autolib.Reporter
eval :: ToDoc a
=> Program
-> Expression a
-> Reporter ( Maybe a )
eval p x = case x of
Constant c -> return $ Just c
Undefined -> return $ Nothing
Apply fun args -> do
d @ ( Definition _ params body ) <- find p fun
when ( length args /= length params ) $ reject $ vcat
[ text "Ausdruck:" <+> toDoc x
, text "Anzahl der Argumente paßt nicht:"
, text "Deklaration:" <+> toDoc d
]
values <- mapM ( eval p ) args
-- static binding: evaluate in fresh environment
res <- eval ( make $ zip params values ) body
when ( not $ null args ) $ inform
$ toDoc fun <+> parens ( sepBy comma $ map ( toDoc . einpack ) values )
<+> equals <+> toDoc ( einpack res )
return res
Branch c y z -> do
mcc <- eval p c
case mcc of
Nothing -> return Nothing
Just cc -> eval p $ if cc then y else z
Plus x y -> bin (+) p x y
Minus x y -> bin (-) p x y
Negate x -> un negate p x
Times x y -> bin (*) p x y
Quotient x y -> bin_nonzero div p x y
Remainder x y -> bin_nonzero mod p x y
Less x y -> bin ( < ) p x y
LessEqual x y -> bin ( <= ) p x y
Equal x y -> bin ( == ) p x y
GreaterEqual x y -> bin ( >= ) p x y
Greater x y -> bin ( > ) p x y
NotEqual x y -> bin ( /= ) p x y
Or x y -> bin ( || ) p x y
And x y -> bin ( && ) p x y
Implies x y -> bin ( >= ) p x y
Not x -> un not p x
bin :: ( ToDoc a, ToDoc b, ToDoc c )
=> ( a -> b -> c )
-> Program
-> Expression a
-> Expression b
-> Reporter ( Maybe c )
bin op p x y = do
ma <- eval p x
mb <- eval p y
case ( ma, mb ) of
( Just a, Just b ) -> return $ Just $ op a b
_ -> return $ Nothing
bin_nonzero op p x y = do
ma <- eval p x
mb <- eval p y
case ( ma, mb ) of
( _ , Just 0 ) -> reject $ text "division by zero"
( Just a, Just b ) -> return $ Just $ op a b
_ -> return $ Nothing
un :: ( ToDoc a, ToDoc b )
=> ( a -> b )
-> Program
-> Expression a
-> Reporter ( Maybe b )
un op p x = do
ma <- eval p x
return $ fmap op ma
|
florianpilz/autotool
|
src/Specify/Eval.hs
|
gpl-2.0
| 2,526 | 27 | 16 | 1,052 | 1,047 | 524 | 523 | 73 | 22 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PatternGuards #-}
-- |
-- Copyright : (c) 2010-2012 Simon Meier, Benedikt Schmidt
-- contributing in 2019: Robert Künnemann, Johannes Wocker
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Portability : portable
--
-- Parsing protocol theories. See the MANUAL for a high-level description of
-- the syntax.
module Theory.Text.Parser (
parseOpenTheory
, parseOpenTheoryString
, parseOpenDiffTheory
, parseOpenDiffTheoryString
, parseLemma
, parseRestriction
, parseIntruderRules
, liftedAddProtoRule
, liftedAddRestriction
) where
import Prelude hiding (id, (.))
import Data.Foldable (asum)
import Data.Label
-- import Data.Monoid hiding (Last)
import qualified Data.Set as S
import System.FilePath
import Control.Category
import Control.Monad
import Control.Applicative hiding (empty, many, optional)
import qualified Control.Monad.Catch as Catch
import System.IO.Unsafe (unsafePerformIO)
import Text.Parsec hiding ((<|>))
import Text.PrettyPrint.Class (render)
import Theory
import Theory.Text.Parser.Token
import Theory.Text.Parser.Lemma
import Theory.Text.Parser.Rule
import Theory.Text.Parser.Exceptions
import Theory.Text.Parser.Signature
import Theory.Text.Parser.Restriction
import Theory.Text.Parser.Sapic
------------------------------------------------------------------------------
-- Lexing and parsing theory files and proof methods
------------------------------------------------------------------------------
-- | Parse a security protocol theory file.
parseOpenTheory :: [String] -- ^ Defined flags
-> FilePath
-> IO OpenTheory
parseOpenTheory flags0 inFile = parseFile flags0 (theory (Just inFile)) inFile
-- | Parse a security protocol theory file.
parseOpenDiffTheory :: [String] -- ^ Defined flags
-> FilePath
-> IO OpenDiffTheory
parseOpenDiffTheory flags0 inFile = parseFile flags0 (diffTheory (Just inFile)) inFile
-- | Parse a security protocol theory from a string.
parseOpenTheoryString :: [String] -- ^ Defined flags.
-> String -> Either ParseError OpenTheory
parseOpenTheoryString flags0 = parseString flags0 "<unknown source>" (theory Nothing)
-- | Parse a security protocol theory from a string.
parseOpenDiffTheoryString :: [String] -- ^ Defined flags.
-> String -> Either ParseError OpenDiffTheory
parseOpenDiffTheoryString flags0 = parseString flags0 "<unknown source>" (diffTheory Nothing)
-- | Parse a lemma for an open theory from a string.
parseLemma :: String -> Either ParseError (SyntacticLemma ProofSkeleton)
parseLemma = parseString [] "<unknown source>" (lemma Nothing)
------------------------------------------------------------------------------
-- Parsing Theories
------------------------------------------------------------------------------
liftedExpandFormula :: Catch.MonadThrow m =>
Theory sig c r p s -> SyntacticLNFormula -> m LNFormula
liftedExpandFormula thy = liftEitherToEx UndefinedPredicate . expandFormula thy
liftedExpandLemma :: Catch.MonadThrow m => Theory sig c r p1 s
-> ProtoLemma SyntacticLNFormula p2 -> m (ProtoLemma LNFormula p2)
liftedExpandLemma thy = liftEitherToEx UndefinedPredicate . expandLemma thy
liftedExpandRestriction :: Catch.MonadThrow m =>
Theory sig c r p s
-> ProtoRestriction SyntacticLNFormula
-> m (ProtoRestriction LNFormula)
liftedExpandRestriction thy = liftEitherToEx UndefinedPredicate . expandRestriction thy
liftedAddProtoRuleNoExpand :: Catch.MonadThrow m => OpenTheory -> Theory.OpenProtoRule -> m OpenTheory
liftedAddProtoRuleNoExpand thy ru = liftMaybeToEx (DuplicateItem (RuleItem ru)) (addOpenProtoRule ru thy)
liftedAddRestriction :: Catch.MonadThrow m =>
Theory sig c r p s
-> ProtoRestriction SyntacticLNFormula -> m (Theory sig c r p s)
liftedAddRestriction thy rstr = do
rstr' <- liftedExpandRestriction thy rstr
liftMaybeToEx (DuplicateItem $ RestrictionItem rstr') (addRestriction rstr' thy)
-- Could catch at which point in to lemma, but need MonadCatch
-- ++ " in definition of predicate: "
-- ++ get rstrName rstr
-- ++ "."
liftedAddLemma :: Catch.MonadThrow m =>
Theory sig c r ProofSkeleton s
-> ProtoLemma SyntacticLNFormula ProofSkeleton
-> m (Theory sig c r ProofSkeleton s)
liftedAddLemma thy lem = do
lem' <- liftedExpandLemma thy lem
liftMaybeToEx (DuplicateItem $ LemmaItem lem') (addLemma lem' thy)
-- Could catch at which point in to lemma, but need MonadCatch
-- ++ " in lemma: "
-- ++ get lName lem
-- ++ "."
-- | Add new protocol rule and introduce restrictions for _restrict contruct
-- 1. expand syntactic restrict constructs
-- 2. for each, chose fresh action and restriction name
-- 3. add action names to rule
-- 4. add rule, fail if duplicate
-- 5. add restrictions, fail if duplicate
-- FIXME: we only deal we the rule modulo E here, if variants modulo AC are
-- imported we do not check if they have _restrict annotations
-- (but they should not, as they will not be exported)
liftedAddProtoRule :: Catch.MonadThrow m => OpenTheory -> OpenProtoRule -> m OpenTheory
liftedAddProtoRule thy ru
| (StandRule rname) <- get (preName . rInfo . oprRuleE) ru = do
rformulasE <- mapM (liftedExpandFormula thy) (rfacts $ get oprRuleE ru)
thy' <- foldM addExpandedRestriction thy (restrictions rname rformulasE)
thy'' <- liftedAddProtoRuleNoExpand thy' (addActions rname rformulasE) -- TODO was ru instead of rformulas
return thy''
| otherwise = Catch.throwM TryingToAddFreshRule
where
rfacts = get (preRestriction . rInfo)
addExpandedRestriction thy' xrstr = liftMaybeToEx
(DuplicateItem $ RestrictionItem xrstr)
(addRestriction xrstr thy')
addActions rname rformulas = modify (rActs . oprRuleE) (++ actions rname rformulas) ru
restrictions rname rformulas = map (fst . fromRuleRestriction' rname) (counter rformulas)
actions rname rformulas = map (snd . fromRuleRestriction' rname) (counter rformulas)
fromRuleRestriction' rname (i,f) = fromRuleRestriction (rname ++ "_" ++ show i) f
counter = zip [1::Int ..]
-- | Flag formulas
data FlagFormula =
FAtom String
| FOr FlagFormula FlagFormula
| FAnd FlagFormula FlagFormula
| FNot FlagFormula
flagatom :: Parser FlagFormula
flagatom = FAtom <$> try identifier
-- | Parse a negation.
flagnegation :: Parser FlagFormula
flagnegation = opLNot *> (FNot <$> flagatom) <|> flagatom
-- | Parse a left-associative sequence of conjunctions.
flagconjuncts :: Parser FlagFormula
flagconjuncts = chainl1 flagnegation (FAnd <$ opLAnd)
-- | Parse a left-associative sequence of disjunctions.
flagdisjuncts :: Parser FlagFormula
flagdisjuncts = chainl1 flagconjuncts (FOr <$ opLOr)
evalformula :: S.Set String -> FlagFormula -> Bool
evalformula flags0 (FAtom t) = S.member t flags0
evalformula flags0 (FNot t) = not (evalformula flags0 t)
evalformula flags0 (FOr t1 t2) = (evalformula flags0 t1) || (evalformula flags0 t2)
evalformula flags0 (FAnd t1 t2) = (evalformula flags0 t1) && (evalformula flags0 t2)
-- | Parse a theory.
theory :: Maybe FilePath
-> Parser OpenTheory
theory inFile = do
flags0 <- flags <$> getState
when ("diff" `S.member` flags0) $ modifyStateSig (`mappend` enableDiffMaudeSig) -- Add the diffEnabled flag into the MaudeSig when the diff flag is set on the command line.
symbol_ "theory"
thyId <- identifier
thy' <- symbol_ "begin"
*> addItems inFile (set thyName thyId (defaultOpenTheory ("diff" `S.member` flags0)))
<* symbol "end"
return thy'
where
addItems :: Maybe FilePath -> OpenTheory -> Parser OpenTheory
addItems inFile0 thy = asum
[ do thy' <- liftedAddHeuristic thy =<< heuristic False workDir
addItems inFile0 thy'
, do thy' <- builtins thy
msig <- sig <$> getState
addItems inFile0 $ set (sigpMaudeSig . thySignature) msig thy'
, do thy' <- options thy
addItems inFile0 thy'
, do functions
msig <- sig <$> getState
addItems inFile0 $ set (sigpMaudeSig . thySignature) msig thy
, do equations
msig <- sig <$> getState
addItems inFile0 $ set (sigpMaudeSig . thySignature) msig thy
-- , do thy' <- foldM liftedAddProtoRule thy =<< transferProto
-- addItems inFile0 flags thy'
, do thy' <- liftedAddRestriction thy =<< restriction
addItems inFile0 thy'
, do thy' <- liftedAddRestriction thy =<< legacyAxiom
addItems inFile0 thy'
-- add legacy deprecation warning output
, do thy' <- liftedAddLemma thy =<< lemma workDir
addItems inFile0 thy'
, do ru <- protoRule
thy' <- liftedAddProtoRule thy ru
-- thy'' <- foldM liftedAddRestriction thy' $
-- map (Restriction "name") [get (preRestriction . rInfo) ru]
addItems inFile0 thy'
, do r <- intrRule
addItems inFile0 (addIntrRuleACs [r] thy)
, do c <- formalComment
addItems inFile0 (addFormalComment c thy)
, do procc <- process thy -- try parsing a process
addItems inFile0 (addProcess procc thy) -- add process to theoryitems and proceed parsing (recursive addItems inFile0 call)
, do thy' <- ((liftedAddProcessDef thy) =<<) (processDef thy) -- similar to process parsing but in addition check that process with this name is only defined once (checked via liftedAddProcessDef)
addItems inFile0 thy'
, do thy' <- preddeclaration thy
addItems inFile0 (thy')
, do ifdef inFile0 thy
, do define inFile0 thy
, do include inFile0 thy
, do return thy
]
where workDir = (takeDirectory <$> inFile0)
define inFile0 thy = do
flag <- try (symbol "#define") *> identifier
modifyStateFlag (S.insert flag)
addItems inFile0 thy
include :: Maybe FilePath -> OpenTheory -> Parser OpenTheory
include inFile0 thy = do
filepath <- try (symbol "#include") *> filePathParser
st <- getState
let (thy', st') = unsafePerformIO (parseFileWState st (addItems' (Just filepath) thy) filepath)
_ <- putState st'
addItems inFile0 $ set (sigpMaudeSig . thySignature) (sig st') thy'
where
addItems' :: Maybe FilePath -> OpenTheory -> Parser (OpenTheory, ParserState)
addItems' inFile1 thy1 = do
thy' <- addItems inFile1 thy1
st <- getState
return (thy', st)
filePathParser = case takeDirectory <$> inFile0 of
Nothing -> do
x <- doubleQuoted filePath
return (x <> [pathSeparator])
Just s -> do
x <- doubleQuoted filePath
return (s </> x)
ifdef :: Maybe FilePath -> OpenTheory -> Parser OpenTheory
ifdef inFile0 thy = do
flagf <- symbol_ "#ifdef" *> flagdisjuncts
flags0 <- flags <$> getState
if evalformula flags0 flagf
then do thy' <- addItems inFile0 thy
asum [do symbol_ "#else"
_ <- manyTill anyChar (try (symbol_ "#endif"))
addItems inFile0 thy'
,do symbol_ "#endif"
addItems inFile0 thy'
]
else parseelse
where
parseelse =
do _ <- manyTill anyChar (try (symbol_ "#"))
asum
[do (symbol_ "else")
thy' <- addItems inFile0 thy
symbol_ "#endif"
addItems inFile0 thy'
,do _ <- symbol_ "endif"
addItems inFile0 thy
, parseelse
]
-- check process defined only once
-- add process to theoryitems
liftedAddProcessDef thy pDef = case addProcessDef pDef thy of
Just thy' -> return thy'
Nothing -> fail $ "duplicate process: " ++ get pName pDef
liftedAddHeuristic thy h = case addHeuristic h thy of
Just thy' -> return thy'
Nothing -> fail $ "default heuristic already defined"
-- | Parse a diff theory.
diffTheory :: Maybe FilePath
-> Parser OpenDiffTheory
diffTheory inFile = do
flags0 <- flags <$> getState
modifyStateSig (`mappend` enableDiffMaudeSig) -- Add the diffEnabled flag into the MaudeSig when the diff flag is set on the command line.
symbol_ "theory"
thyId <- identifier
thy' <- symbol_ "begin"
*> addItems inFile (set diffThyName thyId (defaultOpenDiffTheory ("diff" `S.member` flags0)))
<* symbol "end"
return thy'
where
addItems :: Maybe FilePath -> OpenDiffTheory -> Parser OpenDiffTheory
addItems inFile0 thy = asum
[ do thy' <- liftedAddHeuristic thy =<< heuristic True workDir
addItems inFile0 thy'
, do
diffbuiltins
msig <- sig <$> getState
addItems inFile0 $ set (sigpMaudeSig . diffThySignature) msig thy
, do functions
msig <- sig <$> getState
addItems inFile0 $ set (sigpMaudeSig . diffThySignature) msig thy
, do equations
msig <- sig <$> getState
addItems inFile0 $ set (sigpMaudeSig . diffThySignature) msig thy
-- , do thy' <- foldM liftedAddProtoRule thy =<< transferProto
-- addItems inFile0 thy'
, do thy' <- liftedAddRestriction' thy =<< diffRestriction
addItems inFile0 thy'
, do thy' <- liftedAddRestriction' thy =<< legacyDiffAxiom
addItems inFile0 thy'
-- add legacy deprecation warning output
, do thy' <- liftedAddLemma' thy =<< plainLemma workDir
addItems inFile0 thy'
, do thy' <- liftedAddDiffLemma thy =<< diffLemma workDir
addItems inFile0 thy'
, do ru <- diffRule
thy' <- liftedAddDiffRule thy ru
addItems inFile0 thy'
, do r <- intrRule
addItems inFile0 (addIntrRuleACsDiffAll [r] thy)
, do c <- formalComment
addItems inFile0 (addFormalCommentDiff c thy)
, do ifdef inFile0 thy
, do define inFile0 thy
, do include inFile0 thy
, do return thy
]
where workDir = takeDirectory <$> inFile
define :: Maybe FilePath -> OpenDiffTheory -> Parser OpenDiffTheory
define inFile0 thy = do
flag <- try (symbol "#define") *> identifier
modifyStateFlag (S.insert flag)
addItems inFile0 thy
ifdef :: Maybe FilePath -> OpenDiffTheory -> Parser OpenDiffTheory
ifdef inFile0 thy = do
flagf <- symbol_ "#ifdef" *> flagdisjuncts
flags0 <- flags <$> getState
if evalformula flags0 flagf
then do thy' <- addItems inFile0 thy
asum [do symbol_ "#else"
_ <- manyTill anyChar (try (symbol_ "#endif"))
addItems inFile0 thy'
,do symbol_ "#endif"
addItems inFile0 thy'
]
else parseelse
where
parseelse =
do _ <- manyTill anyChar (try (symbol_ "#"))
asum
[do (symbol_ "else")
thy' <- addItems inFile0 thy
symbol_ "#endif"
addItems inFile0 thy'
,do _ <- symbol_ "endif"
addItems inFile0 thy
, parseelse
]
include :: Maybe FilePath -> OpenDiffTheory -> Parser OpenDiffTheory
include inFile0 thy = do
filepath <- try (symbol "#include") *> filePathParser
st <- getState
let (thy', st') = unsafePerformIO (parseFileWState st (addItems' (Just filepath) thy) filepath)
_ <- putState st'
addItems inFile0 $ set (sigpMaudeSig . diffThySignature) (sig st') thy'
where
addItems' :: Maybe FilePath -> OpenDiffTheory -> Parser (OpenDiffTheory, ParserState)
addItems' inFile1 thy1 = do
thy' <- addItems inFile1 thy1
st' <- getState
return (thy', st')
filePathParser = case takeDirectory <$> inFile0 of
Nothing -> do
x <- doubleQuoted filePath
return (x <> [pathSeparator])
Just s -> do
x <- doubleQuoted filePath
return (s </> x)
liftedAddHeuristic thy h = case addDiffHeuristic h thy of
Just thy' -> return thy'
Nothing -> fail $ "default heuristic already defined"
liftedAddDiffRule thy ru = case addOpenProtoDiffRule ru thy of
Just thy' -> return thy'
Nothing -> fail $ "duplicate rule or inconsistent names: " ++ render (prettyRuleName $ get dprRule ru)
liftedAddDiffLemma thy ru = case addDiffLemma ru thy of
Just thy' -> return thy'
Nothing -> fail $ "duplicate Diff Lemma: " ++ render (prettyDiffLemmaName ru)
liftedAddLemma' thy lem = if isLeftLemma lem
then case addLemmaDiff LHS lem thy of
Just thy' -> return thy'
Nothing -> fail $ "duplicate lemma: " ++ get lName lem
else if isRightLemma lem
then case addLemmaDiff RHS lem thy of
Just thy' -> return thy'
Nothing -> fail $ "duplicate lemma: " ++ get lName lem
else case addLemmaDiff RHS (addRightLemma lem) thy of
Just thy' -> case addLemmaDiff LHS (addLeftLemma lem) thy' of
Just thy'' -> return thy''
Nothing -> fail $ "duplicate lemma: " ++ get lName lem
Nothing -> fail $ "duplicate lemma: " ++ get lName lem
liftedAddRestriction' thy rstr = if isLeftRestriction rstr
then case addRestrictionDiff LHS (toRestriction rstr) thy of
Just thy' -> return thy'
Nothing -> fail $ "duplicate restriction: " ++ get rstrName (toRestriction rstr)
else if isRightRestriction rstr
then case addRestrictionDiff RHS (toRestriction rstr) thy of
Just thy' -> return thy'
Nothing -> fail $ "duplicate restriction: " ++ get rstrName (toRestriction rstr)
else case addRestrictionDiff RHS (toRestriction rstr) thy of
Just thy' -> case addRestrictionDiff LHS (toRestriction rstr) thy' of
Just thy'' -> return thy''
Nothing -> fail $ "duplicate restriction: " ++ get rstrName (toRestriction rstr)
Nothing -> fail $ "duplicate restriction: " ++ get rstrName (toRestriction rstr)
|
tamarin-prover/tamarin-prover
|
lib/theory/src/Theory/Text/Parser.hs
|
gpl-3.0
| 20,623 | 0 | 21 | 7,012 | 4,653 | 2,261 | 2,392 | 337 | 18 |
import Pf.Crafting
import Test.QuickCheck
import Test.Hspec
main :: IO ()
main = hspec $ do
describe "Crafting" $ do
it "should result in success if the roll is greater than the craft dc of the item." $
property craftingSuccessGreater
it "should result in success if the roll is equal to the craft dc of the item." $
property craftingSuccessEqual
it "should result in failure if the roll is less than the dc of the item bt not by more than 4." $
property craftingFailure
it "should result in failure by five if the roll is less than the dc of the item by five or more." $
property craftingFailureByFive
it "should result in completion if progress is greater than the required progress." $
property craftingCompletedItemGreater
it "should result in completion if progress is equal to the required progress." $
property craftingCompletedItemEqual
describe "Duration" $ do
it "should result in 1/7th the duration when the duration is Day" $
property craftingDurationDay
craftingSuccessGreater :: CraftProgress -> Roll -> CraftDuration -> Bool
craftingSuccessGreater cp (Roll r) d =
let x = dc (item cp)
in craftCheck cp (Roll $ r + x) d == (CraftSuccess $ increaseProgress cp (Roll $ r + x) d)
craftingSuccessEqual :: CraftProgress -> CraftDuration -> Bool
craftingSuccessEqual cp d =
let x = dc $ item cp
in craftCheck cp (Roll x) d == (CraftSuccess $ increaseProgress cp (Roll x) d)
craftingFailure :: CraftProgress -> CraftDuration -> Bool
craftingFailure cp d = craftCheck cp (Roll $ dc (item cp) - 4) d == CraftFailure cp
craftingFailureByFive :: CraftProgress -> CraftDuration -> Bool
craftingFailureByFive cp d = craftCheck cp (Roll $ dc (item cp) - 5) d == CraftFailureByFiveOrMore cp
craftingCompletedItemGreater :: CraftProgress -> Roll -> CraftDuration -> Bool
craftingCompletedItemGreater p x d =
let CraftProgress i r (Progress a) (Progress b) = p
prog = CraftProgress i r (Progress $ a + b) (Progress b)
in craft (Just prog) i x d == CraftCompleted prog
craftingCompletedItemEqual :: CraftProgress -> Roll -> CraftDuration -> Bool
craftingCompletedItemEqual p x d =
let (CraftProgress i r _ b) = p
prog = CraftProgress i r b b
in craft (Just prog) i x d == CraftCompleted prog
craftingDurationDay :: CraftProgress -> Roll -> Bool
craftingDurationDay (CraftProgress i r (Progress a) b) (Roll x) =
let prog = CraftProgress i r (Progress a) b
in increaseProgress prog (Roll x) Day == prog { progress = Progress $ ((x * dc i) `div` 7) + a }
|
nickolasacosta/pf-tools
|
test/Spec.hs
|
gpl-3.0
| 2,563 | 0 | 16 | 529 | 769 | 370 | 399 | 47 | 1 |
{---------------------------------------------------------------------}
{- Copyright 2015, 2016 Nathan Bloomfield -}
{- -}
{- This file is part of Carl. -}
{- -}
{- Carl is free software: you can redistribute it and/or modify -}
{- it under the terms of the GNU General Public License version 3, -}
{- as published by the Free Software Foundation. -}
{- -}
{- Carl 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 Carl. If not, see <http://www.gnu.org/licenses/>. -}
{---------------------------------------------------------------------}
module Tests.Lib.Data.Integer where
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (arbitrary)
import Test.QuickCheck
import Tests.Util
import Tests.Lib.Ring
{----------}
{- :Suite -}
{----------}
testInteger :: TestTree
testInteger = testGroup "Integer"
[ testRingoid (0::Integer)
, testCRingoid (0::Integer)
, testURingoid (0::Integer)
, testORingoid (0::Integer)
, testEDoid (0::Integer)
, testGCDoid (0::Integer)
]
{---------------}
{- :Generators -}
{---------------}
instance RingoidArb Integer
instance CRingoidArb Integer
instance URingoidArb Integer
instance ORingoidArb Integer
instance GCDoidArb Integer where
rGCDLNeut _ = arbitrary >>= \a -> return (0,a)
rGCDRNeut _ = arbitrary >>= \a -> return (a,0)
instance EDoidArb Integer where
rQuotRem _ = do
a <- arbitrary
NonZero b <- arbitrary
return (a,b)
{-
, testGroup "intSub"
[ testProperty "a-a == 0 " $ prop_intSub_zero
, testGroup "intAbs"
[ testProperty "|a| == |-a| " $ prop_intAbs_negative
]
]
-}
|
nbloomf/carl
|
test/Tests/Lib/Data/Integer.hs
|
gpl-3.0
| 2,318 | 0 | 9 | 765 | 292 | 170 | 122 | 26 | 1 |
import Data.List
-- data Node = Node Road Road | EndNode Road
data Node = Node Road (Maybe Road)
data Road = Road Int Node
data Section = Section { getA :: Int, getB :: Int, getC :: Int }
type RoadSystem = [Section]
heathrowToLondon :: RoadSystem
heathrowToLondon = [Section 50 10 30, Section 5 90 20, Section 40 2 25,
Section 10 8 0]
data Label = A | B | C deriving (Show)
type Path = [(Label, Int)]
roadStep :: (Path, Path) -> Section -> (Path, Path)
roadStep (pathA, pathB) (Section a b c) =
let priceA = sum $ map snd pathA
priceB = sum $ map snd pathB
forwardPriceToA = priceA + a
crossPriceToA = priceB + b + c
forwardPriceToB = priceB + b
crossPriceToB = priceA + a + c
newPathToA = if forwardPriceToA <= crossPriceToA
then (A,a):pathA
else (C,c):(B,b):pathB
newPathToB = if forwardPriceToB <= crossPriceToB
then (B,b):pathB
else (C,c):(A,a):pathA
in (newPathToA, newPathToB)
optimalPath :: RoadSystem -> Path
optimalPath roadSystem =
let (bestAPath, bestBPath) = foldl roadStep ([],[]) roadSystem
in if sum (map snd bestAPath) < sum (map snd bestBPath)
then reverse bestAPath
else reverse bestBPath
groupOf :: Int -> [a] -> [[a]]
groupOf 0 _ = undefined
groupOf _ [] = []
groupOf n xs = take n xs : groupOf n (drop n xs)
main = do
contents <- getContents
let threes = groupOf 3 (map read $ lines contents)
roadSystem = map (\[a,b,c] -> Section a b c) threes
path = optimalPath roadSystem
pathString = concat $ map (show . fst) path
pathPrice = sum $ map snd path
putStrLn $ "The best path to take is: " ++ pathString
putStrLn $ "The price is: " ++ show pathPrice
|
lamontu/learning_haskell
|
heathrow.hs
|
gpl-3.0
| 1,833 | 0 | 13 | 550 | 696 | 375 | 321 | 44 | 3 |
-- file: ch04/SplitLines.hs
splitLines :: String -> [String]
splitLines [] = []
splitLines cs =
let (pre, suf) = break isLineTerminator cs
in pre : case suf of
('\r':'\n':rest) -> splitLines rest
('\r':rest) -> splitLines rest
('\n':rest) -> splitLines rest
_ -> []
isLineTerminator c = c == '\r' || c == '\n'
|
dkensinger/haskell
|
SplitLines.hs
|
gpl-3.0
| 412 | 0 | 12 | 155 | 141 | 71 | 70 | 10 | 4 |
module PropT28 where
import Prelude(Bool(..))
import Zeno
-- Definitions
True && x = x
_ && _ = False
False || x = x
_ || _ = True
not True = False
not False = True
-- Nats
data Nat = S Nat | Z
(+) :: Nat -> Nat -> Nat
Z + y = y
(S x) + y = S (x + y)
(*) :: Nat -> Nat -> Nat
Z * _ = Z
(S x) * y = y + (x * y)
(==),(/=) :: Nat -> Nat -> Bool
Z == Z = True
Z == _ = False
S _ == Z = False
S x == S y = x == y
x /= y = not (x == y)
(<=) :: Nat -> Nat -> Bool
Z <= _ = True
_ <= Z = False
S x <= S y = x <= y
one, zero :: Nat
zero = Z
one = S Z
double :: Nat -> Nat
double Z = Z
double (S x) = S (S (double x))
even :: Nat -> Bool
even Z = True
even (S Z) = False
even (S (S x)) = even x
half :: Nat -> Nat
half Z = Z
half (S Z) = Z
half (S (S x)) = S (half x)
mult :: Nat -> Nat -> Nat -> Nat
mult Z _ acc = acc
mult (S x) y acc = mult x y (y + acc)
fac :: Nat -> Nat
fac Z = S Z
fac (S x) = S x * fac x
qfac :: Nat -> Nat -> Nat
qfac Z acc = acc
qfac (S x) acc = qfac x (S x * acc)
exp :: Nat -> Nat -> Nat
exp _ Z = S Z
exp x (S n) = x * exp x n
qexp :: Nat -> Nat -> Nat -> Nat
qexp x Z acc = acc
qexp x (S n) acc = qexp x n (x * acc)
-- Lists
length :: [a] -> Nat
length [] = Z
length (_:xs) = S (length xs)
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
drop :: Nat -> [a] -> [a]
drop Z xs = xs
drop _ [] = []
drop (S x) (_:xs) = drop x xs
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]
qrev :: [a] -> [a] -> [a]
qrev [] acc = acc
qrev (x:xs) acc = qrev xs (x:acc)
revflat :: [[a]] -> [a]
revflat [] = []
revflat ([]:xss) = revflat xss
revflat ((x:xs):xss) = revflat (xs:xss) ++ [x]
qrevflat :: [[a]] -> [a] -> [a]
qrevflat [] acc = acc
qrevflat ([]:xss) acc = qrevflat xss acc
qrevflat ((x:xs):xss) acc = qrevflat (xs:xss) (x:acc)
rotate :: Nat -> [a] -> [a]
rotate Z xs = xs
rotate _ [] = []
rotate (S n) (x:xs) = rotate n (xs ++ [x])
elem :: Nat -> [Nat] -> Bool
elem _ [] = False
elem n (x:xs) = n == x || elem n xs
subset :: [Nat] -> [Nat] -> Bool
subset [] ys = True
subset (x:xs) ys = x `elem` xs && subset xs ys
intersect,union :: [Nat] -> [Nat] -> [Nat]
(x:xs) `intersect` ys | x `elem` ys = x:(xs `intersect` ys)
| otherwise = xs `intersect` ys
[] `intersect` ys = []
union (x:xs) ys | x `elem` ys = union xs ys
| otherwise = x:(union xs ys)
union [] ys = ys
isort :: [Nat] -> [Nat]
isort [] = []
isort (x:xs) = insert x (isort xs)
insert :: Nat -> [Nat] -> [Nat]
insert n [] = [n]
insert n (x:xs) =
case n <= x of
True -> n : x : xs
False -> x : (insert n xs)
count :: Nat -> [Nat] -> Nat
count n (x:xs) | n == x = S (count n xs)
| otherwise = count n xs
count n [] = Z
sorted :: [Nat] -> Bool
sorted (x:y:xs) = x <= y && sorted (y:xs)
sorted _ = True
-- Theorem
prop_T28 :: [[a]] -> Prop
prop_T28 x = prove (revflat x :=: qrevflat x [])
|
danr/hipspec
|
testsuite/prod/zeno_version/PropT28.hs
|
gpl-3.0
| 2,969 | 0 | 10 | 914 | 1,993 | 1,037 | 956 | 114 | 2 |
module Model.Id
( module Model.Id.Types
) where
import Model.Id.Types
|
databrary/databrary
|
src/Model/Id.hs
|
agpl-3.0
| 75 | 0 | 5 | 14 | 21 | 14 | 7 | 3 | 0 |
{-# LANGUAGE ForeignFunctionInterface, TypeFamilies, MultiParamTypeClasses,
FlexibleInstances, TypeSynonymInstances, EmptyDataDecls,
OverlappingInstances, IncoherentInstances #-}
module HEP.Jet.FastJet.Class.TNamed.Implementation where
import HEP.Jet.FastJet.TypeCast
import HEP.Jet.FastJet.Class.TNamed.RawType
import HEP.Jet.FastJet.Class.TNamed.FFI
import HEP.Jet.FastJet.Class.TNamed.Interface
import HEP.Jet.FastJet.Class.TNamed.Cast
import HEP.Jet.FastJet.Class.TClass.RawType
import HEP.Jet.FastJet.Class.TClass.Cast
import HEP.Jet.FastJet.Class.TClass.Interface
import HEP.Jet.FastJet.Class.TObject.RawType
import HEP.Jet.FastJet.Class.TObject.Cast
import HEP.Jet.FastJet.Class.TObject.Interface
import HEP.Jet.FastJet.Class.Deletable.RawType
import HEP.Jet.FastJet.Class.Deletable.Cast
import HEP.Jet.FastJet.Class.Deletable.Interface
import Data.Word
-- import Foreign.C
-- import Foreign.Ptr
import Foreign.ForeignPtr
import System.IO.Unsafe
instance ITNamed TNamed where
setName = xform1 c_tnamed_setname
setNameTitle = xform2 c_tnamed_setnametitle
setTitle = xform1 c_tnamed_settitle
instance ITObject TNamed where
draw = xform1 c_tnamed_draw
findObject = xform1 c_tnamed_findobject
getName = xform0 c_tnamed_getname
isA = xform0 c_tnamed_isa
paint = xform1 c_tnamed_paint
printObj = xform1 c_tnamed_printobj
saveAs = xform2 c_tnamed_saveas
write = xform3 c_tnamed_write
instance IDeletable TNamed where
delete = xform0 c_tnamed_delete
instance ITNamed (Exist TNamed) where
setName (ETNamed x) = setName x
setNameTitle (ETNamed x) = setNameTitle x
setTitle (ETNamed x) = setTitle x
instance ITObject (Exist TNamed) where
draw (ETNamed x) = draw x
findObject (ETNamed x) = findObject x
getName (ETNamed x) = getName x
isA (ETNamed x) = isA x
paint (ETNamed x) = paint x
printObj (ETNamed x) = printObj x
saveAs (ETNamed x) = saveAs x
write (ETNamed x) = write x
instance IDeletable (Exist TNamed) where
delete (ETNamed x) = delete x
-- | constructor :
--
-- > TNamed( char* name, char* title)
--
newTNamed :: String -> String -> IO TNamed
newTNamed = xform1 c_tnamed_newtnamed
instance FPtr (Exist TNamed) where
type Raw (Exist TNamed) = RawTNamed
get_fptr (ETNamed obj) = castForeignPtr (get_fptr obj)
cast_fptr_to_obj fptr = ETNamed (cast_fptr_to_obj (fptr :: ForeignPtr RawTNamed) :: TNamed)
|
wavewave/HFastJet
|
oldsrc/HEP/Jet/FastJet/Class/TNamed/Implementation.hs
|
lgpl-2.1
| 2,425 | 0 | 10 | 373 | 628 | 351 | 277 | 57 | 1 |
import Hastistics
import Hastistics.Distributions
import Hastistics.Types hiding ((-))
import Hastistics.Data.CSV
notenFormat = csvTable [toHSString, toHSDouble]
studentsFormat = csvTable (repeat (toHSString))
averages :: (HSTable a) => a -> HSReport
averages tbl = select $
valueOf "Matrikel-Nr" $ avgOf "Note" $
groupBy "Matrikel-Nr" $
from tbl
joined :: (HSTable a, HSTable b) => a -> b -> HSReport
joined stu mrk = select $
valueOf "Matrikel-Nr" $ valueOf "Name" $ valueOf "Average of Note" $ valueOf "Profilierung" $
join mrk "Matrikel-Nr" "Matrikel-Nr" $
byrow $
from stu
profile :: (HSTable a) => a -> HSReport
profile tbl = select $
valueOf "Profilierung" $ avgOf "Average of Note" $
groupBy "Profilierung" $
from tbl
main :: IO ()
main = do marksData <- readFile "noten.csv"
studentsData <- readFile "students.csv"
let marks = notenFormat marksData
let students = studentsFormat studentsData
putStrLn "Hastistics Demo. Press any key to continue"
putStrLn "Noten Tabelle"
getChar
print marks
putStrLn "Students Tabelle"
getChar
print students
putStrLn "Berechnen der Notenschnitte der einzelnen Studenten..."
getChar
print (averages marks)
putStrLn "Verknüpfen der Tabellen..."
getChar
print (joined students (averages marks))
putStrLn "Gruppieren nach Profilierung..."
getChar
print (profile (joined students (averages marks)))
|
fluescher/hastistics
|
tests/profil.hs
|
lgpl-3.0
| 2,128 | 0 | 13 | 978 | 435 | 202 | 233 | 43 | 1 |
-- A solution to Rosalind Problem: DNA by SavinaRoja
-- http://rosalind.info/problems/dna/
-- Uses Data.ByteString to remove unnecessary overhead of string or Text
-- representation, and Data.ByteString.Lazy in particular for safety in
-- handling sequence files of arbitrary length.
--
-- The countMap function expresses the solution to the general problem
-- of efficiently counting all unique bytes encountered in a bytestring.
-- This program should perform linearly with respect to sequence length.
-- Test files may be generated by modifying the following command:
-- dd if=/dev/urandom of=sequence bs=1M count=<N>
module Main where
import Data.List
import Data.Word
import qualified Data.ByteString.Lazy as BL
import qualified Data.Map.Strict as M
import System.Environment
import System.IO
countMap :: Num a => BL.ByteString -> M.Map Word8 a
countMap bs = M.fromListWith (+) [(x, 1) | x <- BL.unpack bs]
main :: IO ()
main = do
args <- getArgs
contents <- BL.readFile (head args)
let counts = countMap contents
let lookupHelper k = show (M.findWithDefault 0 k counts)
-- This prints out the results in problem answer format: #A, #C, #G, #T
-- In ASCII: A = 65, C = 67, G = 71, T = 84
putStr $ intercalate " " $ map lookupHelper [65, 67, 71, 84]
|
SavinaRoja/challenges
|
Rosalind/String_Algorithms/dna.hs
|
unlicense
| 1,273 | 0 | 13 | 222 | 229 | 127 | 102 | 16 | 1 |
module HepMC.Barcoded where
import Control.Lens
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
type BC = Int
class Barcoded b where
bc :: Lens' b BC
instance (Barcoded a, Barcoded b) => Barcoded (Either a b) where
bc = choosing bc bc
liftBC :: Barcoded a => (BC -> b) -> a -> b
liftBC f = f . view bc
liftBC2 :: (Barcoded a, Barcoded b) => (BC -> BC -> c) -> a -> b -> c
liftBC2 f a b = f (view bc a) (view bc b)
withBC :: Barcoded b => b -> (BC, b)
withBC b = (view bc b, b)
insertBC :: Barcoded b => b -> IntMap b -> IntMap b
insertBC b = IM.insert (view bc b) b
deleteBC :: Barcoded b => b -> IntMap b -> IntMap b
deleteBC = sans . view bc
fromListBC :: Barcoded b => [b] -> IntMap b
fromListBC = IM.fromList . map withBC
|
cspollard/HHepMC
|
src/HepMC/Barcoded.hs
|
apache-2.0
| 780 | 0 | 9 | 199 | 377 | 194 | 183 | 21 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-- References, bindings, and heterogenous environments
--
-----------------------------------------------------------------------------
module Ideas.Common.Environment
( -- * Reference
Ref, Reference(..), mapRef
-- * Binding
, Binding, makeBinding
, fromBinding, showValue, getTermValue
-- * Heterogeneous environment
, Environment, makeEnvironment, singleBinding
, HasEnvironment(..), HasRefs(..)
, bindings, noBindings, (?)
) where
import Control.Monad
import Data.Function
import Data.List
import Data.Semigroup as Sem
import Ideas.Common.Id
import Ideas.Common.Rewriting.Term
import Ideas.Common.View
import Ideas.Utils.Prelude
import Ideas.Utils.Typeable
import qualified Data.Map as M
-----------------------------------------------------------
-- Reference
-- | A data type for references (without a value)
data Ref a = Ref
{ identifier :: Id -- Identifier
, printer :: a -> String -- Pretty-printer
, parser :: String -> Maybe a -- Parser
, refView :: View Term a -- Conversion to/from term
, refType :: IsTypeable a
}
instance Show (Ref a) where
show = showId
instance Eq (Ref a) where
(==) = (==) `on` getId
instance HasId (Ref a) where
getId = identifier
changeId f d = d {identifier = f (identifier d)}
instance HasTypeable Ref where
getTypeable = Just . refType
-- | A type class for types as references
class (IsTerm a, Typeable a, Show a, Read a) => Reference a where
makeRef :: IsId n => n -> Ref a
makeRefList :: IsId n => n -> Ref [a]
-- default implementation
makeRef n = Ref (newId n) show readM termView typeable
makeRefList n = Ref (newId n) show readM termView typeable
instance Reference Int
instance Reference Term
instance Reference Char where
makeRefList n = Ref (newId n) id Just variableView typeable
instance Reference ShowString
instance Reference a => Reference [a] where
makeRef = makeRefList
instance (Reference a, Reference b) => Reference (a, b)
mapRef :: Typeable b => Isomorphism a b -> Ref a -> Ref b
mapRef iso r = r
{ printer = printer r . to iso
, parser = fmap (from iso) . parser r
, refView = refView r >>> toView iso
, refType = typeable
}
-----------------------------------------------------------
-- Binding
data Binding = forall a . Binding (Ref a) a
instance Show Binding where
show a = showId a ++ "=" ++ showValue a
instance Eq Binding where
(==) = let f (Binding r a) = (getId r, build (refView r) a)
in (==) `on` f
instance HasId Binding where
getId (Binding r _ ) = getId r
changeId f (Binding r a) = Binding (changeId f r) a
makeBinding :: Ref a -> a -> Binding
makeBinding = Binding
fromBinding :: Typeable a => Binding -> Maybe (Ref a, a)
fromBinding (Binding r a) = liftM2 (,) (gcastFrom r r) (castFrom r a)
showValue :: Binding -> String
showValue (Binding r a) = printer r a
getTermValue :: Binding -> Term
getTermValue (Binding r a) = build (refView r) a
-----------------------------------------------------------
-- Heterogeneous environment
newtype Environment = Env { envMap :: M.Map Id Binding }
deriving Eq
instance Show Environment where
show = intercalate ", " . map show . bindings
instance Sem.Semigroup Environment where
a <> b = Env (envMap a `mappend` envMap b) -- left has presedence
instance Monoid Environment where
mempty = Env mempty
mappend = (<>)
instance HasRefs Environment where
allRefs env = [ Some ref | Binding ref _ <- bindings env ]
makeEnvironment :: [Binding] -> Environment
makeEnvironment xs = Env $ M.fromList [ (getId a, a) | a <- xs ]
singleBinding :: Ref a -> a -> Environment
singleBinding r = makeEnvironment . return . Binding r
class HasEnvironment env where
environment :: env -> Environment
setEnvironment :: Environment -> env -> env
deleteRef :: Ref a -> env -> env
insertRef :: Ref a -> a -> env -> env
changeRef :: Ref a -> (a -> a) -> env -> env
-- default definitions
deleteRef a = changeEnv (Env . M.delete (getId a) . envMap)
insertRef r =
let f b = Env . M.insert (getId b) b . envMap
in changeEnv . f . Binding r
changeRef r f env =
maybe id (insertRef r . f) (r ? env) env
-- local helper
changeEnv :: HasEnvironment env => (Environment -> Environment) -> env -> env
changeEnv f env = setEnvironment (f (environment env)) env
class HasRefs a where
getRefs :: a -> [Some Ref]
allRefs :: a -> [Some Ref] -- with duplicates
getRefIds :: a -> [Id]
-- default implementation
getRefIds a = [ getId r | Some r <- getRefs a]
getRefs = sortBy cmp . nubBy eq . allRefs
where
cmp :: Some Ref -> Some Ref -> Ordering
cmp (Some x) (Some y) = compareId (getId x) (getId y)
eq a b = cmp a b == EQ
instance HasEnvironment Environment where
environment = id
setEnvironment = const
bindings :: HasEnvironment env => env -> [Binding]
bindings = sortBy compareId . M.elems . envMap . environment
noBindings :: HasEnvironment env => env -> Bool
noBindings = M.null . envMap . environment
(?) :: HasEnvironment env => Ref a -> env -> Maybe a
ref ? env = do
let m = envMap (environment env)
Binding r a <- M.lookup (getId ref) m
msum [ castBetween r ref a -- typed value
, castFrom r a >>= parser ref -- value as string
, castFrom r a >>= match (refView ref) -- value as term
]
|
ideas-edu/ideas
|
src/Ideas/Common/Environment.hs
|
apache-2.0
| 6,216 | 0 | 15 | 1,548 | 1,915 | 1,007 | 908 | 122 | 1 |
sm y = y + 1
biggestInt,smallestInt :: Int
biggestInt = maxBound
smallestInt = minBound
reallyBig::Integer
reallyBig = 2^(2^(2^(2^2)))
numDigits :: Int
numDigits = length(show reallyBig)
ex11 = True && False
ex12 = not(False || True)
ex13 = ('a' == 'a')
ex14 = (16 /= 3)
ex15 = (5>3) && ('p' <= 'q')
ex16 = "Haskell" > "C++"
--Pattern matching
--Recursive function
sumtorial :: Int -> Int
sumtorial 0 = 0
sumtorial n = n + sumtorial (n-1)
--Using Guards
hailstone :: Int -> Int
hailstone n
| n `mod` 2 == 0 = n `div` 2
| otherwise = 3*n+1
foo :: Int -> Int
foo 0 = 16
foo 1
| "Haskell" > "C++" = 3
| otherwise = 4
foo n
| n < 0 = 0
| n `mod` 17 == 2 = -43
| otherwise = n + 3
isEven :: Int -> Bool
isEven n
|n `mod` 2 == 0 = True
|otherwise = False
p :: (Int, Char)
p = (3,'x')
sumPair :: (Int,Int) -> Int
sumPair (x,y) = x + y
f :: Int -> Int -> Int -> Int
f x y z = x + y + z
ex17 = f 3 17 8
ex18 = 1:[]
ex19 = 3 : (1:[])
ex20 = 2 : 3 : 4 : []
ex21 = [2,3,4] == 2 : 3 : 4 : []
hailstoneSeq :: Int -> [Int]
hailstoneSeq 1 = [1]
hailstoneSeq n = n : hailstoneSeq(hailstone n)
intListLength :: [Int] -> Int
intListLength [] = 0
intListLength (x:xs) = 1 + intListLength xs
--Takes an type of list and returns the length
intListLength2 [] = 0
intListLength2 (x:xs) = 1 + intListLength2 xs
sumEveryTwo :: [Int] -> [Int]
sumEveryTwo [] = []
sumEveryTwo (x:[]) = [x]
sumEveryTwo (x:(y:zs)) = (x+y) : sumEveryTwo zs
-- The number of hailstone steps needed to reach 1 from a starting
-- number.
hailstoneLen :: Int -> Int
hailstoneLen n = intListLength (hailstoneSeq n) - 1
|
hungaikev/learning-haskell
|
cis194/week1/intro.hs
|
apache-2.0
| 1,695 | 0 | 11 | 461 | 820 | 438 | 382 | 59 | 1 |
module HSRT.Test where
import HSRT
import HSRT.Types
import Test.QuickCheck
---------------------------------------------------
-- QuickCheck testing
---------------------------------------------------
-- Generate random Rays
instance Arbitrary Ray where
arbitrary = do
p1 <- vectorOf 3 (arbitrary::Gen Double) -- A list of 3 random doubles
p2 <- vectorOf 3 (arbitrary::Gen Double) -- A different list of 3 random doubles
return $ Ray p1 p2
-- The idempotency fails due to floating point precision issues...
--prop_normalIdempotency ray = (direction ray) /= [0,0,0] ==> (normalize . normalize) ray == (normalize . normalize . normalize) ray
-- Test the length property of normalized rays. That is the length of a normalized ray is always 1.
prop_lengthOfNormalizedRay ray = (direction ray) /= [0,0,0] ==> 1-fudgefactor <= _len && _len <= 1+fudgefactor
where
_len = ((distance [0,0,0]) . direction . normalize) ray
fudgefactor = 0.0000000000001
-- Test the dot product of normalized rays, which is always 1
prop_normalizeDot p1 = (direction p1) /= [0,0,0] ==> 1-fudgefactor <= _dot && _dot <= 1+fudgefactor
where
np1 = normalize p1
_dot = np1 `dot` np1
fudgefactor = 0.0000000000001
|
brailsmt/hsrt
|
src/hsrt/test.hs
|
apache-2.0
| 1,279 | 0 | 13 | 270 | 265 | 146 | 119 | -1 | -1 |
module Geometry where
import System.Random
import qualified Data.Map.Strict as M
data Point = Point { pointX :: Int, pointY :: Int }
deriving (Eq, Ord)
type Angle = Float
instance Show Point where
show point = "(" ++ (show $ pointX point) ++ "," ++ (show $ pointY point) ++ ")"
randomPoint width height = do x <- randomRIO (0, (width-1)) :: IO Int
y <- randomRIO (0, (height-1)) :: IO Int
return $ Point x y
randomDinstinctPoints :: Int -> Int -> Int -> IO [Point]
randomDinstinctPoints width height nPoints
| (width*height) < nPoints = error "Cannot extract so many distinct points from such a map"
| otherwise = randomDistinctPoints' width height nPoints []
randomDistinctPoints' width height 0 points = return points
randomDistinctPoints' width height nPoints points = do point <- randomPoint width height
if point `elem` points
then randomDistinctPoints' width height nPoints points
else randomDistinctPoints' width height (nPoints-1) (point:points)
toroidalNorth width height point = let y = (pointY point) - 1
in if y < 0 then point { pointY = y + height } else point { pointY = y }
toroidalSouth width height point = let y = (pointY point) + 1
in if y >= height then point { pointY = y - height } else point { pointY = y }
toroidalEast width height point = let x = (pointX point) + 1
in if x >= width then point { pointY = x - width } else point { pointX = x }
toroidalWest width height point = let x = (pointX point) - 1
in if x < 0 then point { pointX = x + width } else point { pointX = x }
data WorldDimension = WorldDimension { worldWidth :: Int, worldHeight :: Int }
type ElevationMap = M.Map Point Float
getElevation :: ElevationMap -> Point -> Float
getElevation elevMap point = case M.lookup point elevMap of
Nothing -> error $ "Elevation map does not have point " ++ (show point)
Just elev -> elev
|
ftomassetti/hplatetectonics
|
src/Geometry.hs
|
apache-2.0
| 2,293 | 0 | 12 | 813 | 712 | 375 | 337 | 34 | 2 |
{-# LANGUAGE PackageImports, TypeFamilies, DataKinds, PolyKinds #-}
module Propellor.Info (
osDebian,
osBuntish,
osArchLinux,
osFreeBSD,
setInfoProperty,
addInfoProperty,
pureInfoProperty,
pureInfoProperty',
askInfo,
getOS,
ipv4,
ipv6,
alias,
addDNS,
hostMap,
aliasMap,
findHost,
findHostNoAlias,
getAddresses,
hostAddresses,
) where
import Propellor.Types
import Propellor.Types.Info
import Propellor.Types.MetaTypes
import "mtl" Control.Monad.Reader
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Control.Applicative
import Prelude
-- | Adds info to a Property.
--
-- The new Property will include HasInfo in its metatypes.
setInfoProperty
-- -Wredundant-constraints is turned off because
-- this constraint appears redundant, but is actually
-- crucial.
:: (MetaTypes metatypes' ~ (+) HasInfo metatypes, SingI metatypes')
=> Property metatypes
-> Info
-> Property (MetaTypes metatypes')
setInfoProperty (Property _ d a oldi c) newi =
Property sing d a (oldi <> newi) c
-- | Adds more info to a Property that already HasInfo.
addInfoProperty
-- -Wredundant-constraints is turned off because
-- this constraint appears redundant, but is actually
-- crucial.
:: (IncludesInfo metatypes ~ 'True)
=> Property metatypes
-> Info
-> Property metatypes
addInfoProperty (Property t d a oldi c) newi =
Property t d a (oldi <> newi) c
-- | Makes a property that does nothing but set some `Info`.
pureInfoProperty :: (IsInfo v) => Desc -> v -> Property (HasInfo + UnixLike)
pureInfoProperty desc v = pureInfoProperty' desc (toInfo v)
pureInfoProperty' :: Desc -> Info -> Property (HasInfo + UnixLike)
pureInfoProperty' desc i = setInfoProperty p i
where
p :: Property UnixLike
p = property ("has " ++ desc) (return NoChange)
-- | Gets a value from the host's Info.
askInfo :: (IsInfo v) => Propellor v
askInfo = asks (fromInfo . hostInfo)
-- | Specifies that a host's operating system is Debian,
-- and further indicates the suite and architecture.
--
-- This provides info for other Properties, so they can act
-- conditionally on the details of the OS.
--
-- It also lets the type checker know that all the properties of the
-- host must support Debian.
--
-- > & osDebian (Stable "jessie") X86_64
osDebian :: DebianSuite -> Architecture -> Property (HasInfo + Debian)
osDebian = osDebian' Linux
-- Use to specify a different `DebianKernel` than the default `Linux`
--
-- > & osDebian' KFreeBSD (Stable "jessie") X86_64
osDebian' :: DebianKernel -> DebianSuite -> Architecture -> Property (HasInfo + Debian)
osDebian' kernel suite arch = tightenTargets $ os (System (Debian kernel suite) arch)
-- | Specifies that a host's operating system is a well-known Debian
-- derivative founded by a space tourist.
--
-- (The actual name of this distribution is not used in Propellor per
-- <http://joeyh.name/blog/entry/trademark_nonsense/>)
osBuntish :: Release -> Architecture -> Property (HasInfo + Buntish)
osBuntish release arch = tightenTargets $ os (System (Buntish release) arch)
-- | Specifies that a host's operating system is FreeBSD
-- and further indicates the release and architecture.
osFreeBSD :: FreeBSDRelease -> Architecture -> Property (HasInfo + FreeBSD)
osFreeBSD release arch = tightenTargets $ os (System (FreeBSD release) arch)
-- | Specifies that a host's operating system is Arch Linux
osArchLinux :: Architecture -> Property (HasInfo + ArchLinux)
osArchLinux arch = tightenTargets $ os (System (ArchLinux) arch)
os :: System -> Property (HasInfo + UnixLike)
os system = pureInfoProperty ("Operating " ++ show system) (InfoVal system)
-- Gets the operating system of a host, if it has been specified.
getOS :: Propellor (Maybe System)
getOS = fromInfoVal <$> askInfo
-- | Indicate that a host has an A record in the DNS.
--
-- When propellor is used to deploy a DNS server for a domain,
-- the hosts in the domain are found by looking for these
-- and similar properites.
--
-- When propellor --spin is used to deploy a host, it checks
-- if the host's IP Property matches the DNS. If the DNS is missing or
-- out of date, the host will instead be contacted directly by IP address.
ipv4 :: String -> Property (HasInfo + UnixLike)
ipv4 = addDNS . Address . IPv4
-- | Indicate that a host has an AAAA record in the DNS.
ipv6 :: String -> Property (HasInfo + UnixLike)
ipv6 = addDNS . Address . IPv6
-- | Indicates another name for the host in the DNS.
--
-- When the host's ipv4/ipv6 addresses are known, the alias is set up
-- to use their address, rather than using a CNAME. This avoids various
-- problems with CNAMEs, and also means that when multiple hosts have the
-- same alias, a DNS round-robin is automatically set up.
alias :: Domain -> Property (HasInfo + UnixLike)
alias d = pureInfoProperty' ("alias " ++ d) $ mempty
`addInfo` toAliasesInfo [d]
-- A CNAME is added here, but the DNS setup code converts it to an
-- IP address when that makes sense.
`addInfo` (toDnsInfo $ S.singleton $ CNAME $ AbsDomain d)
addDNS :: Record -> Property (HasInfo + UnixLike)
addDNS r = pureInfoProperty (rdesc r) (toDnsInfo (S.singleton r))
where
rdesc (CNAME d) = unwords ["alias", ddesc d]
rdesc (Address (IPv4 addr)) = unwords ["ipv4", addr]
rdesc (Address (IPv6 addr)) = unwords ["ipv6", addr]
rdesc (MX n d) = unwords ["MX", show n, ddesc d]
rdesc (NS d) = unwords ["NS", ddesc d]
rdesc (TXT s) = unwords ["TXT", s]
rdesc (SRV x y z d) = unwords ["SRV", show x, show y, show z, ddesc d]
rdesc (SSHFP x y s) = unwords ["SSHFP", show x, show y, s]
rdesc (INCLUDE f) = unwords ["$INCLUDE", f]
rdesc (PTR x) = unwords ["PTR", x]
ddesc (AbsDomain domain) = domain
ddesc (RelDomain domain) = domain
ddesc RootDomain = "@"
hostMap :: [Host] -> M.Map HostName Host
hostMap l = M.fromList $ zip (map hostName l) l
aliasMap :: [Host] -> M.Map HostName Host
aliasMap = M.fromList . concat .
map (\h -> map (\aka -> (aka, h)) $ fromAliasesInfo $ fromInfo $ hostInfo h)
findHost :: [Host] -> HostName -> Maybe Host
findHost l hn = (findHostNoAlias l hn) <|> (findAlias l hn)
findHostNoAlias :: [Host] -> HostName -> Maybe Host
findHostNoAlias l hn = M.lookup hn (hostMap l)
findAlias :: [Host] -> HostName -> Maybe Host
findAlias l hn = M.lookup hn (aliasMap l)
getAddresses :: Info -> [IPAddr]
getAddresses = mapMaybe getIPAddr . S.toList . fromDnsInfo . fromInfo
hostAddresses :: HostName -> [Host] -> [IPAddr]
hostAddresses hn hosts = maybe [] (getAddresses . hostInfo) (findHost hosts hn)
|
ArchiveTeam/glowing-computing-machine
|
src/Propellor/Info.hs
|
bsd-2-clause
| 6,537 | 67 | 15 | 1,149 | 1,760 | 948 | 812 | -1 | -1 |
module Handler.AdminBlog
( getAdminBlogR
, getAdminBlogNewR
, postAdminBlogNewR
, getAdminBlogPostR
, postAdminBlogPostR
, postAdminBlogDeleteR
)
where
import Import
import Yesod.Auth
import Data.Time
import System.Locale (defaultTimeLocale)
-- The view showing the list of articles
getAdminBlogR :: Handler RepHtml
getAdminBlogR = do
maid <- maybeAuthId
muser <- maybeAuth
-- Get the list of articles inside the database
articles <- runDB $ selectList [] [Desc ArticleAdded]
adminLayout $ do
setTitle "Admin: Blog Posts"
$(widgetFile "admin/blog")
-- The form page for posting a new blog post
getAdminBlogNewR :: Handler RepHtml
getAdminBlogNewR = do
formroute <- return $ AdminBlogNewR
marticle <- return $ Nothing
adminLayout $ do
setTitle "Admin: New Post"
$(widgetFile "admin/blogPost")
-- Handling the new posted blog post
postAdminBlogNewR :: Handler ()
postAdminBlogNewR = do
title <- runInputPost $ ireq textField "form-title-field"
mdContent <- runInputPost $ ireq htmlField "form-mdcontent-field"
htmlContent <- runInputPost $ ireq htmlField "form-htmlcontent-field"
wordCount <- runInputPost $ ireq intField "form-wordcount-field"
added <- liftIO getCurrentTime
author <- fmap usersEmail maybeAuth
_ <- runDB $ insert $ Article title mdContent htmlContent wordCount added author 1
setMessage $ "Post Created"
redirect AdminBlogR
-- The form page for updating an existing blog post
getAdminBlogPostR :: ArticleId -> Handler RepHtml
getAdminBlogPostR articleId = do
formroute <- return $ AdminBlogPostR articleId
dbarticle <- runDB $ get404 articleId
marticle <- return $ Just dbarticle
adminLayout $ do
setTitle "Admin: New Post"
$(widgetFile "admin/blogPost")
-- Handling the updated blog post
postAdminBlogPostR :: ArticleId -> Handler ()
postAdminBlogPostR articleId = do
title <- runInputPost $ ireq textField "form-title-field"
mdContent <- runInputPost $ ireq htmlField "form-mdcontent-field"
htmlContent <- runInputPost $ ireq htmlField "form-htmlcontent-field"
wordCount <- runInputPost $ ireq intField "form-wordcount-field"
runDB $ update articleId [ArticleTitle =. title, ArticleMdContent =. mdContent, ArticleHtmlContent =. htmlContent, ArticleWordCount =. wordCount]
setMessage $ "Post Update"
redirect AdminBlogR
-- Handling the updated blog post
postAdminBlogDeleteR :: ArticleId -> Handler ()
postAdminBlogDeleteR articleId = do
runDB $ update articleId [ArticleVisible =. 0]
setMessage $ "Post Deleted"
redirect AdminBlogR
|
BeerAndProgramming/BeerAndProgrammingSite
|
Handler/AdminBlog.hs
|
bsd-2-clause
| 2,678 | 0 | 12 | 548 | 610 | 288 | 322 | 59 | 1 |
--
-- Copyright 2014, General Dynamics C4 Systems
--
-- This software may be distributed and modified according to the terms of
-- the GNU General Public License version 2. Note that NO WARRANTY is provided.
-- See "LICENSE_GPLv2.txt" for details.
--
-- @TAG(GD_GPL)
--
{-# LANGUAGE EmptyDataDecls, ForeignFunctionInterface,
GeneralizedNewtypeDeriving #-}
module SEL4.Machine.Hardware.ARM.Lyrebird where
import SEL4.Machine.RegisterSet
import Foreign.Ptr
import Data.Ix
import Data.Word(Word8)
import Data.Bits
data CallbackData
data IRQ = TimerInterrupt
deriving (Enum, Bounded, Ord, Ix, Eq, Show)
newtype PAddr = PAddr { fromPAddr :: Word }
deriving (Show, Eq, Ord, Bounded, Real, Enum, Integral, Num, Bits)
ptrFromPAddr :: PAddr -> PPtr a
ptrFromPAddr (PAddr addr) = PPtr addr
addrFromPPtr :: PPtr a -> PAddr
addrFromPPtr (PPtr ptr) = PAddr ptr
pageColourBits :: Int
pageColourBits = 0
foreign import ccall "arm_get_mem_top"
getMemorySize :: Ptr CallbackData -> IO Int
getMemoryRegions :: Ptr CallbackData -> IO [(PAddr, PAddr)]
getMemoryRegions env = do
size <- getMemorySize env
return [(PAddr 0, PAddr (bit size))]
getDeviceRegions :: Ptr CallbackData -> IO [(PAddr, PAddr)]
getDeviceRegions _ = return []
getKernelDevices :: Ptr CallbackData -> IO [(PAddr, PPtr Word)]
getKernelDevices _ = return []
maskInterrupt :: Ptr CallbackData -> Bool -> IRQ -> IO ()
maskInterrupt env bool _ = maskIRQCallback env bool
ackInterrupt :: Ptr CallbackData -> IRQ -> IO ()
ackInterrupt env _ = ackIRQCallback env
foreign import ccall "arm_check_interrupt"
getInterruptState :: Ptr CallbackData -> IO Bool
foreign import ccall "arm_mask_interrupt"
maskIRQCallback :: Ptr CallbackData -> Bool -> IO ()
foreign import ccall "arm_ack_interrupt"
ackIRQCallback :: Ptr CallbackData -> IO ()
getActiveIRQ :: Ptr CallbackData -> IO (Maybe IRQ)
getActiveIRQ env = do
timer_irq <- getInterruptState env
return $ if timer_irq then Just TimerInterrupt else Nothing
configureTimer :: Ptr CallbackData -> IO IRQ
configureTimer _ = return TimerInterrupt
resetTimer :: Ptr CallbackData -> IO ()
resetTimer _ = return ()
foreign import ccall unsafe "arm_load_word"
loadWordCallback :: Ptr CallbackData -> PAddr -> IO Word
foreign import ccall unsafe "arm_store_word"
storeWordCallback :: Ptr CallbackData -> PAddr -> Word -> IO ()
foreign import ccall unsafe "arm_tlb_flush"
invalidateTLBCallback :: Ptr CallbackData -> IO ()
foreign import ccall unsafe "arm_tlb_flush_asid"
invalidateHWASIDCallback :: Ptr CallbackData -> Word8 -> IO ()
foreign import ccall unsafe "arm_tlb_flush_vptr"
invalidateMVACallback :: Ptr CallbackData -> Word -> IO ()
cacheCleanMVACallback :: Ptr CallbackData -> PPtr a -> IO ()
cacheCleanMVACallback _cptr _mva = return ()
cacheCleanRangeCallback :: Ptr CallbackData -> PPtr a -> PPtr a -> IO ()
cacheCleanRangeCallback _cptr _vbase _vtop = return ()
cacheCleanCallback :: Ptr CallbackData -> IO ()
cacheCleanCallback _cptr = return ()
cacheInvalidateRangeCallback :: Ptr CallbackData -> PPtr a -> PPtr a -> IO ()
cacheInvalidateRangeCallback _cptr _vbase _vtop = return ()
foreign import ccall unsafe "arm_set_asid"
setHardwareASID :: Ptr CallbackData -> Word8 -> IO ()
foreign import ccall unsafe "arm_set_table_root"
setCurrentPD :: Ptr CallbackData -> PAddr -> IO ()
foreign import ccall unsafe "arm_get_ifsr"
getIFSR :: Ptr CallbackData -> IO Word
foreign import ccall unsafe "arm_get_dfsr"
getDFSR :: Ptr CallbackData -> IO Word
foreign import ccall unsafe "arm_get_far"
getFAR :: Ptr CallbackData -> IO VPtr
|
NICTA/seL4
|
haskell/src/SEL4/Machine/Hardware/ARM/Lyrebird.hs
|
bsd-2-clause
| 3,656 | 0 | 12 | 642 | 1,083 | 545 | 538 | -1 | -1 |
module Main (main) where
import Test.DocTest (doctest)
main :: IO ()
main = doctest ["-isrc","src/Hangman.hs"]
|
stackbuilders/hangman-off
|
tests/DocTests.hs
|
bsd-3-clause
| 113 | 0 | 6 | 17 | 43 | 25 | 18 | 4 | 1 |
import Test.Tasty
import qualified Admin
import qualified Check
main :: IO ()
main = defaultMain $ testGroup "ghc-server"
[ Admin.tests
, Check.tests
]
|
bennofs/ghc-server
|
tests/Main.hs
|
bsd-3-clause
| 159 | 0 | 8 | 30 | 48 | 27 | 21 | 7 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Test.Framework.Providers.Program(
Checker
, testProgramRuns
, testProgramOutput
)
where
import Data.Typeable
import System.Directory
import System.Exit
import System.IO hiding (stdout, stderr)
import System.Process hiding (runProcess)
import Test.Framework.Providers.API
-- |A shorthand for a possible function checking an output stream.
type Checker = Maybe (String -> Bool)
runCheck :: Checker -> String -> Bool
runCheck Nothing _ = True
runCheck (Just f) x = f x
data TestCaseResult = Passed | ProgramFailed ExitCode |
Timeout | CheckFailed |
NotExecutable
data TestCaseRunning = CheckExists | CheckRunnable | Running
data TestCase = TestCase Checker Checker FilePath [FilePath]
deriving (Typeable)
instance Show TestCaseResult where
show Passed = "OK"
show (ProgramFailed c) = "Program failed: Exit code " ++ show c
show Timeout = "Test timed out."
show CheckFailed = "Post-run check failed"
show NotExecutable = "Program not found / executable."
instance Show TestCaseRunning where
show CheckExists = "Checking program existence"
show CheckRunnable = "Checking program is executable"
show Running = "Running"
instance TestResultlike TestCaseRunning TestCaseResult where
testSucceeded x = case x of
Passed -> True
_ -> False
instance Testlike TestCaseRunning TestCaseResult TestCase where
testTypeName _ = "Programs"
runTest topts (TestCase outCheck errCheck prog args) = runImprovingIO $ do
yieldImprovement CheckExists
exists <- liftIO $ doesFileExist prog
if exists
then do yieldImprovement CheckRunnable
perms <- liftIO $ getPermissions prog
if executable perms
then do yieldImprovement Running
runProgram topts outCheck errCheck prog args
else return NotExecutable
else return NotExecutable
runProgram :: TestOptions' K->
Checker -> Checker ->
FilePath -> [String] ->
ImprovingIO i f TestCaseResult
runProgram topts stdoutCheck stderrCheck prog args = do
let timeout = unK (topt_timeout topts)
mres <- maybeTimeoutImprovingIO timeout $ liftIO $ runProcess prog args
case mres of
Nothing -> return Timeout
Just (ExitSuccess, stdout, stderr)
| runCheck stdoutCheck stdout && runCheck stderrCheck stderr ->
return Passed
| otherwise ->
return CheckFailed
Just (x, _, _) ->
return (ProgramFailed x)
runProcess :: FilePath -> [String] -> IO (ExitCode, String, String)
runProcess prog args = do
(_,o,e,p) <- runInteractiveProcess prog args Nothing Nothing
hSetBuffering o NoBuffering
hSetBuffering e NoBuffering
sout <- hGetContents o
serr <- hGetContents e
ecode <- length sout `seq` waitForProcess p
return (ecode, sout, serr)
-- |Test that a given program runs correctly with the given arguments. 'Runs
-- correctly' is defined as running and exiting with a successful (0) error
-- code.
testProgramRuns :: String -> FilePath -> [String] -> Test
testProgramRuns name prog args =
testProgramOutput name prog args Nothing Nothing
-- |Test that a given program runs correctly (exits successfully), and that
-- its stdout / stderr are acceptable.
testProgramOutput :: String -> FilePath -> [String] ->
Checker -> Checker ->
Test
testProgramOutput name prog args soutCheck serrCheck =
Test name (TestCase soutCheck serrCheck prog args)
|
acw/test-framework-program
|
Test/Framework/Providers/Program.hs
|
bsd-3-clause
| 3,747 | 0 | 15 | 1,016 | 885 | 450 | 435 | 81 | 3 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
-----------------------------------------------------------------
-- Auto-generated by regenClassifiers
--
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ranking.Classifiers.PL (classifiers) where
import Prelude
import Duckling.Ranking.Types
import qualified Data.HashMap.Strict as HashMap
import Data.String
classifiers :: Classifiers
classifiers
= HashMap.fromList
[("five",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("integer (numeric)",
Classifier{okData =
ClassData{prior = -0.5997731097824868, unseen = -4.875197323201151,
likelihoods = HashMap.fromList [("", 0.0)], n = 129},
koData =
ClassData{prior = -0.7961464200320919, unseen = -4.68213122712422,
likelihoods = HashMap.fromList [("", 0.0)], n = 106}}),
("exactly <time-of-day>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -1.3862943611198906),
("<integer> (latent time-of-day)", -1.791759469228055),
("hour", -0.8754687373538999),
("<time-of-day> popo\322udniu/wieczorem/w nocy",
-1.791759469228055)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("<cycle> before <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("dayday", -0.6931471805599453),
("day (grain)yesterday", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("Father's Day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<ordinal> <cycle> <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.258096538021482,
likelihoods =
HashMap.fromList
[("daymonth", -2.120263536200091),
("quarteryear", -2.5257286443082556),
("third ordinalday (grain)on <date>", -2.5257286443082556),
("first ordinalweek (grain)named-month", -2.5257286443082556),
("weekmonth", -1.4271163556401458),
("ordinal (digits)quarter (grain)year", -2.5257286443082556),
("first ordinalweek (grain)intersect", -2.120263536200091),
("third ordinalday (grain)named-month", -2.5257286443082556),
("first ordinalweek (grain)on <date>", -2.120263536200091)],
n = 8},
koData =
ClassData{prior = -infinity, unseen = -2.3025850929940455,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> <part-of-day>",
Classifier{okData =
ClassData{prior = -0.7810085363512795, unseen = -4.948759890378168,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)after <time-of-day>", -3.5553480614894135),
("dayhour", -2.995732273553991),
("<ordinal> (as hour)evening|night", -2.5437471498109336),
("<ordinal> (as hour)on <date>", -4.248495242049359),
("yesterdayevening|night", -4.248495242049359),
("hourhour", -1.180442306915742),
("after <time-of-day>after <time-of-day>", -3.8430301339411947),
("until <time-of-day>morning", -3.8430301339411947),
("until <time-of-day>after <time-of-day>", -4.248495242049359),
("minutehour", -4.248495242049359),
("named-daymorning", -4.248495242049359),
("todayevening|night", -4.248495242049359),
("at <time-of-day>evening|night", -4.248495242049359),
("named-dayevening|night", -4.248495242049359),
("intersecton <date>", -4.248495242049359),
("<integer> (latent time-of-day)this <part-of-day>",
-4.248495242049359),
("hh:mmon <date>", -4.248495242049359),
("<integer> (latent time-of-day)morning", -3.5553480614894135),
("at <time-of-day>on <date>", -4.248495242049359),
("intersectmorning", -3.1498829533812494),
("<integer> (latent time-of-day)evening|night",
-2.995732273553991),
("from <datetime> - <datetime> (interval)morning",
-4.248495242049359),
("from <time-of-day> - <time-of-day> (interval)morning",
-4.248495242049359),
("on <date>morning", -4.248495242049359),
("at <time-of-day>morning", -3.8430301339411947),
("tomorrowevening|night", -3.8430301339411947)],
n = 49},
koData =
ClassData{prior = -0.6123858239154869,
unseen = -5.0689042022202315,
likelihoods =
HashMap.fromList
[("dayhour", -1.971552579668651),
("yearhour", -1.9271008170978172),
("year (latent)on <date>", -4.3694478524670215),
("<day-of-month> (ordinal)on <date>", -4.3694478524670215),
("<time-of-day> - <time-of-day> (interval)morning",
-4.3694478524670215),
("<day-of-month> (ordinal)evening|night", -2.6646997602285962),
("by the end of <time>morning", -4.3694478524670215),
("year (latent)evening|night", -3.1166848839716534),
("hourhour", -2.760009940032921),
("after <time-of-day>after <time-of-day>", -3.963982744358857),
("<day-of-month> (ordinal)morning", -3.963982744358857),
("<day-of-month> (ordinal)after <time-of-day>",
-3.270835563798912),
("until <time-of-day>morning", -3.4531571205928664),
("until <time-of-day>after <time-of-day>", -4.3694478524670215),
("about <time-of-day>after <time-of-day>", -4.3694478524670215),
("by <time>morning", -4.3694478524670215),
("<integer> (latent time-of-day)after <time-of-day>",
-3.963982744358857),
("<integer> (latent time-of-day)morning", -3.676300671907076),
("secondhour", -3.1166848839716534),
("intersectmorning", -3.4531571205928664),
("year (latent)morning", -2.6646997602285962),
("year (latent)after <time-of-day>", -3.963982744358857),
("at <time-of-day>after <time-of-day>", -4.3694478524670215)],
n = 58}}),
("today",
Classifier{okData =
ClassData{prior = -0.2876820724517809,
unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -1.3862943611198906,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("mm/dd",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4}}),
("at <time-of-day>",
Classifier{okData =
ClassData{prior = -0.14571181118139365,
unseen = -4.718498871295094,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -1.5740359853831845),
("<integer> (latent time-of-day)", -2.3116349285139637),
("about <time-of-day>", -4.0163830207523885),
("hh:mm", -3.6109179126442243),
("<time-of-day> rano", -2.917770732084279),
("hour", -0.8383291904044432),
("<time-of-day> popo\322udniu/wieczorem/w nocy",
-2.2246235515243336),
("minute", -3.100092288878234)],
n = 51},
koData =
ClassData{prior = -1.9980959022258835, unseen = -3.258096538021482,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -1.8325814637483102),
("<integer> (latent time-of-day)", -1.8325814637483102),
("relative minutes after|past <integer> (hour-of-day)",
-2.5257286443082556),
("hour", -1.1394342831883648),
("<time-of-day> popo\322udniu/wieczorem/w nocy",
-2.5257286443082556),
("minute", -2.5257286443082556)],
n = 8}}),
("absorption of , after named day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.891820298110627,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453),
("named-day", -0.6931471805599453)],
n = 23},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("11th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("on <date>",
Classifier{okData =
ClassData{prior = -7.79615414697118e-2, unseen = -4.51085950651685,
likelihoods =
HashMap.fromList
[("week", -2.890371757896165),
("<time> <part-of-day>", -3.8066624897703196),
("intersect", -2.0149030205422647),
("next <cycle>", -3.1135153092103742),
("named-month", -2.1972245773362196),
("half to|till|before <integer> (hour-of-day)",
-3.8066624897703196),
("day", -2.70805020110221), ("afternoon", -3.1135153092103742),
("this <cycle>", -2.890371757896165),
("year", -3.1135153092103742),
("named-day", -2.890371757896165),
("hour", -2.3025850929940455), ("month", -1.666596326274049),
("minute", -3.8066624897703196),
("this <time>", -3.8066624897703196)],
n = 37},
koData =
ClassData{prior = -2.5902671654458267,
unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("noon", -1.7047480922384253), ("hour", -1.7047480922384253)],
n = 3}}),
("8th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("month (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods = HashMap.fromList [("", 0.0)], n = 11},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time-of-day> o'clock",
Classifier{okData =
ClassData{prior = -0.3184537311185346, unseen = -2.995732273553991,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -0.8649974374866046),
("<integer> (latent time-of-day)", -2.2512917986064953),
("hour", -0.7472144018302211)],
n = 8},
koData =
ClassData{prior = -1.2992829841302609,
unseen = -2.3025850929940455,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -1.5040773967762742),
("<integer> (latent time-of-day)", -1.0986122886681098),
("hour", -0.8109302162163288)],
n = 3}}),
("on a named-day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453),
("named-day", -0.6931471805599453)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("nth <time> <time>",
Classifier{okData =
ClassData{prior = -0.4989911661189879, unseen = -3.951243718581427,
likelihoods =
HashMap.fromList
[("second ordinalnamed-dayintersect", -2.833213344056216),
("first ordinalnamed-dayon <date>", -2.833213344056216),
("daymonth", -1.4469189829363254),
("dayyear", -1.9859154836690123),
("third ordinalnamed-dayintersect", -2.833213344056216),
("third ordinalintersectyear", -2.833213344056216),
("third ordinalnamed-dayon <date>", -3.2386784521643803),
("first ordinalnamed-daynamed-month", -3.2386784521643803),
("first ordinalintersectyear", -2.833213344056216),
("first ordinalnamed-dayintersect", -2.833213344056216),
("second ordinalnamed-dayon <date>", -3.2386784521643803),
("second ordinalintersectyear", -2.833213344056216)],
n = 17},
koData =
ClassData{prior = -0.9343092373768334,
unseen = -3.6888794541139363,
likelihoods =
HashMap.fromList
[("third ordinalnamed-daynamed-month", -2.9704144655697013),
("first ordinalnamed-dayon <date>", -2.9704144655697013),
("daymonth", -1.717651497074333),
("14th ordinalnamed-month<integer> (latent time-of-day)",
-2.5649493574615367),
("monthhour", -1.8718021769015913),
("second ordinalnamed-daynamed-month", -2.9704144655697013),
("third ordinalnamed-dayon <date>", -2.9704144655697013),
("first ordinalnamed-daynamed-month", -2.9704144655697013),
("ordinal (digits)named-month<integer> (latent time-of-day)",
-2.277267285009756),
("second ordinalnamed-dayon <date>", -2.9704144655697013)],
n = 11}}),
("<ordinal> (as hour)",
Classifier{okData =
ClassData{prior = -0.5773153650348236, unseen = -4.454347296253507,
likelihoods =
HashMap.fromList
[("11th ordinal", -3.056356895370426),
("8th ordinal", -3.3440389678222067),
("21st ordinal no space", -3.7495040759303713),
("20th ordinal", -3.7495040759303713),
("third ordinal", -1.8035939268750578),
("16th ordinal", -3.3440389678222067),
("18th ordinal", -3.3440389678222067),
("fifth ordinal", -3.7495040759303713),
("seventh ordinal", -3.3440389678222067),
("19th ordinal", -3.3440389678222067),
("21-29th ordinal", -3.3440389678222067),
("sixth ordinal", -3.3440389678222067),
("15th ordinal", -3.3440389678222067),
("second ordinal", -2.245426679154097),
("ordinal (digits)", -2.3632097148104805),
("10th ordinal", -2.496741107435003),
("9th ordinal", -2.3632097148104805),
("23rd ordinal no space", -3.7495040759303713)],
n = 64},
koData =
ClassData{prior = -0.8241754429663495, unseen = -4.276666119016055,
likelihoods =
HashMap.fromList
[("8th ordinal", -3.164067588373206),
("20th ordinal", -3.164067588373206),
("third ordinal", -2.316769727986002),
("14th ordinal", -3.164067588373206),
("13th ordinal", -3.56953269648137),
("15th ordinal", -2.8763855159214247),
("second ordinal", -2.8763855159214247),
("ordinal (digits)", -1.1716374236829996),
("first ordinal", -1.864784604242945)],
n = 50}}),
("hour (grain)",
Classifier{okData =
ClassData{prior = -0.8472978603872037,
unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -0.5596157879354228, unseen = -2.639057329615259,
likelihoods = HashMap.fromList [("", 0.0)], n = 12}}),
("21st ordinal no space",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<ordinal> quarter",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods =
HashMap.fromList
[("quarter", -0.916290731874155),
("third ordinalquarter (grain)", -0.916290731874155)],
n = 1},
koData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods =
HashMap.fromList
[("ordinal (digits)quarter (grain)", -0.916290731874155),
("quarter", -0.916290731874155)],
n = 1}}),
("intersect",
Classifier{okData =
ClassData{prior = -0.7319205664859061,
unseen = -6.3473892096560105,
likelihoods =
HashMap.fromList
[("<datetime> - <datetime> (interval)on <date>",
-5.247024072160486),
("mm/dd<time-of-day> popo\322udniu/wieczorem/w nocy",
-5.652489180268651),
("<hour-of-day> - <hour-of-day> (interval)on <date>",
-5.247024072160486),
("named-daynamed-month", -4.736198448394496),
("<time-of-day> - <time-of-day> (interval)on <date>",
-5.247024072160486),
("hourday", -3.8607297110405954),
("dayhour", -2.790288299339182),
("daymonth", -3.8607297110405954),
("<time-of-day> popo\322udniu/wieczorem/w nocyabsorption of , after named day",
-4.736198448394496),
("monthyear", -3.1675825304806504),
("from <hour-of-day> - <hour-of-day> (interval)on a named-day",
-5.652489180268651),
("from <time-of-day> - <time-of-day> (interval)on a named-day",
-5.652489180268651),
("absorption of , after named dayintersect by \",\" 2",
-5.247024072160486),
("intersecthh:mm", -5.247024072160486),
("from <datetime> - <datetime> (interval)on a named-day",
-5.652489180268651),
("at <time-of-day>intersect by \",\" 2", -5.247024072160486),
("named-daylast <cycle>", -5.247024072160486),
("named-day<time-of-day> rano", -5.652489180268651),
("on a named-dayat <time-of-day>", -5.247024072160486),
("at <time-of-day>named-day", -5.247024072160486),
("at <time-of-day>on a named-day", -5.652489180268651),
("<time> <part-of-day>on a named-day", -5.247024072160486),
("on a named-day<time> <part-of-day>", -5.652489180268651),
("last <day-of-week> of <time>year", -5.652489180268651),
("today<time> <part-of-day>", -5.652489180268651),
("todayat <time-of-day>", -5.652489180268651),
("on <date>at <time-of-day>", -5.247024072160486),
("dayday", -2.978340530842122),
("on <date><time> <part-of-day>", -5.652489180268651),
("intersect by \",\"hh:mm", -4.399726211773283),
("mm/ddat <time-of-day>", -4.959341999708705),
("last <cycle> <time>year", -4.736198448394496),
("intersect<named-month> <day-of-month> (non ordinal)",
-4.959341999708705),
("intersect<day-of-month> (non ordinal) <named-month>",
-4.959341999708705),
("dayyear", -3.6375861597263857),
("<day-of-month>(ordinal) <named-month>year",
-5.247024072160486),
("day-after-tomorrow (single-word)at <time-of-day>",
-5.652489180268651),
("absorption of , after named day<day-of-month>(ordinal) <named-month>",
-4.148411783492376),
("tomorrow<time-of-day> popo\322udniu/wieczorem/w nocy",
-5.652489180268651),
("named-monthyear", -3.51242301677238),
("absorption of , after named day<named-month> <day-of-month> (non ordinal)",
-4.26619481914876),
("tomorrowuntil <time-of-day>", -5.247024072160486),
("absorption of , after named day<day-of-month> (non ordinal) <named-month>",
-4.148411783492376),
("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\"",
-4.736198448394496),
("named-dayin <duration>", -5.652489180268651),
("last <day-of-week> <time>year", -5.247024072160486),
("<time-of-day> ranoon <date>", -5.247024072160486),
("named-dayfrom <datetime> - <datetime> (interval)",
-4.959341999708705),
("named-daynext <cycle>", -4.736198448394496),
("named-dayintersect", -5.247024072160486),
("named-dayfrom <time-of-day> - <time-of-day> (interval)",
-4.959341999708705),
("on <date><time-of-day> rano", -5.652489180268651),
("<time-of-day> popo\322udniu/wieczorem/w nocytomorrow",
-5.652489180268651),
("from <time-of-day> - <time-of-day> (interval)on <date>",
-5.652489180268651),
("at <time-of-day>intersect", -5.247024072160486),
("dayminute", -3.301113923105173),
("intersect by \",\" 2hh:mm", -4.399726211773283),
("<time-of-day> ranoon a named-day", -5.247024072160486),
("from <hour-of-day> - <hour-of-day> (interval)on <date>",
-5.652489180268651),
("from <datetime> - <datetime> (interval)on <date>",
-5.652489180268651),
("intersectyear", -5.247024072160486),
("on a named-day<time-of-day> rano", -5.652489180268651),
("<ordinal> <cycle> of <time>year", -5.652489180268651),
("minuteday", -2.338303175596125),
("absorption of , after named dayintersect",
-5.247024072160486),
("named-dayon <date>", -4.04305126783455),
("named-day<time> <part-of-day>", -4.959341999708705),
("named-dayat <time-of-day>", -5.247024072160486),
("yearhh:mm", -5.652489180268651),
("at <time-of-day>intersect by \",\"", -5.247024072160486),
("absorption of , after named dayintersect by \",\"",
-5.247024072160486),
("tomorrowexactly <time-of-day>", -4.959341999708705),
("at <time-of-day>absorption of , after named day",
-5.247024072160486),
("at <time-of-day>on <date>", -5.652489180268651),
("on <date>year", -4.26619481914876),
("dayweek", -3.7065790312133373),
("<time> <part-of-day>on <date>", -5.247024072160486),
("weekyear", -4.399726211773283),
("named-day<day-of-month>(ordinal) <named-month>",
-4.959341999708705),
("<ordinal> <cycle> <time>year", -5.247024072160486),
("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\" 2",
-4.736198448394496),
("tomorrowat <time-of-day>", -5.652489180268651),
("named-daythis <cycle>", -5.247024072160486),
("tomorrow<time> <part-of-day>", -5.652489180268651),
("<time-of-day> popo\322udniu/wieczorem/w nocyintersect",
-4.736198448394496),
("<named-month> <day-of-month> (ordinal)year",
-5.652489180268651),
("<time-of-day> popo\322udniu/wieczorem/w nocynamed-day",
-4.736198448394496),
("tomorrow<time-of-day> rano", -5.652489180268651),
("<datetime> - <datetime> (interval)on a named-day",
-5.247024072160486),
("last <cycle> of <time>year", -5.247024072160486),
("<named-month> <day-of-month> (non ordinal)year",
-5.652489180268651),
("<time-of-day> - <time-of-day> (interval)on a named-day",
-5.247024072160486),
("<day-of-month> (non ordinal) <named-month>year",
-5.247024072160486),
("<hour-of-day> - <hour-of-day> (interval)on a named-day",
-5.247024072160486),
("yearminute", -5.652489180268651)],
n = 215},
koData =
ClassData{prior = -0.655821222947259, unseen = -6.405228458030842,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)<named-month> <day-of-month> (non ordinal)",
-4.61181472870676),
("<time-of-day> ranoby <time>", -5.304961909266705),
("intersect by \",\"named-month", -4.206349620598596),
("named-daynamed-month", -5.304961909266705),
("hourday", -2.7926562852905903),
("dayhour", -3.107737331930486),
("daymonth", -3.312531744576499),
("monthday", -5.304961909266705),
("monthyear", -4.794136285500715),
("named-month<hour-of-day> <integer> (as relative minutes)",
-5.71042701737487),
("at <time-of-day>intersect by \",\" 2", -5.71042701737487),
("houryear", -3.570360853878599),
("<time> <part-of-day>until <time-of-day>", -5.304961909266705),
("<ordinal> (as hour)intersect", -3.145477659913333),
("monthhour", -4.61181472870676),
("<time> <part-of-day><time> <part-of-day>",
-5.017279836814924),
("hourmonth", -2.0860860843985045),
("mm/ddat <time-of-day>", -5.71042701737487),
("hourhour", -4.794136285500715),
("<time> <part-of-day>by <time>", -5.304961909266705),
("intersectnamed-month", -3.4591352187683744),
("dayyear", -4.457664048879502),
("<time-of-day> ranoby the end of <time>", -5.304961909266705),
("year<hour-of-day> <integer> (as relative minutes)",
-5.304961909266705),
("intersect by \",\" 2named-month", -4.206349620598596),
("monthminute", -5.304961909266705),
("minutemonth", -5.017279836814924),
("named-monthyear", -4.794136285500715),
("absorption of , after named daynamed-month",
-4.324132656254979),
("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\"",
-5.304961909266705),
("after <time-of-day>at <time-of-day>", -5.71042701737487),
("hh:mmby the end of <time>", -5.71042701737487),
("<ordinal> (as hour)named-month", -3.036278367948341),
("daysecond", -5.304961909266705),
("<time> <part-of-day>by the end of <time>",
-5.304961909266705),
("named-month<ordinal> (as hour)", -4.794136285500715),
("<time> <part-of-day><time-of-day> rano", -5.71042701737487),
("named-dayfrom <datetime> - <datetime> (interval)",
-5.71042701737487),
("named-dayintersect", -4.100989104940769),
("named-dayfrom <time-of-day> - <time-of-day> (interval)",
-5.71042701737487),
("<time-of-day> rano<time> <part-of-day>", -5.304961909266705),
("at <time-of-day>intersect", -5.71042701737487),
("dayminute", -5.304961909266705),
("<named-month> <day-of-month> (non ordinal)by <time>",
-5.71042701737487),
("intersecton <date>", -4.324132656254979),
("intersectyear", -3.312531744576499),
("minuteday", -3.7645168683195562),
("absorption of , after named dayintersect",
-4.206349620598596),
("<ordinal> (as hour)year", -5.71042701737487),
("named-dayon <date>", -4.794136285500715),
("hh:mmon <date>", -5.304961909266705),
("absorption of , after named day<ordinal> (as hour)",
-4.206349620598596),
("at <time-of-day>intersect by \",\"", -5.71042701737487),
("<named-month> <day-of-month> (non ordinal)by the end of <time>",
-5.71042701737487),
("tomorrowexactly <time-of-day>", -5.71042701737487),
("hoursecond", -3.8386248404732783),
("named-month<day-of-month> (non ordinal) <named-month>",
-5.304961909266705),
("named-day<ordinal> (as hour)", -5.017279836814924),
("<ordinal> (as hour)named-day", -4.206349620598596),
("named-monthrelative minutes to|till|before <integer> (hour-of-day)",
-5.71042701737487),
("<named-month> <day-of-month> (non ordinal)named-month",
-5.304961909266705),
("intersectintersect", -4.457664048879502),
("hh:mmon a named-day", -5.304961909266705),
("named-monthintersect", -5.71042701737487),
("<time-of-day> popo\322udniu/wieczorem/w nocyintersect by \",\" 2",
-5.304961909266705),
("hh:mmby <time>", -5.71042701737487),
("tomorrowat <time-of-day>", -5.71042701737487),
("minutesecond", -5.304961909266705),
("<time-of-day> popo\322udniu/wieczorem/w nocyintersect",
-5.304961909266705),
("yearminute", -5.304961909266705)],
n = 232}}),
("half after|past <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("twenty",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("20th ordinal",
Classifier{okData =
ClassData{prior = -1.0986122886681098,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -0.40546510810816444,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("a few",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<ordinal> <cycle> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("daymonth", -1.7047480922384253),
("first ordinalweek (grain)named-month", -1.7047480922384253),
("weekmonth", -1.2992829841302609),
("first ordinalweek (grain)intersect", -1.7047480922384253),
("third ordinalday (grain)named-month", -1.7047480922384253)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [], n = 0}}),
("season",
Classifier{okData =
ClassData{prior = -1.0116009116784799, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -0.45198512374305727,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7}}),
("year (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.890371757896165,
likelihoods = HashMap.fromList [("", 0.0)], n = 16},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("from <datetime> - <datetime> (interval)",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("minuteminute", -1.6739764335716716),
("<time-of-day> rano<time-of-day> rano", -2.0794415416798357),
("hh:mmhh:mm", -1.6739764335716716),
("hourhour", -1.6739764335716716),
("<time-of-day> rano<integer> (latent time-of-day)",
-2.0794415416798357)],
n = 4},
koData =
ClassData{prior = -0.6931471805599453, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("minuteminute", -1.6739764335716716),
("minutehour", -1.6739764335716716),
("hh:mmintersect", -1.6739764335716716),
("hh:mm<integer> (latent time-of-day)", -1.6739764335716716)],
n = 4}}),
("from <hour-of-day> - <hour-of-day> (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("minuteminute", -0.6931471805599453),
("hh:mmhh:mm", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("next <cycle>",
Classifier{okData =
ClassData{prior = -6.453852113757118e-2,
unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("week", -1.540445040947149),
("month (grain)", -3.044522437723423),
("year (grain)", -2.639057329615259),
("second", -3.044522437723423),
("week (grain)", -1.540445040947149),
("quarter", -2.3513752571634776), ("year", -2.639057329615259),
("second (grain)", -3.044522437723423),
("month", -3.044522437723423),
("quarter (grain)", -2.3513752571634776)],
n = 15},
koData =
ClassData{prior = -2.772588722239781, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("minute (grain)", -1.9459101490553135),
("minute", -1.9459101490553135)],
n = 1}}),
("number.number hours",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("from <time-of-day> - <time-of-day> (interval)",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -2.772588722239781,
likelihoods =
HashMap.fromList
[("minuteminute", -1.6094379124341003),
("<time-of-day> rano<time-of-day> rano", -2.0149030205422647),
("hh:mmhh:mm", -1.6094379124341003),
("hourhour", -1.6094379124341003),
("<time-of-day> rano<integer> (latent time-of-day)",
-2.0149030205422647)],
n = 4},
koData =
ClassData{prior = -1.0986122886681098,
unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("minutehour", -1.2992829841302609),
("hh:mm<integer> (latent time-of-day)", -1.2992829841302609)],
n = 2}}),
("integer 21..99",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods =
HashMap.fromList [("integer (numeric)integer (numeric)", 0.0)],
n = 1}}),
("yyyy-mm-dd",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("year (latent)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.295836866004329,
likelihoods =
HashMap.fromList
[("integer (numeric)", -8.004270767353637e-2),
("one", -2.5649493574615367)],
n = 24}}),
("mm/dd/yyyy",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("evening|night",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1780538303479458,
likelihoods = HashMap.fromList [("", 0.0)], n = 22},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("third ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.044522437723423,
likelihoods = HashMap.fromList [("", 0.0)], n = 19},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("yesterday",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<ordinal> quarter <year>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("quarteryear", -0.6931471805599453),
("ordinal (digits)quarter (grain)year", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("hh:mm:ss",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect by \",\" 2",
Classifier{okData =
ClassData{prior = -0.46430560813109784, unseen = -4.74493212836325,
likelihoods =
HashMap.fromList
[("intersect by \",\"year", -4.04305126783455),
("intersect by \",\" 2intersect", -4.04305126783455),
("dayday", -1.4781019103730135),
("named-dayintersect by \",\"", -3.6375861597263857),
("intersect<named-month> <day-of-month> (non ordinal)",
-3.349904087274605),
("intersect<day-of-month> (non ordinal) <named-month>",
-3.349904087274605),
("dayyear", -2.9444389791664407),
("<named-month> <day-of-month> (non ordinal)intersect",
-4.04305126783455),
("named-day<day-of-month> (non ordinal) <named-month>",
-2.538973871058276),
("named-day<named-month> <day-of-month> (non ordinal)",
-2.6567569067146595),
("intersect by \",\"intersect", -4.04305126783455),
("named-dayintersect", -3.6375861597263857),
("intersect by \",\" 2year", -4.04305126783455),
("named-dayintersect by \",\" 2", -3.6375861597263857),
("dayminute", -2.538973871058276),
("intersectyear", -4.04305126783455),
("minuteday", -2.790288299339182),
("intersectintersect", -4.04305126783455),
("named-day<day-of-month>(ordinal) <named-month>",
-2.538973871058276),
("<named-month> <day-of-month> (non ordinal)year",
-3.6375861597263857)],
n = 44},
koData =
ClassData{prior = -0.9903987040278769,
unseen = -4.3694478524670215,
likelihoods =
HashMap.fromList
[("named-daynamed-month", -2.277267285009756),
("dayhour", -1.5234954826333758),
("daymonth", -2.277267285009756),
("intersectnamed-month", -2.9704144655697013),
("minutemonth", -2.9704144655697013),
("named-dayintersect", -2.159484249353372),
("named-day<ordinal> (as hour)", -2.159484249353372)],
n = 26}}),
("16th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("quarter to|till|before <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -1.791759469228055),
("<integer> (latent time-of-day)", -1.791759469228055),
("noon", -1.3862943611198906), ("hour", -0.8754687373538999)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("<integer> (latent time-of-day)",
Classifier{okData =
ClassData{prior = -0.505548566665147, unseen = -3.7376696182833684,
likelihoods =
HashMap.fromList
[("integer (numeric)", -7.598590697792199e-2),
("fifteen", -3.0204248861443626)],
n = 38},
koData =
ClassData{prior = -0.924258901523332, unseen = -3.367295829986474,
likelihoods =
HashMap.fromList
[("integer (numeric)", -0.15415067982725836),
("one", -2.639057329615259), ("fifteen", -2.639057329615259)],
n = 25}}),
("nth <time> of <time>",
Classifier{okData =
ClassData{prior = -0.5596157879354228, unseen = -2.772588722239781,
likelihoods =
HashMap.fromList
[("second ordinalnamed-dayintersect", -2.0149030205422647),
("daymonth", -1.0986122886681098),
("third ordinalnamed-dayintersect", -2.0149030205422647),
("first ordinalnamed-daynamed-month", -2.0149030205422647),
("first ordinalnamed-dayintersect", -2.0149030205422647)],
n = 4},
koData =
ClassData{prior = -0.8472978603872037, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("third ordinalnamed-daynamed-month", -1.8718021769015913),
("daymonth", -1.1786549963416462),
("second ordinalnamed-daynamed-month", -1.8718021769015913),
("first ordinalnamed-daynamed-month", -1.8718021769015913)],
n = 3}}),
("named-month",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.51085950651685,
likelihoods = HashMap.fromList [("", 0.0)], n = 89},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("18th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("week (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.784189633918261,
likelihoods = HashMap.fromList [("", 0.0)], n = 42},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("fifth ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("valentine's day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <day-of-week> <time>",
Classifier{okData =
ClassData{prior = -0.15415067982725836,
unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("named-daynamed-month", -1.791759469228055),
("daymonth", -0.9444616088408514),
("named-dayintersect", -1.791759469228055),
("named-dayon <date>", -1.791759469228055)],
n = 6},
koData =
ClassData{prior = -1.9459101490553135,
unseen = -2.1972245773362196,
likelihoods =
HashMap.fromList
[("named-dayin <duration>", -1.3862943611198906),
("dayminute", -1.3862943611198906)],
n = 1}}),
("now",
Classifier{okData =
ClassData{prior = -0.5108256237659907,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -0.916290731874155, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2}}),
("<unit-of-duration> as a duration",
Classifier{okData =
ClassData{prior = -2.3608540011180215,
unseen = -3.8501476017100584,
likelihoods =
HashMap.fromList
[("week", -1.6314168191528755),
("hour (grain)", -2.7300291078209855),
("second", -2.4423470353692043),
("week (grain)", -1.6314168191528755),
("day", -3.1354942159291497),
("minute (grain)", -3.1354942159291497),
("second (grain)", -2.4423470353692043),
("hour", -2.7300291078209855), ("minute", -3.1354942159291497),
("day (grain)", -3.1354942159291497)],
n = 15},
koData =
ClassData{prior = -9.909090264423089e-2,
unseen = -5.720311776607412,
likelihoods =
HashMap.fromList
[("week", -2.161679639916808),
("month (grain)", -3.2321210516182215),
("hour (grain)", -2.7212954278522306),
("year (grain)", -2.8838143573500057),
("second", -2.8838143573500057),
("week (grain)", -2.161679639916808),
("day", -2.498151876538021), ("quarter", -3.5198031240700023),
("minute (grain)", -2.8838143573500057),
("year", -2.8838143573500057),
("second (grain)", -2.8838143573500057),
("hour", -2.7212954278522306), ("month", -3.2321210516182215),
("quarter (grain)", -3.5198031240700023),
("minute", -2.8838143573500057),
("day (grain)", -2.498151876538021)],
n = 144}}),
("this <part-of-day>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3025850929940455,
likelihoods =
HashMap.fromList
[("on <date>", -1.5040773967762742),
("evening|night", -1.0986122886681098),
("hour", -0.8109302162163288)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("christmas eve",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<day-of-month>(ordinal) <named-month>",
Classifier{okData =
ClassData{prior = -0.19671029424605427,
unseen = -4.007333185232471,
likelihoods =
HashMap.fromList
[("third ordinalnamed-month", -3.295836866004329),
("8th ordinalnamed-month", -2.890371757896165),
("first ordinalnamed-month", -2.890371757896165),
("15th ordinalnamed-month", -2.890371757896165),
("ordinal (digits)named-month", -1.2163953243244932),
("month", -0.8109302162163288),
("13th ordinalnamed-month", -3.295836866004329)],
n = 23},
koData =
ClassData{prior = -1.7227665977411035,
unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("14th ordinalnamed-month", -1.791759469228055),
("ordinal (digits)named-month", -1.5040773967762742),
("month", -1.0986122886681098)],
n = 5}}),
("<duration> hence",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -3.295836866004329,
likelihoods =
HashMap.fromList
[("week", -1.3121863889661687),
("<unit-of-duration> as a duration", -1.8718021769015913),
("day", -2.159484249353372), ("year", -2.5649493574615367),
("<integer> <unit-of-duration>", -1.1786549963416462),
("month", -2.5649493574615367)],
n = 10},
koData =
ClassData{prior = -1.0986122886681098, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("week", -2.0794415416798357),
("<unit-of-duration> as a duration", -0.9808292530117262),
("day", -1.6739764335716716), ("year", -2.0794415416798357),
("month", -2.0794415416798357)],
n = 5}}),
("numbers prefix with -, negative or minus",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 11}}),
("new year's eve",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("tomorrow",
Classifier{okData =
ClassData{prior = -0.2876820724517809,
unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -1.3862943611198906,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3}}),
("<cycle> after <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("day (grain)tomorrow", -0.6931471805599453),
("dayday", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("Mother's Day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("half to|till|before <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> after next",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods =
HashMap.fromList
[("named-month", -1.3862943611198906),
("day", -1.3862943611198906),
("named-day", -1.3862943611198906),
("month", -1.3862943611198906)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("two",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("by <time>",
Classifier{okData =
ClassData{prior = -infinity, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.58351893845611,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -2.456735772821304),
("year (latent)", -2.8622008809294686),
("<integer> (latent time-of-day)", -1.9459101490553135),
("day", -2.456735772821304), ("year", -2.8622008809294686),
("hh:mm", -2.8622008809294686),
("<day-of-month> (ordinal)", -2.456735772821304),
("noon", -2.8622008809294686),
("<time-of-day> rano", -2.8622008809294686),
("hour", -1.3581234841531944), ("minute", -2.8622008809294686)],
n = 12}}),
("seventh ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("half an hour",
Classifier{okData =
ClassData{prior = -0.2876820724517809,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -1.3862943611198906,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("one",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("afternoon",
Classifier{okData =
ClassData{prior = -0.5108256237659907,
unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -0.916290731874155, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4}}),
("<duration> from now",
Classifier{okData =
ClassData{prior = -0.40546510810816444, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("second", -1.9459101490553135),
("<unit-of-duration> as a duration", -1.540445040947149),
("day", -1.9459101490553135), ("year", -1.9459101490553135),
("<integer> <unit-of-duration>", -1.540445040947149),
("minute", -1.9459101490553135)],
n = 4},
koData =
ClassData{prior = -1.0986122886681098,
unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("<unit-of-duration> as a duration", -1.2039728043259361),
("year", -1.6094379124341003), ("minute", -1.6094379124341003)],
n = 2}}),
("this <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.8066624897703196,
likelihoods =
HashMap.fromList
[("week", -1.5869650565820417),
("year (grain)", -1.9924301646902063),
("week (grain)", -1.5869650565820417),
("day", -2.6855773452501515), ("quarter", -2.3978952727983707),
("year", -1.9924301646902063),
("quarter (grain)", -2.3978952727983707),
("day (grain)", -2.6855773452501515)],
n = 18},
koData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0}}),
("minute (grain)",
Classifier{okData =
ClassData{prior = -0.3483066942682157, unseen = -2.639057329615259,
likelihoods = HashMap.fromList [("", 0.0)], n = 12},
koData =
ClassData{prior = -1.2237754316221157,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5}}),
("last <cycle> <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.367295829986474,
likelihoods =
HashMap.fromList
[("daymonth", -1.540445040947149),
("week (grain)named-month", -2.639057329615259),
("day (grain)intersect", -2.2335922215070942),
("day (grain)on <date>", -2.2335922215070942),
("weekmonth", -1.540445040947149),
("day (grain)named-month", -2.639057329615259),
("week (grain)intersect", -2.2335922215070942),
("week (grain)on <date>", -2.2335922215070942)],
n = 10},
koData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0}}),
("about <time-of-day>",
Classifier{okData =
ClassData{prior = -0.11778303565638351,
unseen = -3.1780538303479458,
likelihoods =
HashMap.fromList
[("at <time-of-day>", -2.4423470353692043),
("<ordinal> (as hour)", -1.5260563034950494),
("<integer> (latent time-of-day)", -2.03688192726104),
("hour", -0.9382696385929302),
("<time-of-day> popo\322udniu/wieczorem/w nocy",
-2.4423470353692043)],
n = 8},
koData =
ClassData{prior = -2.1972245773362196,
unseen = -2.3025850929940455,
likelihoods =
HashMap.fromList
[("relative minutes after|past <integer> (hour-of-day)",
-1.5040773967762742),
("minute", -1.5040773967762742)],
n = 1}}),
("year",
Classifier{okData =
ClassData{prior = -0.14842000511827333,
unseen = -3.295836866004329,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 25},
koData =
ClassData{prior = -1.9810014688665833, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 4}}),
("last <day-of-week> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods =
HashMap.fromList
[("named-daynamed-month", -1.252762968495368),
("daymonth", -0.8472978603872037),
("named-dayintersect", -1.252762968495368)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("<integer> <unit-of-duration>",
Classifier{okData =
ClassData{prior = -0.7404000654104909, unseen = -4.59511985013459,
likelihoods =
HashMap.fromList
[("week", -2.2823823856765264),
("threemonth (grain)", -3.4863551900024623),
("fifteenminute (grain)", -3.891820298110627),
("a fewhour (grain)", -3.891820298110627),
("integer (numeric)day (grain)", -2.793208009442517),
("twoweek (grain)", -3.891820298110627),
("fiveday (grain)", -3.891820298110627),
("oneweek (grain)", -3.1986731175506815),
("oneminute (grain)", -3.891820298110627),
("integer (numeric)year (grain)", -3.891820298110627),
("day", -2.505525936990736), ("year", -3.1986731175506815),
("integer (numeric)week (grain)", -3.1986731175506815),
("oneday (grain)", -3.891820298110627),
("hour", -3.1986731175506815), ("month", -3.4863551900024623),
("threeweek (grain)", -3.4863551900024623),
("integer (numeric)minute (grain)", -2.793208009442517),
("minute", -2.505525936990736),
("integer (numeric)hour (grain)", -3.4863551900024623),
("twoyear (grain)", -3.4863551900024623)],
n = 31},
koData =
ClassData{prior = -0.6480267452794757, unseen = -4.653960350157523,
likelihoods =
HashMap.fromList
[("week", -2.8526314299133175),
("threemonth (grain)", -3.951243718581427),
("threehour (grain)", -3.951243718581427),
("integer (numeric)day (grain)", -3.258096538021482),
("twoweek (grain)", -3.951243718581427),
("twominute (grain)", -3.951243718581427),
("second", -2.6984807500860595),
("threeday (grain)", -3.951243718581427),
("threeyear (grain)", -3.951243718581427),
("integer (numeric)second (grain)", -3.0349529867072724),
("twomonth (grain)", -3.951243718581427),
("onehour (grain)", -3.951243718581427),
("integer (numeric)year (grain)", -3.545778610473263),
("threesecond (grain)", -3.951243718581427),
("day", -2.6984807500860595), ("year", -3.0349529867072724),
("threeminute (grain)", -3.951243718581427),
("integer (numeric)week (grain)", -3.258096538021482),
("twoday (grain)", -3.951243718581427),
("hour", -2.6984807500860595), ("month", -3.258096538021482),
("threeweek (grain)", -3.951243718581427),
("integer (numeric)minute (grain)", -3.545778610473263),
("a fewday (grain)", -3.951243718581427),
("integer (numeric)month (grain)", -3.951243718581427),
("minute", -3.0349529867072724),
("twosecond (grain)", -3.951243718581427),
("integer (numeric)hour (grain)", -3.258096538021482),
("fifteenhour (grain)", -3.951243718581427),
("twoyear (grain)", -3.951243718581427)],
n = 34}}),
("19th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("thanksgiving day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> after <time>",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("dayday", -0.6931471805599453),
("<unit-of-duration> as a durationtomorrow",
-0.6931471805599453)],
n = 1}}),
("relative minutes after|past <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = -0.5108256237659907,
unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("integer (numeric)<integer> (latent time-of-day)",
-1.7047480922384253),
("fifteen<ordinal> (as hour)", -1.7047480922384253),
("hour", -1.0116009116784799),
("integer (numeric)<ordinal> (as hour)", -1.7047480922384253)],
n = 3},
koData =
ClassData{prior = -0.916290731874155, unseen = -2.3025850929940455,
likelihoods =
HashMap.fromList
[("integer (numeric)noon", -1.0986122886681098),
("hour", -1.0986122886681098)],
n = 2}}),
("intersect by \",\"",
Classifier{okData =
ClassData{prior = -0.46430560813109784, unseen = -4.74493212836325,
likelihoods =
HashMap.fromList
[("intersect by \",\"year", -4.04305126783455),
("intersect by \",\" 2intersect", -4.04305126783455),
("dayday", -1.4781019103730135),
("named-dayintersect by \",\"", -3.6375861597263857),
("intersect<named-month> <day-of-month> (non ordinal)",
-3.349904087274605),
("intersect<day-of-month> (non ordinal) <named-month>",
-3.349904087274605),
("dayyear", -2.9444389791664407),
("<named-month> <day-of-month> (non ordinal)intersect",
-4.04305126783455),
("named-day<day-of-month> (non ordinal) <named-month>",
-2.538973871058276),
("named-day<named-month> <day-of-month> (non ordinal)",
-2.6567569067146595),
("intersect by \",\"intersect", -4.04305126783455),
("named-dayintersect", -3.6375861597263857),
("intersect by \",\" 2year", -4.04305126783455),
("named-dayintersect by \",\" 2", -3.6375861597263857),
("dayminute", -2.538973871058276),
("intersectyear", -4.04305126783455),
("minuteday", -2.790288299339182),
("intersectintersect", -4.04305126783455),
("named-day<day-of-month>(ordinal) <named-month>",
-2.538973871058276),
("<named-month> <day-of-month> (non ordinal)year",
-3.6375861597263857)],
n = 44},
koData =
ClassData{prior = -0.9903987040278769,
unseen = -4.3694478524670215,
likelihoods =
HashMap.fromList
[("named-daynamed-month", -2.277267285009756),
("dayhour", -1.5234954826333758),
("daymonth", -2.277267285009756),
("intersectnamed-month", -2.9704144655697013),
("minutemonth", -2.9704144655697013),
("named-dayintersect", -2.159484249353372),
("named-day<ordinal> (as hour)", -2.159484249353372)],
n = 26}}),
("hh:mm",
Classifier{okData =
ClassData{prior = -4.652001563489282e-2,
unseen = -3.1354942159291497,
likelihoods = HashMap.fromList [("", 0.0)], n = 21},
koData =
ClassData{prior = -3.0910424533583156,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("quarter after|past <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)", -0.6931471805599453),
("hour", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("14th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("21-29th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("second ordinal", -0.6931471805599453),
("first ordinal", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("named-day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -4.584967478670572,
likelihoods = HashMap.fromList [("", 0.0)], n = 96},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> before <time>",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("dayday", -0.6931471805599453),
("<unit-of-duration> as a durationyesterday",
-0.6931471805599453)],
n = 1}}),
("second (grain)",
Classifier{okData =
ClassData{prior = -0.9985288301111273,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -0.4595323293784402, unseen = -2.639057329615259,
likelihoods = HashMap.fromList [("", 0.0)], n = 12}}),
("13th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect by \"of\", \"from\", \"'s\"",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("named-daylast <cycle>", -0.6931471805599453),
("dayweek", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> ago",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -3.295836866004329,
likelihoods =
HashMap.fromList
[("week", -1.3121863889661687),
("<unit-of-duration> as a duration", -1.8718021769015913),
("day", -2.159484249353372), ("year", -2.5649493574615367),
("<integer> <unit-of-duration>", -1.1786549963416462),
("month", -2.5649493574615367)],
n = 10},
koData =
ClassData{prior = -1.0986122886681098, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("week", -2.0794415416798357),
("<unit-of-duration> as a duration", -0.9808292530117262),
("day", -1.6739764335716716), ("year", -2.0794415416798357),
("month", -2.0794415416798357)],
n = 5}}),
("last <time>",
Classifier{okData =
ClassData{prior = -1.6094379124341003, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("day", -1.1631508098056809),
("named-day", -1.1631508098056809)],
n = 4},
koData =
ClassData{prior = -0.2231435513142097, unseen = -3.713572066704308,
likelihoods =
HashMap.fromList
[("<time-of-day> o'clock", -2.5902671654458267),
("intersect", -2.3025850929940455),
("year (latent)", -2.0794415416798357),
("<integer> (latent time-of-day)", -2.0794415416798357),
("day", -1.742969305058623), ("year", -2.0794415416798357),
("named-day", -2.3025850929940455),
("hour", -1.742969305058623)],
n = 16}}),
("sixth ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<day-of-month> (ordinal)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.367295829986474,
likelihoods =
HashMap.fromList
[("11th ordinal", -2.2335922215070942),
("8th ordinal", -2.639057329615259),
("third ordinal", -2.2335922215070942),
("16th ordinal", -2.639057329615259),
("second ordinal", -1.7227665977411035),
("ordinal (digits)", -2.2335922215070942),
("10th ordinal", -1.7227665977411035),
("9th ordinal", -1.7227665977411035)],
n = 20}}),
("noon",
Classifier{okData =
ClassData{prior = -1.791759469228055, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -0.1823215567939546,
unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10}}),
("until <time-of-day>",
Classifier{okData =
ClassData{prior = -1.0986122886681098,
unseen = -3.6375861597263857,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -2.2246235515243336),
("<ordinal> (as hour)", -2.512305623976115),
("<integer> (latent time-of-day)", -2.512305623976115),
("<time-of-day> rano", -2.512305623976115),
("hour", -1.213022639845854),
("<time-of-day> popo\322udniu/wieczorem/w nocy",
-2.917770732084279)],
n = 10},
koData =
ClassData{prior = -0.40546510810816444,
unseen = -4.060443010546419,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -2.2512917986064953),
("<ordinal> (as hour)", -2.9444389791664407),
("year (latent)", -2.6567569067146595),
("yesterday", -3.349904087274605),
("<integer> (latent time-of-day)", -3.349904087274605),
("day", -2.9444389791664407), ("year", -2.6567569067146595),
("hh:mm", -3.349904087274605),
("<day-of-month> (ordinal)", -3.349904087274605),
("noon", -2.9444389791664407),
("<time-of-day> rano", -3.349904087274605),
("hour", -1.3350010667323402),
("<datetime> - <datetime> (interval)", -3.349904087274605),
("<time-of-day> - <time-of-day> (interval)",
-3.349904087274605),
("<hour-of-day> - <hour-of-day> (interval)",
-3.349904087274605),
("minute", -3.349904087274605)],
n = 20}}),
("<integer> and an half hours",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time-of-day> rano",
Classifier{okData =
ClassData{prior = -0.10008345855698253,
unseen = -3.828641396489095,
likelihoods =
HashMap.fromList
[("at <time-of-day>", -2.0149030205422647),
("<ordinal> (as hour)", -2.70805020110221),
("<integer> (latent time-of-day)", -1.5040773967762742),
("hh:mm", -3.1135153092103742),
("until <time-of-day>", -2.70805020110221),
("hour", -0.8622235106038793), ("minute", -3.1135153092103742)],
n = 19},
koData =
ClassData{prior = -2.3513752571634776,
unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)", -1.7047480922384253),
("until <time-of-day>", -1.7047480922384253),
("hour", -1.2992829841302609)],
n = 2}}),
("after <duration>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453),
("<integer> <unit-of-duration>", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("decimal number",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("next <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.2188758248682006,
likelihoods =
HashMap.fromList
[("named-month", -2.4849066497880004),
("day", -0.8754687373538999),
("named-day", -0.8754687373538999),
("month", -2.4849066497880004)],
n = 10},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("last <cycle>",
Classifier{okData =
ClassData{prior = -0.2876820724517809,
unseen = -3.4965075614664802,
likelihoods =
HashMap.fromList
[("week", -1.6739764335716716),
("month (grain)", -1.6739764335716716),
("year (grain)", -2.367123614131617),
("week (grain)", -1.6739764335716716),
("year", -2.367123614131617), ("month", -1.6739764335716716)],
n = 12},
koData =
ClassData{prior = -1.3862943611198906, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("week", -1.6739764335716716),
("week (grain)", -1.6739764335716716),
("day", -1.6739764335716716),
("day (grain)", -1.6739764335716716)],
n = 4}}),
("christmas",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -1.0986122886681098,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("next n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.912023005428146,
likelihoods =
HashMap.fromList
[("week", -2.793208009442517),
("threemonth (grain)", -3.1986731175506815),
("threehour (grain)", -3.1986731175506815),
("integer (numeric)day (grain)", -3.1986731175506815),
("second", -2.793208009442517),
("threeday (grain)", -3.1986731175506815),
("threeyear (grain)", -3.1986731175506815),
("integer (numeric)second (grain)", -3.1986731175506815),
("integer (numeric)year (grain)", -3.1986731175506815),
("threesecond (grain)", -3.1986731175506815),
("day", -2.505525936990736), ("year", -2.793208009442517),
("threeminute (grain)", -3.1986731175506815),
("integer (numeric)week (grain)", -3.1986731175506815),
("hour", -2.793208009442517), ("month", -3.1986731175506815),
("threeweek (grain)", -3.1986731175506815),
("integer (numeric)minute (grain)", -3.1986731175506815),
("a fewday (grain)", -3.1986731175506815),
("minute", -2.793208009442517),
("integer (numeric)hour (grain)", -3.1986731175506815)],
n = 14},
koData =
ClassData{prior = -infinity, unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [], n = 0}}),
("15th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("halloween day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("by the end of <time>",
Classifier{okData =
ClassData{prior = -infinity, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.58351893845611,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)", -2.456735772821304),
("year (latent)", -2.8622008809294686),
("<integer> (latent time-of-day)", -1.9459101490553135),
("day", -2.456735772821304), ("year", -2.8622008809294686),
("hh:mm", -2.8622008809294686),
("<day-of-month> (ordinal)", -2.456735772821304),
("noon", -2.8622008809294686),
("<time-of-day> rano", -2.8622008809294686),
("hour", -1.3581234841531944), ("minute", -2.8622008809294686)],
n = 12}}),
("in <duration>",
Classifier{okData =
ClassData{prior = -0.2231435513142097, unseen = -4.0943445622221,
likelihoods =
HashMap.fromList
[("week", -2.691243082785829),
("number.number hours", -3.3843902633457743),
("second", -2.9789251552376097),
("<unit-of-duration> as a duration", -1.9980959022258835),
("day", -2.9789251552376097),
("half an hour", -3.3843902633457743),
("<integer> <unit-of-duration>", -1.5125880864441827),
("<integer> and an half hours", -3.3843902633457743),
("hour", -2.2857779746776643), ("minute", -1.5125880864441827),
("about <duration>", -2.9789251552376097)],
n = 24},
koData =
ClassData{prior = -1.6094379124341003,
unseen = -3.1780538303479458,
likelihoods =
HashMap.fromList
[("week", -1.749199854809259), ("second", -2.03688192726104),
("<unit-of-duration> as a duration", -1.5260563034950494),
("<integer> <unit-of-duration>", -2.03688192726104),
("minute", -2.4423470353692043)],
n = 6}}),
("<datetime> - <datetime> (interval)",
Classifier{okData =
ClassData{prior = -1.466337068793427, unseen = -3.367295829986474,
likelihoods =
HashMap.fromList
[("minuteminute", -1.7227665977411035),
("hh:mmhh:mm", -1.7227665977411035),
("dayday", -2.2335922215070942),
("<named-month> <day-of-month> (non ordinal)<named-month> <day-of-month> (non ordinal)",
-2.2335922215070942)],
n = 6},
koData =
ClassData{prior = -0.262364264467491, unseen = -4.04305126783455,
likelihoods =
HashMap.fromList
[("daymonth", -2.9267394020670396),
("about <time-of-day>noon", -3.332204510175204),
("minuteminute", -2.2335922215070942),
("<time-of-day> rano<time-of-day> rano", -3.332204510175204),
("until <time-of-day>noon", -3.332204510175204),
("hh:mmhh:mm", -3.332204510175204),
("hourhour", -1.540445040947149),
("year<hour-of-day> <integer> (as relative minutes)",
-2.9267394020670396),
("after <time-of-day>noon", -2.9267394020670396),
("hh:mmintersect", -2.4159137783010487),
("at <time-of-day>noon", -3.332204510175204),
("<ordinal> (as hour)noon", -2.2335922215070942),
("<named-month> <day-of-month> (non ordinal)named-month",
-2.9267394020670396),
("yearminute", -2.9267394020670396)],
n = 20}}),
("second ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods = HashMap.fromList [("", 0.0)], n = 11},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time-of-day> popo\322udniu/wieczorem/w nocy",
Classifier{okData =
ClassData{prior = -1.5037877364540559e-2,
unseen = -4.962844630259907,
likelihoods =
HashMap.fromList
[("exactly <time-of-day>", -4.2626798770413155),
("at <time-of-day>", -2.4709204078132605),
("<ordinal> (as hour)", -1.5218398531161146),
("<integer> (latent time-of-day)", -2.01138807843482),
("about <time-of-day>", -4.2626798770413155),
("hh:mm", -3.857214768933151),
("until <time-of-day>", -4.2626798770413155),
("hour", -0.812692331209728), ("minute", -3.3463891451671604),
("after <time-of-day>", -3.857214768933151)],
n = 66},
koData =
ClassData{prior = -4.204692619390966, unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("at <time-of-day>", -1.791759469228055),
("hour", -1.791759469228055)],
n = 1}}),
("fifteen",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time-of-day> - <time-of-day> (interval)",
Classifier{okData =
ClassData{prior = -1.749199854809259, unseen = -3.0910424533583156,
likelihoods =
HashMap.fromList
[("minuteminute", -1.4350845252893227),
("hh:mmhh:mm", -1.4350845252893227)],
n = 4},
koData =
ClassData{prior = -0.19105523676270922,
unseen = -3.951243718581427,
likelihoods =
HashMap.fromList
[("about <time-of-day>noon", -3.2386784521643803),
("relative minutes to|till|before <integer> (hour-of-day)<integer> (latent time-of-day)",
-3.2386784521643803),
("minuteminute", -3.2386784521643803),
("<time-of-day> rano<time-of-day> rano", -3.2386784521643803),
("until <time-of-day>noon", -3.2386784521643803),
("hh:mmhh:mm", -3.2386784521643803),
("hourhour", -1.3668762752627892),
("minutehour", -1.9859154836690123),
("after <time-of-day>noon", -2.833213344056216),
("at <time-of-day>noon", -3.2386784521643803),
("<ordinal> (as hour)noon", -2.1400661634962708),
("<time-of-day> rano<integer> (latent time-of-day)",
-3.2386784521643803),
("hh:mm<integer> (latent time-of-day)", -2.1400661634962708)],
n = 19}}),
("<hour-of-day> - <hour-of-day> (interval)",
Classifier{okData =
ClassData{prior = -1.6094379124341003, unseen = -2.995732273553991,
likelihoods =
HashMap.fromList
[("minuteminute", -1.3350010667323402),
("hh:mmhh:mm", -1.3350010667323402)],
n = 4},
koData =
ClassData{prior = -0.2231435513142097, unseen = -3.784189633918261,
likelihoods =
HashMap.fromList
[("about <time-of-day>noon", -3.068052935133617),
("minuteminute", -3.068052935133617),
("<time-of-day> rano<time-of-day> rano", -3.068052935133617),
("until <time-of-day>noon", -3.068052935133617),
("hh:mmhh:mm", -3.068052935133617),
("hourhour", -0.9886113934537812),
("after <time-of-day>noon", -2.662587827025453),
("at <time-of-day>noon", -3.068052935133617),
("<ordinal> (as hour)noon", -1.9694406464655074),
("<integer> (latent time-of-day)noon", -2.662587827025453),
("<integer> (latent time-of-day)<ordinal> (as hour)",
-2.662587827025453)],
n = 16}}),
("last n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.9889840465642745,
likelihoods =
HashMap.fromList
[("week", -2.583997552432231),
("integer (numeric)day (grain)", -2.871679624884012),
("twoweek (grain)", -3.2771447329921766),
("twominute (grain)", -3.2771447329921766),
("second", -2.871679624884012),
("integer (numeric)second (grain)", -3.2771447329921766),
("twomonth (grain)", -3.2771447329921766),
("onehour (grain)", -3.2771447329921766),
("integer (numeric)year (grain)", -3.2771447329921766),
("day", -2.583997552432231), ("year", -2.871679624884012),
("integer (numeric)week (grain)", -2.871679624884012),
("twoday (grain)", -3.2771447329921766),
("hour", -2.871679624884012), ("month", -2.871679624884012),
("integer (numeric)minute (grain)", -3.2771447329921766),
("integer (numeric)month (grain)", -3.2771447329921766),
("minute", -2.871679624884012),
("twosecond (grain)", -3.2771447329921766),
("integer (numeric)hour (grain)", -3.2771447329921766),
("twoyear (grain)", -3.2771447329921766)],
n = 16},
koData =
ClassData{prior = -infinity, unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [], n = 0}}),
("<named-month> <day-of-month> (non ordinal)",
Classifier{okData =
ClassData{prior = -0.3364722366212129,
unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("named-monthinteger (numeric)", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 20},
koData =
ClassData{prior = -1.252762968495368, unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("named-monthinteger (numeric)", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 8}}),
("<day-of-month> (non ordinal) <named-month>",
Classifier{okData =
ClassData{prior = -0.1431008436406733, unseen = -3.367295829986474,
likelihoods =
HashMap.fromList
[("integer (numeric)named-month", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 13},
koData =
ClassData{prior = -2.0149030205422647,
unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("integer (numeric)named-month", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 2}}),
("this|next <day-of-week>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.044522437723423,
likelihoods =
HashMap.fromList
[("day", -0.6931471805599453),
("named-day", -0.6931471805599453)],
n = 9},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("three",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods = HashMap.fromList [("", 0.0)], n = 11},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("ordinal (digits)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.4011973816621555,
likelihoods = HashMap.fromList [("", 0.0)], n = 28},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("quarter (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3025850929940455,
likelihoods = HashMap.fromList [("", 0.0)], n = 8},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <cycle> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("daymonth", -1.540445040947149),
("week (grain)named-month", -1.9459101490553135),
("day (grain)intersect", -1.9459101490553135),
("weekmonth", -1.540445040947149),
("day (grain)named-month", -1.9459101490553135),
("week (grain)intersect", -1.9459101490553135)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("<day-of-month>(ordinal) <named-month> year",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("14th ordinalnamed-month", -1.791759469228055),
("third ordinalnamed-month", -2.1972245773362196),
("ordinal (digits)named-month", -1.2809338454620642),
("month", -0.8109302162163288)],
n = 7},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("morning",
Classifier{okData =
ClassData{prior = -0.7731898882334817,
unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -0.6190392084062235,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7}}),
("relative minutes to|till|before <integer> (hour-of-day)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("integer (numeric)<integer> (latent time-of-day)",
-0.6931471805599453),
("hour", -0.6931471805599453)],
n = 2}}),
("week-end",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("10th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("after <time-of-day>",
Classifier{okData =
ClassData{prior = -1.4403615823901665,
unseen = -3.4657359027997265,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -2.3353749158170367),
("<ordinal> (as hour)", -2.3353749158170367),
("afternoon", -2.0476928433652555),
("hour", -1.1314021114911006),
("<time-of-day> popo\322udniu/wieczorem/w nocy",
-2.3353749158170367)],
n = 9},
koData =
ClassData{prior = -0.2702903297399117, unseen = -4.276666119016055,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -3.164067588373206),
("<ordinal> (as hour)", -2.8763855159214247),
("intersect", -3.56953269648137),
("tomorrow", -2.653241964607215), ("day", -2.316769727986002),
("afternoon", -2.653241964607215),
("<day-of-month> (ordinal)", -3.164067588373206),
("noon", -2.1832383353614793), ("hour", -1.08462604669337),
("<datetime> - <datetime> (interval)", -3.164067588373206),
("<time-of-day> - <time-of-day> (interval)",
-3.164067588373206),
("<hour-of-day> - <hour-of-day> (interval)",
-3.164067588373206)],
n = 29}}),
("day (grain)",
Classifier{okData =
ClassData{prior = -0.12783337150988489,
unseen = -3.1780538303479458,
likelihoods = HashMap.fromList [("", 0.0)], n = 22},
koData =
ClassData{prior = -2.120263536200091, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3}}),
("9th ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("first ordinal",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<month> dd-dd (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("named-month", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("about <duration>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("half an hour", -0.6931471805599453),
("minute", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("day-after-tomorrow (single-word)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<hour-of-day> <integer> (as relative minutes)",
Classifier{okData =
ClassData{prior = -1.0986122886681098,
unseen = -2.1972245773362196,
likelihoods =
HashMap.fromList
[("<ordinal> (as hour)twenty", -1.3862943611198906),
("hour", -0.9808292530117262),
("<ordinal> (as hour)fifteen", -1.3862943611198906)],
n = 2},
koData =
ClassData{prior = -0.40546510810816444,
unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("<integer> (latent time-of-day)integer (numeric)",
-0.8754687373538999),
("hour", -0.8754687373538999)],
n = 4}}),
("23rd ordinal no space",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("this <time>",
Classifier{okData =
ClassData{prior = -0.6286086594223742,
unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("on <date>", -3.044522437723423),
("season", -2.128231705849268),
("evening|night", -3.044522437723423),
("day", -1.252762968495368), ("named-day", -1.6582280766035324),
("hour", -1.9459101490553135),
("week-end", -2.3513752571634776)],
n = 16},
koData =
ClassData{prior = -0.7621400520468967,
unseen = -3.6635616461296463,
likelihoods =
HashMap.fromList
[("on <date>", -2.9444389791664407),
("evening|night", -2.9444389791664407),
("named-month", -1.2396908869280152),
("day", -2.538973871058276), ("hour", -2.538973871058276),
("month", -1.2396908869280152),
("<named-month> <day-of-month> (non ordinal)",
-2.538973871058276)],
n = 14}}),
("<named-month> <day-of-month> (ordinal)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("named-monthfirst ordinal", -1.791759469228055),
("named-month15th ordinal", -1.791759469228055),
("month", -0.8754687373538999),
("named-monthordinal (digits)", -1.3862943611198906)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("within <duration>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("week", -0.6931471805599453),
("<integer> <unit-of-duration>", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}})]
|
rfranek/duckling
|
Duckling/Ranking/Classifiers/PL.hs
|
bsd-3-clause
| 144,652 | 0 | 15 | 71,224 | 24,067 | 15,028 | 9,039 | 2,270 | 1 |
module TestUtil where
import Test.Hspec
import Util
spec :: Spec
spec =
it "size2humanSize" $
size2humanSize . fst <$> sizeHumanSizes
`shouldBe` snd <$> sizeHumanSizes
where
sizeHumanSizes =
[ ( 0, "0B")
, ( 1, "1B")
, ( 125, "125B")
, ( 999, "999B")
, ( 1000, "1.0K")
, ( 1023, "1.0K")
, ( 1024, "1.0K")
, ( 1025, "1.0K")
, ( 2048, "2.0K")
, ( 8192, "8.0K")
, ( 16384, "16.0K")
, ( 32768, "32.0K")
, ( 65536, "64.0K")
, ( 131072, "128.0K")
, ( 262144, "256.0K")
, ( 524288, "512.0K")
, ( 1048575, "1.0M")
, ( 1048576, "1.0M")
, ( 2097152, "2.0M")
, ( 4194304, "4.0M")
, (1073741823, "1.0G")
, (1073741824, "1.0G")
, (1073741825, "1.0G")
]
|
oshyshko/adventofcode
|
test/TestUtil.hs
|
bsd-3-clause
| 1,165 | 0 | 10 | 642 | 261 | 169 | 92 | 32 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module IptAdmin.EditPolicyForm.Render where
import Data.Monoid
import Data.String
import Iptables.Types
import Text.Blaze
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
editPolicyForm :: (String, String) -> Policy -> Markup
editPolicyForm (tableName, chainName) policy = do
case policy of
ACCEPT -> mempty :: Markup
DROP -> mempty
a -> fromString ("Unsupported policy type: " ++ show a)
H.div ! A.class_ "editForm" $
H.form ! A.id "editPolicyForm" ! A.method "post" $ do
H.input ! A.type_ "hidden" ! A.name "table" ! A.value (fromString tableName)
H.input ! A.type_ "hidden" ! A.name "chain" ! A.value (fromString chainName)
H.table $ do
H.tr $
H.td $ do
let acceptRadio = H.input ! A.type_ "radio" ! A.name "policy" ! A.value "accept"
case policy of
ACCEPT -> acceptRadio ! A.checked "checked"
_ -> acceptRadio
"Accept"
H.tr $
H.td $ do
let dropRadio = H.input ! A.type_ "radio" ! A.name "policy" ! A.value "drop"
case policy of
DROP -> dropRadio ! A.checked "checked"
_ -> dropRadio
"Drop"
|
etarasov/iptadmin
|
src/IptAdmin/EditPolicyForm/Render.hs
|
bsd-3-clause
| 1,476 | 0 | 23 | 568 | 418 | 206 | 212 | 33 | 5 |
{- OPTIONS_GHC -fplugin Brisk.Plugin #-}
{- OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-}
{-# LANGUAGE TemplateHaskell #-}
module SpawnSym (main) where
import Control.Monad (forM, foldM)
import Control.Distributed.Process
import Control.Distributed.BriskStatic
import Control.Distributed.Process.Closure
import Control.Distributed.Process.SymmetricProcess
import GHC.Base.Brisk
p :: ProcessId -> Process ()
p who = do self <- getSelfPid
expect :: Process ()
-- return ()
remotable ['p]
ack :: ProcessId -> Process ()
ack p = send p ()
broadCast :: SymSet ProcessId -> Process ()
broadCast pids
= do foldM go () pids
return ()
where
go _ = ack
main :: [NodeId] -> Process ()
main nodes = do me <- getSelfPid
symSet <- spawnSymmetric nodes $ $(mkBriskClosure 'p) me
broadCast symSet
return ()
|
abakst/brisk-prelude
|
examples/SpawnSym.hs
|
bsd-3-clause
| 902 | 0 | 12 | 223 | 263 | 135 | 128 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Network.NetSpec
import Network.NetSpec.Text
main :: IO ()
main = runSpec ServerSpec
{ _ports = [PortNumber 5001]
, _begin = (! "I'll echo anything you say.")
, _loop = \[h] () -> receive h >>= \line -> case line of
"bye" -> stop_
_ -> h ! line >> continue_
, _end = \h () -> h ! "Bye bye now."
}
|
DanBurton/netspec
|
examples/Echo.hs
|
bsd-3-clause
| 368 | 0 | 14 | 96 | 131 | 73 | 58 | 11 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Sky.Parsing.Invertible3.PartialType
( PartialType
, PartialType'
, basicType
, fullAlgebraicType
, partialAlgebraicType
, isOfType -- shortcut "contains" for types
--, contains -- re-export from NewContainer
, union -- re-export from NewContainer
, intersection -- re-export from NewContainer
, disjunct -- re-export from NewContainer
) where
import Sky.Util.NewContainer
import Sky.Util.AllSet
import qualified Data.Set
import Data.Proxy (Proxy(..))
import Data.Data (Data, Constr, DataType, toConstr, constrType, dataTypeOf, dataTypeName, dataTypeConstrs)
-- newtype PartialType a = PartialType (AllSet Data.Set.Set Constr)
-- deriving (Show, Eq, Monoid, BaseContainer, Constructible, Collapseable, Intersectable, Container, ContainerMappable)
type PartialType a = AllSet Data.Set.Set Constr
type PartialType' = AllSet Data.Set.Set Constr
instance Ord Constr where -- Required for Data.Set
compare a b = compare (dataTypeName $ constrType a) (dataTypeName $ constrType b)
`mappend` compare (show a) (show b) -- I don't like using "show" here, but we don't have anything else (it should be "constring")
----------------------------------------------------------------------------------------------------
basicType :: Proxy a -> PartialType a
basicType _ = All
fullAlgebraicType :: forall a. (Data a) => Proxy a -> PartialType a
fullAlgebraicType _ = fromList $ dataTypeConstrs $ dataTypeOf (undefined :: a)
partialAlgebraicType :: forall a. (Data a) => a -> PartialType a
partialAlgebraicType proxy = singleton $ toConstr proxy
isOfType :: forall a. (Data a) => a -> PartialType a -> Bool
isOfType value typ = typ `contains` toConstr value
-- class Eq t => PartialType t where
-- contains :: t -> Constr -> Bool
-- disjunct :: t -> t -> Bool
-- union :: t -> t -> t
----------------------------------------------------------------------------------------------------
-- data PseudoType a
-- = Any
-- | Constrs (Set Constr)
-- deriving (Show, Eq)
-- instance PartialType (PseudoType a) where
-- contains :: PseudoType a -> Constr -> Bool
-- contains (Any) _ = True
-- contains (Constrs set) =
-- disjunct :: PseudoType a -> PseudoType a -> Bool
-- disjunct
|
xicesky/sky-haskell-playground
|
src/Sky/Parsing/Invertible3/PartialType.hs
|
bsd-3-clause
| 2,503 | 0 | 10 | 511 | 391 | 231 | 160 | 32 | 1 |
{-# language CPP #-}
-- No documentation found for Chapter "PipelineShaderStageCreateFlagBits"
module Vulkan.Core10.Enums.PipelineShaderStageCreateFlagBits ( PipelineShaderStageCreateFlags
, PipelineShaderStageCreateFlagBits( PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT
, PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT
, ..
)
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
type PipelineShaderStageCreateFlags = PipelineShaderStageCreateFlagBits
-- | VkPipelineShaderStageCreateFlagBits - Bitmask controlling how a pipeline
-- shader stage is created
--
-- = Description
--
-- Note
--
-- If
-- 'Vulkan.Extensions.VK_EXT_subgroup_size_control.PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT'
-- and
-- 'Vulkan.Extensions.VK_EXT_subgroup_size_control.PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT'
-- are specified and
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-minSubgroupSize minSubgroupSize>
-- does not equal
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#limits-maxSubgroupSize maxSubgroupSize>
-- and no
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#pipelines-required-subgroup-size required subgroup size>
-- is specified, then the only way to guarantee that the \'X\' dimension of
-- the local workgroup size is a multiple of
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgs SubgroupSize>
-- is to make it a multiple of @maxSubgroupSize@. Under these conditions,
-- you are guaranteed full subgroups but not any particular subgroup size.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'PipelineShaderStageCreateFlags'
newtype PipelineShaderStageCreateFlagBits = PipelineShaderStageCreateFlagBits Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
-- | 'PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT' specifies that
-- the subgroup sizes /must/ be launched with all invocations active in the
-- compute stage.
pattern PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT = PipelineShaderStageCreateFlagBits 0x00000002
-- | 'PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT' specifies
-- that the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgs SubgroupSize>
-- /may/ vary in the shader stage.
pattern PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT = PipelineShaderStageCreateFlagBits 0x00000001
conNamePipelineShaderStageCreateFlagBits :: String
conNamePipelineShaderStageCreateFlagBits = "PipelineShaderStageCreateFlagBits"
enumPrefixPipelineShaderStageCreateFlagBits :: String
enumPrefixPipelineShaderStageCreateFlagBits = "PIPELINE_SHADER_STAGE_CREATE_"
showTablePipelineShaderStageCreateFlagBits :: [(PipelineShaderStageCreateFlagBits, String)]
showTablePipelineShaderStageCreateFlagBits =
[ (PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT , "REQUIRE_FULL_SUBGROUPS_BIT")
, (PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT, "ALLOW_VARYING_SUBGROUP_SIZE_BIT")
]
instance Show PipelineShaderStageCreateFlagBits where
showsPrec = enumShowsPrec enumPrefixPipelineShaderStageCreateFlagBits
showTablePipelineShaderStageCreateFlagBits
conNamePipelineShaderStageCreateFlagBits
(\(PipelineShaderStageCreateFlagBits x) -> x)
(\x -> showString "0x" . showHex x)
instance Read PipelineShaderStageCreateFlagBits where
readPrec = enumReadPrec enumPrefixPipelineShaderStageCreateFlagBits
showTablePipelineShaderStageCreateFlagBits
conNamePipelineShaderStageCreateFlagBits
PipelineShaderStageCreateFlagBits
|
expipiplus1/vulkan
|
src/Vulkan/Core10/Enums/PipelineShaderStageCreateFlagBits.hs
|
bsd-3-clause
| 4,741 | 1 | 10 | 930 | 380 | 238 | 142 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeSynonymInstances #-}
-- | Complex Type: @extensionsType@ <http://www.topografix.com/GPX/1/1/#type_extensionsType>
module Data.Geo.GPX.Type.Extensions(
Extensions
, extensions
, runExtensions
) where
import Text.XML.HXT.Arrow.Pickle
import Text.XML.HXT.DOM.TypeDefs
import Control.Newtype
newtype Extensions = Extensions XmlTrees
deriving (Eq, Show)
extensions ::
XmlTrees
-> Extensions
extensions =
Extensions
runExtensions ::
Extensions
-> XmlTrees
runExtensions (Extensions t) =
t
instance XmlPickler Extensions where
xpickle =
xpWrap (Extensions, \(Extensions t) -> t) xpTrees
instance Newtype Extensions XmlTrees where
pack =
Extensions
unpack (Extensions x) =
x
|
tonymorris/geo-gpx
|
src/Data/Geo/GPX/Type/Extensions.hs
|
bsd-3-clause
| 770 | 0 | 10 | 123 | 163 | 96 | 67 | 28 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Skywalker.RestServer (RestAPI, restOr, buildRest) where
import Data.Text hiding (tail)
import Data.ByteString.Lazy hiding (tail)
import Network.Wai
import Network.HTTP.Types.Status
safeHead [] = Nothing
safeHead (a:_) = Just a
restOr :: Text -> Application -> Application -> Application
restOr endPoint restApp backupApp req send_response = do
let p = safeHead $ pathInfo req
if p == Just endPoint
then restApp req send_response
else backupApp req send_response
type RestAPI = (Text, Request -> IO ByteString)
buildRest :: [RestAPI] -> Application
buildRest apis req send_response = do
let pm = safeHead (tail $ pathInfo req) >>= flip lookup apis
case pm of
Nothing -> send_response $ responseBuilder status404 [] "invalid API call"
Just p -> p req >>= (send_response . responseLBS status200 [])
|
manyoo/skywalker
|
src/Skywalker/RestServer.hs
|
bsd-3-clause
| 897 | 0 | 14 | 182 | 288 | 150 | 138 | 21 | 2 |
import Control.Applicative
import Control.Monad.Reader
import Control.Monad.State
import Data.List
import Data.Map (Map)
import qualified Data.Map as M
import System.Directory
import System.FilePath
import System.Environment
import System.Exit
import System.IO
import AST
import CppLexer (lexCpp)
import CodeGen
import TypeCheck (typecheck)
import ScopeCheck (scopecheck)
import Grammar (pUnit, pName, runParser, initialParserState)
parse path = do
input <- readFile path
-- We use only the filename so that tests can run in a temporary directory
-- but still produce predictable error messages.
let res = lexCpp (takeFileName path) input
case res of
Left err -> do
hPutStrLn stderr "Error in lexical analysis:" >> print err
exitFailure
Right tokens ->
case runParser pUnit initialParserState tokens of
(Right (res,_),_) -> return res
(res,_rest) -> do
-- TODO Flags for debug output...
--putStrLn "*** Parse left residue (only 10 tokens shown):"
--mapM_ print (take 10 rest)
--putStrLn "*** Full token stream:"
--mapM_ print (map snd tokens)
let msg = case res of Left err -> err; _ -> show res
hPutStrLn stderr msg
exitFailure
firstM :: Monad m => (a -> m (Maybe b)) -> [a] -> m (Maybe b)
firstM f (x:xs) = do
fx <- f x
maybe (firstM f xs) (return . Just) fx
firstM _ [] = return Nothing
nameToPath (QualifiedName components) = joinPath components
tryImportModule name path = do
let modPath = addExtension (path </> nameToPath name) ".m"
--printf "tryImportModule: %s: Trying %s\n" (show name) modPath
e <- doesFileExist modPath
if e then Just <$> parse modPath else return Nothing
defaultIncludePath = ["stdlib", "tests"]
type ModMap = Map Name (Unit LocE)
type ModT m = ReaderT Options (StateT ModMap m)
type Mod = ModT IO
runMod :: Options -> ModMap -> Mod a -> IO ModMap
runMod opts mods m = execStateT (runReaderT m opts) mods
ifNotLoaded name m = gets (M.lookup name) >>= \res -> case res of
Just modul -> return modul
Nothing -> m >>= \modul -> modul <$ modify (M.insert name modul)
processImport :: Name -> Mod (Unit LocE)
processImport name = ifNotLoaded name $ do
inc <- asks includePath
res <- liftIO $ firstM (tryImportModule name) inc
case res of
Just unit -> do
mapM_ processImport (unitImports unit)
return unit
Nothing -> error ("Error: Can't locate module "++show name)
parseName name = case lexCpp "cmd-line" name of
Left err -> hPutStrLn stderr "Error: Can't lex name:" >> print err >> exitFailure
Right tokens -> case fst (runParser pName () tokens) of
Left err -> hPutStrLn stderr "Error: Can't parse name:" >> print err >> exitFailure
Right (name,_) -> return name
data Options = Options { includePath :: [FilePath], outputPath :: FilePath }
defaultOptions = Options
{ includePath = defaultIncludePath
, outputPath = "out"
}
parseArgs :: [String] -> (Options, [String])
parseArgs args = (opts, mods)
where
opts = foldr addOption defaultOptions optargs
addOption ('-':'I':path) opts =
opts { includePath = path : includePath opts }
addOption ('-':'o':path) opts = opts { outputPath = path }
(optargs,mods) = partition ((== '-').head) args
main = do
(opts,mods) <- parseArgs <$> getArgs
mapM_ (doMain opts <=< parseName) mods
doMain opts name = do
mods <- runMod opts M.empty (processImport name)
process opts name mods
mapMapM f m = M.fromList <$> mapM (secondM f) (M.toList m)
where
secondM f (a,b) = f b >>= \b' -> return (a,b')
process :: Options -> Name -> ModMap -> IO ()
process opts name mods'' = do
mods' <- mapMapM scopecheck mods''
mods <- runReaderT (typecheck name) mods'
let outfile = outputPath opts </> encodeName name ++ ".ll"
--mapM_ print (M.toList mods)
runReaderT (printLLVM outfile name) mods
|
olsner/m3
|
Main.hs
|
bsd-3-clause
| 3,898 | 23 | 21 | 851 | 1,315 | 667 | 648 | 89 | 4 |
module Cipher where
import Data.Char
import Data.List
letterIndex :: Char -> Int
letterIndex = (+ (-(ord 'a'))) . ord . toLower
offsettedChar :: Int -> Char -> Char
offsettedChar offset c =
toOriginalCharCase . chr . (+ firstLetterOrd) . (`mod` numLetters) . (+ offset) . (+ (-firstLetterOrd)) . ord . toLower $ c
where toOriginalCharCase = if isUpper c then toUpper else id
firstLetterOrd = ord 'a'
numLetters = (ord 'z' - firstLetterOrd) + 1
cipherCaesar :: String -> Int -> String
cipherCaesar s offset = map (offsettedChar offset) s
unCipherCaesar :: String -> Int -> String
unCipherCaesar s offset = cipherCaesar s (-offset)
cipherVignere :: String -> String -> String
cipherVignere s password = result where
(result, pass) = foldl' cipherCharWithNextPassChar ("", cycle password) s
where cipherCharWithNextPassChar (result, pass) ' ' = (result ++ " ", pass)
cipherCharWithNextPassChar (result, pass) c = (result ++ [offsettedChar (letterIndex . head $ pass) c], tail pass)
unCipherVignere :: String -> String -> String
unCipherVignere s password = result where
(result, pass) = foldl' unCipherCharWithNextPassChar ("", cycle password) s
where unCipherCharWithNextPassChar (result, pass) ' ' = (result ++ " ", pass)
unCipherCharWithNextPassChar (result, pass) c = (result ++ [offsettedChar (-(letterIndex . head $ pass)) c], tail pass)
cipherUserInput :: (String -> String) -> IO()
cipherUserInput cipherFunc = do
putStrLn "Type a message:"
userInput <- getLine
putStrLn $ "Ciphered message: " ++ cipherFunc userInput
cipherCaesarUserInput :: IO()
cipherCaesarUserInput = cipherUserInput (`cipherCaesar` 1)
cipherVignereUserInput :: IO()
cipherVignereUserInput = cipherUserInput (`cipherVignere` "password")
|
abhean/phffp-examples
|
src/Cipher.hs
|
bsd-3-clause
| 1,795 | 0 | 17 | 328 | 608 | 330 | 278 | 34 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Concurrent (ThreadId, forkIO, myThreadId)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar, readMVar)
import qualified Control.Exception as E
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as C
import Network.Socket hiding (recv, recvFrom, send, sendTo)
import Network.Socket.ByteString
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, (@=?))
------------------------------------------------------------------------
serverAddr :: String
serverAddr = "127.0.0.1"
testMsg :: S.ByteString
testMsg = C.pack "This is a test message."
------------------------------------------------------------------------
-- Tests
------------------------------------------------------------------------
-- Sending and receiving
testSend :: Assertion
testSend = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock = send sock testMsg
testSendAll :: Assertion
testSendAll = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock = sendAll sock testMsg
testSendTo :: Assertion
testSendTo = udpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock serverPort = do
addr <- inet_addr serverAddr
sendTo sock testMsg (SockAddrInet serverPort addr)
testSendAllTo :: Assertion
testSendAllTo = udpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock serverPort = do
addr <- inet_addr serverAddr
sendAllTo sock testMsg (SockAddrInet serverPort addr)
testSendMany :: Assertion
testSendMany = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) (S.append seg1 seg2)
client sock = sendMany sock [seg1, seg2]
seg1 = C.pack "This is a "
seg2 = C.pack "test message."
testSendManyTo :: Assertion
testSendManyTo = udpTest client server
where
server sock = recv sock 1024 >>= (@=?) (S.append seg1 seg2)
client sock serverPort = do
addr <- inet_addr serverAddr
sendManyTo sock [seg1, seg2] (SockAddrInet serverPort addr)
seg1 = C.pack "This is a "
seg2 = C.pack "test message."
testRecv :: Assertion
testRecv = tcpTest client server
where
server sock = recv sock 1024 >>= (@=?) testMsg
client sock = send sock testMsg
testOverFlowRecv :: Assertion
testOverFlowRecv = tcpTest client server
where
server sock = do seg1 <- recv sock (S.length testMsg - 3)
seg2 <- recv sock 1024
let msg = S.append seg1 seg2
testMsg @=? msg
client sock = send sock testMsg
testRecvFrom :: Assertion
testRecvFrom = tcpTest client server
where
server sock = do (msg, _) <- recvFrom sock 1024
testMsg @=? msg
client sock = do
serverPort <- getPeerPort sock
addr <- inet_addr serverAddr
sendTo sock testMsg (SockAddrInet serverPort addr)
testOverFlowRecvFrom :: Assertion
testOverFlowRecvFrom = tcpTest client server
where
server sock = do (seg1, _) <- recvFrom sock (S.length testMsg - 3)
(seg2, _) <- recvFrom sock 1024
let msg = S.append seg1 seg2
testMsg @=? msg
client sock = send sock testMsg
------------------------------------------------------------------------
-- Other
------------------------------------------------------------------------
-- List of all tests
basicTests :: Test
basicTests = testGroup "Basic socket operations"
[
-- Sending and receiving
testCase "testSend" testSend
, testCase "testSendAll" testSendAll
, testCase "testSendTo" testSendTo
, testCase "testSendAllTo" testSendAllTo
, testCase "testSendMany" testSendMany
, testCase "testSendManyTo" testSendManyTo
, testCase "testRecv" testRecv
, testCase "testOverFlowRecv" testOverFlowRecv
, testCase "testRecvFrom" testRecvFrom
, testCase "testOverFlowRecvFrom" testOverFlowRecvFrom
]
tests :: [Test]
tests = [basicTests]
------------------------------------------------------------------------
-- Test helpers
-- | Returns the 'PortNumber' of the peer. Will throw an 'error' if
-- used on a non-IP socket.
getPeerPort :: Socket -> IO PortNumber
getPeerPort sock = do
sockAddr <- getPeerName sock
case sockAddr of
(SockAddrInet port _) -> return port
(SockAddrInet6 port _ _ _) -> return port
_ -> error "getPeerPort: only works with IP sockets"
-- | Establish a connection between client and server and then run
-- 'clientAct' and 'serverAct', in different threads. Both actions
-- get passed a connected 'Socket', used for communicating between
-- client and server. 'tcpTest' makes sure that the 'Socket' is
-- closed after the actions have run.
tcpTest :: (Socket -> IO a) -> (Socket -> IO b) -> IO ()
tcpTest clientAct serverAct = do
portVar <- newEmptyMVar
test (clientSetup portVar) clientAct (serverSetup portVar) server
where
clientSetup portVar = do
sock <- socket AF_INET Stream defaultProtocol
addr <- inet_addr serverAddr
serverPort <- readMVar portVar
connect sock $ SockAddrInet serverPort addr
return sock
serverSetup portVar = do
sock <- socket AF_INET Stream defaultProtocol
setSocketOption sock ReuseAddr 1
addr <- inet_addr serverAddr
bindSocket sock (SockAddrInet aNY_PORT addr)
listen sock 1
serverPort <- socketPort sock
putMVar portVar serverPort
return sock
server sock = do
(clientSock, _) <- accept sock
serverAct clientSock
sClose clientSock
-- | Create an unconnected 'Socket' for sending UDP and receiving
-- datagrams and then run 'clientAct' and 'serverAct'.
udpTest :: (Socket -> PortNumber -> IO a) -> (Socket -> IO b) -> IO ()
udpTest clientAct serverAct = do
portVar <- newEmptyMVar
test clientSetup (client portVar) (serverSetup portVar) serverAct
where
clientSetup = socket AF_INET Datagram defaultProtocol
client portVar sock = do
serverPort <- readMVar portVar
clientAct sock serverPort
serverSetup portVar = do
sock <- socket AF_INET Datagram defaultProtocol
setSocketOption sock ReuseAddr 1
addr <- inet_addr serverAddr
bindSocket sock (SockAddrInet aNY_PORT addr)
serverPort <- socketPort sock
putMVar portVar serverPort
return sock
-- | Run a client/server pair and synchronize them so that the server
-- is started before the client and the specified server action is
-- finished before the client closes the 'Socket'.
test :: IO Socket -> (Socket -> IO b) -> IO Socket -> (Socket -> IO c) -> IO ()
test clientSetup clientAct serverSetup serverAct = do
tid <- myThreadId
barrier <- newEmptyMVar
forkIO $ server barrier
client tid barrier
where
server barrier = do
E.bracket serverSetup sClose $ \sock -> do
serverReady
serverAct sock
putMVar barrier ()
where
-- | Signal to the client that it can proceed.
serverReady = putMVar barrier ()
client tid barrier = do
takeMVar barrier
-- Transfer exceptions to the main thread.
bracketWithReraise tid clientSetup sClose $ \res -> do
clientAct res
takeMVar barrier
-- | Like 'bracket' but catches and reraises the exception in another
-- thread, specified by the first argument.
bracketWithReraise :: ThreadId -> IO a -> (a -> IO b) -> (a -> IO ()) -> IO ()
bracketWithReraise tid before after thing =
E.bracket before after thing
`E.catch` \ (e :: E.SomeException) -> E.throwTo tid e
------------------------------------------------------------------------
-- Test harness
main :: IO ()
main = withSocketsDo $ defaultMain tests
|
jspahrsummers/network
|
tests/Simple.hs
|
bsd-3-clause
| 8,034 | 0 | 14 | 1,875 | 2,009 | 996 | 1,013 | 160 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.