code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE 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.Content.Accounts.Labels.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a label and removes it from all accounts to which it was
-- assigned.
--
-- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.accounts.labels.delete@.
module Network.Google.Resource.Content.Accounts.Labels.Delete
(
-- * REST Resource
AccountsLabelsDeleteResource
-- * Creating a Request
, accountsLabelsDelete
, AccountsLabelsDelete
-- * Request Lenses
, aldXgafv
, aldUploadProtocol
, aldAccessToken
, aldUploadType
, aldAccountId
, aldLabelId
, aldCallback
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.accounts.labels.delete@ method which the
-- 'AccountsLabelsDelete' request conforms to.
type AccountsLabelsDeleteResource =
"content" :>
"v2.1" :>
"accounts" :>
Capture "accountId" (Textual Int64) :>
"labels" :>
Capture "labelId" (Textual Int64) :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a label and removes it from all accounts to which it was
-- assigned.
--
-- /See:/ 'accountsLabelsDelete' smart constructor.
data AccountsLabelsDelete =
AccountsLabelsDelete'
{ _aldXgafv :: !(Maybe Xgafv)
, _aldUploadProtocol :: !(Maybe Text)
, _aldAccessToken :: !(Maybe Text)
, _aldUploadType :: !(Maybe Text)
, _aldAccountId :: !(Textual Int64)
, _aldLabelId :: !(Textual Int64)
, _aldCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsLabelsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aldXgafv'
--
-- * 'aldUploadProtocol'
--
-- * 'aldAccessToken'
--
-- * 'aldUploadType'
--
-- * 'aldAccountId'
--
-- * 'aldLabelId'
--
-- * 'aldCallback'
accountsLabelsDelete
:: Int64 -- ^ 'aldAccountId'
-> Int64 -- ^ 'aldLabelId'
-> AccountsLabelsDelete
accountsLabelsDelete pAldAccountId_ pAldLabelId_ =
AccountsLabelsDelete'
{ _aldXgafv = Nothing
, _aldUploadProtocol = Nothing
, _aldAccessToken = Nothing
, _aldUploadType = Nothing
, _aldAccountId = _Coerce # pAldAccountId_
, _aldLabelId = _Coerce # pAldLabelId_
, _aldCallback = Nothing
}
-- | V1 error format.
aldXgafv :: Lens' AccountsLabelsDelete (Maybe Xgafv)
aldXgafv = lens _aldXgafv (\ s a -> s{_aldXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aldUploadProtocol :: Lens' AccountsLabelsDelete (Maybe Text)
aldUploadProtocol
= lens _aldUploadProtocol
(\ s a -> s{_aldUploadProtocol = a})
-- | OAuth access token.
aldAccessToken :: Lens' AccountsLabelsDelete (Maybe Text)
aldAccessToken
= lens _aldAccessToken
(\ s a -> s{_aldAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aldUploadType :: Lens' AccountsLabelsDelete (Maybe Text)
aldUploadType
= lens _aldUploadType
(\ s a -> s{_aldUploadType = a})
-- | Required. The id of the account that owns the label.
aldAccountId :: Lens' AccountsLabelsDelete Int64
aldAccountId
= lens _aldAccountId (\ s a -> s{_aldAccountId = a})
. _Coerce
-- | Required. The id of the label to delete.
aldLabelId :: Lens' AccountsLabelsDelete Int64
aldLabelId
= lens _aldLabelId (\ s a -> s{_aldLabelId = a}) .
_Coerce
-- | JSONP
aldCallback :: Lens' AccountsLabelsDelete (Maybe Text)
aldCallback
= lens _aldCallback (\ s a -> s{_aldCallback = a})
instance GoogleRequest AccountsLabelsDelete where
type Rs AccountsLabelsDelete = ()
type Scopes AccountsLabelsDelete =
'["https://www.googleapis.com/auth/content"]
requestClient AccountsLabelsDelete'{..}
= go _aldAccountId _aldLabelId _aldXgafv
_aldUploadProtocol
_aldAccessToken
_aldUploadType
_aldCallback
(Just AltJSON)
shoppingContentService
where go
= buildClient
(Proxy :: Proxy AccountsLabelsDeleteResource)
mempty
| brendanhay/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Accounts/Labels/Delete.hs | mpl-2.0 | 5,257 | 0 | 19 | 1,259 | 828 | 479 | 349 | 117 | 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.DialogFlow.Projects.Locations.Agents.Flows.Pages.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the specified page.
--
-- /See:/ <https://cloud.google.com/dialogflow/ Dialogflow API Reference> for @dialogflow.projects.locations.agents.flows.pages.get@.
module Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Flows.Pages.Get
(
-- * REST Resource
ProjectsLocationsAgentsFlowsPagesGetResource
-- * Creating a Request
, projectsLocationsAgentsFlowsPagesGet
, ProjectsLocationsAgentsFlowsPagesGet
-- * Request Lenses
, plafpgXgafv
, plafpgLanguageCode
, plafpgUploadProtocol
, plafpgAccessToken
, plafpgUploadType
, plafpgName
, plafpgCallback
) where
import Network.Google.DialogFlow.Types
import Network.Google.Prelude
-- | A resource alias for @dialogflow.projects.locations.agents.flows.pages.get@ method which the
-- 'ProjectsLocationsAgentsFlowsPagesGet' request conforms to.
type ProjectsLocationsAgentsFlowsPagesGetResource =
"v3" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "languageCode" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GoogleCloudDialogflowCxV3Page
-- | Retrieves the specified page.
--
-- /See:/ 'projectsLocationsAgentsFlowsPagesGet' smart constructor.
data ProjectsLocationsAgentsFlowsPagesGet =
ProjectsLocationsAgentsFlowsPagesGet'
{ _plafpgXgafv :: !(Maybe Xgafv)
, _plafpgLanguageCode :: !(Maybe Text)
, _plafpgUploadProtocol :: !(Maybe Text)
, _plafpgAccessToken :: !(Maybe Text)
, _plafpgUploadType :: !(Maybe Text)
, _plafpgName :: !Text
, _plafpgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsAgentsFlowsPagesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plafpgXgafv'
--
-- * 'plafpgLanguageCode'
--
-- * 'plafpgUploadProtocol'
--
-- * 'plafpgAccessToken'
--
-- * 'plafpgUploadType'
--
-- * 'plafpgName'
--
-- * 'plafpgCallback'
projectsLocationsAgentsFlowsPagesGet
:: Text -- ^ 'plafpgName'
-> ProjectsLocationsAgentsFlowsPagesGet
projectsLocationsAgentsFlowsPagesGet pPlafpgName_ =
ProjectsLocationsAgentsFlowsPagesGet'
{ _plafpgXgafv = Nothing
, _plafpgLanguageCode = Nothing
, _plafpgUploadProtocol = Nothing
, _plafpgAccessToken = Nothing
, _plafpgUploadType = Nothing
, _plafpgName = pPlafpgName_
, _plafpgCallback = Nothing
}
-- | V1 error format.
plafpgXgafv :: Lens' ProjectsLocationsAgentsFlowsPagesGet (Maybe Xgafv)
plafpgXgafv
= lens _plafpgXgafv (\ s a -> s{_plafpgXgafv = a})
-- | The language to retrieve the page for. The following fields are language
-- dependent: * \`Page.entry_fulfillment.messages\` *
-- \`Page.entry_fulfillment.conditional_cases\` *
-- \`Page.event_handlers.trigger_fulfillment.messages\` *
-- \`Page.event_handlers.trigger_fulfillment.conditional_cases\` *
-- \`Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages\`
-- *
-- \`Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases\`
-- *
-- \`Page.form.parameters.fill_behavior.reprompt_event_handlers.messages\`
-- *
-- \`Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases\`
-- * \`Page.transition_routes.trigger_fulfillment.messages\` *
-- \`Page.transition_routes.trigger_fulfillment.conditional_cases\` If not
-- specified, the agent\'s default language is used. [Many
-- languages](https:\/\/cloud.google.com\/dialogflow\/cx\/docs\/reference\/language)
-- are supported. Note: languages must be enabled in the agent before they
-- can be used.
plafpgLanguageCode :: Lens' ProjectsLocationsAgentsFlowsPagesGet (Maybe Text)
plafpgLanguageCode
= lens _plafpgLanguageCode
(\ s a -> s{_plafpgLanguageCode = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plafpgUploadProtocol :: Lens' ProjectsLocationsAgentsFlowsPagesGet (Maybe Text)
plafpgUploadProtocol
= lens _plafpgUploadProtocol
(\ s a -> s{_plafpgUploadProtocol = a})
-- | OAuth access token.
plafpgAccessToken :: Lens' ProjectsLocationsAgentsFlowsPagesGet (Maybe Text)
plafpgAccessToken
= lens _plafpgAccessToken
(\ s a -> s{_plafpgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plafpgUploadType :: Lens' ProjectsLocationsAgentsFlowsPagesGet (Maybe Text)
plafpgUploadType
= lens _plafpgUploadType
(\ s a -> s{_plafpgUploadType = a})
-- | Required. The name of the page. Format:
-- \`projects\/\/locations\/\/agents\/\/flows\/\/pages\/\`.
plafpgName :: Lens' ProjectsLocationsAgentsFlowsPagesGet Text
plafpgName
= lens _plafpgName (\ s a -> s{_plafpgName = a})
-- | JSONP
plafpgCallback :: Lens' ProjectsLocationsAgentsFlowsPagesGet (Maybe Text)
plafpgCallback
= lens _plafpgCallback
(\ s a -> s{_plafpgCallback = a})
instance GoogleRequest
ProjectsLocationsAgentsFlowsPagesGet
where
type Rs ProjectsLocationsAgentsFlowsPagesGet =
GoogleCloudDialogflowCxV3Page
type Scopes ProjectsLocationsAgentsFlowsPagesGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow"]
requestClient
ProjectsLocationsAgentsFlowsPagesGet'{..}
= go _plafpgName _plafpgXgafv _plafpgLanguageCode
_plafpgUploadProtocol
_plafpgAccessToken
_plafpgUploadType
_plafpgCallback
(Just AltJSON)
dialogFlowService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsAgentsFlowsPagesGetResource)
mempty
| brendanhay/gogol | gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Locations/Agents/Flows/Pages/Get.hs | mpl-2.0 | 6,797 | 0 | 16 | 1,310 | 799 | 474 | 325 | 120 | 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.Books.Bookshelves.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves metadata for a specific bookshelf for the specified user.
--
-- /See:/ <https://developers.google.com/books/docs/v1/getting_started Books API Reference> for @books.bookshelves.get@.
module Network.Google.Resource.Books.Bookshelves.Get
(
-- * REST Resource
BookshelvesGetResource
-- * Creating a Request
, bookshelvesGet
, BookshelvesGet
-- * Request Lenses
, bgUserId
, bgShelf
, bgSource
) where
import Network.Google.Books.Types
import Network.Google.Prelude
-- | A resource alias for @books.bookshelves.get@ method which the
-- 'BookshelvesGet' request conforms to.
type BookshelvesGetResource =
"books" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"bookshelves" :>
Capture "shelf" Text :>
QueryParam "source" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Bookshelf
-- | Retrieves metadata for a specific bookshelf for the specified user.
--
-- /See:/ 'bookshelvesGet' smart constructor.
data BookshelvesGet = BookshelvesGet'
{ _bgUserId :: !Text
, _bgShelf :: !Text
, _bgSource :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'BookshelvesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bgUserId'
--
-- * 'bgShelf'
--
-- * 'bgSource'
bookshelvesGet
:: Text -- ^ 'bgUserId'
-> Text -- ^ 'bgShelf'
-> BookshelvesGet
bookshelvesGet pBgUserId_ pBgShelf_ =
BookshelvesGet'
{ _bgUserId = pBgUserId_
, _bgShelf = pBgShelf_
, _bgSource = Nothing
}
-- | ID of user for whom to retrieve bookshelves.
bgUserId :: Lens' BookshelvesGet Text
bgUserId = lens _bgUserId (\ s a -> s{_bgUserId = a})
-- | ID of bookshelf to retrieve.
bgShelf :: Lens' BookshelvesGet Text
bgShelf = lens _bgShelf (\ s a -> s{_bgShelf = a})
-- | String to identify the originator of this request.
bgSource :: Lens' BookshelvesGet (Maybe Text)
bgSource = lens _bgSource (\ s a -> s{_bgSource = a})
instance GoogleRequest BookshelvesGet where
type Rs BookshelvesGet = Bookshelf
type Scopes BookshelvesGet =
'["https://www.googleapis.com/auth/books"]
requestClient BookshelvesGet'{..}
= go _bgUserId _bgShelf _bgSource (Just AltJSON)
booksService
where go
= buildClient (Proxy :: Proxy BookshelvesGetResource)
mempty
| rueshyna/gogol | gogol-books/gen/Network/Google/Resource/Books/Bookshelves/Get.hs | mpl-2.0 | 3,323 | 0 | 15 | 791 | 461 | 274 | 187 | 67 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.SSLPolicies.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all of the ordered rules present in a single specified policy.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.sslPolicies.get@.
module Network.Google.Resource.Compute.SSLPolicies.Get
(
-- * REST Resource
SSLPoliciesGetResource
-- * Creating a Request
, sslPoliciesGet
, SSLPoliciesGet
-- * Request Lenses
, spgSSLPolicy
, spgProject
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.sslPolicies.get@ method which the
-- 'SSLPoliciesGet' request conforms to.
type SSLPoliciesGetResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"sslPolicies" :>
Capture "sslPolicy" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] SSLPolicy
-- | Lists all of the ordered rules present in a single specified policy.
--
-- /See:/ 'sslPoliciesGet' smart constructor.
data SSLPoliciesGet =
SSLPoliciesGet'
{ _spgSSLPolicy :: !Text
, _spgProject :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SSLPoliciesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'spgSSLPolicy'
--
-- * 'spgProject'
sslPoliciesGet
:: Text -- ^ 'spgSSLPolicy'
-> Text -- ^ 'spgProject'
-> SSLPoliciesGet
sslPoliciesGet pSpgSSLPolicy_ pSpgProject_ =
SSLPoliciesGet' {_spgSSLPolicy = pSpgSSLPolicy_, _spgProject = pSpgProject_}
-- | Name of the SSL policy to update. The name must be 1-63 characters long,
-- and comply with RFC1035.
spgSSLPolicy :: Lens' SSLPoliciesGet Text
spgSSLPolicy
= lens _spgSSLPolicy (\ s a -> s{_spgSSLPolicy = a})
-- | Project ID for this request.
spgProject :: Lens' SSLPoliciesGet Text
spgProject
= lens _spgProject (\ s a -> s{_spgProject = a})
instance GoogleRequest SSLPoliciesGet where
type Rs SSLPoliciesGet = SSLPolicy
type Scopes SSLPoliciesGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient SSLPoliciesGet'{..}
= go _spgProject _spgSSLPolicy (Just AltJSON)
computeService
where go
= buildClient (Proxy :: Proxy SSLPoliciesGetResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/SSLPolicies/Get.hs | mpl-2.0 | 3,331 | 0 | 15 | 757 | 392 | 236 | 156 | 63 | 1 |
-- Simple test of recursive integrals, from Beelsebob
import Control.Arrow (first)
import Data.Max
import Data.AddBounds
import FRP.Reactive.Behavior
import FRP.Reactive.PrimReactive
import FRP.Reactive.Internal.Reactive
import FRP.Reactive.Internal.Behavior
import FRP.Reactive.Future
import FRP.Reactive
import FRP.Reactive.Improving
-- For ticker
import FRP.Reactive.Internal.Clock
import FRP.Reactive.Internal.TVal
import System.IO.Unsafe
tick = atTimes [0,0.01 .. 2]
it = integral tick
ib = 1 + it ib :: Behavior Double
e' = atTimes [0,0.1 .. 1.1]
-- [(0.0,1.0),(0.1,1.1046221254112045),(0.2,1.2081089504435316),(0.30000000000000004,1.3345038765672335),(0.4000000000000001,1.4741225085031893),(0.5000000000000001,1.6283483384592894),(0.6000000000000001,1.7987096025387035),(0.7000000000000001,1.9868944241538458),(0.8,2.1947675417764927),(0.9,2.424388786780674),(1.0,2.67803349447676),(1.1,2.7048138294215276)]
i1 = occs (ib `snapshot_` e')
itst b = occs (it b `snapshot_` e')
occs :: Event a -> [(TimeT, a)]
occs = map (first (unNo . exact . getMax) . unFuture) . eFutures
where
unNo (NoBound a) = a
-- [(0.0,0.0),(0.1,9.999999999999996e-2),(0.2,0.19),(0.30000000000000004,0.2900000000000001),(0.4000000000000001,0.3900000000000002),(0.5000000000000001,0.49000000000000027),(0.6000000000000001,0.5900000000000003),(0.7000000000000001,0.6900000000000004),(0.8,0.7900000000000005),(0.9,0.8900000000000006),(1.0,0.9900000000000007),(1.1,1.0000000000000007)]
i2 = itst 1
-- K 0.0 `Stepper` (1.0e-2,K 1.0e-2)->(2.0e-2,K 2.0e-2)->(3.0e-2,K 3.0e-2)->(3.9999999999999994e-2,K 3.9999999999999994e-2)->(4.999999999999999e-2,K 4.999999999999999e-2)->(5.9999999999999984e-2,K 5.9999999999999984e-2)->(6.999999999999998e-2,K 6.999999999999998e-2)->(7.999999999999997e-2,K 7.999999999999997e-2)->(8.999999999999997e-2,K 8.999999999999997e-2)->(9.999999999999996e-2,K 9.999999999999996e-2)->(0.10999999999999996,K 0.10999999999999996)->(0.11999999999999995,K 0.11999999999999995)->(0.12999999999999995,K 0.12999999999999995)->(0.13999999999999996,K 0.13999999999999996)->(0.14999999999999997,K 0.14999999999999997)->(0.15999999999999998,K 0.15999999999999998)->(0.16999999999999998,K 0.16999999999999998)->(0.18,K 0.18)->(0.19,K 0.19)->(0.2,K 0.2)-> ...
r2 = unb (it 1)
main = print i1
-- Integration seems much slower than i'd expect it to be, even in the
-- non-recursive case. Recursive and non-recursive examples slow down as
-- they go.
| ekmett/reactive | src/Test/Integ.hs | agpl-3.0 | 2,456 | 9 | 12 | 196 | 316 | 171 | 145 | 25 | 1 |
module AlecSequences.A273190Spec (main, spec) where
import Test.Hspec
import AlecSequences.A273190 (a273190)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A273190" $
it "correctly computes the first 20 elements" $
take 20 (map a273190 [0..]) `shouldBe` expectedValue where
expectedValue = [0,1,0,1,1,1,1,1,1,2,1,1,1,2,2,2,2,1,1,2]
| peterokagey/haskellOEIS | test/AlecSequences/A273190Spec.hs | apache-2.0 | 361 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
-- Isomorphism for sum and product types
-- a+a = 2*a
module Main where
aa2a :: Either a a -> (Bool,a)
aa2a (Left x) = (False,x)
aa2a (Right x) = (True, x)
_2aaa :: (Bool, a) -> Either a a
_2aaa (False, x) = Left x
_2aaa (True, x) = Right x
print2 :: Either a a -> String
print2 (Left x) = "Left"
print2 (Right x) = "Right"
print3 :: (Bool,a) -> String
print3 (False, x) = "False"
print3 (True, x) = "True"
main = do
putStrLn . print3 . aa2a $ Left 1
putStrLn . print3 . aa2a $ Right 1
putStrLn . print2 . _2aaa $ (False, 1)
putStrLn . print2 . _2aaa $ (True, 1) | xunilrj/sandbox | books/category4programmers/6.5.main.hs | apache-2.0 | 638 | 0 | 9 | 194 | 288 | 154 | 134 | 18 | 1 |
import Data.List
isLeap year
| year `mod` 400 == 0 = True
| year `mod` 100 == 0 = False
| year `mod` 4 == 0 = True
| otherwise = False
ans (from:to:_) =
filter isLeap [from..to]
toStr :: [Int] -> String
toStr [] = "NA\n"
toStr x = unlines $ map show x
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Int]]
i'= takeWhile (/= [0,0]) i
o = map ans i'
-- print o
-- print [2001..2010]
putStr $ intercalate "\n" $ map toStr o
| a143753/AOJ | 0093.hs | apache-2.0 | 496 | 3 | 14 | 145 | 265 | 131 | 134 | 17 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Util where
import Test.QuickCheck.Property.Comb
import Data.Set
import qualified Data.List as L
import Control.Applicative
import Prelude hiding (pred, null)
type LabelledSet a = (String, Set a)
disjoint :: forall a. (Ord a) => Invariants [LabelledSet a]
disjoint =
sat $ do
non_disjoint <- L.filter (not . snd) . L.map (uncurry pred) . toPairings <$> cause
doc . L.intercalate "\n" . L.map fst $ non_disjoint
return $ L.null non_disjoint
where
-- TODO Remove (a, b), (b, a) from the subsequences
toPairings :: [LabelledSet a] -> [(LabelledSet a, LabelledSet a)]
toPairings =
L.map (\l-> (head l, l !! 1))
. L.filter (\l -> length l == 2)
. L.subsequences
pred :: LabelledSet a -> LabelledSet a -> (String, Bool)
pred (desc1, s1) (desc2, s2) =
(,)
(desc1 ++ " and " ++ desc2 ++ " disjoint ")
(null $ intersection s1 s2)
| jfeltz/tasty-integrate | tests/Util.hs | bsd-2-clause | 946 | 0 | 14 | 226 | 350 | 189 | 161 | 24 | 1 |
module Codewars.Parentheses where
validParentheses :: String -> Bool
validParentheses = validate 0
where validate depth [] = depth == 0
validate depth (b:bs) = if depth < 0 then
False
else
case b of
'(' -> validate (depth + 1) bs
')' -> validate (depth - 1) bs
| lisphacker/codewars | Parantheses.hs | bsd-2-clause | 473 | 0 | 13 | 260 | 110 | 58 | 52 | 9 | 4 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Lens hiding ( Context, contexts )
import Control.Monad.Trans.Either ( EitherT(..)
, runEitherT
, hoistEither )
import Control.Monad.Trans.Class ( lift )
import Control.Applicative ( (<*>), (<$>) )
import Data.Default ( def )
import qualified Data.HashMap.Strict as M
import Data.List ( foldl'
, intercalate
, sortBy )
import qualified Data.Vector as V
import Data.Csv ( encode
, ToRecord(..)
, record
, toField )
import qualified Data.ByteString.Lazy as BL
import System.Environment ( getArgs )
import Text.Printf ( printf )
import TrueSkill ( predict
, fromMuSigma2
, toMuSigma2
, skills
, games
, makeSkills
, Parameter(..)
, Message
, predictionMessage
, offense
, defense
, Result(..) )
import Train
import Types
import Parameter
data Prediction = Prediction
{ _predictionHome :: Int
, _predictionGuest :: Int
, _predictionExpectedLoss :: Double
}
makeLenses ''Prediction
predictionSpace :: [Prediction]
predictionSpace = Prediction <$> [0..9] <*> [0..9] <*> [0]
loss :: Game -> Result -> Prediction -> Double
loss game (Result (home, guest)) p
| home == guest && p^.predictionHome == p^.predictionGuest = -game^.gameOdds._2
| home > guest && p^.predictionHome > p^.predictionGuest = -game^.gameOdds._1
| home < guest && p^.predictionHome < p^.predictionGuest = -game^.gameOdds._3
| otherwise = 0
-- fromIntegral ((home - p^.predictionHome)^(2 :: Int)) +
-- fromIntegral ((guest - p^.predictionGuest)^(2 :: Int))
data Context = Context
{ _contextPrediction :: Prediction
, _contextProbabilities :: ([Double], [Double])
, _contextMessage :: (Message Double, Message Double)
, _contextGame :: Game
, _contextModel :: Model Double
}
makeLenses ''Context
data LatentPlayer = LatentPlayer
{ playerName :: !String
, playerMuOffense :: !Double
, playerSigmaOffense :: !Double
, playerMuDefense :: !Double
, playerSigmaDefense :: !Double
, playerOffenseScore :: !Double
, playerDefenseScore :: !Double
, playerGames :: Int
}
instance ToRecord LatentPlayer where
toRecord p = record $ map (\f -> f p)
[ toField . playerName
, toField . playerMuOffense
, toField . playerSigmaOffense
, toField . playerMuDefense
, toField . playerSigmaDefense
, toField . playerOffenseScore
, toField . playerDefenseScore ]
instance Show Prediction where
show p = printf "%d:%d - %f" (p^.predictionHome) (p^.predictionGuest) (p^.predictionExpectedLoss)
instance Show Context where
show c = printf "(%d, %d):" homeGoals guestGoals ++
" -> " ++ (show $ c^.contextPrediction)
where
Result (homeGoals, guestGoals) = c^.contextGame.result
instance ToRecord Context where
toRecord c = record $ (toField $ c^.contextGame.gameID) :
(toField $ show homeGoals ++ ":" ++ show guestGoals) :
(toField $ show $ c^.contextPrediction) :
[toField muPredictionHomeMessage,
toField sigma2PredictionHomeMessage] ++
[toField muPredictionGuestMessage,
toField sigma2PredictionGuestMessage] ++
map toField (c^.contextProbabilities._1) ++
map toField (c^.contextProbabilities._2)
where
Result (homeGoals, guestGoals) = c^.contextGame.result
(muPredictionHomeMessage, sigma2PredictionHomeMessage) =
toMuSigma2 $ c^.contextMessage._1
(muPredictionGuestMessage, sigma2PredictionGuestMessage) =
toMuSigma2 $ c^.contextMessage._2
argMin :: Ord d => [(d, a)] -> (d, a)
argMin [] = undefined
argMin (s:ss) = foldl' go s ss
where
go left@(v, _) right@(w, _)
| w < v = right
| otherwise = left
decide :: Game -> ([Double], [Double]) -> Prediction
decide game probabilities = prediction { _predictionExpectedLoss = minLoss }
where
(minLoss, prediction) = argMin predictionCosts
predictionCosts :: [(Double, Prediction)]
predictionCosts = map (\p -> (predictionCost p, p)) predictionSpace
predictionCost :: Prediction -> Double
predictionCost p = sum $ map (\ ((h, hp), (g, gp)) ->
hp * gp * loss game (Result (h, g)) p) $
((,) <$>
(zip [0..] (fst probabilities)) <*>
(zip [0..] (snd probabilities)))
rollingPredict :: FilePath -> FilePath -> Knobs -> IO (Either String Double)
rollingPredict trainFile testFile knobs = runEitherT $ do
trainData <- hoistEither =<<
lift (readGamesFromCsv trainFile)
testData <- hoistEither =<<
lift (readGamesFromCsv testFile)
let initModel = trainModel (getMessagePasses knobs) parameter
defaultPlayer trainData
let initContext = Context undefined undefined undefined undefined initModel
let contexts = V.scanl' roll initContext testData
let finalPrediction = V.last contexts
let latentPlayers = map convert $ M.toList $
finalPrediction^.contextModel
lift $ BL.writeFile "player.csv" $ encode $ latentPlayers
lift $ BL.writeFile "games.csv" $ encode $
V.toList $ V.tail contexts
lift $ putStrLn "Offense:"
lift $ putStrLn $ intercalate "\n" $ map playerName $ take 12
$ sortLadder playerOffenseScore latentPlayers
lift $ putStrLn ""
lift $ putStrLn "Defense:"
lift $ putStrLn $ intercalate "\n" $ map playerName $ take 12
$ sortLadder playerDefenseScore latentPlayers
lift $ putStrLn ""
return $ (V.sum $ V.map
(\c -> (loss (c^.contextGame) (c^.contextGame.result) (c^.contextPrediction) + 1)) $
V.filter (\c -> c^.contextPrediction.predictionExpectedLoss + 1 < 0) $
V.tail contexts)
where
sortLadder crit players =
reverse
$ sortBy (\p p' ->
compare (crit p) (crit p'))
$ filter (\p -> playerGames p >= 30)
players
evalPlayer skill' p = mu - 2 * sqrt sigma2
where
(mu, sigma2) = toMuSigma2 (p^.skills.skill')
convert (name, p) = LatentPlayer name
muOffense sigmaOffense
muDefense sigmaDefense
(evalPlayer offense p)
(evalPlayer defense p)
(length $ M.toList $ p^.games)
where
(muOffense, sigmaOffense) = toMuSigma2 (p^.skills.offense)
(muDefense, sigmaDefense) = toMuSigma2 (p^.skills.defense)
roll context game =
Context prediction probabilities
(fromHomeMessage, fromGuestMessage) game $
model
-- updateModel parameter defaultPlayer model game
where
model = context ^. contextModel
get p = M.lookupDefault defaultPlayer p model
(fromHomeMessage, fromGuestMessage) =
predict parameter
( map get $ game ^. team1
, map get $ game ^. team2
)
probabilities = both %~ predictionMessage $
(fromHomeMessage, fromGuestMessage)
prediction = decide game probabilities
parameter =
(def :: Parameter Double)
{ _sigmaOffense = getSigmaOffense knobs
, _sigmaDefense = getSigmaDefense knobs
, _homeBonus = makeSkills
(fromMuSigma2 (getMuHomeBonusOffense knobs)
(getSigmaHomeBonusOffense knobs ^ (2 :: Int)))
(fromMuSigma2 (getMuHomeBonusDefense knobs)
(getSigmaHomeBonusDefense knobs ^ (2 :: Int)))
}
defaultPlayer = skills .~ makeSkills
(fromMuSigma2 (getDefaultMuOffense knobs)
(getDefaultSigmaOffense knobs ^ (2 :: Int)))
(fromMuSigma2 (getDefaultMuDefense knobs)
(getDefaultSigmaDefense knobs ^ (2 :: Int)))
$ def
main :: IO ()
main = do
[trainFile, testFile, knobsFile] <- getArgs
rawKnobs <- readKnobs knobsFile
case rawKnobs of
Just knobs ->
print =<< rollingPredict trainFile testFile knobs
Nothing ->
putStrLn "error reading knobs file"
| mkiefel/trueskill | rolling_predict_app.hs | bsd-2-clause | 9,272 | 0 | 21 | 3,339 | 2,424 | 1,288 | 1,136 | -1 | -1 |
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses, TypeSynonymInstances, PatternGuards, DeriveDataTypeable,
FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.UrgencyHook
-- Copyright : Devin Mullins <me@twifkak.com>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Devin Mullins <me@twifkak.com>
-- Stability : unstable
-- Portability : unportable
--
-- UrgencyHook lets you configure an action to occur when a window demands
-- your attention. (In traditional WMs, this takes the form of \"flashing\"
-- on your \"taskbar.\" Blech.)
--
-----------------------------------------------------------------------------
module XMonad.Hooks.UrgencyHook (
-- * Usage
-- $usage
-- ** Pop up a temporary dzen
-- $temporary
-- ** Highlight in existing dzen
-- $existing
-- ** Useful keybinding
-- $keybinding
-- ** Note
-- $note
-- * Troubleshooting
-- $troubleshooting
-- * Example: Setting up irssi + rxvt-unicode
-- $example
-- ** Configuring irssi
-- $irssi
-- ** Configuring screen
-- $screen
-- ** Configuring rxvt-unicode
-- $urxvt
-- ** Configuring xmonad
-- $xmonad
-- * Stuff for your config file:
withUrgencyHook, withUrgencyHookC,
UrgencyConfig(..), urgencyConfig,
SuppressWhen(..), RemindWhen(..),
focusUrgent, clearUrgents,
dzenUrgencyHook,
DzenUrgencyHook(..),
NoUrgencyHook(..),
BorderUrgencyHook(..),
FocusHook(..),
minutes, seconds,
-- * Stuff for developers:
readUrgents, withUrgents,
StdoutUrgencyHook(..),
SpawnUrgencyHook(..),
UrgencyHook(urgencyHook),
Interval,
borderUrgencyHook, focusHook, spawnUrgencyHook, stdoutUrgencyHook
) where
import XMonad
import qualified XMonad.StackSet as W
import XMonad.Util.Dzen (dzenWithArgs, seconds)
import qualified XMonad.Util.ExtensibleState as XS
import XMonad.Util.NamedWindows (getName)
import XMonad.Util.Timer (TimerId, startTimer, handleTimer)
import Control.Applicative ((<$>))
import Control.Monad (when)
import Data.Bits (testBit)
import Data.List (delete, (\\))
import Data.Maybe (listToMaybe, maybeToList)
import qualified Data.Set as S
import System.IO (hPutStrLn, stderr)
-- $usage
--
-- To wire this up, first add:
--
-- > import XMonad.Hooks.UrgencyHook
--
-- to your import list in your config file. Now, you have a decision to make:
-- When a window deems itself urgent, do you want to pop up a temporary dzen
-- bar telling you so, or do you have an existing dzen wherein you would like to
-- highlight urgent workspaces?
-- $temporary
--
-- Enable your urgency hook by wrapping your config record in a call to
-- 'withUrgencyHook'. For example:
--
-- > main = xmonad $ withUrgencyHook dzenUrgencyHook { args = ["-bg", "darkgreen", "-xs", "1"] }
-- > $ defaultConfig
--
-- This will pop up a dzen bar for five seconds telling you you've got an
-- urgent window.
-- $existing
--
-- In order for xmonad to track urgent windows, you must install an urgency hook.
-- You can use the above 'dzenUrgencyHook', or if you're not interested in the
-- extra popup, install NoUrgencyHook, as so:
--
-- > main = xmonad $ withUrgencyHook NoUrgencyHook
-- > $ defaultConfig
--
-- Now, your "XMonad.Hooks.DynamicLog" must be set up to display the urgent
-- windows. If you're using the 'dzen' or 'dzenPP' functions from that module,
-- then you should be good. Otherwise, you want to figure out how to set
-- 'ppUrgent'.
-- $keybinding
--
-- You can set up a keybinding to jump to the window that was recently marked
-- urgent. See an example at 'focusUrgent'.
-- $note
-- Note: UrgencyHook installs itself as a LayoutModifier, so if you modify your
-- urgency hook and restart xmonad, you may need to rejigger your layout by
-- hitting mod-shift-space.
-- $troubleshooting
--
-- There are three steps to get right:
--
-- 1. The X client must set the UrgencyHint flag. How to configure this
-- depends on the application. If you're using a terminal app, this is in
-- two parts:
--
-- * The console app must send a ^G (bell). In bash, a helpful trick is
-- @sleep 1; echo -e \'\\a\'@.
--
-- * The terminal must convert the bell into UrgencyHint.
--
-- 2. XMonad must be configured to notice UrgencyHints. If you've added
-- withUrgencyHook, you may need to hit mod-shift-space to reset the layout.
--
-- 3. The dzen must run when told. Run @dzen2 -help@ and make sure that it
-- supports all of the arguments you told DzenUrgencyHook to pass it. Also,
-- set up a keybinding to the 'dzen' action in "XMonad.Util.Dzen" to test
-- if that works.
--
-- As best you can, try to isolate which one(s) of those is failing.
-- $example
--
-- This is a commonly asked example. By default, the window doesn't get flagged
-- urgent when somebody messages you in irssi. You will have to configure some
-- things. If you're using different tools than this, your mileage will almost
-- certainly vary. (For example, in Xchat2, it's just a simple checkbox.)
-- $irssi
-- @Irssi@ is not an X11 app, so it can't set the @UrgencyHint@ flag on @XWMHints@.
-- However, on all console applications is bestown the greatest of all notification
-- systems: the bell. That's right, Ctrl+G, ASCII code 7, @echo -e '\a'@, your
-- friend, the bell. To configure @irssi@ to send a bell when you receive a message:
--
-- > /set beep_msg_level MSGS NOTICES INVITES DCC DCCMSGS HILIGHT
--
-- Consult your local @irssi@ documentation for more detail.
-- $screen
-- A common way to run @irssi@ is within the lovable giant, @screen@. Some distros
-- (e.g. Ubuntu) like to configure @screen@ to trample on your poor console
-- applications -- in particular, to turn bell characters into evil, smelly
-- \"visual bells.\" To turn this off, add:
--
-- > vbell off # or remove the existing 'vbell on' line
--
-- to your .screenrc, or hit @C-a C-g@ within a running @screen@ session for an
-- immediate but temporary fix.
-- $urxvt
-- Rubber, meet road. Urxvt is the gateway between console apps and X11. To tell
-- urxvt to set an @UrgencyHint@ when it receives a bell character, first, have
-- an urxvt version 8.3 or newer, and second, set the following in your
-- @.Xdefaults@:
--
-- > urxvt.urgentOnBell: true
--
-- Depending on your setup, you may need to @xrdb@ that.
-- $xmonad
-- Hopefully you already read the section on how to configure xmonad. If not,
-- hopefully you know where to find it.
-- | This is the method to enable an urgency hook. It uses the default
-- 'urgencyConfig' to control behavior. To change this, use 'withUrgencyHookC'
-- instead.
withUrgencyHook :: (LayoutClass l Window, UrgencyHook h) =>
h -> XConfig l -> XConfig l
withUrgencyHook hook conf = withUrgencyHookC hook urgencyConfig conf
-- | This lets you modify the defaults set in 'urgencyConfig'. An example:
--
-- > withUrgencyHookC dzenUrgencyHook { ... } urgencyConfig { suppressWhen = Focused }
--
-- (Don't type the @...@, you dolt.) See 'UrgencyConfig' for details on configuration.
withUrgencyHookC :: (LayoutClass l Window, UrgencyHook h) =>
h -> UrgencyConfig -> XConfig l -> XConfig l
withUrgencyHookC hook urgConf conf = conf {
handleEventHook = \e -> handleEvent (WithUrgencyHook hook urgConf) e >> handleEventHook conf e,
logHook = cleanupUrgents (suppressWhen urgConf) >> logHook conf
}
data Urgents = Urgents { fromUrgents :: [Window] } deriving (Read,Show,Typeable)
onUrgents :: ([Window] -> [Window]) -> Urgents -> Urgents
onUrgents f = Urgents . f . fromUrgents
instance ExtensionClass Urgents where
initialValue = Urgents []
extensionType = PersistentExtension
-- | Global configuration, applied to all types of 'UrgencyHook'. See
-- 'urgencyConfig' for the defaults.
data UrgencyConfig = UrgencyConfig
{ suppressWhen :: SuppressWhen -- ^ when to trigger the urgency hook
, remindWhen :: RemindWhen -- ^ when to re-trigger the urgency hook
} deriving (Read, Show)
-- | A set of choices as to /when/ you should (or rather, shouldn't) be notified of an urgent window.
-- The default is 'Visible'. Prefix each of the following with \"don't bug me when\":
data SuppressWhen = Visible -- ^ the window is currently visible
| OnScreen -- ^ the window is on the currently focused physical screen
| Focused -- ^ the window is currently focused
| Never -- ^ ... aww, heck, go ahead and bug me, just in case.
deriving (Read, Show)
-- | A set of choices as to when you want to be re-notified of an urgent
-- window. Perhaps you focused on something and you miss the dzen popup bar. Or
-- you're AFK. Or you feel the need to be more distracted. I don't care.
--
-- The interval arguments are in seconds. See the 'minutes' helper.
data RemindWhen = Dont -- ^ triggering once is enough
| Repeatedly Int Interval -- ^ repeat <arg1> times every <arg2> seconds
| Every Interval -- ^ repeat every <arg1> until the urgency hint is cleared
deriving (Read, Show)
-- | A prettified way of multiplying by 60. Use like: @(5 `minutes`)@.
minutes :: Rational -> Rational
minutes secs = secs * 60
-- | The default 'UrgencyConfig'. suppressWhen = Visible, remindWhen = Dont.
-- Use a variation of this in your config just as you use a variation of
-- defaultConfig for your xmonad definition.
urgencyConfig :: UrgencyConfig
urgencyConfig = UrgencyConfig { suppressWhen = Visible, remindWhen = Dont }
-- | Focuses the most recently urgent window. Good for what ails ya -- I mean, your keybindings.
-- Example keybinding:
--
-- > , ((modm , xK_BackSpace), focusUrgent)
focusUrgent :: X ()
focusUrgent = withUrgents $ flip whenJust (windows . W.focusWindow) . listToMaybe
-- | Just makes the urgents go away.
-- Example keybinding:
--
-- > , ((modm .|. shiftMask, xK_BackSpace), clearUrgents)
clearUrgents :: X ()
clearUrgents = adjustUrgents (const []) >> adjustReminders (const [])
-- | X action that returns a list of currently urgent windows. You might use
-- it, or 'withUrgents', in your custom logHook, to display the workspaces that
-- contain urgent windows.
readUrgents :: X [Window]
readUrgents = XS.gets fromUrgents
-- | An HOF version of 'readUrgents', for those who prefer that sort of thing.
withUrgents :: ([Window] -> X a) -> X a
withUrgents f = readUrgents >>= f
adjustUrgents :: ([Window] -> [Window]) -> X ()
adjustUrgents = XS.modify . onUrgents
type Interval = Rational
-- | An urgency reminder, as reified for 'RemindWhen'.
-- The last value is the countdown number, for 'Repeatedly'.
data Reminder = Reminder { timer :: TimerId
, window :: Window
, interval :: Interval
, remaining :: Maybe Int
} deriving (Show,Read,Eq,Typeable)
instance ExtensionClass [Reminder] where
initialValue = []
extensionType = PersistentExtension
-- | Stores the list of urgency reminders.
readReminders :: X [Reminder]
readReminders = XS.get
adjustReminders :: ([Reminder] -> [Reminder]) -> X ()
adjustReminders = XS.modify
clearUrgency :: Window -> X ()
clearUrgency w = adjustUrgents (delete w) >> adjustReminders (filter $ (w /=) . window)
data WithUrgencyHook h = WithUrgencyHook h UrgencyConfig
deriving (Read, Show)
-- The Non-ICCCM Manifesto:
-- Note: Some non-standard choices have been made in this implementation to
-- account for the fact that things are different in a tiling window manager:
-- 1. In normal window managers, windows may overlap, so clients wait for focus to
-- be set before urgency is cleared. In a tiling WM, it's sufficient to be able
-- see the window, since we know that means you can see it completely.
-- 2. The urgentOnBell setting in rxvt-unicode sets urgency even when the window
-- has focus, and won't clear until it loses and regains focus. This is stupid.
-- In order to account for these quirks, we track the list of urgent windows
-- ourselves, allowing us to clear urgency when a window is visible, and not to
-- set urgency if a window is visible. If you have a better idea, please, let us
-- know!
handleEvent :: UrgencyHook h => WithUrgencyHook h -> Event -> X ()
handleEvent wuh event =
case event of
PropertyEvent { ev_event_type = t, ev_atom = a, ev_window = w } -> do
when (t == propertyNotify && a == wM_HINTS) $ withDisplay $ \dpy -> do
WMHints { wmh_flags = flags } <- io $ getWMHints dpy w
if (testBit flags urgencyHintBit) then do
adjustUrgents (\ws -> if elem w ws then ws else w : ws)
callUrgencyHook wuh w
else
clearUrgency w
userCodeDef () =<< asks (logHook . config)
DestroyWindowEvent {ev_window = w} ->
clearUrgency w
_ ->
mapM_ handleReminder =<< readReminders
where handleReminder reminder = handleTimer (timer reminder) event $ reminderHook wuh reminder
callUrgencyHook :: UrgencyHook h => WithUrgencyHook h -> Window -> X ()
callUrgencyHook (WithUrgencyHook hook UrgencyConfig { suppressWhen = sw, remindWhen = rw }) w =
whenX (not <$> shouldSuppress sw w) $ do
userCodeDef () $ urgencyHook hook w
case rw of
Repeatedly times int -> addReminder w int $ Just times
Every int -> addReminder w int Nothing
Dont -> return ()
addReminder :: Window -> Rational -> Maybe Int -> X ()
addReminder w int times = do
timerId <- startTimer int
let reminder = Reminder timerId w int times
adjustReminders (\rs -> if w `elem` map window rs then rs else reminder : rs)
reminderHook :: UrgencyHook h => WithUrgencyHook h -> Reminder -> X (Maybe a)
reminderHook (WithUrgencyHook hook _) reminder = do
case remaining reminder of
Just x | x > 0 -> remind $ Just (x - 1)
Just _ -> adjustReminders $ delete reminder
Nothing -> remind Nothing
return Nothing
where remind remaining' = do userCode $ urgencyHook hook (window reminder)
adjustReminders $ delete reminder
addReminder (window reminder) (interval reminder) remaining'
shouldSuppress :: SuppressWhen -> Window -> X Bool
shouldSuppress sw w = elem w <$> suppressibleWindows sw
cleanupUrgents :: SuppressWhen -> X ()
cleanupUrgents sw = do
sw' <- suppressibleWindows sw
adjustUrgents (\\ sw') >> adjustReminders (filter $ ((`notElem` sw') . window))
suppressibleWindows :: SuppressWhen -> X [Window]
suppressibleWindows Visible = gets $ S.toList . mapped
suppressibleWindows OnScreen = gets $ W.index . windowset
suppressibleWindows Focused = gets $ maybeToList . W.peek . windowset
suppressibleWindows Never = return []
--------------------------------------------------------------------------------
-- Urgency Hooks
-- | The class definition, and some pre-defined instances.
class UrgencyHook h where
urgencyHook :: h -> Window -> X ()
instance UrgencyHook (Window -> X ()) where
urgencyHook = id
data NoUrgencyHook = NoUrgencyHook deriving (Read, Show)
instance UrgencyHook NoUrgencyHook where
urgencyHook _ _ = return ()
-- | Your set of options for configuring a dzenUrgencyHook.
data DzenUrgencyHook = DzenUrgencyHook {
duration :: Int, -- ^ number of microseconds to display the dzen
-- (hence, you'll probably want to use 'seconds')
args :: [String] -- ^ list of extra args (as 'String's) to pass to dzen
}
deriving (Read, Show)
instance UrgencyHook DzenUrgencyHook where
urgencyHook DzenUrgencyHook { duration = d, args = a } w = do
name <- getName w
ws <- gets windowset
whenJust (W.findTag w ws) (flash name)
where flash name index =
dzenWithArgs (show name ++ " requests your attention on workspace " ++ index) a d
{- | A hook which will automatically send you to anything which sets the urgent
flag (as opposed to printing some sort of message. You would use this as
usual, eg.
> withUrgencyHook FocusHook $ myconfig { ...
-}
focusHook = urgencyHook FocusHook
data FocusHook = FocusHook deriving (Read, Show)
instance UrgencyHook FocusHook where
urgencyHook _ _ = focusUrgent
-- | A hook that sets the border color of an urgent window. The color
-- will remain until the next time the window gains or loses focus, at
-- which point the standard border color from the XConfig will be applied.
-- You may want to use suppressWhen = Never with this:
--
-- > withUrgencyHookC BorderUrgencyHook { urgencyBorderColor = "#ff0000" } urgencyConfig { suppressWhen = Never } ...
--
-- (This should be @urgentBorderColor@ but that breaks "XMonad.Layout.Decoration".
-- @borderColor@ breaks anyone using 'XPConfig' from "XMonad.Prompt". We need to
-- think a bit more about namespacing issues, maybe.)
borderUrgencyHook = urgencyHook . BorderUrgencyHook
data BorderUrgencyHook = BorderUrgencyHook { urgencyBorderColor :: !String }
deriving (Read, Show)
instance UrgencyHook BorderUrgencyHook where
urgencyHook BorderUrgencyHook { urgencyBorderColor = cs } w =
withDisplay $ \dpy -> io $ do
c' <- initColor dpy cs
case c' of
Just c -> setWindowBorder dpy w c
_ -> hPutStrLn stderr $ concat ["Warning: bad urgentBorderColor "
,show cs
," in BorderUrgencyHook"
]
-- | Flashes when a window requests your attention and you can't see it.
-- Defaults to a duration of five seconds, and no extra args to dzen.
-- See 'DzenUrgencyHook'.
dzenUrgencyHook :: DzenUrgencyHook
dzenUrgencyHook = DzenUrgencyHook { duration = seconds 5, args = [] }
-- | Spawn a commandline thing, appending the window id to the prefix string
-- you provide. (Make sure to add a space if you need it.) Do your crazy
-- xcompmgr thing.
spawnUrgencyHook = urgencyHook . SpawnUrgencyHook
newtype SpawnUrgencyHook = SpawnUrgencyHook String deriving (Read, Show)
instance UrgencyHook SpawnUrgencyHook where
urgencyHook (SpawnUrgencyHook prefix) w = spawn $ prefix ++ show w
-- | For debugging purposes, really.
stdoutUrgencyHook = urgencyHook StdoutUrgencyHook
data StdoutUrgencyHook = StdoutUrgencyHook deriving (Read, Show)
instance UrgencyHook StdoutUrgencyHook where
urgencyHook _ w = io $ putStrLn $ "Urgent: " ++ show w
| reenberg/XMonadContrib | XMonad/Hooks/UrgencyHook.hs | bsd-3-clause | 20,088 | 0 | 21 | 5,511 | 2,744 | 1,552 | 1,192 | 189 | 5 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE MultiWayIf #-}
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Control.Concurrent.MVar
import FRP.Yampa as Yampa
import Arduino
import Data.IORef
import System.IO
main = do
-- Initialise arduino
input <- defaultArduinoInput
output <- defaultArduinoOutput
thrd <- arduinoThread input output
reactimate (readMVar input)
(\_ -> do i <- readMVar input
-- putStrLn $ "Yampa input: " ++ show i
return $ (1, Just i))
(\_ (i, o) -> do swapMVar output o
-- putStrLn $ "Yampa output: " ++ show o
threadDelay 10
return False)
sf
sf = proc i -> do
s0 <- fastPFW 200 400 -< ()
s1 <- fastPFW 3 5 -< ()
let output = ArduinoOutput s0 s1
returnA -< (i, output)
fastPFW n mx =
arr ((< n).(`mod` mx).round) <<< localTime
-- proc i -> do
-- t <- round ^<< localTime -< ()
-- let v = t `mod` mx < n
-- returnA -< v
| turion/hacknotts14 | src/Main.hs | bsd-3-clause | 1,082 | 3 | 14 | 370 | 288 | 149 | 139 | 28 | 1 |
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
module Main where
import qualified Data.Map as Map
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.RWS.Strict
import Control.Monad.ST
import Data.Array.Repa
import Data.Array.Repa.Repr.ForeignPtr
import Data.Array.Repa.IO.DevIL
import Data.Array.ST
import Data.Map (Map)
import Data.Word
import Foreign (pokeElemOff, withForeignPtr)
import System.Directory
import System.Environment
import System.Exit
import Config
import Types
--------------------------------------------------------------------------------
main = do
-- Args: map image, conf file, output path
argv <- getArgs
when (length argv /= 4) $ do
putStrLn "Usage: dom3conquestmaptool mapimage-file borderimage-file conf-file output-file"
exitFailure
let [imagePath, borderPath, confPath, outPath] = argv
-- Load images
img <- runIL $ readImage imagePath
bImg <- runIL $ readImage borderPath
-- Load conf
conf <- loadConfig confPath
-- Create the new image
work img bImg conf outPath
-- exit(1)
exitSuccess
work img bImg conf outPath = do
-- Parse provinces out of the image
provs <- findProvinces img
-- Do floodfill on the pixel data, based on province ownerships from conf
floodfill conf provs bImg img
-- DevIL refuses to overwrite files, so delete the target file first if it exists
whenM (doesFileExist outPath) $
removeFile outPath
-- Save modified image to file
runIL $ writeImage outPath img
-- | Finds the province dot coordinates from the image.
findProvinces :: Image -> IO [(Int, (Int, Int))]
findProvinces img =
case img of
RGB pixs -> findProvinces' pixs
RGBA pixs -> findProvinces' pixs
BGR pixs -> findProvinces' pixs
BGRA pixs -> findProvinces' pixs
where
findProvinces' pixs =
let Z :. maxY :. maxX :. _ = extent pixs
whites = do
y <- [0 .. maxY - 1]
x <- [0 .. maxX - 1]
guard (pixs `unsafeIndex` (ix3 y x 0) == 0xff &&
pixs `unsafeIndex` (ix3 y x 1) == 0xff &&
pixs `unsafeIndex` (ix3 y x 2) == 0xff)
return (y, x)
in return $ zip [1 ..] whites
-- | Floodfill depth-first from each of the province dots. Handle wraparound in the
-- neighbor selection.
floodfill :: Config -> [(Int, (Int, Int))] -> Image -> Image -> IO ()
floodfill conf provs bordersImg img =
let (pixs, rc, gc, bc) = case img of
RGB pixs -> (pixs, 0, 1, 2)
RGBA pixs -> (pixs, 0, 1, 2)
BGR pixs -> (pixs, 2, 1, 0)
BGRA pixs -> (pixs, 2, 1, 0)
(bPixs, bRc, bGc, bBc) = case bordersImg of
RGB pixs -> (pixs, 0, 1, 2)
RGBA pixs -> (pixs, 0, 1, 2)
BGR pixs -> (pixs, 2, 1, 0)
BGRA pixs -> (pixs, 2, 1, 0)
in floodfill' pixs rc gc bc bPixs bRc bGc bBc
where
floodfill' pixs rc gc bc bPixs bRc bGc bBc =
withForeignPtr (toForeignPtr pixs) $ \ptr -> do
let Z :. maxY :. maxX :. chans = extent pixs
forM_ provs $ \(pnum, (y0, x0)) ->
when (pnum `Map.member` provinces conf) $ do
-- What's our colour for this province?
let owner = provinces conf Map.! pnum
Colour { red = r, green = g, blue = b } = nations conf Map.! owner
-- Find colourable pixels
let toFill = seek conf bPixs bRc bGc bBc y0 x0
-- Paint them
forM_ toFill $ \(y, x) -> do
pokeElemOff ptr (y * maxX * chans + x * chans + rc) r
pokeElemOff ptr (y * maxX * chans + x * chans + gc) g
pokeElemOff ptr (y * maxX * chans + x * chans + bc) b
seek :: Config -> Array F DIM3 Word8 ->
Int -> Int -> Int ->
Int -> Int ->
[(Int, Int)]
seek conf pixs rc gc bc y0 x0 = runST $ do
visited0 <- newArray ((0,0), (maxY, maxX)) False
execRWST (seek' y0 x0) visited0 [] >>= return . fst
where
Z :. maxY :. maxX :. chans = extent pixs
visit y x = do
arr <- ask
lift $ writeArray arr (y, x) True
isVisited y x = do
arr <- ask
lift $ readArray arr (y, x)
found y x = modify $ ((y,x):)
isBorder y x =
let r = pixs `unsafeIndex` ix3 y x rc
g = pixs `unsafeIndex` ix3 y x gc
b = pixs `unsafeIndex` ix3 y x bc
in return $
r == red (borderColour conf) &&
g == green (borderColour conf) &&
b == blue (borderColour conf)
inBounds y x = y >= 0 && y < maxY && x >= 0 && x < maxX
wrap y x =
if wraparound conf
then ((y + maxY) `mod` maxY, (x + maxX) `mod` maxX)
else (y, x)
seek' :: Int -> Int -> RWST (STUArray s (Int, Int) Bool) () [(Int, Int)] (ST s) ()
seek' y x = do
-- Do nothing if we've already visited
beenHere <- isVisited y x
when (inBounds y x && not beenHere) $ do
-- Mark this pixel visited
visit y x
-- Is it border? If it is, we're done
border <- isBorder y x
when (not border) $ do
-- Add this pixel to the ones we need to colour
found y x
-- Walk to the neighbouring pixels
--- Up
uncurry seek' $ wrap (y + 1) x
--- Down
uncurry seek' $ wrap (y - 1) x
--- Right
uncurry seek' $ wrap y (x + 1)
--- Left
uncurry seek' $ wrap y (x - 1)
whenM :: Monad m => m Bool -> m () -> m ()
whenM pred act = pred >>= flip when act
| Ornedan/dom3conquestmaptool | dom3conquestmaptool.hs | bsd-3-clause | 5,602 | 0 | 26 | 1,812 | 1,948 | 1,013 | 935 | 120 | 7 |
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
-- | This module is where all the routes and handlers are defined for your
-- site. The 'app' function is the initializer that combines everything
-- together and is exported by this module.
module Site
( app
) where
------------------------------------------------------------------------------
import Control.Applicative
import Data.ByteString (ByteString)
--import Data.Monoid
import qualified Data.Text as T
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Auth
import Snap.Snaplet.Auth.Backends.JsonFile
import Snap.Snaplet.Heist
import Snap.Snaplet.Session.Backends.CookieSession
import Snap.Snaplet.PostgresqlSimple hiding (query)
import Snap.Util.FileServe
import Heist
import qualified Heist.Interpreted as I
------------------------------------------------------------------------------
import Application
import CollabTypes
import CollabHandlers
------------------------------------------------------------------------------
-- | Render login form
handleLogin :: Maybe T.Text -> Handler App (AuthManager App) ()
handleLogin authError = heistLocal (I.bindSplices errs) $ render "login"
where
errs = maybe mempty splice authError
splice err = "loginError" ## I.textSplice err
------------------------------------------------------------------------------
-- | Handle login submit
handleLoginSubmit :: Handler App (AuthManager App) ()
handleLoginSubmit =
loginUser "login" "password" Nothing
(\_ -> handleLogin err) (redirect "/")
where
err = Just "Unknown user or password"
------------------------------------------------------------------------------
-- | Logs out and redirects the user to the site index.
handleLogout :: Handler App (AuthManager App) ()
handleLogout = logout >> redirect "/"
------------------------------------------------------------------------------
-- | Handle new user form submit
handleNewUser :: Handler App (AuthManager App) ()
handleNewUser = method GET handleForm <|> method POST handleFormSubmit
where
handleForm = render "new_user"
handleFormSubmit = registerUser "login" "password" >> redirect "/"
------------------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = [ ("/login", with auth handleLoginSubmit)
, ("/logout", with auth handleLogout)
, ("/new_user", with auth handleNewUser)
, ("/model", with auth handleModel)
, ("/thrusts", with auth handleThrusts)
, ("/thrust/:id", with auth handleThrust)
, ("/projects", with auth handleProjects)
, ("/project/:id", with auth handleProject)
, ("/members" , with auth handleMembers)
, ("/member/:id", with auth handleMember)
, ("/pis", with auth handlePIs)
, ("/pi/:id", with auth handlePI)
, ("/collabplot", render "_collabplot")
, ("", serveDirectory "static")
]
------------------------------------------------------------------------------
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
h <- nestSnaplet "" heist $ heistInit "templates"
s <- nestSnaplet "sess" sess $
initCookieSessionManager "site_key.txt" "sess" (Just 3600)
-- NOTE: We're using initJsonFileAuthManager here because it's easy and
-- doesn't require any kind of database server to run. In practice,
-- you'll probably want to change this to a more robust auth backend.
a <- nestSnaplet "auth" auth $
initJsonFileAuthManager defAuthSettings sess "users.json"
d <- nestSnaplet "db" db pgsInit
addRoutes routes
addAuthSplices h auth
return $ App h s a d
| imalsogreg/collabplot | server/src/Site.hs | bsd-3-clause | 4,042 | 0 | 12 | 837 | 739 | 405 | 334 | 60 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DataKinds #-}
-- | Shared types for various stackage packages.
module Stack.Types.BuildPlan
( -- * Types
BuildPlan (..)
, PackagePlan (..)
, PackageConstraints (..)
, TestState (..)
, SystemInfo (..)
, Maintainer (..)
, ExeName (..)
, SimpleDesc (..)
, Snapshots (..)
, DepInfo (..)
, Component (..)
, SnapName (..)
, MiniBuildPlan (..)
, MiniPackageInfo (..)
, CabalFileInfo (..)
, GitSHA1 (..)
, renderSnapName
, parseSnapName
, SnapshotHash (..)
, trimmedSnapshotHash
) where
import Control.Applicative
import Control.Arrow ((&&&))
import Control.DeepSeq (NFData)
import Control.Exception (Exception)
import Control.Monad.Catch (MonadThrow, throwM)
import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject, withText, (.!=), (.:), (.:?), (.=))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.HashMap.Strict as HashMap
import Data.Hashable (Hashable)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Set (Set)
import Data.Store (Store)
import Data.Store.TypeHash (mkManyHasTypeHash)
import Data.String (IsString, fromString)
import Data.Text (Text, pack, unpack)
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Data.Time (Day)
import qualified Data.Traversable as T
import Data.Typeable (TypeRep, Typeable, typeOf)
import Data.Vector (Vector)
import Distribution.System (Arch, OS (..))
import qualified Distribution.Text as DT
import qualified Distribution.Version as C
import GHC.Generics (Generic)
import Prelude -- Fix AMP warning
import Safe (readMay)
import Stack.Types.Compiler
import Stack.Types.FlagName
import Stack.Types.PackageName
import Stack.Types.Version
-- | The name of an LTS Haskell or Stackage Nightly snapshot.
data SnapName
= LTS !Int !Int
| Nightly !Day
deriving (Show, Eq, Ord)
data BuildPlan = BuildPlan
{ bpSystemInfo :: SystemInfo
, bpTools :: Vector (PackageName, Version)
, bpPackages :: Map PackageName PackagePlan
, bpGithubUsers :: Map Text (Set Text)
}
deriving (Show, Eq)
instance ToJSON BuildPlan where
toJSON BuildPlan {..} = object
[ "system-info" .= bpSystemInfo
, "tools" .= fmap goTool bpTools
, "packages" .= bpPackages
, "github-users" .= bpGithubUsers
]
where
goTool (k, v) = object
[ "name" .= k
, "version" .= v
]
instance FromJSON BuildPlan where
parseJSON = withObject "BuildPlan" $ \o -> do
bpSystemInfo <- o .: "system-info"
bpTools <- o .: "tools" >>= T.mapM goTool
bpPackages <- o .: "packages"
bpGithubUsers <- o .:? "github-users" .!= mempty
return BuildPlan {..}
where
goTool = withObject "Tool" $ \o -> (,)
<$> o .: "name"
<*> o .: "version"
data PackagePlan = PackagePlan
{ ppVersion :: Version
, ppCabalFileInfo :: Maybe CabalFileInfo
, ppGithubPings :: Set Text
, ppUsers :: Set PackageName
, ppConstraints :: PackageConstraints
, ppDesc :: SimpleDesc
}
deriving (Show, Eq)
instance ToJSON PackagePlan where
toJSON PackagePlan {..} = object
$ maybe id (\cfi -> (("cabal-file-info" .= cfi):)) ppCabalFileInfo $
[ "version" .= ppVersion
, "github-pings" .= ppGithubPings
, "users" .= ppUsers
, "constraints" .= ppConstraints
, "description" .= ppDesc
]
instance FromJSON PackagePlan where
parseJSON = withObject "PackageBuild" $ \o -> do
ppVersion <- o .: "version"
ppCabalFileInfo <- o .:? "cabal-file-info"
ppGithubPings <- o .:? "github-pings" .!= mempty
ppUsers <- o .:? "users" .!= mempty
ppConstraints <- o .: "constraints"
ppDesc <- o .: "description"
return PackagePlan {..}
-- | Information on the contents of a cabal file
data CabalFileInfo = CabalFileInfo
{ cfiSize :: !Int
-- ^ File size in bytes
, cfiHashes :: !(Map.Map Text Text)
-- ^ Various hashes of the file contents
}
deriving (Show, Eq, Generic)
instance ToJSON CabalFileInfo where
toJSON CabalFileInfo {..} = object
[ "size" .= cfiSize
, "hashes" .= cfiHashes
]
instance FromJSON CabalFileInfo where
parseJSON = withObject "CabalFileInfo" $ \o -> do
cfiSize <- o .: "size"
cfiHashes <- o .: "hashes"
return CabalFileInfo {..}
display :: DT.Text a => a -> Text
display = fromString . DT.display
simpleParse :: (MonadThrow m, DT.Text a, Typeable a) => Text -> m a
simpleParse orig = withTypeRep $ \rep ->
case DT.simpleParse str of
Nothing -> throwM (ParseFailedException rep (pack str))
Just v -> return v
where
str = unpack orig
withTypeRep :: Typeable a => (TypeRep -> m a) -> m a
withTypeRep f =
res
where
res = f (typeOf (unwrap res))
unwrap :: m a -> a
unwrap _ = error "unwrap"
data BuildPlanTypesException
= ParseSnapNameException Text
| ParseFailedException TypeRep Text
deriving Typeable
instance Exception BuildPlanTypesException
instance Show BuildPlanTypesException where
show (ParseSnapNameException t) = "Invalid snapshot name: " ++ T.unpack t
show (ParseFailedException rep t) =
"Unable to parse " ++ show t ++ " as " ++ show rep
data PackageConstraints = PackageConstraints
{ pcVersionRange :: VersionRange
, pcMaintainer :: Maybe Maintainer
, pcTests :: TestState
, pcHaddocks :: TestState
, pcBuildBenchmarks :: Bool
, pcFlagOverrides :: Map FlagName Bool
, pcEnableLibProfile :: Bool
}
deriving (Show, Eq)
instance ToJSON PackageConstraints where
toJSON PackageConstraints {..} = object $ addMaintainer
[ "version-range" .= display pcVersionRange
, "tests" .= pcTests
, "haddocks" .= pcHaddocks
, "build-benchmarks" .= pcBuildBenchmarks
, "flags" .= pcFlagOverrides
, "library-profiling" .= pcEnableLibProfile
]
where
addMaintainer = maybe id (\m -> (("maintainer" .= m):)) pcMaintainer
instance FromJSON PackageConstraints where
parseJSON = withObject "PackageConstraints" $ \o -> do
pcVersionRange <- (o .: "version-range")
>>= either (fail . show) return . simpleParse
pcTests <- o .: "tests"
pcHaddocks <- o .: "haddocks"
pcBuildBenchmarks <- o .: "build-benchmarks"
pcFlagOverrides <- o .: "flags"
pcMaintainer <- o .:? "maintainer"
pcEnableLibProfile <- fmap (fromMaybe True) (o .:? "library-profiling")
return PackageConstraints {..}
data TestState = ExpectSuccess
| ExpectFailure
| Don'tBuild -- ^ when the test suite will pull in things we don't want
deriving (Show, Eq, Ord, Bounded, Enum)
testStateToText :: TestState -> Text
testStateToText ExpectSuccess = "expect-success"
testStateToText ExpectFailure = "expect-failure"
testStateToText Don'tBuild = "do-not-build"
instance ToJSON TestState where
toJSON = toJSON . testStateToText
instance FromJSON TestState where
parseJSON = withText "TestState" $ \t ->
case HashMap.lookup t states of
Nothing -> fail $ "Invalid state: " ++ unpack t
Just v -> return v
where
states = HashMap.fromList
$ map (\x -> (testStateToText x, x)) [minBound..maxBound]
data SystemInfo = SystemInfo
{ siCompilerVersion :: CompilerVersion
, siOS :: OS
, siArch :: Arch
, siCorePackages :: Map PackageName Version
, siCoreExecutables :: Set ExeName
}
deriving (Show, Eq, Ord)
instance ToJSON SystemInfo where
toJSON SystemInfo {..} = object $
(case siCompilerVersion of
GhcVersion version -> "ghc-version" .= version
_ -> "compiler-version" .= siCompilerVersion) :
[ "os" .= display siOS
, "arch" .= display siArch
, "core-packages" .= siCorePackages
, "core-executables" .= siCoreExecutables
]
instance FromJSON SystemInfo where
parseJSON = withObject "SystemInfo" $ \o -> do
let helper name = (o .: name) >>= either (fail . show) return . simpleParse
ghcVersion <- o .:? "ghc-version"
compilerVersion <- o .:? "compiler-version"
siCompilerVersion <-
case (ghcVersion, compilerVersion) of
(Just _, Just _) -> fail "can't have both compiler-version and ghc-version fields"
(Just ghc, _) -> return (GhcVersion ghc)
(_, Just compiler) -> return compiler
_ -> fail "expected field \"ghc-version\" or \"compiler-version\" not present"
siOS <- helper "os"
siArch <- helper "arch"
siCorePackages <- o .: "core-packages"
siCoreExecutables <- o .: "core-executables"
return SystemInfo {..}
newtype Maintainer = Maintainer { unMaintainer :: Text }
deriving (Show, Eq, Ord, Hashable, ToJSON, FromJSON, IsString)
-- | Name of an executable.
newtype ExeName = ExeName { unExeName :: Text }
deriving (Show, Eq, Ord, Hashable, IsString, Generic, Store, NFData)
instance ToJSON ExeName where
toJSON = toJSON . unExeName
instance FromJSON ExeName where
parseJSON = withText "ExeName" $ return . ExeName
-- | A simplified package description that tracks:
--
-- * Package dependencies
--
-- * Build tool dependencies
--
-- * Provided executables
--
-- It has fully resolved all conditionals
data SimpleDesc = SimpleDesc
{ sdPackages :: Map PackageName DepInfo
, sdTools :: Map ExeName DepInfo
, sdProvidedExes :: Set ExeName
, sdModules :: Set Text
-- ^ modules exported by the library
}
deriving (Show, Eq)
instance Monoid SimpleDesc where
mempty = SimpleDesc mempty mempty mempty mempty
mappend (SimpleDesc a b c d) (SimpleDesc w x y z) = SimpleDesc
(Map.unionWith (<>) a w)
(Map.unionWith (<>) b x)
(c <> y)
(d <> z)
instance ToJSON SimpleDesc where
toJSON SimpleDesc {..} = object
[ "packages" .= sdPackages
, "tools" .= sdTools
, "provided-exes" .= sdProvidedExes
, "modules" .= sdModules
]
instance FromJSON SimpleDesc where
parseJSON = withObject "SimpleDesc" $ \o -> do
sdPackages <- o .: "packages"
sdTools <- o .: "tools"
sdProvidedExes <- o .: "provided-exes"
sdModules <- o .: "modules"
return SimpleDesc {..}
data DepInfo = DepInfo
{ diComponents :: Set Component
, diRange :: VersionRange
}
deriving (Show, Eq)
instance Monoid DepInfo where
mempty = DepInfo mempty C.anyVersion
DepInfo a x `mappend` DepInfo b y = DepInfo
(mappend a b)
(C.intersectVersionRanges x y)
instance ToJSON DepInfo where
toJSON DepInfo {..} = object
[ "components" .= diComponents
, "range" .= display diRange
]
instance FromJSON DepInfo where
parseJSON = withObject "DepInfo" $ \o -> do
diComponents <- o .: "components"
diRange <- o .: "range" >>= either (fail . show) return . simpleParse
return DepInfo {..}
data Component = CompLibrary
| CompExecutable
| CompTestSuite
| CompBenchmark
deriving (Show, Read, Eq, Ord, Enum, Bounded)
compToText :: Component -> Text
compToText CompLibrary = "library"
compToText CompExecutable = "executable"
compToText CompTestSuite = "test-suite"
compToText CompBenchmark = "benchmark"
instance ToJSON Component where
toJSON = toJSON . compToText
instance FromJSON Component where
parseJSON = withText "Component" $ \t -> maybe
(fail $ "Invalid component: " ++ unpack t)
return
(HashMap.lookup t comps)
where
comps = HashMap.fromList $ map (compToText &&& id) [minBound..maxBound]
-- | Convert a 'SnapName' into its short representation, e.g. @lts-2.8@,
-- @nightly-2015-03-05@.
renderSnapName :: SnapName -> Text
renderSnapName (LTS x y) = T.pack $ concat ["lts-", show x, ".", show y]
renderSnapName (Nightly d) = T.pack $ "nightly-" ++ show d
-- | Parse the short representation of a 'SnapName'.
parseSnapName :: MonadThrow m => Text -> m SnapName
parseSnapName t0 =
case lts <|> nightly of
Nothing -> throwM $ ParseSnapNameException t0
Just sn -> return sn
where
lts = do
t1 <- T.stripPrefix "lts-" t0
Right (x, t2) <- Just $ decimal t1
t3 <- T.stripPrefix "." t2
Right (y, "") <- Just $ decimal t3
return $ LTS x y
nightly = do
t1 <- T.stripPrefix "nightly-" t0
Nightly <$> readMay (T.unpack t1)
-- | Most recent Nightly and newest LTS version per major release.
data Snapshots = Snapshots
{ snapshotsNightly :: !Day
, snapshotsLts :: !(IntMap Int)
}
deriving Show
instance FromJSON Snapshots where
parseJSON = withObject "Snapshots" $ \o -> Snapshots
<$> (o .: "nightly" >>= parseNightly)
<*> (fmap IntMap.unions
$ mapM (parseLTS . snd)
$ filter (isLTS . fst)
$ HashMap.toList o)
where
parseNightly t =
case parseSnapName t of
Left e -> fail $ show e
Right (LTS _ _) -> fail "Unexpected LTS value"
Right (Nightly d) -> return d
isLTS = ("lts-" `T.isPrefixOf`)
parseLTS = withText "LTS" $ \t ->
case parseSnapName t of
Left e -> fail $ show e
Right (LTS x y) -> return $ IntMap.singleton x y
Right (Nightly _) -> fail "Unexpected nightly value"
instance ToJSON a => ToJSON (Map ExeName a) where
toJSON = toJSON . Map.mapKeysWith const unExeName
instance FromJSON a => FromJSON (Map ExeName a) where
parseJSON = fmap (Map.mapKeysWith const ExeName) . parseJSON
-- | A simplified version of the 'BuildPlan' + cabal file.
data MiniBuildPlan = MiniBuildPlan
{ mbpCompilerVersion :: !CompilerVersion
, mbpPackages :: !(Map PackageName MiniPackageInfo)
}
deriving (Generic, Show, Eq)
instance Store MiniBuildPlan
instance NFData MiniBuildPlan
-- | Information on a single package for the 'MiniBuildPlan'.
data MiniPackageInfo = MiniPackageInfo
{ mpiVersion :: !Version
, mpiFlags :: !(Map FlagName Bool)
, mpiGhcOptions :: ![Text]
, mpiPackageDeps :: !(Set PackageName)
, mpiToolDeps :: !(Set Text)
-- ^ Due to ambiguity in Cabal, it is unclear whether this refers to the
-- executable name, the package name, or something else. We have to guess
-- based on what's available, which is why we store this is an unwrapped
-- 'Text'.
, mpiExes :: !(Set ExeName)
-- ^ Executables provided by this package
, mpiHasLibrary :: !Bool
-- ^ Is there a library present?
, mpiGitSHA1 :: !(Maybe GitSHA1)
-- ^ An optional SHA1 representation in hex format of the blob containing
-- the cabal file contents. Useful for grabbing the correct cabal file
-- revision directly from a Git repo
}
deriving (Generic, Show, Eq)
instance Store MiniPackageInfo
instance NFData MiniPackageInfo
newtype GitSHA1 = GitSHA1 ByteString
deriving (Generic, Show, Eq, NFData, Store)
newtype SnapshotHash = SnapshotHash { unShapshotHash :: ByteString }
deriving (Generic, Show, Eq)
trimmedSnapshotHash :: SnapshotHash -> ByteString
trimmedSnapshotHash = BS.take 12 . unShapshotHash
$(mkManyHasTypeHash [ [t| MiniBuildPlan |] ])
| sjakobi/stack | src/Stack/Types/BuildPlan.hs | bsd-3-clause | 16,476 | 0 | 17 | 4,611 | 4,288 | 2,299 | 1,989 | 407 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Generics.Instant.Functions.Bytes
( -- $defaults
gserializeDefault
, gdeserializeDefault
, RepGSerial
-- * Internals
, GSerial(..)
-- ** Even more internal
, GSumSerial
, GSumSize
) where
import qualified Data.Bytes.Serial as Bytes
import qualified Data.Bytes.Put as Bytes
import qualified Data.Bytes.Get as Bytes
import Data.Bits
import Data.Word
import Generics.Instant
import Prelude
--------------------------------------------------------------------------------
-- $defaults
--
-- You can use 'gserializeDefault' and 'gdeserializeDefault' as your generic
-- 'Bytes.serialize' and 'Bytes.deserialize' implementations for any 'Representable'
-- type as follows:
--
-- @
-- instance 'Bytes.Serial' MyType where
-- serialize = 'gserializeDefault'
-- deserialize = 'gdeserializeDefault'
-- @
gserializeDefault :: (Representable a, GSerial (Rep a), Bytes.MonadPut m) => a -> m ()
gserializeDefault = \a -> gserialize (from a)
{-# INLINABLE gserializeDefault #-}
gdeserializeDefault :: (Representable a, GSerial (Rep a), Bytes.MonadGet m) => m a
gdeserializeDefault = fmap to gdeserialize
{-# INLINABLE gdeserializeDefault #-}
--------------------------------------------------------------------------------
-- | @'RepGSerial'@ is simply a synonym for
-- @('Representable' a, 'GSerial' ('Rep' a))@ with the convenient
-- kind @(* -> 'GHC.Exts.Constraint')@
class (Representable a, GSerial (Rep a)) => RepGSerial a
instance (Representable a, GSerial (Rep a)) => RepGSerial a
--------------------------------------------------------------------------------
class GSerial a where
gserialize :: Bytes.MonadPut m => a -> m ()
gdeserialize :: Bytes.MonadGet m => m a
instance GSerial Z where
gserialize _ = fail "Generics.Instant.Functions.Serial.GSerial Z gserialize - impossible"
gdeserialize = fail "Generics.Instant.Functions.Serial.GSerial Z gdeserialize - impossible"
instance GSerial U where
gserialize U = Bytes.serialize ()
{-# INLINABLE gserialize #-}
gdeserialize = Bytes.deserialize >>= \() -> return U
{-# INLINABLE gdeserialize #-}
instance GSerial a => GSerial (CEq c p p a) where
gserialize (C a) = gserialize a
{-# INLINABLE gserialize #-}
gdeserialize = gdeserialize >>= \a -> return (C a)
{-# INLINABLE gdeserialize #-}
instance {-# OVERLAPPABLE #-} GSerial a => GSerial (CEq c p q a) where
gserialize (C a) = gserialize a
{-# INLINABLE gserialize #-}
gdeserialize = fail "Generics.Instant.Functions.Serial.GSerial (CEq c p q a) gdeserialize - impossible"
instance Bytes.Serial a => GSerial (Var a) where
gserialize (Var a) = Bytes.serialize a
{-# INLINABLE gserialize #-}
gdeserialize = Bytes.deserialize >>= \a -> return (Var a)
{-# INLINABLE gdeserialize #-}
instance Bytes.Serial a => GSerial (Rec a) where
gserialize (Rec a) = Bytes.serialize a
{-# INLINABLE gserialize #-}
gdeserialize = Bytes.deserialize >>= \a -> return (Rec a)
{-# INLINABLE gdeserialize #-}
instance (GSerial a, GSerial b) => GSerial (a :*: b) where
gserialize (a :*: b) = gserialize a >> gserialize b
{-# INLINABLE gserialize #-}
gdeserialize = gdeserialize >>= \a ->
gdeserialize >>= \b ->
return (a :*: b)
{-# INLINABLE gdeserialize #-}
---
-- Borrowed from the "binary" package, which borrowed this from "cereal".
-- The following GSerial instance for sums has support for serializing
-- types with up to 2^64-1 constructors. It will use the minimal
-- number of bytes needed to encode the constructor. For example when
-- a type has 2^8 constructors or less it will use a single byte to
-- encode the constructor. If it has 2^16 constructors or less it will
-- use two bytes, and so on till 2^64-1.
instance
( GSumSerial a, GSumSerial b, GSerial a, GSerial b, GSumSize a, GSumSize b
) => GSerial (a :+: b)
where
{-# INLINABLE gserialize #-}
gserialize x
| predSize <= fromIntegral (maxBound :: Word8)
= putSum (0 :: Word8) (fromIntegral size) x
| predSize <= fromIntegral (maxBound :: Word16)
= putSum (0 :: Word16) (fromIntegral size) x
| predSize <= fromIntegral (maxBound :: Word32)
= putSum (0 :: Word32) (fromIntegral size) x
| predSize <= fromIntegral (maxBound :: Word64)
= putSum (0 :: Word64) (fromIntegral size) x
| otherwise = sizeError "encode" size
where
size = unTagged (sumSize :: Tagged (a :+: b) Word64)
predSize = size - 1
{-# INLINABLE gdeserialize #-}
gdeserialize
| predSize <= fromIntegral (maxBound :: Word8)
= Bytes.deserialize >>= \(c :: Word8) ->
checkGetSum (fromIntegral size) c
| predSize <= fromIntegral (maxBound :: Word16)
= Bytes.deserialize >>= \(c :: Word16) ->
checkGetSum (fromIntegral size) c
| predSize <= fromIntegral (maxBound :: Word32)
= Bytes.deserialize >>= \(c :: Word32) ->
checkGetSum (fromIntegral size) c
| predSize <= fromIntegral (maxBound :: Word64)
= Bytes.deserialize >>= \(c :: Word64) ->
checkGetSum (fromIntegral size) c
| otherwise = sizeError "decode" size
where
size = unTagged (sumSize :: Tagged (a :+: b) Word64)
predSize = size - 1
sizeError :: Show size => String -> size -> error
sizeError s size =
error $ "Generics.Instant.Functions.Serial.sizeError: Can't " ++ s ++ " a type with " ++
show size ++ " constructors"
------------------------------------------------------------------------
checkGetSum
:: (Ord w, Num w, Bits w, GSumSerial a, Bytes.MonadGet m) => w -> w -> m a
checkGetSum size code
| code < size = getSum code size
| otherwise = fail "Generics.Instant.Functions.Serial.checkGetSum: Unknown encoding for constructor"
{-# INLINABLE checkGetSum #-}
class GSumSerial a where
putSum :: (Num w, Bits w, Bytes.Serial w, Bytes.MonadPut m) => w -> w -> a -> m ()
getSum :: (Ord w, Num w, Bits w, Bytes.MonadGet m) => w -> w -> m a
instance (GSumSerial a, GSumSerial b, GSerial a, GSerial b) => GSumSerial (a :+: b) where
{-# INLINABLE putSum #-}
putSum !code !size x =
let sizeL = size `shiftR` 1
sizeR = size - sizeL
in case x of
L l -> putSum code sizeL l
R r -> putSum (code + sizeL) sizeR r
{-# INLINABLE getSum #-}
getSum !code !size
| code < sizeL = L <$> getSum code sizeL
| otherwise = R <$> getSum (code - sizeL) sizeR
where
sizeL = size `shiftR` 1
sizeR = size - sizeL
instance GSerial a => GSumSerial (CEq c p p a) where
putSum !code _ ca = Bytes.serialize code >> gserialize ca
{-# INLINABLE putSum #-}
getSum _ _ = gdeserialize
{-# INLINABLE getSum #-}
instance {-# OVERLAPPABLE #-} GSerial a => GSumSerial (CEq c p q a) where
putSum !code _ ca = Bytes.serialize code >> gserialize ca
{-# INLINABLE putSum #-}
getSum _ _ = fail "Generics.Instant.Functions.Serial.GSumSerial (CEq c p q a) getSum - impossible"
------------------------------------------------------------------------
class GSumSize a where
sumSize :: Tagged a Word64
newtype Tagged s b = Tagged {unTagged :: b}
instance (GSumSize a, GSumSize b) => GSumSize (a :+: b) where
{-# INLINABLE sumSize #-}
sumSize = Tagged (unTagged (sumSize :: Tagged a Word64) +
unTagged (sumSize :: Tagged b Word64))
instance GSumSize (CEq c p q a) where
{-# INLINABLE sumSize #-}
sumSize = Tagged 1
| k0001/instant-bytes | src/lib/Generics/Instant/Functions/Bytes.hs | bsd-3-clause | 7,757 | 0 | 13 | 1,662 | 2,010 | 1,053 | 957 | -1 | -1 |
module Turbinado.View.Monad (
-- * The 'View' Monad
View, ViewT, ViewT',
runView, runViewT,
get,
put,
-- * Functions
liftIO, catch
) where
import Control.OldException (catchDyn)
import Control.Monad.State
import Control.Monad.Trans (MonadIO(..), liftIO)
import Data.Maybe
import HSX.XMLGenerator (XMLGenT(..), unXMLGenT)
import qualified Network.HTTP as HTTP
import Prelude hiding (catch)
import Turbinado.Environment.Types
import Turbinado.View.Exception
import Turbinado.Utility.General
--------------------------------------------------------------
-- The View Monad
-- | The View monad is a reader wrapper around
-- the IO monad, but extended with an XMLGenerator wrapper.
-- View = XMLGenT (StateT Environment IO) a
type View = ViewT IO
type ViewT' m = StateT Environment m
type ViewT m = XMLGenT (ViewT' m)
instance HasEnvironment View where
getEnvironment = lift get
setEnvironment = lift . put
getEnvironment :: View Environment
getEnvironment = lift get
setEnvironment :: Environment -> View ()
setEnvironment e = lift $ put e
-- do NOT export this in the final version
dummyEnv = undefined
-- | Runs a View computation in a particular environment. Since View wraps the IO monad,
-- the result of running it will be an IO computation.
runView :: View a -> Environment -> IO (a, Environment)
runView p e = runStateT (unXMLGenT p) e
runViewT :: ViewT IO a -> Environment -> IO (a, Environment)
runViewT = runStateT . unXMLGenT
-----------------------------------------------------------------------
-- Exception handling
-- | Catch a user-caused exception.
catch :: View a -> (Exception -> View a) -> View a
catch (XMLGenT (StateT f)) handler = XMLGenT $ StateT $ \e ->
f e `catchDyn` (\ex -> (let (XMLGenT (StateT g)) = handler ex
in g e))
| abuiles/turbinado-blog | Turbinado/View/Monad.hs | bsd-3-clause | 1,881 | 0 | 18 | 393 | 448 | 255 | 193 | 35 | 1 |
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE LambdaCase #-}
module Data.Logic.Boolean
( module Data.Logic.Boolean
, module Data.Logic.Boolean.Class
) where
import Data.Logic.Atomic.Class
import Data.Logic.Boolean.Class
import Data.Logic.Propositional.Class
import Data.Logic.Modal.Class
import Data.Logic.Decidable
import Data.Logic.Embed
import Data.Logic.Util
import Test.QuickCheck (Arbitrary(..),oneof)
data BoolI r
= TT
| FF
| LiftBool r
deriving (Eq,Ord,Show)
instance Arbitrary r => Arbitrary (BoolI r) where
arbitrary = oneof
[ pure TT
, pure FF
, LiftBool <$> arbitrary
]
shrink = \case
LiftBool p -> [LiftBool q | q <- shrink p]
_ -> []
instance Boolean r => Embed r (BoolI r) where
embed = LiftBool
lower = \case
TT -> tt
FF -> ff
LiftBool p -> p
instance (Boolean r, EmbedStar a r) => EmbedStar a (BoolI r)
instance Contextual r (BoolI r) where
type Context (BoolI r) = Either Bool
embedCxt = either (TT ? FF) LiftBool
lowerCxt = \case
TT -> Left True
FF -> Left False
LiftBool p -> Right p
instance ContextStar a r => ContextStar a (BoolI r) where
type AllContext (BoolI r) = CompAllCxt r (BoolI r)
instance Decidable r => Decidable (BoolI r) where
type Decide (BoolI r) = Decide r
truth = either pure truth . lowerCxt
instance Atomic a r => Atomic a (BoolI r) where
atom = LiftBool . atom
instance Boolean (BoolI r) where
tt = TT
ff = FF
instance (Boolean r, Propositional r) => Propositional (BoolI r) where
neg = overLower neg
(.|.) = overLower2 (.|.)
(.^.) = overLower2 (.^.)
(.&.) = overLower2 (.&.)
(.->.) = overLower2 (.->.)
(.==.) = overLower2 (.==.)
instance (Boolean r, Modal m r) => Modal m (BoolI r) where
square = overLower . square
diamond = overLower . diamond
| kylcarte/finally-logical | src/Data/Logic/Boolean.hs | bsd-3-clause | 1,968 | 0 | 12 | 461 | 698 | 381 | 317 | 63 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RankNTypes #-}
-- |
-- Module : Data.Binary.Serialise.CBOR.Decoding
-- Copyright : (c) Duncan Coutts 2015
-- License : BSD3-style (see LICENSE.txt)
--
-- Maintainer : duncan@community.haskell.org
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Lorem ipsum...
--
module Data.Binary.Serialise.CBOR.Decoding (
-- * Decode primitive operations
Decoder,
DecodeAction(..),
getDecodeAction,
-- ** Read input tokens
decodeWord,
decodeWord64,
decodeNegWord,
decodeNegWord64,
decodeInt,
decodeInt64,
decodeInteger,
decodeFloat,
decodeDouble,
decodeBytes,
decodeBytesIndef,
decodeString,
decodeStringIndef,
decodeListLen,
decodeListLenIndef,
decodeMapLen,
decodeMapLenIndef,
decodeTag,
decodeTag64,
decodeBool,
decodeNull,
decodeSimple,
-- ** Specialised Read input token operations
decodeWordOf,
decodeListLenOf,
-- ** Branching operations
-- decodeBytesOrIndef,
-- decodeStringOrIndef,
decodeListLenOrIndef,
decodeMapLenOrIndef,
decodeBreakOr,
-- ** Inspecting the token type
peekTokenType,
TokenType(..),
-- ** Special operations
-- ignoreTerms,
-- decodeTrace,
-- * Sequence operations
decodeSequenceLenIndef,
decodeSequenceLenN,
) where
import GHC.Exts
import GHC.Word
import GHC.Int
import Data.Text (Text)
import Data.ByteString (ByteString)
import Control.Applicative
import Prelude hiding (decodeFloat)
#include "MachDeps.h"
#if WORD_SIZE_IN_BITS == 64
#define ARCH_64bit
#elif WORD_SIZE_IN_BITS == 32
import GHC.IntWord64 (wordToWord64#)
#else
#error expected WORD_SIZE_IN_BITS to be 32 or 64
#endif
data Decoder a = Decoder {
runDecoder :: forall r. (a -> DecodeAction r) -> DecodeAction r
}
data DecodeAction a
= ConsumeWord (Word# -> DecodeAction a)
| ConsumeNegWord (Word# -> DecodeAction a)
| ConsumeInt (Int# -> DecodeAction a)
| ConsumeListLen (Int# -> DecodeAction a)
| ConsumeMapLen (Int# -> DecodeAction a)
| ConsumeTag (Word# -> DecodeAction a)
-- 64bit variants for 32bit machines
#ifndef ARCH_64bit
| ConsumeWord64 (Word64# -> DecodeAction a)
| ConsumeNegWord64 (Word64# -> DecodeAction a)
| ConsumeInt64 (Int64# -> DecodeAction a)
| ConsumeListLen64 (Int64# -> DecodeAction a)
| ConsumeMapLen64 (Int64# -> DecodeAction a)
| ConsumeTag64 (Word64# -> DecodeAction a)
#endif
| ConsumeInteger (Integer -> DecodeAction a)
| ConsumeFloat (Float# -> DecodeAction a)
| ConsumeDouble (Double# -> DecodeAction a)
| ConsumeBytes (ByteString -> DecodeAction a)
| ConsumeString (Text -> DecodeAction a)
| ConsumeBool (Bool -> DecodeAction a)
| ConsumeSimple (Word# -> DecodeAction a)
| ConsumeBytesIndef (DecodeAction a)
| ConsumeStringIndef (DecodeAction a)
| ConsumeListLenIndef (DecodeAction a)
| ConsumeMapLenIndef (DecodeAction a)
| ConsumeNull (DecodeAction a)
| ConsumeListLenOrIndef (Int# -> DecodeAction a)
| ConsumeMapLenOrIndef (Int# -> DecodeAction a)
| ConsumeBreakOr (Bool -> DecodeAction a)
| PeekTokenType (TokenType -> DecodeAction a)
| Fail String
| Done a
data TokenType = TypeUInt
| TypeUInt64
| TypeNInt
| TypeNInt64
| TypeInteger
| TypeFloat16
| TypeFloat32
| TypeFloat64
| TypeBytes
| TypeBytesIndef
| TypeString
| TypeStringIndef
| TypeListLen
| TypeListLen64
| TypeListLenIndef
| TypeMapLen
| TypeMapLen64
| TypeMapLenIndef
| TypeTag
| TypeTag64
| TypeBool
| TypeNull
| TypeUndef
| TypeSimple
| TypeBreak
| TypeInvalid
deriving (Eq, Ord, Enum, Bounded, Show)
instance Functor Decoder where
{-# INLINE fmap #-}
fmap f = \d -> Decoder $ \k -> runDecoder d (k . f)
instance Applicative Decoder where
{-# INLINE pure #-}
pure = \x -> Decoder $ \k -> k x
{-# INLINE (<*>) #-}
(<*>) = \df dx -> Decoder $ \k ->
runDecoder df (\f -> runDecoder dx (\x -> k (f x)))
instance Monad Decoder where
return = pure
{-# INLINE (>>=) #-}
(>>=) = \dm f -> Decoder $ \k -> runDecoder dm (\m -> runDecoder (f m) k)
{-# INLINE (>>) #-}
(>>) = \dm dn -> Decoder $ \k -> runDecoder dm (\_ -> runDecoder dn k)
fail msg = Decoder $ \_ -> Fail msg
getDecodeAction :: Decoder a -> DecodeAction a
getDecodeAction (Decoder k) = k (\x -> Done x)
---------------------------------------
-- Read input tokens of various types
--
{-# INLINE decodeWord #-}
decodeWord :: Decoder Word
decodeWord = Decoder (\k -> ConsumeWord (\w# -> k (W# w#)))
{-# INLINE decodeWord64 #-}
decodeWord64 :: Decoder Word64
decodeWord64 =
#ifdef ARCH_64bit
Decoder (\k -> ConsumeWord (\w# -> k (W64# w#)))
#else
Decoder (\k -> ConsumeWord64 (\w64# -> k (W64# w64#)))
#endif
{-# INLINE decodeNegWord #-}
decodeNegWord :: Decoder Word
decodeNegWord = Decoder (\k -> ConsumeNegWord (\w# -> k (W# w#)))
{-# INLINE decodeNegWord64 #-}
decodeNegWord64 :: Decoder Word64
decodeNegWord64 =
#ifdef ARCH_64bit
Decoder (\k -> ConsumeNegWord (\w# -> k (W64# w#)))
#else
Decoder (\k -> ConsumeNegWord64 (\w64# -> k (W64# w64#)))
#endif
{-# INLINE decodeInt #-}
decodeInt :: Decoder Int
decodeInt = Decoder (\k -> ConsumeInt (\n# -> k (I# n#)))
{-# INLINE decodeInt64 #-}
decodeInt64 :: Decoder Int64
decodeInt64 =
#ifdef ARCH_64bit
Decoder (\k -> ConsumeInt (\n# -> k (I64# n#)))
#else
Decoder (\k -> ConsumeInt64 (\n64# -> k (I64# n64#)))
#endif
{-# INLINE decodeInteger #-}
decodeInteger :: Decoder Integer
decodeInteger = Decoder (\k -> ConsumeInteger (\n -> k n))
{-# INLINE decodeFloat #-}
decodeFloat :: Decoder Float
decodeFloat = Decoder (\k -> ConsumeFloat (\f# -> k (F# f#)))
{-# INLINE decodeDouble #-}
decodeDouble :: Decoder Double
decodeDouble = Decoder (\k -> ConsumeDouble (\f# -> k (D# f#)))
{-# INLINE decodeBytes #-}
decodeBytes :: Decoder ByteString
decodeBytes = Decoder (\k -> ConsumeBytes (\bs -> k bs))
{-# INLINE decodeBytesIndef #-}
decodeBytesIndef :: Decoder ()
decodeBytesIndef = Decoder (\k -> ConsumeBytesIndef (k ()))
{-# INLINE decodeString #-}
decodeString :: Decoder Text
decodeString = Decoder (\k -> ConsumeString (\str -> k str))
{-# INLINE decodeStringIndef #-}
decodeStringIndef :: Decoder ()
decodeStringIndef = Decoder (\k -> ConsumeStringIndef (k ()))
{-# INLINE decodeListLen #-}
decodeListLen :: Decoder Int
decodeListLen = Decoder (\k -> ConsumeListLen (\n# -> k (I# n#)))
{-# INLINE decodeListLenIndef #-}
decodeListLenIndef :: Decoder ()
decodeListLenIndef = Decoder (\k -> ConsumeListLenIndef (k ()))
{-# INLINE decodeMapLen #-}
decodeMapLen :: Decoder Int
decodeMapLen = Decoder (\k -> ConsumeMapLen (\n# -> k (I# n#)))
{-# INLINE decodeMapLenIndef #-}
decodeMapLenIndef :: Decoder ()
decodeMapLenIndef = Decoder (\k -> ConsumeMapLenIndef (k ()))
{-# INLINE decodeTag #-}
decodeTag :: Decoder Word
decodeTag = Decoder (\k -> ConsumeTag (\w# -> k (W# w#)))
{-# INLINE decodeTag64 #-}
decodeTag64 :: Decoder Word64
decodeTag64 =
#ifdef ARCH_64bit
Decoder (\k -> ConsumeTag (\w# -> k (W64# w#)))
#else
Decoder (\k -> ConsumeTag64 (\w64# -> k (W64# w64#)))
#endif
{-# INLINE decodeBool #-}
decodeBool :: Decoder Bool
decodeBool = Decoder (\k -> ConsumeBool (\b -> k b))
{-# INLINE decodeNull #-}
decodeNull :: Decoder ()
decodeNull = Decoder (\k -> ConsumeNull (k ()))
{-# INLINE decodeSimple #-}
decodeSimple :: Decoder Word8
decodeSimple = Decoder (\k -> ConsumeSimple (\w# -> k (W8# w#)))
--------------------------------------------------------------
-- Specialised read operations: expect a token with a specific value
--
{-# INLINE decodeWordOf #-}
decodeWordOf :: Word -> Decoder ()
decodeWordOf n = do
n' <- decodeWord
if n == n' then return ()
else fail $ "expected word " ++ show n
{-# INLINE decodeListLenOf #-}
decodeListLenOf :: Int -> Decoder ()
decodeListLenOf len = do
len' <- decodeListLen
if len == len' then return ()
else fail $ "expected list of length " ++ show len
--------------------------------------------------------------
-- Branching operations
{-# INLINE decodeListLenOrIndef #-}
decodeListLenOrIndef :: Decoder (Maybe Int)
decodeListLenOrIndef =
Decoder (\k -> ConsumeListLenOrIndef (\n# ->
if I# n# >= 0
then k (Just (I# n#))
else k Nothing))
{-# INLINE decodeMapLenOrIndef #-}
decodeMapLenOrIndef :: Decoder (Maybe Int)
decodeMapLenOrIndef =
Decoder (\k -> ConsumeMapLenOrIndef (\n# ->
if I# n# >= 0
then k (Just (I# n#))
else k Nothing))
{-# INLINE decodeBreakOr #-}
decodeBreakOr :: Decoder Bool
decodeBreakOr = Decoder (\k -> ConsumeBreakOr (\b -> k b))
--------------------------------------------------------------
-- Special operations
{-# INLINE peekTokenType #-}
peekTokenType :: Decoder TokenType
peekTokenType = Decoder (\k -> PeekTokenType (\tk -> k tk))
{-
expectExactly :: Word -> Decoder (Word :#: s) s
expectExactly n = expectExactly_ n done
expectAtLeast :: Word -> Decoder (Word :#: s) (Word :#: s)
expectAtLeast n = expectAtLeast_ n done
ignoreTrailingTerms :: Decoder (a :*: Word :#: s) (a :*: s)
ignoreTrailingTerms = IgnoreTerms done
-}
------------------------------------------------------------------------------
-- Special combinations for sequences
--
{-# INLINE decodeSequenceLenIndef #-}
decodeSequenceLenIndef :: (r -> a -> r)
-> r
-> (r -> r')
-> Decoder a
-> Decoder r'
decodeSequenceLenIndef f z g get =
go z
where
go !acc = do
stop <- decodeBreakOr
if stop then return $! g acc
else do !x <- get; go (f acc x)
{-# INLINE decodeSequenceLenN #-}
decodeSequenceLenN :: (r -> a -> r)
-> r
-> (r -> r')
-> Int
-> Decoder a
-> Decoder r'
decodeSequenceLenN f z g c get =
go z c
where
go !acc 0 = return $! g acc
go !acc n = do !x <- get; go (f acc x) (n-1)
| thoughtpolice/binary-serialise-cbor | Data/Binary/Serialise/CBOR/Decoding.hs | bsd-3-clause | 10,709 | 0 | 17 | 2,748 | 2,625 | 1,445 | 1,180 | -1 | -1 |
{- ------------------------------------------------------------------------
(c) The GHC Team, 1992-2012
DeriveConstants is a program that extracts information from the C
declarations in the header files (primarily struct field offsets)
and generates various files, such as a header file that can be #included
into non-C source containing this information.
We want to get information about code generated by the C compiler,
such as the sizes of types, and offsets of struct fields. We need
this because the layout of certain runtime objects is defined in C
headers (e.g. includes/rts/storage/Closures.h), but we need access to
the layout of these structures from a Haskell program (GHC).
One way to do this is to compile and run a C program that includes the
header files and prints out the sizes and offsets. However, when we
are cross-compiling, we can't run a C program compiled for the target
platform.
So, this program works as follows: we generate a C program that when
compiled to an object file, has the information we need encoded as
symbol sizes. This means that we can extract the information without
needing to run the program, by inspecting the object file using 'nm'.
------------------------------------------------------------------------ -}
import Control.Monad (when, unless)
import Data.Bits (shiftL)
import Data.Char (toLower)
import Data.List (stripPrefix)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import Numeric (readHex)
import System.Environment (getArgs)
import System.Exit (ExitCode(ExitSuccess), exitFailure)
import System.FilePath ((</>))
import System.IO (stderr, hPutStrLn)
import System.Process (showCommandForUser, readProcess, rawSystem)
main :: IO ()
main = do opts <- parseArgs
let getOption descr opt = case opt opts of
Just x -> return x
Nothing -> die ("No " ++ descr ++ " given")
mode <- getOption "mode" o_mode
fn <- getOption "output filename" o_outputFilename
os <- getOption "target os" o_targetOS
let haskellWanteds = [ what | (wh, what) <- wanteds os
, wh `elem` [Haskell, Both] ]
case mode of
Gen_Haskell_Type -> writeHaskellType fn haskellWanteds
Gen_Haskell_Wrappers -> writeHaskellWrappers fn haskellWanteds
Gen_Haskell_Exports -> writeHaskellExports fn haskellWanteds
Gen_Computed cm ->
do tmpdir <- getOption "tmpdir" o_tmpdir
gccProg <- getOption "gcc program" o_gccProg
nmProg <- getOption "nm program" o_nmProg
let verbose = o_verbose opts
gccFlags = o_gccFlags opts
rs <- getWanted verbose os tmpdir gccProg gccFlags nmProg
(o_objdumpProg opts)
let haskellRs = [ what
| (wh, what) <- rs
, wh `elem` [Haskell, Both] ]
cRs = [ what
| (wh, what) <- rs
, wh `elem` [C, Both] ]
case cm of
ComputeHaskell -> writeHaskellValue fn haskellRs
ComputeHeader -> writeHeader fn cRs
data Options = Options {
o_verbose :: Bool,
o_mode :: Maybe Mode,
o_tmpdir :: Maybe FilePath,
o_outputFilename :: Maybe FilePath,
o_gccProg :: Maybe FilePath,
o_gccFlags :: [String],
o_nmProg :: Maybe FilePath,
o_objdumpProg :: Maybe FilePath,
o_targetOS :: Maybe String
}
parseArgs :: IO Options
parseArgs = do args <- getArgs
opts <- f emptyOptions args
return (opts {o_gccFlags = reverse (o_gccFlags opts)})
where emptyOptions = Options {
o_verbose = False,
o_mode = Nothing,
o_tmpdir = Nothing,
o_outputFilename = Nothing,
o_gccProg = Nothing,
o_gccFlags = [],
o_nmProg = Nothing,
o_objdumpProg = Nothing,
o_targetOS = Nothing
}
f opts [] = return opts
f opts ("-v" : args')
= f (opts {o_verbose = True}) args'
f opts ("--gen-haskell-type" : args')
= f (opts {o_mode = Just Gen_Haskell_Type}) args'
f opts ("--gen-haskell-value" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHaskell)}) args'
f opts ("--gen-haskell-wrappers" : args')
= f (opts {o_mode = Just Gen_Haskell_Wrappers}) args'
f opts ("--gen-haskell-exports" : args')
= f (opts {o_mode = Just Gen_Haskell_Exports}) args'
f opts ("--gen-header" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHeader)}) args'
f opts ("--tmpdir" : dir : args')
= f (opts {o_tmpdir = Just dir}) args'
f opts ("-o" : fn : args')
= f (opts {o_outputFilename = Just fn}) args'
f opts ("--gcc-program" : prog : args')
= f (opts {o_gccProg = Just prog}) args'
f opts ("--gcc-flag" : flag : args')
= f (opts {o_gccFlags = flag : o_gccFlags opts}) args'
f opts ("--nm-program" : prog : args')
= f (opts {o_nmProg = Just prog}) args'
f opts ("--objdump-program" : prog : args')
= f (opts {o_objdumpProg = Just prog}) args'
f opts ("--target-os" : os : args')
= f (opts {o_targetOS = Just os}) args'
f _ (flag : _) = die ("Unrecognised flag: " ++ show flag)
data Mode = Gen_Haskell_Type
| Gen_Haskell_Wrappers
| Gen_Haskell_Exports
| Gen_Computed ComputeMode
data ComputeMode = ComputeHaskell | ComputeHeader
type Wanteds = [(Where, What Fst)]
type Results = [(Where, What Snd)]
type Name = String
newtype CExpr = CExpr String
newtype CPPExpr = CPPExpr String
data What f = GetFieldType Name (f CExpr Integer)
| GetClosureSize Name (f CExpr Integer)
| GetWord Name (f CExpr Integer)
| GetInt Name (f CExpr Integer)
| GetNatural Name (f CExpr Integer)
| GetBool Name (f CPPExpr Bool)
| StructFieldMacro Name
| ClosureFieldMacro Name
| ClosurePayloadMacro Name
| FieldTypeGcptrMacro Name
data Fst a b = Fst a
data Snd a b = Snd b
data Where = C | Haskell | Both
deriving Eq
constantInt :: Where -> Name -> String -> Wanteds
constantInt w name expr = [(w, GetInt name (Fst (CExpr expr)))]
constantWord :: Where -> Name -> String -> Wanteds
constantWord w name expr = [(w, GetWord name (Fst (CExpr expr)))]
constantNatural :: Where -> Name -> String -> Wanteds
constantNatural w name expr = [(w, GetNatural name (Fst (CExpr expr)))]
constantBool :: Where -> Name -> String -> Wanteds
constantBool w name expr = [(w, GetBool name (Fst (CPPExpr expr)))]
fieldOffset :: Where -> String -> String -> Wanteds
fieldOffset w theType theField = fieldOffset_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldOffset_ :: Where -> Name -> String -> String -> Wanteds
fieldOffset_ w nameBase theType theField = [(w, GetWord name (Fst (CExpr expr)))]
where name = "OFFSET_" ++ nameBase
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ")"
-- FieldType is for defining REP_x to be b32 etc
-- These are both the C-- types used in a load
-- e.g. b32[addr]
-- and the names of the CmmTypes in the compiler
-- b32 :: CmmType
fieldType' :: Where -> String -> String -> Wanteds
fieldType' w theType theField
= fieldType_' w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldType_' :: Where -> Name -> String -> String -> Wanteds
fieldType_' w nameBase theType theField
= [(w, GetFieldType name (Fst (CExpr expr)))]
where name = "REP_" ++ nameBase
expr = "FIELD_SIZE(" ++ theType ++ ", " ++ theField ++ ")"
structField :: Where -> String -> String -> Wanteds
structField = structFieldHelper C
structFieldH :: Where -> String -> String -> Wanteds
structFieldH w = structFieldHelper w w
structField_ :: Where -> Name -> String -> String -> Wanteds
structField_ w nameBase theType theField
= fieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ structFieldMacro nameBase
structFieldMacro :: Name -> Wanteds
structFieldMacro nameBase = [(C, StructFieldMacro nameBase)]
-- Outputs the byte offset and MachRep for a field
structFieldHelper :: Where -> Where -> String -> String -> Wanteds
structFieldHelper wFT w theType theField = fieldOffset w theType theField
++ fieldType' wFT theType theField
++ structFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
closureFieldMacro :: Name -> Wanteds
closureFieldMacro nameBase = [(C, ClosureFieldMacro nameBase)]
closurePayload :: Where -> String -> String -> Wanteds
closurePayload w theType theField
= closureFieldOffset_ w nameBase theType theField
++ closurePayloadMacro nameBase
where nameBase = theType ++ "_" ++ theField
closurePayloadMacro :: Name -> Wanteds
closurePayloadMacro nameBase = [(C, ClosurePayloadMacro nameBase)]
-- Byte offset and MachRep for a closure field, minus the header
closureField_ :: Where -> Name -> String -> String -> Wanteds
closureField_ w nameBase theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ closureFieldMacro nameBase
closureField :: Where -> String -> String -> Wanteds
closureField w theType theField = closureField_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
closureFieldOffset_ :: Where -> Name -> String -> String -> Wanteds
closureFieldOffset_ w nameBase theType theField
= defOffset w nameBase (CExpr ("offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"))
-- Size of a closure type, minus the header, named SIZEOF_<type>_NoHdr
-- Also, we #define SIZEOF_<type> to be the size of the whole closure for .cmm.
closureSize :: Where -> String -> Wanteds
closureSize w theType = defSize w (theType ++ "_NoHdr") (CExpr expr)
++ defClosureSize C theType (CExpr expr)
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgHeader)"
-- Byte offset and MachRep for a closure field, minus the header
closureFieldGcptr :: Where -> String -> String -> Wanteds
closureFieldGcptr w theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldTypeGcptr nameBase
++ closureFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
fieldTypeGcptr :: Name -> Wanteds
fieldTypeGcptr nameBase = [(C, FieldTypeGcptrMacro nameBase)]
closureFieldOffset :: Where -> String -> String -> Wanteds
closureFieldOffset w theType theField
= defOffset w nameBase (CExpr expr)
where nameBase = theType ++ "_" ++ theField
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"
thunkSize :: Where -> String -> Wanteds
thunkSize w theType
= defSize w (theType ++ "_NoThunkHdr") (CExpr expr)
++ closureSize w theType
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgThunkHeader)"
defIntOffset :: Where -> Name -> String -> Wanteds
defIntOffset w nameBase cExpr = [(w, GetInt ("OFFSET_" ++ nameBase) (Fst (CExpr cExpr)))]
defOffset :: Where -> Name -> CExpr -> Wanteds
defOffset w nameBase cExpr = [(w, GetWord ("OFFSET_" ++ nameBase) (Fst cExpr))]
structSize :: Where -> String -> Wanteds
structSize w theType = defSize w theType (CExpr ("TYPE_SIZE(" ++ theType ++ ")"))
defSize :: Where -> Name -> CExpr -> Wanteds
defSize w nameBase cExpr = [(w, GetWord ("SIZEOF_" ++ nameBase) (Fst cExpr))]
defClosureSize :: Where -> Name -> CExpr -> Wanteds
defClosureSize w nameBase cExpr = [(w, GetClosureSize ("SIZEOF_" ++ nameBase) (Fst cExpr))]
haskellise :: Name -> Name
haskellise (c : cs) = toLower c : cs
haskellise "" = ""
wanteds :: String -> Wanteds
wanteds os = concat
[-- Closure header sizes.
constantWord Both "STD_HDR_SIZE"
-- grrr.. PROFILING is on so we need to
-- subtract sizeofW(StgProfHeader)
"sizeofW(StgHeader) - sizeofW(StgProfHeader)"
,constantWord Both "PROF_HDR_SIZE" "sizeofW(StgProfHeader)"
-- Size of a storage manager block (in bytes).
,constantWord Both "BLOCK_SIZE" "BLOCK_SIZE"
,constantWord C "MBLOCK_SIZE" "MBLOCK_SIZE"
-- blocks that fit in an MBlock, leaving space for the block
-- descriptors
,constantWord Both "BLOCKS_PER_MBLOCK" "BLOCKS_PER_MBLOCK"
-- could be derived, but better to save doing the calculation twice
,fieldOffset Both "StgRegTable" "rR1"
,fieldOffset Both "StgRegTable" "rR2"
,fieldOffset Both "StgRegTable" "rR3"
,fieldOffset Both "StgRegTable" "rR4"
,fieldOffset Both "StgRegTable" "rR5"
,fieldOffset Both "StgRegTable" "rR6"
,fieldOffset Both "StgRegTable" "rR7"
,fieldOffset Both "StgRegTable" "rR8"
,fieldOffset Both "StgRegTable" "rR9"
,fieldOffset Both "StgRegTable" "rR10"
,fieldOffset Both "StgRegTable" "rF1"
,fieldOffset Both "StgRegTable" "rF2"
,fieldOffset Both "StgRegTable" "rF3"
,fieldOffset Both "StgRegTable" "rF4"
,fieldOffset Both "StgRegTable" "rF5"
,fieldOffset Both "StgRegTable" "rF6"
,fieldOffset Both "StgRegTable" "rD1"
,fieldOffset Both "StgRegTable" "rD2"
,fieldOffset Both "StgRegTable" "rD3"
,fieldOffset Both "StgRegTable" "rD4"
,fieldOffset Both "StgRegTable" "rD5"
,fieldOffset Both "StgRegTable" "rD6"
,fieldOffset Both "StgRegTable" "rXMM1"
,fieldOffset Both "StgRegTable" "rXMM2"
,fieldOffset Both "StgRegTable" "rXMM3"
,fieldOffset Both "StgRegTable" "rXMM4"
,fieldOffset Both "StgRegTable" "rXMM5"
,fieldOffset Both "StgRegTable" "rXMM6"
,fieldOffset Both "StgRegTable" "rYMM1"
,fieldOffset Both "StgRegTable" "rYMM2"
,fieldOffset Both "StgRegTable" "rYMM3"
,fieldOffset Both "StgRegTable" "rYMM4"
,fieldOffset Both "StgRegTable" "rYMM5"
,fieldOffset Both "StgRegTable" "rYMM6"
,fieldOffset Both "StgRegTable" "rZMM1"
,fieldOffset Both "StgRegTable" "rZMM2"
,fieldOffset Both "StgRegTable" "rZMM3"
,fieldOffset Both "StgRegTable" "rZMM4"
,fieldOffset Both "StgRegTable" "rZMM5"
,fieldOffset Both "StgRegTable" "rZMM6"
,fieldOffset Both "StgRegTable" "rL1"
,fieldOffset Both "StgRegTable" "rSp"
,fieldOffset Both "StgRegTable" "rSpLim"
,fieldOffset Both "StgRegTable" "rHp"
,fieldOffset Both "StgRegTable" "rHpLim"
,fieldOffset Both "StgRegTable" "rCCCS"
,fieldOffset Both "StgRegTable" "rCurrentTSO"
,fieldOffset Both "StgRegTable" "rCurrentNursery"
,fieldOffset Both "StgRegTable" "rHpAlloc"
,structField C "StgRegTable" "rRet"
,structField C "StgRegTable" "rNursery"
,defIntOffset Both "stgEagerBlackholeInfo"
"FUN_OFFSET(stgEagerBlackholeInfo)"
,defIntOffset Both "stgGCEnter1" "FUN_OFFSET(stgGCEnter1)"
,defIntOffset Both "stgGCFun" "FUN_OFFSET(stgGCFun)"
,fieldOffset Both "Capability" "r"
,fieldOffset C "Capability" "lock"
,structField C "Capability" "no"
,structField C "Capability" "mut_lists"
,structField C "Capability" "context_switch"
,structField C "Capability" "interrupt"
,structField C "Capability" "sparks"
,structField C "Capability" "total_allocated"
,structField C "Capability" "weak_ptr_list_hd"
,structField C "Capability" "weak_ptr_list_tl"
,structField Both "bdescr" "start"
,structField Both "bdescr" "free"
,structField Both "bdescr" "blocks"
,structField C "bdescr" "gen_no"
,structField C "bdescr" "link"
,structSize C "generation"
,structField C "generation" "n_new_large_words"
,structField C "generation" "weak_ptr_list"
,structSize Both "CostCentreStack"
,structField C "CostCentreStack" "ccsID"
,structFieldH Both "CostCentreStack" "mem_alloc"
,structFieldH Both "CostCentreStack" "scc_count"
,structField C "CostCentreStack" "prevStack"
,structField C "CostCentre" "ccID"
,structField C "CostCentre" "link"
,structField C "StgHeader" "info"
,structField_ Both "StgHeader_ccs" "StgHeader" "prof.ccs"
,structField_ Both "StgHeader_ldvw" "StgHeader" "prof.hp.ldvw"
,structSize Both "StgSMPThunkHeader"
,closurePayload C "StgClosure" "payload"
,structFieldH Both "StgEntCounter" "allocs"
,structFieldH Both "StgEntCounter" "allocd"
,structField Both "StgEntCounter" "registeredp"
,structField Both "StgEntCounter" "link"
,structField Both "StgEntCounter" "entry_count"
,closureSize Both "StgUpdateFrame"
,closureSize C "StgCatchFrame"
,closureSize C "StgStopFrame"
,closureSize Both "StgMutArrPtrs"
,closureField Both "StgMutArrPtrs" "ptrs"
,closureField Both "StgMutArrPtrs" "size"
,closureSize Both "StgSmallMutArrPtrs"
,closureField Both "StgSmallMutArrPtrs" "ptrs"
,closureSize Both "StgArrBytes"
,closureField Both "StgArrBytes" "bytes"
,closurePayload C "StgArrBytes" "payload"
,closureField C "StgTSO" "_link"
,closureField C "StgTSO" "global_link"
,closureField C "StgTSO" "what_next"
,closureField C "StgTSO" "why_blocked"
,closureField C "StgTSO" "block_info"
,closureField C "StgTSO" "blocked_exceptions"
,closureField C "StgTSO" "id"
,closureField C "StgTSO" "cap"
,closureField C "StgTSO" "saved_errno"
,closureField C "StgTSO" "trec"
,closureField C "StgTSO" "flags"
,closureField C "StgTSO" "dirty"
,closureField C "StgTSO" "bq"
,closureField Both "StgTSO" "alloc_limit"
,closureField_ Both "StgTSO_cccs" "StgTSO" "prof.cccs"
,closureField Both "StgTSO" "stackobj"
,closureField Both "StgStack" "sp"
,closureFieldOffset Both "StgStack" "stack"
,closureField C "StgStack" "stack_size"
,closureField C "StgStack" "dirty"
,structSize C "StgTSOProfInfo"
,closureField Both "StgUpdateFrame" "updatee"
,closureField C "StgCatchFrame" "handler"
,closureField C "StgCatchFrame" "exceptions_blocked"
,closureSize C "StgPAP"
,closureField C "StgPAP" "n_args"
,closureFieldGcptr C "StgPAP" "fun"
,closureField C "StgPAP" "arity"
,closurePayload C "StgPAP" "payload"
,thunkSize C "StgAP"
,closureField C "StgAP" "n_args"
,closureFieldGcptr C "StgAP" "fun"
,closurePayload C "StgAP" "payload"
,thunkSize C "StgAP_STACK"
,closureField C "StgAP_STACK" "size"
,closureFieldGcptr C "StgAP_STACK" "fun"
,closurePayload C "StgAP_STACK" "payload"
,thunkSize C "StgSelector"
,closureFieldGcptr C "StgInd" "indirectee"
,closureSize C "StgMutVar"
,closureField C "StgMutVar" "var"
,closureSize C "StgAtomicallyFrame"
,closureField C "StgAtomicallyFrame" "exceptions_blocked"
,closureField C "StgAtomicallyFrame" "code"
,closureField C "StgAtomicallyFrame" "finalizer"
,closureField C "StgAtomicallyFrame" "next_invariant_to_check"
,closureField C "StgAtomicallyFrame" "result"
,closureField C "StgInvariantCheckQueue" "invariant"
,closureField C "StgInvariantCheckQueue" "my_execution"
,closureField C "StgInvariantCheckQueue" "next_queue_entry"
,closureField C "StgAtomicInvariant" "code"
,closureField C "StgTRecHeader" "enclosing_trec"
,closureField C "StgTRecHeader" "state"
,closureSize C "StgCatchSTMFrame"
,closureField C "StgCatchSTMFrame" "handler"
,closureField C "StgCatchSTMFrame" "code"
,closureSize C "StgCatchRetryFrame"
,closureField C "StgCatchRetryFrame" "running_alt_code"
,closureField C "StgCatchRetryFrame" "first_code"
,closureField C "StgCatchRetryFrame" "alt_code"
,closureField C "StgTVarWatchQueue" "closure"
,closureField C "StgTVarWatchQueue" "next_queue_entry"
,closureField C "StgTVarWatchQueue" "prev_queue_entry"
,closureSize C "StgTVar"
,closureField C "StgTVar" "current_value"
,closureField C "StgTVar" "frozen_by"
,closureField C "StgTVar" "first_watch_queue_entry"
,closureField C "StgTVar" "num_updates"
,closureSize C "StgWeak"
,closureField C "StgWeak" "link"
,closureField C "StgWeak" "key"
,closureField C "StgWeak" "value"
,closureField C "StgWeak" "finalizer"
,closureField C "StgWeak" "cfinalizers"
,closureSize C "StgCFinalizerList"
,closureField C "StgCFinalizerList" "link"
,closureField C "StgCFinalizerList" "fptr"
,closureField C "StgCFinalizerList" "ptr"
,closureField C "StgCFinalizerList" "eptr"
,closureField C "StgCFinalizerList" "flag"
,closureSize C "StgMVar"
,closureField C "StgMVar" "head"
,closureField C "StgMVar" "tail"
,closureField C "StgMVar" "value"
,closureSize C "StgMVarTSOQueue"
,closureField C "StgMVarTSOQueue" "link"
,closureField C "StgMVarTSOQueue" "tso"
,closureSize C "StgBCO"
,closureField C "StgBCO" "instrs"
,closureField C "StgBCO" "literals"
,closureField C "StgBCO" "ptrs"
,closureField C "StgBCO" "arity"
,closureField C "StgBCO" "size"
,closurePayload C "StgBCO" "bitmap"
,closureSize C "StgStableName"
,closureField C "StgStableName" "sn"
,closureSize C "StgBlockingQueue"
,closureField C "StgBlockingQueue" "bh"
,closureField C "StgBlockingQueue" "owner"
,closureField C "StgBlockingQueue" "queue"
,closureField C "StgBlockingQueue" "link"
,closureSize C "MessageBlackHole"
,closureField C "MessageBlackHole" "link"
,closureField C "MessageBlackHole" "tso"
,closureField C "MessageBlackHole" "bh"
,structField_ C "RtsFlags_ProfFlags_showCCSOnException"
"RTS_FLAGS" "ProfFlags.showCCSOnException"
,structField_ C "RtsFlags_DebugFlags_apply"
"RTS_FLAGS" "DebugFlags.apply"
,structField_ C "RtsFlags_DebugFlags_sanity"
"RTS_FLAGS" "DebugFlags.sanity"
,structField_ C "RtsFlags_DebugFlags_weak"
"RTS_FLAGS" "DebugFlags.weak"
,structField_ C "RtsFlags_GcFlags_initialStkSize"
"RTS_FLAGS" "GcFlags.initialStkSize"
,structField_ C "RtsFlags_MiscFlags_tickInterval"
"RTS_FLAGS" "MiscFlags.tickInterval"
,structSize C "StgFunInfoExtraFwd"
,structField C "StgFunInfoExtraFwd" "slow_apply"
,structField C "StgFunInfoExtraFwd" "fun_type"
,structFieldH Both "StgFunInfoExtraFwd" "arity"
,structField_ C "StgFunInfoExtraFwd_bitmap" "StgFunInfoExtraFwd" "b.bitmap"
,structSize Both "StgFunInfoExtraRev"
,structField C "StgFunInfoExtraRev" "slow_apply_offset"
,structField C "StgFunInfoExtraRev" "fun_type"
,structFieldH Both "StgFunInfoExtraRev" "arity"
,structField_ C "StgFunInfoExtraRev_bitmap" "StgFunInfoExtraRev" "b.bitmap"
,structField_ C "StgFunInfoExtraRev_bitmap_offset" "StgFunInfoExtraRev" "b.bitmap_offset"
,structField C "StgLargeBitmap" "size"
,fieldOffset C "StgLargeBitmap" "bitmap"
,structSize C "snEntry"
,structField C "snEntry" "sn_obj"
,structField C "snEntry" "addr"
,structSize C "spEntry"
,structField C "spEntry" "addr"
-- Note that this conditional part only affects the C headers.
-- That's important, as it means we get the same PlatformConstants
-- type on all platforms.
,if os == "mingw32"
then concat [structSize C "StgAsyncIOResult"
,structField C "StgAsyncIOResult" "reqID"
,structField C "StgAsyncIOResult" "len"
,structField C "StgAsyncIOResult" "errCode"]
else []
-- pre-compiled thunk types
,constantWord Haskell "MAX_SPEC_SELECTEE_SIZE" "MAX_SPEC_SELECTEE_SIZE"
,constantWord Haskell "MAX_SPEC_AP_SIZE" "MAX_SPEC_AP_SIZE"
-- closure sizes: these do NOT include the header (see below for
-- header sizes)
,constantWord Haskell "MIN_PAYLOAD_SIZE" "MIN_PAYLOAD_SIZE"
,constantInt Haskell "MIN_INTLIKE" "MIN_INTLIKE"
,constantWord Haskell "MAX_INTLIKE" "MAX_INTLIKE"
,constantWord Haskell "MIN_CHARLIKE" "MIN_CHARLIKE"
,constantWord Haskell "MAX_CHARLIKE" "MAX_CHARLIKE"
,constantWord Haskell "MUT_ARR_PTRS_CARD_BITS" "MUT_ARR_PTRS_CARD_BITS"
-- A section of code-generator-related MAGIC CONSTANTS.
,constantWord Haskell "MAX_Vanilla_REG" "MAX_VANILLA_REG"
,constantWord Haskell "MAX_Float_REG" "MAX_FLOAT_REG"
,constantWord Haskell "MAX_Double_REG" "MAX_DOUBLE_REG"
,constantWord Haskell "MAX_Long_REG" "MAX_LONG_REG"
,constantWord Haskell "MAX_XMM_REG" "MAX_XMM_REG"
,constantWord Haskell "MAX_Real_Vanilla_REG" "MAX_REAL_VANILLA_REG"
,constantWord Haskell "MAX_Real_Float_REG" "MAX_REAL_FLOAT_REG"
,constantWord Haskell "MAX_Real_Double_REG" "MAX_REAL_DOUBLE_REG"
,constantWord Haskell "MAX_Real_XMM_REG" "MAX_REAL_XMM_REG"
,constantWord Haskell "MAX_Real_Long_REG" "MAX_REAL_LONG_REG"
-- This tells the native code generator the size of the spill
-- area is has available.
,constantWord Haskell "RESERVED_C_STACK_BYTES" "RESERVED_C_STACK_BYTES"
-- The amount of (Haskell) stack to leave free for saving
-- registers when returning to the scheduler.
,constantWord Haskell "RESERVED_STACK_WORDS" "RESERVED_STACK_WORDS"
-- Continuations that need more than this amount of stack
-- should do their own stack check (see bug #1466).
,constantWord Haskell "AP_STACK_SPLIM" "AP_STACK_SPLIM"
-- Size of a word, in bytes
,constantWord Haskell "WORD_SIZE" "SIZEOF_HSWORD"
-- Size of a double in StgWords.
,constantWord Haskell "DOUBLE_SIZE" "SIZEOF_DOUBLE"
-- Size of a C int, in bytes. May be smaller than wORD_SIZE.
,constantWord Haskell "CINT_SIZE" "SIZEOF_INT"
,constantWord Haskell "CLONG_SIZE" "SIZEOF_LONG"
,constantWord Haskell "CLONG_LONG_SIZE" "SIZEOF_LONG_LONG"
-- Number of bits to shift a bitfield left by in an info table.
,constantWord Haskell "BITMAP_BITS_SHIFT" "BITMAP_BITS_SHIFT"
-- Amount of pointer bits used for semi-tagging constructor closures
,constantWord Haskell "TAG_BITS" "TAG_BITS"
,constantBool Haskell "WORDS_BIGENDIAN" "defined(WORDS_BIGENDIAN)"
,constantBool Haskell "DYNAMIC_BY_DEFAULT" "defined(DYNAMIC_BY_DEFAULT)"
,constantWord Haskell "LDV_SHIFT" "LDV_SHIFT"
,constantNatural Haskell "ILDV_CREATE_MASK" "LDV_CREATE_MASK"
,constantNatural Haskell "ILDV_STATE_CREATE" "LDV_STATE_CREATE"
,constantNatural Haskell "ILDV_STATE_USE" "LDV_STATE_USE"
]
getWanted :: Bool -> String -> FilePath -> FilePath -> [String] -> FilePath -> Maybe FilePath
-> IO Results
getWanted verbose os tmpdir gccProgram gccFlags nmProgram mobjdumpProgram
= do let cStuff = unlines (headers ++ concatMap (doWanted . snd) (wanteds os))
cFile = tmpdir </> "tmp.c"
oFile = tmpdir </> "tmp.o"
writeFile cFile cStuff
execute verbose gccProgram (gccFlags ++ ["-c", cFile, "-o", oFile])
xs <- case os of
"openbsd" -> readProcess objdumpProgam ["--syms", oFile] ""
"aix" -> readProcess objdumpProgam ["--syms", oFile] ""
_ -> readProcess nmProgram ["-P", oFile] ""
let ls = lines xs
m = Map.fromList $ case os of
"aix" -> parseAixObjdump ls
_ -> catMaybes $ map parseNmLine ls
rs <- mapM (lookupResult m) (wanteds os)
return rs
where headers = ["#define IN_STG_CODE 0",
"",
"/*",
" * We need offsets of profiled things...",
" * better be careful that this doesn't",
" * affect the offsets of anything else.",
" */",
"",
"#define PROFILING",
"#define THREADED_RTS",
"",
"#include \"PosixSource.h\"",
"#include \"Rts.h\"",
"#include \"Stable.h\"",
"#include \"Capability.h\"",
"",
"#include <inttypes.h>",
"#include <stddef.h>",
"#include <stdio.h>",
"#include <string.h>",
"",
"#define FIELD_SIZE(s_type, field) ((size_t)sizeof(((s_type*)0)->field))",
"#define TYPE_SIZE(type) (sizeof(type))",
"#define FUN_OFFSET(sym) (offsetof(Capability,f.sym) - offsetof(Capability,r))",
"",
"#pragma GCC poison sizeof"
]
objdumpProgam = maybe (error "no objdump program given") id mobjdumpProgram
prefix = "derivedConstant"
mkFullName name = prefix ++ name
-- We add 1 to the value, as some platforms will make a symbol
-- of size 1 when for
-- char foo[0];
-- We then subtract 1 again when parsing.
doWanted (GetFieldType name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetClosureSize name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetWord name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetInt name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "Mag[1 + ((intptr_t)(" ++ cExpr ++ ") >= 0 ? (" ++ cExpr ++ ") : -(" ++ cExpr ++ "))];",
"char " ++ mkFullName name ++ "Sig[(intptr_t)(" ++ cExpr ++ ") >= 0 ? 3 : 1];"]
doWanted (GetNatural name (Fst (CExpr cExpr)))
= -- These casts fix "right shift count >= width of type"
-- warnings
let cExpr' = "(uint64_t)(size_t)(" ++ cExpr ++ ")"
in ["char " ++ mkFullName name ++ "0[1 + ((" ++ cExpr' ++ ") & 0xFFFF)];",
"char " ++ mkFullName name ++ "1[1 + (((" ++ cExpr' ++ ") >> 16) & 0xFFFF)];",
"char " ++ mkFullName name ++ "2[1 + (((" ++ cExpr' ++ ") >> 32) & 0xFFFF)];",
"char " ++ mkFullName name ++ "3[1 + (((" ++ cExpr' ++ ") >> 48) & 0xFFFF)];"]
doWanted (GetBool name (Fst (CPPExpr cppExpr)))
= ["#if " ++ cppExpr,
"char " ++ mkFullName name ++ "[1];",
"#else",
"char " ++ mkFullName name ++ "[2];",
"#endif"]
doWanted (StructFieldMacro {}) = []
doWanted (ClosureFieldMacro {}) = []
doWanted (ClosurePayloadMacro {}) = []
doWanted (FieldTypeGcptrMacro {}) = []
-- parseNmLine parses "nm -P" output that looks like
-- "derivedConstantMAX_Vanilla_REG C 0000000b 0000000b" (GNU nm)
-- "_derivedConstantMAX_Vanilla_REG C b 0" (Mac OS X)
-- "_derivedConstantMAX_Vanilla_REG C 000000b" (MinGW)
-- "derivedConstantMAX_Vanilla_REG D 1 b" (Solaris)
-- and returns ("MAX_Vanilla_REG", 11)
parseNmLine line
= case words line of
('_' : n) : "C" : s : _ -> mkP n s
n : "C" : s : _ -> mkP n s
[n, "D", _, s] -> mkP n s
[s, "O", "*COM*", _, n] -> mkP n s
_ -> Nothing
where mkP r s = case (stripPrefix prefix r, readHex s) of
(Just name, [(size, "")]) -> Just (name, size)
_ -> Nothing
-- On AIX, `nm` isn't able to tell us the symbol size, so we
-- need to use `objdump --syms`. However, unlike on OpenBSD,
-- `objdump --syms` outputs entries spanning two lines, e.g.
--
-- [ 50](sec 3)(fl 0x00)(ty 0)(scl 2) (nx 1) 0x00000318 derivedConstantBLOCK_SIZE
-- AUX val 4097 prmhsh 0 snhsh 0 typ 3 algn 3 clss 5 stb 0 snstb 0
--
parseAixObjdump :: [String] -> [(String,Integer)]
parseAixObjdump = catMaybes . goAix
where
goAix (l1@('[':_):l2@('A':'U':'X':_):ls')
= parseObjDumpEntry l1 l2 : goAix ls'
goAix (_:ls') = goAix ls'
goAix [] = []
parseObjDumpEntry l1 l2
| ["val",n] <- take 2 (tail $ words l2)
, Just sym <- stripPrefix prefix sym0 = Just (sym, read n)
| otherwise = Nothing
where
[sym0, _] = take 2 (reverse $ words l1)
-- If an Int value is larger than 2^28 or smaller
-- than -2^28, then fail.
-- This test is a bit conservative, but if any
-- constants are roughly maxBound or minBound then
-- we probably need them to be Integer rather than
-- Int so that -- cross-compiling between 32bit and
-- 64bit platforms works.
lookupSmall :: Map String Integer -> Name -> IO Integer
lookupSmall m name
= case Map.lookup name m of
Just v
| v > 2^(28 :: Int) ||
v < -(2^(28 :: Int)) ->
die ("Value too large for GetWord: " ++ show v)
| otherwise -> return v
Nothing -> die ("Can't find " ++ show name)
lookupResult :: Map String Integer -> (Where, What Fst)
-> IO (Where, What Snd)
lookupResult m (w, GetWord name _)
= do v <- lookupSmall m name
return (w, GetWord name (Snd (v - 1)))
lookupResult m (w, GetInt name _)
= do mag <- lookupSmall m (name ++ "Mag")
sig <- lookupSmall m (name ++ "Sig")
return (w, GetWord name (Snd ((mag - 1) * (sig - 2))))
lookupResult m (w, GetNatural name _)
= do v0 <- lookupSmall m (name ++ "0")
v1 <- lookupSmall m (name ++ "1")
v2 <- lookupSmall m (name ++ "2")
v3 <- lookupSmall m (name ++ "3")
let v = (v0 - 1)
+ shiftL (v1 - 1) 16
+ shiftL (v2 - 1) 32
+ shiftL (v3 - 1) 48
return (w, GetWord name (Snd v))
lookupResult m (w, GetBool name _)
= do v <- lookupSmall m name
case v of
1 -> return (w, GetBool name (Snd True))
2 -> return (w, GetBool name (Snd False))
_ -> die ("Bad boolean: " ++ show v)
lookupResult m (w, GetFieldType name _)
= do v <- lookupSmall m name
return (w, GetFieldType name (Snd (v - 1)))
lookupResult m (w, GetClosureSize name _)
= do v <- lookupSmall m name
return (w, GetClosureSize name (Snd (v - 1)))
lookupResult _ (w, StructFieldMacro name)
= return (w, StructFieldMacro name)
lookupResult _ (w, ClosureFieldMacro name)
= return (w, ClosureFieldMacro name)
lookupResult _ (w, ClosurePayloadMacro name)
= return (w, ClosurePayloadMacro name)
lookupResult _ (w, FieldTypeGcptrMacro name)
= return (w, FieldTypeGcptrMacro name)
writeHaskellType :: FilePath -> [What Fst] -> IO ()
writeHaskellType fn ws = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["data PlatformConstants = PlatformConstants {"
-- Now a kludge that allows the real entries to
-- all start with a comma, which makes life a
-- little easier
," pc_platformConstants :: ()"]
footers = [" } deriving Read"]
body = concatMap doWhat ws
doWhat (GetClosureSize name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetFieldType name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetWord name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetInt name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetNatural name _) = [" , pc_" ++ name ++ " :: Integer"]
doWhat (GetBool name _) = [" , pc_" ++ name ++ " :: Bool"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellValue :: FilePath -> [What Snd] -> IO ()
writeHaskellValue fn rs = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["PlatformConstants {"
," pc_platformConstants = ()"]
footers = [" }"]
body = concatMap doWhat rs
doWhat (GetClosureSize name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetFieldType name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetWord name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetInt name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetNatural name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetBool name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellWrappers :: FilePath -> [What Fst] -> IO ()
writeHaskellWrappers fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetInt name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetNatural name _) = [haskellise name ++ " :: DynFlags -> Integer",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetBool name _) = [haskellise name ++ " :: DynFlags -> Bool",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellExports :: FilePath -> [What Fst] -> IO ()
writeHaskellExports fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [" " ++ haskellise name ++ ","]
doWhat (GetInt name _) = [" " ++ haskellise name ++ ","]
doWhat (GetNatural name _) = [" " ++ haskellise name ++ ","]
doWhat (GetBool name _) = [" " ++ haskellise name ++ ","]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHeader :: FilePath -> [What Snd] -> IO ()
writeHeader fn rs = writeFile fn xs
where xs = unlines (headers ++ body)
headers = ["/* This file is created automatically. Do not edit by hand.*/", ""]
body = concatMap doWhat rs
doWhat (GetFieldType name (Snd v)) = ["#define " ++ name ++ " b" ++ show (v * 8)]
doWhat (GetClosureSize name (Snd v)) = ["#define " ++ name ++ " (SIZEOF_StgHeader+" ++ show v ++ ")"]
doWhat (GetWord name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetInt name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetNatural name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetBool name (Snd v)) = ["#define " ++ name ++ " " ++ show (fromEnum v)]
doWhat (StructFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosureFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosurePayloadMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__,__ix__) W_[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ " + WDS(__ix__)]"]
doWhat (FieldTypeGcptrMacro nameBase) =
["#define REP_" ++ nameBase ++ " gcptr"]
die :: String -> IO a
die err = do hPutStrLn stderr err
exitFailure
execute :: Bool -> FilePath -> [String] -> IO ()
execute verbose prog args
= do when verbose $ putStrLn $ showCommandForUser prog args
ec <- rawSystem prog args
unless (ec == ExitSuccess) $
die ("Executing " ++ show prog ++ " failed")
| mcschroeder/ghc | utils/deriveConstants/Main.hs | bsd-3-clause | 44,564 | 2 | 18 | 14,461 | 10,187 | 5,251 | 4,936 | 736 | 32 |
{-# LANGUAGE ForeignFunctionInterface #-}
-------------------------------------------------------------------------------
-- |
-- Copyright : (c) 2015 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module Sound.Csound.RealtimeAudioIO (
--csoundSetRTAudioModule,
--csoundGetModule,
csoundGetInputBufferSize,
csoundGetOutputBufferSize
--csoundGetInputBuffer,
--csoundGetOutputBuffer,
--csoundGetSpin,
--csoundAddSpinSample,
--csoundGetSpout,
--csoundGetSpoutSample,
--csoundGetRtRecordUserData,
--csoundGetRtPlayUserData,
--csoundSetHostImplementedAudioIO,
--csoundGetAudioDevList,
--csoundSetPlayOpenCallback,
--csoundSetRtPlayCallback,
--csoundSetRecOpenCallback,
--csoundSetRtRecordCallback,
--csoundSetRtCloseCallback,
--csoundSetAudioDeviceListCallback
) where
import Control.Monad.IO.Class
import Foreign.Ptr
import Foreign.C.Types
--foreign import ccall "csound.h csoundSetRTAudioModule" csoundSetRTAudioModule'
--foreign import ccall "csound.h csoundGetModule" csoundGetModule'
foreign import ccall "csound.h csoundGetInputBufferSize" csoundGetInputBufferSize' :: Ptr () -> IO CLong
foreign import ccall "csound.h csoundGetOutputBufferSize" csoundGetOutputBufferSize' :: Ptr () -> IO CLong
--foreign import ccall "csound.h csoundGetInputBuffer" csoundGetInputBuffer'
--foreign import ccall "csound.h csoundGetOutputBuffer" csoundGetOutput'
--foreign import ccall "csound.h csoundGetSpin" csoundGetSpin'
--foreign import ccall "csound.h csoundAddSpinSample" csoundAddSpinSample'
--foreign import ccall "csound.h csoundGetSpout" csoundGetSpout'
--foreign import ccall "csound.h csoundGetSpoutSample" csoundGetSpoutSample'
--foreign import ccall "csound.h csoundGetRtRecordUserData" csoundGetRtRecordUserData'
--foreign import ccall "csound.h csoundGetRtPlayUserData" csoundGetRtPlayUserData'
--foreign import ccall "csound.h csoundSetHostImplementedAudioIO" csoundSetHostImplementedAudioIO'
--foreign import ccall "csound.h csoundGetAudioDevList" csoundGetAudioDevList'
--foreign import ccall "csound.h csoundSetPlayopenCallback" csoundSetPlayopenCallback'
--foreign import ccall "csound.h csoundSetRtplayCallback" csoundSetRtplayCallback'
--foreign import ccall "csound.h csoundSetRecopenCallback" csoundSetrecopenCallback'
--foreign import ccall "csound.h csoundSetRtrecordCallback" csoundSetRtrecordCallback'
--foreign import ccall "csound.h csoundSetRtcloseCallback" csoundSetRtcloseCallback'
--foreign import ccall "csound.h csoundSetAudioDeviceListCallback" csoundSetAudioDeviceListCallback'
--csoundSetRTAudioModule
--csoundSetRTAudioModule
--csoundGetModule
--csoundGetModule
csoundGetInputBufferSize :: MonadIO m => Ptr () -> m CLong
csoundGetInputBufferSize csnd = liftIO (csoundGetInputBufferSize' csnd)
csoundGetOutputBufferSize :: MonadIO m => Ptr () -> m CLong
csoundGetOutputBufferSize csnd = liftIO (csoundGetOutputBufferSize' csnd)
--csoundGetInputBuffer
--csoundGetInputBuffer
--csoundGetOutputBuffer
--csoundGetOutputBuffer
--csoundGetSpin
--csoundGetSpin
--csoundAddSpinSample
--csoundAddSpinSample
--csoundGetSpout
--csoundGetSpout
--csoundGetSpoutSample
--csoundGetSpoutSample
--csoundGetRtRecordUserData
--csoundGetRtRecordUserData
--csoundGetRtPlayUserData
--csoundGetRtPlayUserData
--csoundSetHostImplementedAudioIO
--csoundSetHostImplementedAudioIO
--csoundGetAudioDevList
--csoundGetAudioDevList
--csoundSetPlayOpenCallback
--csoundSetPlayOpenCallback
--csoundSetRtPlayCallback
--csoundSetRtPlayCallback
--csoundSetRecOpenCallback
--csoundSetRecOpenCallback
--csoundSetRtRecordCallback
--csoundSetRtRecordCallback
--csoundSetRtCloseCallback
--csoundSetRtCloseCallback
--csoundSetAudioDeviceListCallback
--csoundSetAudioDeviceListCallback
| oldmanmike/CsoundRaw | src/Sound/Csound/RealtimeAudioIO.hs | bsd-3-clause | 3,972 | 0 | 8 | 381 | 245 | 166 | 79 | 13 | 1 |
module Lib (main) where
import BasePrelude
import Control.Monad.IO.Class
import Control.Monad.Random (getRandomR)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Vector (Vector, fromList, (!))
import Web.Spock
main :: IO ()
main = do
port <- fromMaybe 3030
<$> fmap read
<$> lookupEnv "PORT"
list <- fromList
<$> T.splitOn "%\r\n"
<$> T.readFile "data/limericks.txt"
runServer port list
runServer :: Int -> Vector T.Text -> IO ()
runServer port list = runSpock port $ spockT id $ do
get root $ do
setHeader "Access-Control-Allow-Origin" "*"
text =<< liftIO randLimeric
where
randLimeric = (list !) <$> getRandomR (0, length list - 1)
| nejstastnejsistene/dirty-limericks | src/Lib.hs | bsd-3-clause | 714 | 0 | 12 | 149 | 248 | 130 | 118 | 23 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
module Fragment.IsoRec.Ast.Term (
TmFIsoRec
, AsTmIsoRec(..)
) where
import Data.Functor.Classes (Eq1(..), Ord1(..), Show1(..), showsBinaryWith)
import Bound (Bound(..))
import Control.Lens.Prism (Prism')
import Control.Lens.Wrapped (_Wrapped, _Unwrapped)
import Control.Lens.TH (makePrisms)
import Data.Deriving (makeLiftEq, makeLiftCompare, makeLiftShowsPrec)
import Ast.Type
import Ast.Term
import Data.Bitransversable
import Data.Functor.Rec
import Util.Prisms
data TmFIsoRec (ki :: (* -> *) -> * -> *) (ty :: ((* -> *) -> * -> *) -> (* -> *) -> * -> *) (pt :: (* -> *) -> * -> *) k a =
TmFoldF (k a) (k a)
| TmUnfoldF (k a) (k a)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
makePrisms ''TmFIsoRec
instance (Eq1 f, Monad f) => Eq1 (TmFIsoRec ki ty pt f) where
liftEq = $(makeLiftEq ''TmFIsoRec)
instance (Ord1 f, Monad f) => Ord1 (TmFIsoRec ki ty pt f) where
liftCompare = $(makeLiftCompare ''TmFIsoRec)
instance (Show1 f) => Show1 (TmFIsoRec ki ty pt f) where
liftShowsPrec = $(makeLiftShowsPrec ''TmFIsoRec)
instance EqRec (TmFIsoRec ki ty pt) where
liftEqRec eR _ (TmFoldF x1 y1) (TmFoldF x2 y2) =
eR x1 x2 && eR y1 y2
liftEqRec eR _ (TmUnfoldF x1 y1) (TmUnfoldF x2 y2) =
eR x1 x2 && eR y1 y2
liftEqRec _ _ _ _ = False
instance OrdRec (TmFIsoRec ki ty pt) where
liftCompareRec cR _ (TmFoldF x1 y1) (TmFoldF x2 y2) =
case cR x1 x2 of
EQ -> cR y1 y2
z -> z
liftCompareRec _ _ (TmFoldF _ _) _ = LT
liftCompareRec _ _ _ (TmFoldF _ _) = GT
liftCompareRec cR _ (TmUnfoldF x1 y1) (TmUnfoldF x2 y2) =
case cR x1 x2 of
EQ -> cR y1 y2
z -> z
instance ShowRec (TmFIsoRec ki ty pt) where
liftShowsPrecRec sR _ _ _ n (TmFoldF x y) =
showsBinaryWith sR sR "TmFoldF" n x y
liftShowsPrecRec sR _ _ _ n (TmUnfoldF x y) =
showsBinaryWith sR sR "TmUnfoldF" n x y
instance Bound (TmFIsoRec ki ty pt) where
TmFoldF x y >>>= f = TmFoldF (x >>= f) (y >>= f)
TmUnfoldF x y >>>= f = TmUnfoldF (x >>= f) (y >>= f)
instance Bitransversable (TmFIsoRec ki ty pt) where
bitransverse fT fL (TmFoldF x y) = TmFoldF <$> fT fL x <*> fT fL y
bitransverse fT fL (TmUnfoldF x y) = TmUnfoldF <$> fT fL x <*> fT fL y
class (TmAstBound ki ty pt tm, TmAstTransversable ki ty pt tm) => AsTmIsoRec ki ty pt tm where
_TmIsoRecP :: Prism' (tm ki ty pt f a) (TmFIsoRec ki ty pt f a)
_TmFold :: Prism' (Term ki ty pt tm a) (Type ki ty a, Term ki ty pt tm a)
_TmFold = _Wrapped . _TmAstTerm . _TmIsoRecP . _TmFoldF . mkPair _TmType _Unwrapped
_TmUnfold :: Prism' (Term ki ty pt tm a) (Type ki ty a, Term ki ty pt tm a)
_TmUnfold = _Wrapped . _TmAstTerm . _TmIsoRecP . _TmUnfoldF . mkPair _TmType _Unwrapped
instance (Bound ki, Bound (ty ki), Bound pt, Bitransversable ki, Bitransversable (ty ki), Bitransversable pt) => AsTmIsoRec ki ty pt TmFIsoRec where
_TmIsoRecP = id
instance {-# OVERLAPPABLE #-} (Bound (x ki ty pt), Bitransversable (x ki ty pt), AsTmIsoRec ki ty pt (TmSum xs)) => AsTmIsoRec ki ty pt (TmSum (x ': xs)) where
_TmIsoRecP = _TmNext . _TmIsoRecP
instance {-# OVERLAPPING #-} (Bound ki, Bound (ty ki), Bound pt, Bound (TmSum xs ki ty pt), Bitransversable ki, Bitransversable (ty ki), Bitransversable pt, Bitransversable (TmSum xs ki ty pt)) => AsTmIsoRec ki ty pt (TmSum (TmFIsoRec ': xs)) where
_TmIsoRecP = _TmNow . _TmIsoRecP
| dalaing/type-systems | src/Fragment/IsoRec/Ast/Term.hs | bsd-3-clause | 3,833 | 0 | 10 | 785 | 1,549 | 809 | 740 | 75 | 0 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
module UniqMap
( UniqMap
, buildUniqMap
, (!)
, lookupName
, nameAt
, exprAt
, keys
, elems
, assocs
, intersectUniq
) where
import Control.Lens
import Data.Either.Validation
import Data.Foldable
import Data.Map (Map)
import qualified Data.Map as M
newtype UniqMap k v = UMap (Map k v)
deriving (Eq,Ord,Monoid,Show,Functor,Foldable,Traversable)
type instance Index (UniqMap k v) = k
type instance IxValue (UniqMap k v) = v
instance Ord k => Ixed (UniqMap k v) where
ix k f (UMap m) = case M.lookup k m of
Just v -> f v <&> \v' -> UMap (M.insert k v' m)
Nothing -> pure (UMap m)
{-# INLINE ix #-}
instance FunctorWithIndex k (UniqMap k)
instance FoldableWithIndex k (UniqMap k)
instance TraversableWithIndex k (UniqMap k) where
itraverse f (UMap m) = UMap <$> M.traverseWithKey f m
buildUniqMap
:: (Foldable f, Ord k)
=> f (k,v)
-> Validation [k] (UniqMap k v)
buildUniqMap = fmap UMap . buildMap . map wrap . toList
where
wrap (k, v) = (k, Success (k, v))
dedupKey (Success (k1, _)) (Success (k2, _)) = Failure [k1,k2]
dedupKey (Success (k, _)) (Failure l) = Failure (k:l)
dedupKey (Failure _) _ = error "Shouldn't happen."
buildMap = traverse (fmap snd) . M.fromListWith dedupKey
(!) :: Ord k => UniqMap k v -> k -> v
UMap m ! k = m M.! k
lookupName :: Ord k => UniqMap k v -> k -> Maybe Int
lookupName (UMap m) = (`M.lookupIndex` m)
nameAt :: UniqMap k v -> Int -> k
nameAt (UMap m) i = fst $ M.elemAt i m
exprAt :: UniqMap k v -> Int -> v
exprAt (UMap m) i = snd $ M.elemAt i m
keys :: UniqMap k v -> [k]
keys (UMap m) = M.keys m
elems :: UniqMap k v -> [v]
elems (UMap m) = M.elems m
assocs :: UniqMap k v -> [(k, v)]
assocs (UMap m) = M.assocs m
intersectUniq
:: (Ord k)
=> (a -> b -> c)
-> UniqMap k a
-> UniqMap k b
-> Validation ([k], [k]) (UniqMap k c)
intersectUniq f (UMap m1) (UMap m2) = sequenceA . UMap $
M.mergeWithKey combine (failed (,[])) (failed ([],)) m1 m2
where
combine _ x y = Just . Success $ f x y
failed wrap = M.mapWithKey (\k _ -> Failure $ wrap [k])
| merijn/lambda-except | UniqMap.hs | bsd-3-clause | 2,436 | 0 | 14 | 576 | 1,071 | 563 | 508 | 72 | 3 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Serv.Server.ServerEnv
( ServerEnv(..)
, setupServerEnv
) where
import Control.Exception
import Data.Default.Class
import Network.Wai
import Network.Wai.Middleware.RequestLogger
import Serv.Server.Core.Config
import Serv.Server.Core.Logger
import Serv.Server.Core.Metrics
import System.Log.FastLogger
data ServerEnv = ServerEnv
{ serverConfig :: Config
, serverMetrics :: ServerMetrics
, log :: LogStr -> IO ()
, logH :: HandlerLogger
, logEnv :: LogEnv
}
setupServerEnv :: IO ServerEnv
setupServerEnv = do
-- bootstrap configuration
conf <- loadConfig
config <- case conf of
(Left errs) -> fail (concat ("Configuration errors.\n" : errs))
(Right c) -> return c
-- bootstrap metrics
metrics <- setupMetrics
-- bootstrap logging
logEnv <- setupLogger (logConf config)
-- WAI logging middleware
return (ServerEnv config metrics (logMsg logEnv) (logMsgH logEnv) logEnv)
| orangefiredragon/bear | src/Serv/Server/ServerEnv.hs | bsd-3-clause | 1,111 | 0 | 15 | 290 | 252 | 143 | 109 | 28 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Control.Quantum
( Amplitude
, WaveFunction
, Quantum
, quantize
, MonadQuantum
, runQuantum
, runQuantum'
, measure
, measurements
)
where
import qualified Data.Map as M
import Data.Map (Map)
import Data.Monoid
import Control.Monad
import Control.Applicative
import Control.Monad.Random as R
import Data.Complex
nearZero :: Double -> Bool
nearZero x = abs x <= 1e-12
type Amplitude = Complex Double
-- | The Wave function is the distribution of amplitudes over the
-- possible states of the underlying data type
type WaveFunction a = [(a, Amplitude)]
class (Monad m) => MonadQuantum m where
quantize :: (Ord a) => WaveFunction a -> m a
quantize' :: WaveFunction a -> m a
condition :: Bool -> m ()
liftQ :: (Ord b, MonadQuantum m) => (a -> b) -> m a -> m b
liftQ f q1 = q1 >>= always . f
liftQ2 :: (Ord c, MonadQuantum m) => (a -> b -> c) -> m a -> m b -> m c
liftQ2 f p1 p2 = do x1 <- p1
x2 <- p2
always (f x1 x2)
liftQ3 :: (Ord d, MonadQuantum m) => (a -> b -> c -> d) -> m a -> m b -> m c -> m d
liftQ3 f p1 p2 p3 = do x1 <- p1
x2 <- p2
x3 <- p3
always (f x1 x2 x3)
always a = quantize [(a, 1.0:+0.0)]
always' a = quantize' [(a, 1.0:+0.0)]
-- | Describes the quantized version of an arbitrary data type.
-- The underlying data type defines the basis that the state is measured in.
data Quantum a where
Quantum :: Ord a => Map (Maybe a) Amplitude -> Quantum a
QuantumAny :: [(Maybe a, Amplitude)] -> Quantum a
noState :: (Ord a) => Quantum a
noState = Quantum (M.singleton Nothing (1.0:+0.0))
noState' :: Quantum a
noState' = QuantumAny [(Nothing, 1.0 :+ 0.0)]
deriving instance (Show a) => Show (Quantum a)
instance Functor Quantum where
fmap = liftM
instance Applicative Quantum where
pure = return
(<*>) = ap
instance Monad Quantum where
return = always'
m >>= f = if unitary then next
else error "Non-unitary transformation applied to quantum state!"
where
unitary = nearZero $ l2norm (map snd $ toList' next) - 1.0
next = collect [multAmpl q (go a) | (a, q) <- toList' m]
go = maybe noState' f
multAmpl :: Amplitude -> Quantum a -> Quantum a
multAmpl q (Quantum x) = Quantum $ M.map (* conjugate q) x
multAmpl q (QuantumAny x) = QuantumAny [ (a, q * r) | (a, r) <- x ]
toList' :: Quantum a -> [(Maybe a, Amplitude)]
toList' (Quantum x) = M.toList x
toList' (QuantumAny x) = x
toList :: (Ord a) => Quantum a -> [(Maybe a, Amplitude)]
toList (Quantum x) = M.toList x
toList (QuantumAny x) = merge x
collect :: [Quantum a] -> Quantum a
collect [ ] = QuantumAny []
collect [x] = x
collect (Quantum x:t) = case collect t of
Quantum y -> Quantum (M.unionWith (+) x y)
QuantumAny y -> Quantum (M.unionWith (+) x (M.fromList y))
collect (QuantumAny x:t) = case collect t of
Quantum y -> Quantum (M.unionWith (+) (M.fromList x) y)
QuantumAny y -> QuantumAny (x ++ y)
merge :: (Ord a) => WaveFunction a -> WaveFunction a
merge = M.toList . M.fromListWith (+)
instance MonadQuantum Quantum where
quantize = Quantum . M.fromListWith (+) . normalize
quantize' = QuantumAny . normalize
condition test = if test then always () else noState
instance (Ord a, Monoid a) => Monoid (Quantum a) where
mempty = always mempty
mappend = liftQ2 mappend
normalize :: WaveFunction a -> [(Maybe a, Amplitude)]
normalize xs = map (\(a, q) -> (Just a, q / total)) xs
where
total = sum $ zipWith (*) (map conjugate ampl) ampl
ampl = map snd xs
-- | Remove all impossible states from the quantum state and renormalize
collapse :: [(Maybe a, Amplitude)] -> WaveFunction a
collapse xs = [ (x, q / (norm:+0)) | (Just x, q) <- xs ]
where
norm = l2norm [ q | (Just x, q) <- xs ]
l2norm :: [Amplitude] -> Double
l2norm xs = sqrt $ sum $ map (\x -> (magnitude x)**2) xs
-- | Extracts the wave function from a quantum state.
runQuantum :: (Ord a) => Quantum a -> WaveFunction a
runQuantum = collapse . toList
runQuantum' :: Quantum a -> WaveFunction a
runQuantum' = collapse . toList'
-- | Measures a quantum state. Returns a single realization of the underlying data type
-- with probability equal to the squared magnitude of the amplitude of that realization.
-- Note that if this Module would be backed by a real quantum processor, this would be
-- the only valid way to extract information from the Monad.
measure :: (Ord a) => Quantum a -> IO a
measure q = do
x <- evalRandIO $ R.fromList $ map (\(a, b) -> (a, toRational b)) $ measurements q
return x
-- | Converts a quantum state into a probability state through measurement.
-- Equivalent to performing repeated measurements on equally prepared quantum states
-- and noting the frequency of each possible realization.
measurements :: (Ord a) => Quantum a -> [(a, Double)]
measurements = f . runQuantum
where f xs = [(x, (magnitude q)**2) | (x, q) <- xs]
| ibab/haskell-quantum | src/Control/Quantum.hs | bsd-3-clause | 5,371 | 0 | 14 | 1,452 | 1,888 | 993 | 895 | 109 | 3 |
{- |
Module : Control.Monad.IO.Peel
Copyright : © Anders Kaseorg, 2010
License : BSD-style
Maintainer : Anders Kaseorg <andersk@mit.edu>
Stability : experimental
Portability : portable
This module defines the class 'MonadPeelIO' of 'IO'-based monads into
which control operations on 'IO' (such as exception catching; see
"Control.Exception.Peel") can be lifted.
'liftIOOp' and 'liftIOOp_' enable convenient lifting of two common
special cases of control operation types.
-}
module Control.Monad.IO.Peel (
MonadPeelIO(..),
liftIOOp,
liftIOOp_,
) where
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Peel
import Control.Monad.Trans.Identity
import Control.Monad.Trans.List
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State
import qualified Control.Monad.Trans.State.Strict as Strict
import Control.Monad.Trans.Writer
import qualified Control.Monad.Trans.Writer.Strict as Strict
import qualified Control.Monad.Trans.RWS as RWS
import qualified Control.Monad.Trans.RWS.Strict as RWS.Strict
import Data.Monoid
-- |@MonadPeelIO@ is the class of 'IO'-based monads supporting an
-- extra operation 'peelIO', enabling control operations on 'IO' to be
-- lifted into the monad.
class MonadIO m => MonadPeelIO m where
-- |@peelIO@ is a version of 'peel' that operates through an
-- arbitrary stack of monad transformers directly to an inner 'IO'
-- (analagously to how 'liftIO' is a version of @lift@). So it can
-- be used with 'liftIO' to lift control operations on 'IO' into any
-- monad in 'MonadPeelIO'. For example:
--
-- @
-- foo :: 'IO' a -> 'IO' a
-- foo' :: 'MonadPeelIO' m => m a -> m a
-- foo' a = do
-- k \<- 'peelIO' -- k :: m a -> IO (m a)
-- 'join' $ 'liftIO' $ foo (k a) -- uses foo :: 'IO' (m a) -> 'IO' (m a)
-- @
--
-- Note that the \"obvious\" term of this type (@peelIO = 'return'
-- 'return'@) /does not/ work correctly. Instances of 'MonadPeelIO'
-- should be constructed via 'MonadTransPeel', using @peelIO =
-- 'liftPeel' peelIO@.
peelIO :: m (m a -> IO (m a))
instance MonadPeelIO IO where
peelIO = idPeel
instance MonadPeelIO m => MonadPeelIO (IdentityT m) where
peelIO = liftPeel peelIO
instance MonadPeelIO m => MonadPeelIO (ListT m) where
peelIO = liftPeel peelIO
instance MonadPeelIO m => MonadPeelIO (MaybeT m) where
peelIO = liftPeel peelIO
instance (MonadPeelIO m) => MonadPeelIO (ExceptT e m) where
peelIO = liftPeel peelIO
instance MonadPeelIO m => MonadPeelIO (ReaderT r m) where
peelIO = liftPeel peelIO
instance MonadPeelIO m => MonadPeelIO (StateT s m) where
peelIO = liftPeel peelIO
instance MonadPeelIO m => MonadPeelIO (Strict.StateT s m) where
peelIO = liftPeel peelIO
instance (Monoid w, MonadPeelIO m) => MonadPeelIO (WriterT w m) where
peelIO = liftPeel peelIO
instance (Monoid w, MonadPeelIO m) => MonadPeelIO (Strict.WriterT w m) where
peelIO = liftPeel peelIO
instance (Monoid w, MonadPeelIO m) => MonadPeelIO (RWS.RWST r w s m) where
peelIO = liftPeel peelIO
instance (Monoid w, MonadPeelIO m) =>
MonadPeelIO (RWS.Strict.RWST r w s m) where
peelIO = liftPeel peelIO
-- |@liftIOOp@ is a particular application of 'peelIO' that allows
-- lifting control operations of type @(a -> 'IO' b) -> 'IO' b@
-- (e.g. @alloca@, @withMVar v@) to @'MonadPeelIO' m => (a -> m b) ->
-- m b@.
--
-- @
-- 'liftIOOp' f g = do
-- k \<- 'peelIO'
-- 'join' $ 'liftIO' $ f (k . g)
-- @
liftIOOp :: MonadPeelIO m => ((a -> IO (m b)) -> IO (m c)) -> (a -> m b) -> m c
liftIOOp f g = do
k <- peelIO
join $ liftIO $ f (k . g)
-- |@liftIOOp_@ is a particular application of 'peelIO' that allows
-- lifting control operations of type @'IO' a -> 'IO' a@
-- (e.g. @block@) to @'MonadPeelIO' m => m a -> m a@.
--
-- @
-- 'liftIOOp_' f m = do
-- k \<- 'peelIO'
-- 'join' $ 'liftIO' $ f (k m)
-- @
liftIOOp_ :: MonadPeelIO m => (IO (m a) -> IO (m b)) -> m a -> m b
liftIOOp_ f m = do
k <- peelIO
join $ liftIO $ f (k m)
| mcmaniac/monad-peel | Control/Monad/IO/Peel.hs | bsd-3-clause | 4,111 | 0 | 13 | 824 | 816 | 456 | 360 | 54 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module SMACCMPilot.GCS.Gateway.Monad
( GW
, runGW
, lift
, writeErr
, writeLog
, writeDbg
, queuePushGW
, queuePopGW
, (>~>)
, (>*>)
, (>>~)
) where
import qualified MonadLib as M
import Control.Applicative
import SMACCMPilot.GCS.Gateway.Console
import SMACCMPilot.GCS.Gateway.Queue
--------------------------------------------------------------------------------
newtype GW a =
GW { unGW :: M.ReaderT Console IO a }
deriving (Functor, Monad, Applicative)
runGW :: Console -> GW a -> IO a
runGW console gw = M.runReaderT console (unGW gw)
lift :: IO a -> GW a
lift = GW . M.lift
getConsole :: GW Console
getConsole = GW M.ask
writeErr :: String -> GW ()
writeErr msg = do
c <- getConsole
lift $ consoleError c msg
writeDbg :: String -> GW ()
writeDbg msg = do
c <- getConsole
lift $ consoleDebug c msg
writeLog :: String -> GW ()
writeLog msg = do
c <- getConsole
lift $ consoleLog c msg
queuePopGW :: QueueInput a -> GW a
queuePopGW q = lift (queuePop q)
queuePushGW :: QueueOutput a -> a -> GW ()
queuePushGW q v = lift (queuePush q v)
infixr 0 >~>
(>~>) :: Monad m => (a -> m (Maybe b)) -> (b -> m ()) -> a -> m ()
(>~>) a b a1 = a a1 >>= maybe (return ()) b
infixr 0 >*>
(>*>) :: Monad m => (a -> m [b]) -> (b -> m ()) -> a -> m ()
(>*>) a b a1 = a a1 >>= mapM_ b
infixr 0 >>~
(>>~) :: Monad m => (m (Maybe b)) -> (b -> m ()) -> m ()
(>>~) a b = (const a >~> b) ()
| GaloisInc/smaccmpilot-gcs-gateway | SMACCMPilot/GCS/Gateway/Monad.hs | bsd-3-clause | 1,471 | 0 | 11 | 333 | 663 | 348 | 315 | 51 | 1 |
module Data.Picture.Drawing.ShapeMatrix (
module Data.Picture.Drawing.ShapeMatrix.ShapeMatrix,
-- * Point Matrix
module Data.Picture.Drawing.ShapeMatrix.PointMatrix,
-- * Edge Matrix
module Data.Picture.Drawing.ShapeMatrix.EdgeMatrix,
-- * Polygon Matrix
module Data.Picture.Drawing.ShapeMatrix.PolyMatrix
) where
import Data.Picture.Drawing.ShapeMatrix.ShapeMatrix
import Data.Picture.Drawing.ShapeMatrix.PointMatrix
import Data.Picture.Drawing.ShapeMatrix.EdgeMatrix
import Data.Picture.Drawing.ShapeMatrix.PolyMatrix
| jbaum98/graphics | src/Data/Picture/Drawing/ShapeMatrix.hs | bsd-3-clause | 537 | 0 | 5 | 50 | 81 | 62 | 19 | 9 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Util.Pseudo where
import Control.Applicative
import Control.Monad
import Data.Monoid
class PseudoFunctor pd where
pdfmap :: (pd -> pd) -> pd -> pd
class PseudoFoldable pd where
pdfoldMap :: Monoid b => (pd -> b) -> pd -> b
class (Applicative m, Monad m) => PseudoTraversable m pd where
pdmapM :: (pd -> m pd) -> pd -> m pd
pdforM :: pd -> (pd -> m pd) -> m pd
pdforM = flip pdmapM
class Convert a b where
convert :: a -> b
| ocean0yohsuke/Simply-Typed-Lambda | src/Util/Pseudo.hs | bsd-3-clause | 500 | 0 | 11 | 119 | 193 | 100 | 93 | 15 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-}
module Network.Wai.Handler.Warp.HTTP2.HPACK where
import Control.Arrow (first)
import qualified Control.Exception as E
import Data.ByteString.Builder (Builder)
import qualified Data.ByteString.Char8 as B8
import Data.CaseInsensitive (foldedCase)
import Data.IORef (readIORef, writeIORef)
import Network.HPACK
import qualified Network.HTTP.Types as H
import Network.HTTP2
import Network.Wai
import Network.Wai.Handler.Warp.HTTP2.Types
import Network.Wai.Handler.Warp.Header
import Network.Wai.Handler.Warp.Response
import qualified Network.Wai.Handler.Warp.Settings as S
import Network.Wai.Handler.Warp.Types
hpackEncodeHeader :: Context -> InternalInfo -> S.Settings -> Response
-> IO Builder
hpackEncodeHeader Context{encodeDynamicTable} ii settings rsp = do
hdr1 <- addServerAndDate hdr0
let hdr2 = (":status", status) : map (first foldedCase) hdr1
ehdrtbl <- readIORef encodeDynamicTable
(ehdrtbl', builder) <- encodeHeaderBuilder defaultEncodeStrategy ehdrtbl hdr2
writeIORef encodeDynamicTable ehdrtbl'
return builder
where
hdr0 = responseHeaders rsp
status = B8.pack $ show $ H.statusCode $ responseStatus rsp
dc = dateCacher ii
rspidxhdr = indexResponseHeader hdr0
defServer = S.settingsServerName settings
addServerAndDate = addDate dc rspidxhdr . addServer defServer rspidxhdr
----------------------------------------------------------------
hpackDecodeHeader :: HeaderBlockFragment -> Context -> IO HeaderList
hpackDecodeHeader hdrblk Context{decodeDynamicTable} = do
hdrtbl <- readIORef decodeDynamicTable
(hdrtbl', hdr) <- decodeHeader hdrtbl hdrblk `E.onException` cleanup
writeIORef decodeDynamicTable hdrtbl'
return hdr
where
cleanup = E.throwIO $ ConnectionError CompressionError "cannot decompress the header"
| mfine/wai | warp/Network/Wai/Handler/Warp/HTTP2/HPACK.hs | mit | 1,907 | 0 | 13 | 282 | 451 | 249 | 202 | 40 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Webserver where
import Control.Applicative
import Snap.Core
import Snap.Util.FileServe
import Snap.Http.Server
import Snap.Util.FileUploads
import qualified Data.Enumerator.List as EL
import Control.Monad (liftM)
import Control.Applicative ((<$>))
import qualified Data.ByteString.UTF8 as BS8 (toString, fromString)
import qualified Data.ByteString as BS (readFile, ByteString(..), pack, writeFile, concat)
import Control.Monad.IO.Class (liftIO)
import Data.Text.Encoding (encodeUtf8)
import qualified Data.Text as T (pack)
import System.Directory (getDirectoryContents, getCurrentDirectory)
import System.FilePath.Posix ((</>))
import RawRGB
main :: IO ()
main = quickHttpServe site
site :: Snap ()
site =
ifTop (method GET homeHandler) <|> -- /
dir "static" (serveDirectory ".") <|> -- /static/FILE
route [ ("picCount", picInfoHandler)
, ("upload" , uploadHandler)
, ("convert", convertHandler)
-- ("instagram/:user", instagramHandler)
]
homeHandler :: Snap ()
homeHandler = writeBS "#This is my first Snap Server!"
picInfoHandler :: Snap ()
picInfoHandler = do
content <- liftIO $ getCurrentDirectory >>= \fp -> getDirectoryContents (fp </> "raw")
let elements = filter (`notElem` [".", ".."]) content
let elementsf = map (\x -> '#' : x ++ "\n") elements
writeBS $ encodeUtf8 $ T.pack $ '#' : show ((length elements) - 1) ++ '\n' : concat elementsf
convertHandler :: Snap ()
convertHandler = do
elements <- liftIO $ do
convertJpgDirToBMP "jpg" "raw"
convertBmpDirToTxt "raw" "raw"
removeWithExtentionAt "raw" ".bmp"
filter (`notElem` [".", ".."]) <$> getDirectoryContents "raw"
writeBS $ encodeUtf8 $ T.pack $ '#' : show (length elements)
uploadHandler :: Snap ()
uploadHandler = method POST uploadPost <|> error405
uploadPost :: Snap ()
uploadPost = do
--files <- handleMultipart defaultUploadPolicy $ \part -> do
-- content <- liftM BS.concat EL.consume
-- return (part, content)
--saveFiles files
mcount <- getPostParam "count"
mbs <- getPostParam "bytestring"
case (mcount, mbs) of
(Just count, Just bs) -> do
liftIO $ putStrLn $ BS8.toString count
-- let name = BS8.toString count
-- saveFile ((undefined, bs), name)
-- liftIO $ jpgToBMP (name ++ ".jpg")
(_) -> return ()
-- saveFiles :: [(PartInfo, ByteString)] -> Snap ()
-- saveFiles fs = mapM_ saveFile (zip fs [0..])
saveFile :: ((PartInfo, BS.ByteString), String) -> Snap ()
saveFile ((_, bs), count) = liftIO $ BS.writeFile (count ++ ".jpg") bs
error405 = genericError 405 "Method Not Allowed"
genericError :: Int -> String -> Snap ()
genericError c s = do
modifyResponse $ setResponseStatus c $ BS8.fromString s
writeText $ T.pack ((show c) ++ " - " ++ s)
r <- getResponse
finishWith r
-- instagramHandler :: Snap ()
-- instagramHandler = do
-- user <- getParam "user"
-- let url = "http://iconosquare.com/feed/" ++ (BS8.toString (fromJust user))
-- urls <- liftIO (getUserPics url)
-- mapM_ writeText urls
--maybe (writeBS "must specify echo/param in URL")
-- writeBS
-- param
| cirquit/Personal-Repository | Haskell/arduino-webserver/old-repo/src/Webserver.hs | mit | 3,306 | 0 | 14 | 746 | 846 | 465 | 381 | 62 | 2 |
f :: Int -> Int
f x =
x
| itchyny/vim-haskell-indent | test/function/function_eq_last.out.hs | mit | 26 | 0 | 5 | 11 | 18 | 9 | 9 | 3 | 1 |
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- 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.
-}
{-# LANGUAGE LambdaCase #-}
module Norm.DoWToWhile where
import Util.Monad (traverseJ)
import Norm.NormCS
stage :: Int
stage = 7
-- | finds all do-while and changes them into while
-- do{s}while(e); => s; while(e){s}
normDoWToWhile :: NormCUR
normDoWToWhile = makeRule' "dowtowhile.stmt.do_while_to_while" [stage]
execDoWToWhile
-- dowtowhile.stmt.do_while_to_while
execDoWToWhile :: NormCUA
execDoWToWhile = normEvery $ traverseJ $ \case
SDo expr stmt -> change [stmt, SWhile expr stmt]
x -> unique [x]
| Centril/DATX02-17-26 | libsrc/Norm/DoWToWhile.hs | gpl-2.0 | 1,378 | 0 | 11 | 275 | 113 | 64 | 49 | 13 | 2 |
{-# 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.AutoScaling.DescribeLaunchConfigurations
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Describes one or more launch configurations. If you omit the list of
-- names, then the call describes all launch configurations.
--
-- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeLaunchConfigurations.html AWS API Reference> for DescribeLaunchConfigurations.
--
-- This operation returns paginated results.
module Network.AWS.AutoScaling.DescribeLaunchConfigurations
(
-- * Creating a Request
describeLaunchConfigurations
, DescribeLaunchConfigurations
-- * Request Lenses
, dlcLaunchConfigurationNames
, dlcNextToken
, dlcMaxRecords
-- * Destructuring the Response
, describeLaunchConfigurationsResponse
, DescribeLaunchConfigurationsResponse
-- * Response Lenses
, dlcrsNextToken
, dlcrsResponseStatus
, dlcrsLaunchConfigurations
) where
import Network.AWS.AutoScaling.Types
import Network.AWS.AutoScaling.Types.Product
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'describeLaunchConfigurations' smart constructor.
data DescribeLaunchConfigurations = DescribeLaunchConfigurations'
{ _dlcLaunchConfigurationNames :: !(Maybe [Text])
, _dlcNextToken :: !(Maybe Text)
, _dlcMaxRecords :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeLaunchConfigurations' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dlcLaunchConfigurationNames'
--
-- * 'dlcNextToken'
--
-- * 'dlcMaxRecords'
describeLaunchConfigurations
:: DescribeLaunchConfigurations
describeLaunchConfigurations =
DescribeLaunchConfigurations'
{ _dlcLaunchConfigurationNames = Nothing
, _dlcNextToken = Nothing
, _dlcMaxRecords = Nothing
}
-- | The launch configuration names.
dlcLaunchConfigurationNames :: Lens' DescribeLaunchConfigurations [Text]
dlcLaunchConfigurationNames = lens _dlcLaunchConfigurationNames (\ s a -> s{_dlcLaunchConfigurationNames = a}) . _Default . _Coerce;
-- | The token for the next set of items to return. (You received this token
-- from a previous call.)
dlcNextToken :: Lens' DescribeLaunchConfigurations (Maybe Text)
dlcNextToken = lens _dlcNextToken (\ s a -> s{_dlcNextToken = a});
-- | The maximum number of items to return with this call. The default is
-- 100.
dlcMaxRecords :: Lens' DescribeLaunchConfigurations (Maybe Int)
dlcMaxRecords = lens _dlcMaxRecords (\ s a -> s{_dlcMaxRecords = a});
instance AWSPager DescribeLaunchConfigurations where
page rq rs
| stop (rs ^. dlcrsNextToken) = Nothing
| stop (rs ^. dlcrsLaunchConfigurations) = Nothing
| otherwise =
Just $ rq & dlcNextToken .~ rs ^. dlcrsNextToken
instance AWSRequest DescribeLaunchConfigurations
where
type Rs DescribeLaunchConfigurations =
DescribeLaunchConfigurationsResponse
request = postQuery autoScaling
response
= receiveXMLWrapper
"DescribeLaunchConfigurationsResult"
(\ s h x ->
DescribeLaunchConfigurationsResponse' <$>
(x .@? "NextToken") <*> (pure (fromEnum s)) <*>
(x .@? "LaunchConfigurations" .!@ mempty >>=
parseXMLList "member"))
instance ToHeaders DescribeLaunchConfigurations where
toHeaders = const mempty
instance ToPath DescribeLaunchConfigurations where
toPath = const "/"
instance ToQuery DescribeLaunchConfigurations where
toQuery DescribeLaunchConfigurations'{..}
= mconcat
["Action" =:
("DescribeLaunchConfigurations" :: ByteString),
"Version" =: ("2011-01-01" :: ByteString),
"LaunchConfigurationNames" =:
toQuery
(toQueryList "member" <$>
_dlcLaunchConfigurationNames),
"NextToken" =: _dlcNextToken,
"MaxRecords" =: _dlcMaxRecords]
-- | /See:/ 'describeLaunchConfigurationsResponse' smart constructor.
data DescribeLaunchConfigurationsResponse = DescribeLaunchConfigurationsResponse'
{ _dlcrsNextToken :: !(Maybe Text)
, _dlcrsResponseStatus :: !Int
, _dlcrsLaunchConfigurations :: ![LaunchConfiguration]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeLaunchConfigurationsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dlcrsNextToken'
--
-- * 'dlcrsResponseStatus'
--
-- * 'dlcrsLaunchConfigurations'
describeLaunchConfigurationsResponse
:: Int -- ^ 'dlcrsResponseStatus'
-> DescribeLaunchConfigurationsResponse
describeLaunchConfigurationsResponse pResponseStatus_ =
DescribeLaunchConfigurationsResponse'
{ _dlcrsNextToken = Nothing
, _dlcrsResponseStatus = pResponseStatus_
, _dlcrsLaunchConfigurations = mempty
}
-- | The token to use when requesting the next set of items. If there are no
-- additional items to return, the string is empty.
dlcrsNextToken :: Lens' DescribeLaunchConfigurationsResponse (Maybe Text)
dlcrsNextToken = lens _dlcrsNextToken (\ s a -> s{_dlcrsNextToken = a});
-- | The response status code.
dlcrsResponseStatus :: Lens' DescribeLaunchConfigurationsResponse Int
dlcrsResponseStatus = lens _dlcrsResponseStatus (\ s a -> s{_dlcrsResponseStatus = a});
-- | The launch configurations.
dlcrsLaunchConfigurations :: Lens' DescribeLaunchConfigurationsResponse [LaunchConfiguration]
dlcrsLaunchConfigurations = lens _dlcrsLaunchConfigurations (\ s a -> s{_dlcrsLaunchConfigurations = a}) . _Coerce;
| fmapfmapfmap/amazonka | amazonka-autoscaling/gen/Network/AWS/AutoScaling/DescribeLaunchConfigurations.hs | mpl-2.0 | 6,551 | 0 | 14 | 1,365 | 908 | 530 | 378 | 109 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_HADDOCK hide #-}
module SecondTransfer.MainLoop.Tokens(
packHeaderTuples
,unpackHeaderTuples
,getHeader
,actionIsForAssociatedStream
,UnpackedNameValueList (..)
,StreamInputToken (..)
,StreamOutputAction (..)
,StreamWorker
,StreamWorkerClass (..)
,LocalStreamId
,GlobalStreamId
) where
import Control.Monad (forM_, replicateM)
import Data.Binary (Binary, get, put)
import Data.Binary.Get (getByteString, getWord32be)
import Data.Binary.Put (putWord32be, putByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString as BS
import Data.Conduit (Conduit)
import Data.List (sortBy, find)
import Data.Word
-- Not to use raw....
newtype UnpackedNameValueList = UnpackedNameValueList [(B.ByteString, B.ByteString)]
deriving Show
data StreamInputToken = Headers_STk UnpackedNameValueList
| Data_Stk B.ByteString
| Finish_Stk
deriving Show
type LocalStreamId = Int
type GlobalStreamId = Int
data StreamOutputAction = SendHeaders_SOA UnpackedNameValueList
| SendAssociatedHeaders_SOA LocalStreamId UnpackedNameValueList
| SendData_SOA B.ByteString
| SendAssociatedData_SOA LocalStreamId B.ByteString
| SendAssociatedFinish_SOA LocalStreamId
| Finish_SOA
deriving Show
actionIsForAssociatedStream :: StreamOutputAction -> Maybe (LocalStreamId, StreamOutputAction)
actionIsForAssociatedStream (SendAssociatedData_SOA stream_id x ) = Just (stream_id, SendData_SOA x)
actionIsForAssociatedStream (SendAssociatedHeaders_SOA stream_id x ) = Just (stream_id, SendHeaders_SOA x)
actionIsForAssociatedStream (SendAssociatedFinish_SOA stream_id ) = Just (stream_id, Finish_SOA )
actionIsForAssociatedStream _ = Nothing
-- | A StreamWorker: a conduit that takes input tokens and answers with output
-- tokens. It can perform I/O.
type StreamWorker = Conduit StreamInputToken IO StreamOutputAction
-- | Sequence of steps to get a StreamWorker. This class is independent of things
-- like the finer details concerning the frames and the streams.
--
-- Todo: although this shows a common pattern, I'm not sure how having a class
-- here helps....
class StreamWorkerClass serviceParams servicePocket sessionPocket |
serviceParams -> sessionPocket servicePocket,
servicePocket -> sessionPocket serviceParams,
sessionPocket -> servicePocket where
initService :: serviceParams -> IO servicePocket
initSession :: servicePocket -> IO sessionPocket
initStream :: servicePocket -> sessionPocket -> IO StreamWorker
instance Binary UnpackedNameValueList where
put unvl =
do
putWord32be length32
forM_ packed $ \ (h,v) -> do
putWord32be $ fromIntegral (BS.length h)
putByteString h
putWord32be $ fromIntegral (BS.length v)
putByteString v
where
length32 = (fromIntegral $ length packed)::Word32
packed = packHeaderTuples unvl
get =
do
entry_count <- getWord32be
packed_entries <- replicateM (fromIntegral entry_count) $ do {
name_length <- getWord32be
; name <- getByteString (fromIntegral name_length)
; value_length <- getWord32be
; value <- getByteString (fromIntegral value_length)
; return (name, value) }
return $ unpackHeaderTuples packed_entries
-- Just puts them together, as per the spec
packHeaderTuples :: UnpackedNameValueList -> [(BS.ByteString, BS.ByteString)]
packHeaderTuples (UnpackedNameValueList uvl) = let
sortFun (h1, _) (h2, _) = compare h1 h2
sorted_uvl = sortBy sortFun uvl
sameName [] = []
sameName ((h, v):rest) = let
(cousins,nocousins) = span (\ (hh, _) -> hh == h ) rest
cousings_value = BS.intercalate "\0" $ v:(map snd cousins)
in
(h, cousings_value):(sameName nocousins)
in
sameName sorted_uvl
-- And unputs them together
unpackHeaderTuples :: [(BS.ByteString, BS.ByteString)] -> UnpackedNameValueList
unpackHeaderTuples [] = UnpackedNameValueList []
unpackHeaderTuples vl = UnpackedNameValueList $ step vl
where
valueSplit v = BS.split 0 v
step [] = []
step ((h,v):rest) = [ (h,vv) | vv <- valueSplit v ] ++ (step rest)
getHeader :: UnpackedNameValueList -> BS.ByteString -> Maybe BS.ByteString
getHeader (UnpackedNameValueList unvl) bs =
case find (\ (x,_) -> x==bs ) unvl of
Just (_, found_value) -> Just found_value
Nothing -> Nothing | shimmercat/second-transfer | hs-src/SecondTransfer/MainLoop/Tokens.hs | bsd-3-clause | 5,141 | 0 | 16 | 1,448 | 1,105 | 607 | 498 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module URI.ByteString.Types where
-------------------------------------------------------------------------------
import Data.ByteString (ByteString)
import Data.Monoid
import Data.Typeable
import Data.Word
import GHC.Generics
-------------------------------------------------------------------------------
import Prelude
-------------------------------------------------------------------------------
-- | Required first component to referring to a specification for the
-- remainder of the URI's components, e.g. "http" or "https"
newtype Scheme = Scheme { schemeBS :: ByteString }
deriving (Show, Eq, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
newtype Host = Host { hostBS :: ByteString }
deriving (Show, Eq, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
-- | While some libraries have chosen to limit this to a Word16, the
-- spec only specifies that the string be comprised of digits.
newtype Port = Port { portNumber :: Int }
deriving (Show, Eq, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
data Authority = Authority {
authorityUserInfo :: Maybe UserInfo
, authorityHost :: Host
, authorityPort :: Maybe Port
} deriving (Show, Eq, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
data UserInfo = UserInfo {
uiUsername :: ByteString
, uiPassword :: ByteString
} deriving (Show, Eq, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
newtype Query = Query { queryPairs :: [(ByteString, ByteString)] }
deriving (Show, Eq, Monoid, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
data URI = URI {
uriScheme :: Scheme
, uriAuthority :: Maybe Authority
, uriPath :: ByteString
, uriQuery :: Query
, uriFragment :: Maybe ByteString
-- ^ URI fragment. Does not include the #
} deriving (Show, Eq, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
data RelativeRef = RelativeRef {
rrAuthority :: Maybe Authority
, rrPath :: ByteString
, rrQuery :: Query
, rrFragment :: Maybe ByteString
-- ^ URI fragment. Does not include the #
} deriving (Show, Eq, Generic, Typeable, Ord)
-------------------------------------------------------------------------------
-- | Options for the parser. You will probably want to use either
-- "strictURIParserOptions" or "laxURIParserOptions"
data URIParserOptions = URIParserOptions {
upoValidQueryChar :: Word8 -> Bool
}
-------------------------------------------------------------------------------
-- | URI Parser Types
-------------------------------------------------------------------------------
data SchemaError = NonAlphaLeading -- ^ Scheme must start with an alphabet character
| InvalidChars -- ^ Subsequent characters in the schema were invalid
| MissingColon -- ^ Schemas must be followed by a colon
deriving (Show, Eq, Read, Generic, Typeable)
-------------------------------------------------------------------------------
data URIParseError = MalformedScheme SchemaError
| MalformedUserInfo
| MalformedQuery
| MalformedFragment
| MalformedHost
| MalformedPort
| MalformedPath
| OtherError String -- ^ Catchall for unpredictable errors
deriving (Show, Eq, Generic, Read, Typeable)
| bitemyapp/uri-bytestring | src/URI/ByteString/Types.hs | bsd-3-clause | 3,997 | 0 | 9 | 845 | 567 | 340 | 227 | 55 | 0 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-------------------------------------------------------------------------------------
-- |
-- Copyright : (c) Hans Hoglund 2012-2014
--
-- License : BSD-style
--
-- Maintainer : hans@hanshoglund.se
-- Stability : experimental
-- Portability : non-portable (TF,GNTD)
--
-------------------------------------------------------------------------------------
module Music.Score.Internal.Export (
extractTimeSignatures,
voiceToBars',
-- separateBars,
spellPitch,
MVoice,
toMVoice,
unvoice,
openCommand
) where
import Prelude hiding (concat, concatMap, foldl,
foldr, mapM, maximum, minimum, sum)
import Control.Applicative
import Control.Lens
import Control.Monad hiding (mapM)
import Control.Monad.Plus
import Data.AffineSpace
import Data.AffineSpace.Point
import Data.Basis
import Data.Either
import Data.Foldable
import Data.Function (on)
import Data.Maybe
import Data.Ord (comparing)
import Data.Ratio
import Data.Semigroup
import Data.String
import Data.Traversable
import Data.Typeable
import Data.VectorSpace
import Music.Score.Articulation
import Music.Time.Internal.Convert
import Music.Score.Dynamics
import Music.Score.Part
import Music.Score.Pitch
import Music.Score.Internal.Quantize
import Music.Score.Ties
import Music.Score.Meta.Time
import Music.Time
import qualified Codec.Midi as Midi
import qualified Data.List as List
import qualified Data.Map as Map
import qualified System.Info as Info
import qualified Text.Pretty as Pretty
import Control.Exception
import Music.Dynamics.Literal
import Music.Pitch.Literal
import Music.Score.Internal.Util
import System.IO.Unsafe
import System.Process
extractTimeSignatures :: Score a -> ([Maybe TimeSignature], [Duration])
extractTimeSignatures score = (barTimeSignatures, barDurations)
where
defaultTimeSignature = time 4 4
timeSignatures = fmap swap
$ view pairs . fuse . reactiveToVoice' (0 <-> (score^.offset))
$ getTimeSignatures defaultTimeSignature score
-- Despite the fuse above we need retainUpdates here to prevent redundant repetition of time signatures
barTimeSignatures = retainUpdates $ getBarTimeSignatures timeSignatures
barDurations = getBarDurations timeSignatures
-- | Convert a voice to a list of bars using the given bar durations.
voiceToBars' :: Tiable a => [Duration] -> Voice (Maybe a) -> [[(Duration, Maybe a)]]
voiceToBars' barDurs = fmap (map (^. from note) . (^. notes)) . splitTiesAt barDurs
-- TODO remove prime from name
-- | Basic spelling for integral types.
spellPitch :: Integral a => a -> (a, a, a)
spellPitch p = (
pitchClass,
alteration,
octave
)
where
octave = (p `div` 12) - 1
semitone = p `mod` 12
pitchClass = fromStep major semitone
alteration = semitone - step major pitchClass
step xs p = xs !! (fromIntegral p `mod` length xs)
fromStep xs p = fromIntegral $ fromMaybe (length xs - 1) $ List.findIndex (>= p) xs
scaleFromSteps = snd . List.mapAccumL add 0
where
add a x = (a + x, a + x)
major = scaleFromSteps [0,2,2,1,2,2,2,1]
type MVoice a = Voice (Maybe a)
toMVoice :: (Semigroup a, Transformable a) => Score a -> MVoice a
toMVoice = scoreToVoice . simultaneous
unvoice :: Voice b -> [(Duration, b)]
unvoice = toListOf (notes . traverse . from note)
-- unvoice = fmap (^. from note) . (^. notes)
{-# DEPRECATED unvoice "Use 'unsafeEventsV'" #-}
openCommand :: String
openCommand = case Info.os of
"darwin" -> "open"
"linux" -> "xdg-open"
{-
-- TODO any version and/or OS
hasMuseScore = do
result <- try (readProcess "ls" ["/Applications/MuseScore.app"] "")
return $ case result of
Left e -> (e::SomeException) `assumed` False
Right _ -> True
hasSibelius = do
result <- try (readProcess "ls" ["/Applications/Sibelius 7.app"] "")
return $ case result of
Left e -> (e::SomeException) `assumed` False
Right _ -> True
assumed = flip const
-}
-- JUNK
| music-suite/music-score | src/Music/Score/Internal/Export.hs | bsd-3-clause | 4,770 | 0 | 13 | 1,399 | 900 | 530 | 370 | 86 | 2 |
module Events where
import GHC.RTS.Events.Analysis
runMachine :: Machine s e -> [e] -> s
runMachine machine = getState . validate machine
where
getState (Left (s,_)) = s
getState (Right s) = s
| mainland/dph | dph-event-seer/src/Events.hs | bsd-3-clause | 202 | 0 | 10 | 41 | 83 | 45 | 38 | 6 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Layout.Grid
-- Copyright : (c) 2014 Pontus Granström
-- License : BSD-style (see LICENSE)
-- Maintainer : pnutus@gmail.com
--
-- Functions for effortlessly putting lists of diagrams in a grid layout.
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Layout.Grid
(
gridCat
, gridCat'
, gridSnake
, gridSnake'
, gridWith
, sameBoundingRect
, sameBoundingSquare
) where
import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.List.Split (chunksOf)
import Diagrams.Prelude
-- * Grid Layout
-- | Puts a list of diagrams in a grid, left-to-right, top-to-bottom.
-- The grid is as close to square as possible.
--
-- > import Diagrams.TwoD.Layout.Grid
-- > gridCatExample = gridCat $ map (flip regPoly 1) [3..10]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridCatExample.svg#diagram=gridCatExample&width=200>>
gridCat
:: TypeableFloat n
=> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridCat diagrams = gridCat' (intSqrt $ length diagrams) diagrams
-- | Same as 'gridCat', but with a specified number of columns.
--
-- > import Diagrams.TwoD.Layout.Grid
-- > gridCatExample' = gridCat' 4 $ map (flip regPoly 1) [3..10]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridCatExample'.svg#diagram=gridCatExample'&width=200>>
gridCat'
:: TypeableFloat n
=> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridCat' = gridAnimal id
-- | Puts a list of diagrams in a grid, alternating left-to-right
-- and right-to-left. Useful for comparing sequences of diagrams.
-- The grid is as close to square as possible.
--
-- > import Diagrams.TwoD.Layout.Grid
-- > gridSnakeExample = gridSnake $ map (flip regPoly 1) [3..10]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridSnakeExample.svg#diagram=gridSnakeExample&width=200>>
gridSnake
:: TypeableFloat n
=> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridSnake diagrams = gridSnake' (intSqrt $ length diagrams) diagrams
-- | Same as 'gridSnake', but with a specified number of columns.
--
-- > import Diagrams.TwoD.Layout.Grid
-- > gridSnakeExample' = gridSnake' 4 $ map (flip regPoly 1) [3..10]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridSnakeExample'.svg#diagram=gridSnakeExample'&width=200>>
gridSnake'
:: TypeableFloat n
=> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridSnake' = gridAnimal (everyOther reverse)
-- | Generalisation of gridCat and gridSnake to not repeat code.
gridAnimal
:: TypeableFloat n
=> ([[QDiagram b V2 n Any]] -> [[QDiagram b V2 n Any]]) -> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridAnimal rowFunction cols = vcat . map hcat . rowFunction
. chunksOf cols . sameBoundingRect . padList cols mempty
-- | `gridWith f (cols, rows)` uses `f`, a function of two
-- zero-indexed integer coordinates, to generate a grid of diagrams
-- with the specified dimensions.
gridWith
:: TypeableFloat n
=> (Int -> Int -> QDiagram b V2 n Any) -> (Int, Int)
-> QDiagram b V2 n Any
gridWith f (cols, rows) = gridCat' cols diagrams
where
diagrams = [ f x y | y <- [0..rows - 1] , x <- [0..cols - 1] ]
-- * Bounding boxes
-- | Make all diagrams have the same bounding square,
-- one that bounds them all.
sameBoundingSquare
:: forall b n. TypeableFloat n
=> [QDiagram b V2 n Any]
-> [QDiagram b V2 n Any]
sameBoundingSquare diagrams = map frameOne diagrams
where
biggest = maximumBy (comparing maxDim) diagrams
maxDim diagram = max (width diagram) (height diagram)
centerP = centerPoint biggest
padSquare = (square (maxDim biggest) :: D V2 n) # phantom
frameOne = atop padSquare . moveOriginTo centerP
-- | Make all diagrams have the same bounding rect,
-- one that bounds them all.
sameBoundingRect
:: forall n b. TypeableFloat n
=> [QDiagram b V2 n Any]
-> [QDiagram b V2 n Any]
sameBoundingRect diagrams = map frameOne diagrams
where
widest = maximumBy (comparing width) diagrams
tallest = maximumBy (comparing height) diagrams
(xCenter :& _) = coords (centerPoint widest)
(_ :& yCenter) = coords (centerPoint tallest)
padRect = (rect (width widest) (height tallest) :: D V2 n) # phantom
frameOne = atop padRect . moveOriginTo (xCenter ^& yCenter)
-- * Helper functions.
intSqrt :: Int -> Int
intSqrt = round . sqrt . (fromIntegral :: Int -> Float)
everyOther :: (a -> a) -> [a] -> [a]
everyOther f = zipWith ($) (cycle [id, f])
padList :: Int -> a -> [a] -> [a]
padList m padding xs = xs ++ replicate (mod (- length xs) m) padding
| diagrams/diagrams-contrib | src/Diagrams/TwoD/Layout/Grid.hs | bsd-3-clause | 4,927 | 1 | 11 | 1,005 | 1,084 | 585 | 499 | 76 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module T16104_Plugin (plugin) where
import GhcPlugins
import Data.Bits
plugin :: Plugin
plugin = defaultPlugin {installCoreToDos = install}
where install _ todos = return (test : todos)
test = CoreDoPluginPass "Test" check
check :: ModGuts -> CoreM ModGuts
check m = do mbN <- thNameToGhcName 'complement
case mbN of
Just _ -> liftIO $ putStrLn "Found complement!"
Nothing -> error "Failed to locate complement"
return m
| sdiehl/ghc | testsuite/tests/plugins/T16104-plugin/T16104_Plugin.hs | bsd-3-clause | 575 | 0 | 13 | 190 | 137 | 70 | 67 | 14 | 2 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "src/System/PosixCompat/Time.hs" #-}
{-# LANGUAGE CPP #-}
{-|
This module makes the operations exported by @System.Posix.Time@
available on all platforms. On POSIX systems it re-exports operations from
@System.Posix.Time@, on other platforms it emulates the operations as far
as possible.
-}
module System.PosixCompat.Time (
epochTime
) where
import System.Posix.Time
| phischu/fragnix | tests/packages/scotty/System.PosixCompat.Time.hs | bsd-3-clause | 470 | 0 | 4 | 118 | 22 | 16 | 6 | 6 | 0 |
module Peano.Infer where
import qualified Peano.Type as T
import qualified Peano.Data as D
import Autolib.Reporter
import Autolib.ToDoc
type Env = String -> Maybe T.Type
std :: Env
std "s" = Just $ T.App T.Nat T.Nat
std "z" = Just $ T.Nat
std _ = Nothing
typeof :: Env -> D.Exp -> Reporter T.Type
typeof env x = do
inform $ toDoc x <+> text "::" <+> text "?"
t <- nested 4 $ typeof_ env x
inform $ toDoc x <+> text "::" <+> toDoc t
return t
typeof_ env x = case x of
D.Const n -> return T.Nat
D.Ref n -> case env n of
Just v -> return v
Nothing -> reject $ hsep [ text "Name", text n, text "nicht gebunden" ]
D.Abs n t b -> do
b <- typeof ( extend n t env ) b
return $ T.App t b
D.App f a ->
with_app ( typeof env f ) $ \ arg res ->
with_val ( typeof env a ) $ \ a -> do
when ( arg /= a ) $ reject $ text "Argumenttyp" </> vcat
[ text "erwartet:" </> toDoc arg
, text "erhalten:" </> toDoc a
]
return res
D.Fold z s ->
with_val ( typeof env z ) $ \ z ->
with_app ( typeof env s ) $ \ arg res -> do
when ( z /= arg ) $ reject
$ text "fold-Typschema paßt nicht (z /= arg)"
when ( z /= res ) $ reject
$ text "fold-Typschema paßt nicht (z /= res)"
return $ T.App T.Nat z
extend n v env =
\ m -> if n == m then Just v else env m
with_val :: Reporter T.Type
-> ( T.Type -> Reporter T.Type )
-> Reporter T.Type
with_val v k = do
x <- v
k x
with_app :: Reporter T.Type
-> ( T.Type -> T.Type -> Reporter T.Type )
-> Reporter T.Type
with_app v k = do
x <- v
case x of
T.App arg res -> k arg res
_ -> reject $ text "Funktionstyp erwartet"
| Erdwolf/autotool-bonn | src/Peano/Infer.hs | gpl-2.0 | 1,871 | 0 | 19 | 688 | 772 | 368 | 404 | 55 | 6 |
module Options.Misc where
import Types
miscOptions :: [Flag]
miscOptions =
[ flag { flagName = "-jN"
, flagDescription =
"When compiling with :ghc-flag:`--make`, compile ⟨N⟩ modules in parallel."
, flagType = DynamicFlag
}
, flag { flagName = "-fno-hi-version-check"
, flagDescription = "Don't complain about ``.hi`` file mismatches"
, flagType = DynamicFlag
}
, flag { flagName = "-fhistory-size"
, flagDescription = "Set simplification history size"
, flagType = DynamicFlag
}
, flag { flagName = "-fno-ghci-history"
, flagDescription =
"Do not use the load/store the GHCi command history from/to "++
"``ghci_history``."
, flagType = DynamicFlag
}
, flag { flagName = "-fno-ghci-sandbox"
, flagDescription =
"Turn off the GHCi sandbox. Means computations are run in "++
"the main thread, rather than a forked thread."
, flagType = DynamicFlag
}
, flag { flagName = "-freverse-errors"
, flagDescription =
"Display errors in GHC/GHCi sorted by reverse order of "++
"source code line numbers."
, flagType = DynamicFlag
, flagReverse = "-fno-reverse-errors"
}
]
| sgillespie/ghc | utils/mkUserGuidePart/Options/Misc.hs | bsd-3-clause | 1,328 | 0 | 8 | 427 | 178 | 114 | 64 | 30 | 1 |
{- |
Module : $Header$
Description : union of signature parts
Copyright : (c) Christian Maeder and Uni Bremen 2003-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : experimental
Portability : portable
merging parts of local environment
-}
module HasCASL.Merge
( merge
, mergeTypeInfo
, mergeTypeDefn
, mergeOpInfo
, addUnit
) where
import Common.Id
import Common.DocUtils
import Common.Result
import HasCASL.As
import HasCASL.Le
import HasCASL.AsUtils
import HasCASL.PrintLe
import HasCASL.ClassAna
import HasCASL.TypeAna
import HasCASL.Builtin
import HasCASL.MapTerm
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Maybe
import Control.Monad (foldM)
mergeTypeInfo :: ClassMap -> TypeInfo -> TypeInfo -> Result TypeInfo
mergeTypeInfo cm t1 t2 = do
let o = keepMinKinds cm [otherTypeKinds t1, otherTypeKinds t2]
s = Set.union (superTypes t1) $ superTypes t2
k <- minRawKind "type raw kind" (typeKind t1) $ typeKind t2
d <- mergeTypeDefn (typeDefn t1) $ typeDefn t2
return $ TypeInfo k o s d
mergeTypeDefn :: TypeDefn -> TypeDefn -> Result TypeDefn
mergeTypeDefn d1 d2 = case (d1, d2) of
(_, DatatypeDefn _) -> return d2
(PreDatatype, _) -> fail "expected data type definition"
(_, PreDatatype) -> return d1
(NoTypeDefn, _) -> return d2
(_, NoTypeDefn) -> return d1
(AliasTypeDefn s1, AliasTypeDefn s2) -> do
s <- mergeAlias s1 s2
return $ AliasTypeDefn s
(_, _) -> mergeA "TypeDefn" d1 d2
mergeAlias :: Type -> Type -> Result Type
mergeAlias s1 s2 = if eqStrippedType s1 s2 then return s1 else
fail $ "wrong type" ++ expected s1 s2
mergeOpBrand :: OpBrand -> OpBrand -> OpBrand
mergeOpBrand b1 b2 = case (b1, b2) of
(Pred, _) -> Pred
(_, Pred) -> Pred
(Op, _) -> Op
(_, Op) -> Op
_ -> Fun
mergeOpDefn :: OpDefn -> OpDefn -> Result OpDefn
mergeOpDefn d1 d2 = case (d1, d2) of
(NoOpDefn b1, NoOpDefn b2) -> do
let b = mergeOpBrand b1 b2
return $ NoOpDefn b
(SelectData c1 s, SelectData c2 _) -> do
let c = Set.union c1 c2
return $ SelectData c s
(Definition b1 e1, Definition b2 e2) -> do
d <- mergeTerm Hint e1 e2
let b = mergeOpBrand b1 b2
return $ Definition b d
(NoOpDefn b1, Definition b2 e2) -> do
let b = mergeOpBrand b1 b2
return $ Definition b e2
(Definition b1 e1, NoOpDefn b2) -> do
let b = mergeOpBrand b1 b2
return $ Definition b e1
(ConstructData _, SelectData _ _) ->
fail "illegal selector as constructor redefinition"
(SelectData _ _, ConstructData _) ->
fail "illegal constructor as selector redefinition"
(ConstructData _, _) -> return d1
(_, ConstructData _) -> return d2
(SelectData _ _, _) -> return d1
(_, SelectData _ _) -> return d2
addUnit :: ClassMap -> TypeMap -> TypeMap
addUnit cm = fromMaybe (error "addUnit") . maybeResult . mergeTypeMap cm bTypes
mergeOpInfos :: Set.Set OpInfo -> Set.Set OpInfo -> Result (Set.Set OpInfo)
mergeOpInfos s1 s2 = if Set.null s1 then return s2 else do
let (o, os) = Set.deleteFindMin s1
(es, us) = Set.partition ((opType o ==) . opType) s2
s <- mergeOpInfos os us
r <- foldM mergeOpInfo o $ Set.toList es
return $ Set.insert r s
mergeOpInfo :: OpInfo -> OpInfo -> Result OpInfo
mergeOpInfo o1 o2 = do
let as = Set.union (opAttrs o1) $ opAttrs o2
d <- mergeOpDefn (opDefn o1) $ opDefn o2
return $ OpInfo (opType o1) as d
mergeTypeMap :: ClassMap -> TypeMap -> TypeMap -> Result TypeMap
mergeTypeMap = mergeMap . mergeTypeInfo
merge :: Env -> Env -> Result Env
merge e1 e2 = do
clMap <- mergeClassMap (classMap e1) $ classMap e2
tMap <- mergeTypeMap clMap (typeMap e1) $ typeMap e2
let tAs = filterAliases tMap
as <- mergeMap mergeOpInfos (assumps e1) $ assumps e2
bs <- mergeMap (\ i1 i2 -> if i1 == i2 then return i1 else
fail "conflicting operation for binder syntax")
(binders e1) $ binders e2
return initialEnv
{ classMap = clMap
, typeMap = tMap
, assumps = Map.map (Set.map $ mapOpInfo (id, expandAliases tAs)) as
, binders = bs }
mergeA :: (Pretty a, Eq a) => String -> a -> a -> Result a
mergeA str t1 t2 = if t1 == t2 then return t1 else
fail ("different " ++ str ++ expected t1 t2)
mergeTerm :: DiagKind -> Term -> Term -> Result Term
mergeTerm k t1 t2 = if t1 == t2 then return t1 else
Result [Diag k ("different terms" ++ expected t1 t2) $ getRange t2] $ Just t2
| keithodulaigh/Hets | HasCASL/Merge.hs | gpl-2.0 | 4,634 | 0 | 15 | 1,164 | 1,692 | 840 | 852 | 111 | 11 |
import System.IO
import Network.HaskellNet.SMTP
import Text.Mime
import qualified Data.ByteString.Char8 as BS
import Codec.Binary.Base64.String
smtpServer = "outmail.f2s.com"
sendFrom = "test@test.org"
sendTo = ["wrwills@gmail.com"]
main = do
con <- connectSMTP smtpServer
message <- BS.readFile "example/message.txt"
messageHtml <- BS.readFile "example/message.html"
let textP = SinglePart [("Content-Type", "text/plain; charset=utf-8")] message
let htmlP = SinglePart [("Content-Type", "text/html; charset=utf-8")] messageHtml
let msg = MultiPart [("From", "Network.HaskellNet <" ++ sendFrom ++ ">"),("Subject","Test")] [htmlP, textP]
sendMail sendFrom sendTo (BS.pack $ show $ showMime "utf-8" msg) con
closeSMTP con
--let msg = ([("From", "Network.HaskellNet <" ++ sendFrom ++ ">"),("Subject","Test")], MultiPart [] [textP, htmlP])
--sendMail sendFrom sendTo (BS.pack $ show $ showMessage "utf-8" msg) con
-- let msg = ([("From", "Network.HaskellNet <" ++ sendFrom ++ ">"),("Subject","Test")], BS.pack "\r\nhello 算法是指完成一个任from haskellnet")
--htmlP = SinglePart [("Content-Type", "text/html; charset=utf-8", "Content-Transfer-Encoding", ""] BS.pack $ encode $
| beni55/HaskellNet | example/smtp.hs | bsd-3-clause | 1,224 | 0 | 14 | 174 | 222 | 120 | 102 | 17 | 1 |
yes = a >>= return . bob | mpickering/hlint-refactor | tests/examples/Default13.hs | bsd-3-clause | 24 | 0 | 6 | 6 | 14 | 7 | 7 | 1 | 1 |
module Main where
import qualified System.Directory as Dir
import qualified System.Environment as Env
import System.Exit (exitWith)
import System.IO (hPutStrLn, stderr, stdin, stdout)
import qualified System.Process as Proc
import qualified Elm.Compiler.Version as Compiler
import qualified Elm.Package as Pkg
main :: IO ()
main =
do allArgs <- Env.getArgs
case allArgs of
[] ->
putStrLn usageMessage
command : args ->
attemptToRun command args
attemptToRun :: String -> [String] -> IO ()
attemptToRun command args =
do found <- Dir.findExecutable ("elm-" ++ command)
case found of
Nothing ->
hPutStrLn stderr $
"Could not find command `" ++ command ++ "`. Maybe there is a typo?\n\n\
\Default commands include:\n\n"
++ availableCommands ++
"\nWhen you try to run the command `" ++ command ++ "` we actually search for an\n\
\ executable named elm-" ++ command ++ ". Are you able to run elm-" ++ command ++ "?\n\
\ Is it on your PATH?"
Just path ->
let createProc =
(Proc.proc path args)
{ Proc.std_in = Proc.UseHandle stdin
, Proc.std_out = Proc.UseHandle stdout
, Proc.std_err = Proc.UseHandle stderr
}
in
do (_, _, _, handle) <- Proc.createProcess createProc
exitWith =<< Proc.waitForProcess handle
usageMessage :: String
usageMessage =
"Elm Platform " ++ (Pkg.versionToString Compiler.version) ++ " - a way to run all Elm tools\n\
\\n\
\Usage: elm <command> [<args>]\n\
\\n\
\Available commands include:\n\n"
++ availableCommands ++
"\nYou can learn more about a specific command by running things like:\n\
\\n\
\ elm make --help\n\
\ elm package --help\n\
\ elm <command> --help\n\
\\n\
\In all these cases we are simply running 'elm-<command>' so if you create an\n\
\executable named 'elm-foobar' you will be able to run it as 'elm foobar' as\n\
\long as it appears on your PATH."
availableCommands :: String
availableCommands =
" make Compile an Elm file or project into JS or HTML\n\
\ package Manage packages from <http://package.elm-lang.org>\n\
\ reactor Develop with compile-on-refresh and time-travel debugging\n\
\ repl A REPL for running individual expressions\n"
| laszlopandy/elm-compiler | src/CommandLineRouter.hs | bsd-3-clause | 2,447 | 2 | 21 | 687 | 403 | 212 | 191 | 42 | 2 |
-- |
-- Copyright : (c) 2011 Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
-- Portability : portable
--
-- Pretty-printing with support for highlighting keywords and comments.
-- Currently this module is not functional on itself, but geared towards its
-- use in Text.PrettyPrint.Html.
module Text.PrettyPrint.Highlight (
-- * Highlight style
HighlightStyle(..)
-- * HighlightDocument class
, HighlightDocument(..)
, comment
, keyword
, operator
, comment_
, keyword_
, operator_
, opParens
, module Text.PrettyPrint.Class
) where
import Text.PrettyPrint.Class
-- | Currently we support only keywords, operators, and comments.
data HighlightStyle = Keyword | Comment | Operator
deriving( Eq, Ord, Show )
class Document d => HighlightDocument d where
-- 'highlight' @style d@ marks that the document @d@ should be highlighted
-- using the @style@.
highlight :: HighlightStyle -> d -> d
instance HighlightDocument Doc where
highlight _ = id
------------------------------------------------------------------------------
-- General highlighters
------------------------------------------------------------------------------
comment, keyword, operator :: HighlightDocument d => d -> d
comment = highlight Comment
keyword = highlight Keyword
operator = highlight Operator
comment_, keyword_, operator_ :: HighlightDocument d => String -> d
comment_ = comment . text
keyword_ = keyword . text
operator_ = operator . text
opParens :: HighlightDocument d => d -> d
opParens d = operator_ "(" <> d <> operator_ ")"
| rsasse/tamarin-prover | lib/utils/src/Text/PrettyPrint/Highlight.hs | gpl-3.0 | 1,641 | 0 | 8 | 303 | 277 | 164 | 113 | 28 | 1 |
module Test8 where
f l = let x = 56 in x
| SAdams601/HaRe | old/testing/refacSlicing/Test8AST.hs | bsd-3-clause | 42 | 0 | 8 | 13 | 23 | 12 | 11 | 2 | 1 |
module Warning
{-# WARNING ["You are configuring this package without cabal-doctest installed.",
"The doctests test-suite will not work as a result.",
"To fix this, install cabal-doctest before configuring."] #-}
() where
| Javran/twitter-conduit | Warning.hs | bsd-2-clause | 256 | 0 | 3 | 65 | 8 | 6 | 2 | -1 | -1 |
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, StandaloneDeriving, FlexibleInstances #-}
-- Test Trac #2856
module T2856 where
import Data.Ratio
----------------------
class C a where
data D a
instance C Bool where
newtype D Bool = DInt Int deriving (Eq, Show, Num)
instance C a => C [a] where
newtype D [a] = DList (Ratio a) deriving (Eq, Show, Num)
----------------------
data family W a
newtype instance W Bool = WInt Int deriving( Eq, Show )
newtype instance W [a] = WList (Ratio a) deriving( Eq, Show )
deriving instance Num (W Bool)
deriving instance (Integral a, Num a) => Num (W [a])
-- Integral needed because superclass Eq needs it,
-- because of the stupid context on Ratio
| lukexi/ghc | testsuite/tests/deriving/should_compile/T2856.hs | bsd-3-clause | 718 | 0 | 8 | 140 | 225 | 124 | 101 | 14 | 0 |
{-# LANGUAGE PartialTypeSignatures, NamedWildCards, DatatypeContexts #-}
module WildcardInADTContext2 where
data (Eq _a) => Foo a = Foo { getFoo :: a }
| ghc-android/ghc | testsuite/tests/partial-sigs/should_fail/WildcardInADTContext2.hs | bsd-3-clause | 153 | 0 | 8 | 23 | 30 | 19 | 11 | 3 | 0 |
module Settings.Development where
import Prelude
development :: Bool
development =
#if DEVELOPMENT
True
#else
False
#endif
production :: Bool
production = not development
| zhy0216/haskell-learning | yosog/Settings/Development.hs | mit | 178 | 0 | 5 | 30 | 35 | 22 | 13 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
--import Uri
import Control.Applicative
import Data.Attoparsec.Text as A
import Data.Bits ((.|.), (.&.), shiftL)
import Data.Char (chr, digitToInt, isAlpha, isAlphaNum, isHexDigit)
--import Data.Attoparsec.Combinator
import Data.Text
--import Data.Text.Read as T
type Scheme = Text
type Username = Text
type Password = Text
type Hostname = Text
type Port = Int
parseUri :: Parser (Scheme, Maybe Username, Maybe Password, Hostname, Maybe Port)
parseUri = do
scheme <- parseScheme
(user, pwd, hostname, port) <- parseAuthority
return (scheme, user, pwd, hostname, port)
parseScheme :: Parser Text
parseScheme = do
schemeFirst <- A.satisfy isAlpha
schemeRest <- A.takeWhile isAlphaNum
_ <- string "://"
return $ schemeFirst `cons` schemeRest
parseAuthority :: Parser (Maybe Username, Maybe Password, Hostname, Maybe Port)
parseAuthority = do
(username, pwd) <- parseUserInfo
hostname <- parseHostname
port <- parsePort
return (username, pwd, hostname, port)
parseUserInfo :: Parser (Maybe Username, Maybe Password)
parseUserInfo = do
username <- A.takeWhile isUserInfoChar
_ <- char ':'
password <- A.takeWhile isUserInfoChar
_ <- char '@'
return (Just username, Just password)
<|> do
username <- A.takeWhile isUserInfoChar
_ <- char '@'
return (Just username, Nothing)
<|>
return (Nothing, Nothing)
parseHostname :: Parser Text
parseHostname = do
hostname <- A.takeWhile isHostnameChar
return hostname
parsePort :: Parser (Maybe Port)
parsePort = do
_ <- char ':'
port <- decimal
return $ Just port
<|> do
return Nothing
isUserInfoChar :: Char -> Bool
isUserInfoChar c =
((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) ||
((c >= '$') && (c <= '.')) || -- one of: $%&'()*+,-.
(c == '!') || (c == ';') || (c == '=') || (c == '_') || (c == '~') ||
(isAlphaNum c)
isHostnameChar :: Char -> Bool
isHostnameChar c =
((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) ||
((c >= '$') && (c <= '.')) || -- one of: $%&'()*+,-.
(c == '!') || (c == ';') || (c == '=') || (c == '_') || (c == '~') ||
(isAlphaNum c)
isPathChar :: Char -> Bool
isPathChar c =
((c >= 'a') && (c <= '~')) || -- one of: abcdefghijklmnopqrstuvwxyz{|}~
((c >= '@') && (c <= '_')) || -- one of: @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
((c >= '$') && (c <= ';')) || -- one of: $%&'()*+,-./0123456789:;
(c == '=') || (c == '!') ||
(isAlphaNum c)
isQueryChar :: Char -> Bool
isQueryChar c =
((c >= 'a') && (c <= '~')) || -- one of: abcdefghijklmnopqrstuvwxyz{|}~
((c >= '?') && (c <= '_')) || -- one of: ?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
((c >= '\'') && (c <= ';')) || -- one of: '()*+,-./0123456789:;
(c == '$') || (c == '%') || (c == '!') ||
(isAlphaNum c)
isFragmentChar :: Char -> Bool
isFragmentChar c =
((c >= 'a') && (c <= '~')) || -- one of: abcdefghijklmnopqrstuvwxyz{|}~
((c >= '?') && (c <= '_')) || -- one of: ?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
((c >= '#') && (c <= ';')) || -- one of: #$%&'()*+,-./0123456789:;
(c == '=') || (c == '!') ||
(isAlphaNum c)
-- adapated from http://hackage.haskell.org/package/network
-- by Graham Klyne, BSD-style
decode :: [Char] -> [Char]
decode [] = ""
decode s@(c : cs) = case decodeChar s of
Just (byte, rest) -> decodeUtf8 byte rest
Nothing -> c : decode cs
decodeChar :: [Char] -> Maybe (Int, [Char])
decodeChar ('%' : h : l : s) | isHexDigit h && isHexDigit l =
Just (digitToInt h * 16 + digitToInt l, s)
decodeChar _ = Nothing
-- Adapted from http://hackage.haskell.org/package/utf8-string
-- by Eric Mertens, BSD3
decodeUtf8 :: Int -> [Char] -> [Char]
decodeUtf8 c rest
| c < 0x80 = chr c : decode rest
| c < 0xc0 = replacement_character : decode rest
| c < 0xe0 = multi1
| c < 0xf0 = multi_byte 2 0xf 0x800
| c < 0xf8 = multi_byte 3 0x7 0x10000
| c < 0xfc = multi_byte 4 0x3 0x200000
| c < 0xfe = multi_byte 5 0x1 0x4000000
| otherwise = replacement_character : decode rest
where
replacement_character = '\xfffd'
multi1 = case decodeChar rest of
Just (c1, ds) | c1 .&. 0xc0 == 0x80 ->
let d = ((fromEnum c .&. 0x1f) `shiftL` 6) .|. fromEnum (c1 .&. 0x3f)
in if d >= 0x000080 then toEnum d : decode ds
else replacement_character : decode ds
_ -> replacement_character : decode rest
multi_byte :: Int -> Int -> Int -> [Char]
multi_byte i mask overlong =
aux i rest (decodeChar rest) (c .&. mask)
where
aux 0 rs _ acc
| overlong <= acc && acc <= 0x10ffff &&
(acc < 0xd800 || 0xdfff < acc) &&
(acc < 0xfffe || 0xffff < acc) = chr acc : decode rs
| otherwise = replacement_character : decode rs
aux n _ (Just (r, rs)) acc
| r .&. 0xc0 == 0x80 = aux (n-1) rs (decodeChar rs)
$! shiftL acc 6 .|. (r .&. 0x3f)
aux _ rs _ _ = replacement_character : decode rs
| bjorg/HPlug | uriparser.hs | mit | 5,343 | 0 | 20 | 1,515 | 2,030 | 1,061 | 969 | 127 | 5 |
{-# LANGUAGE BangPatterns, MultiWayIf #-}
module Data.Smashy.Set where
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VM
import qualified Data.Vector.Storable.ByteString as BV
import Data.Word
import qualified System.Directory as SD
import qualified Data.Serialize as CE
import qualified Data.ByteString.Char8 as C8
import Data.Smashy.Types
import Data.Smashy.Constants
import Data.Smashy.Encoding
import Data.Smashy.Shared
import Data.Smashy.Util
import Prelude hiding (elem)
toDisk :: HashSet a -> IO (HashSet a)
toDisk d@(HashSet (Disk _) _ _) = return d
toDisk (HashSet (Hybrid fp)
(HashTable hashSize hashData hashSpace)
termList) = do
let newLoc = Disk fp
hashDest <- getMem (getHashLocation newLoc) (fromIntegral hashSize)
VM.copy hashDest hashData
unmapData hashData
return (HashSet newLoc
(HashTable hashSize hashDest hashSpace)
termList)
close :: HashSet a -> IO ()
close (HashSet loc
(HashTable hashSize hashData hashSpace)
(TermList termPosition termSize termData termSpace)) = do
unmapData hashData
unmapData termData
case getBasePath loc of
Nothing -> return ()
Just fp -> writeFile (fp ++ "/metaset")
(show (hashSize, hashSpace,
termPosition, termSize, termSpace))
open :: Location -> IO (HashSet a)
open loc = case getBasePath loc of
Nothing -> error "Can't 'open' a RAM hashset"
Just fp -> do
(hashSize, hashSpace, termPosition, termSize, termSpace) <- fmap read (readFile (fp ++ "/metaset"))
hashData <- getMem (getHashLocation loc) (fromIntegral hashSize)
termData <- getMem (getKeysLocation loc) termSize
return $ HashSet loc
(HashTable hashSize hashData hashSpace)
(TermList termPosition termSize termData termSpace)
new :: Location -> IO (HashSet a)
new loc = do
clear loc
let (hashLocation, termLocation) =
case loc of
Ram -> (InRam, InRam)
Hybrid fp -> (InRam, OnDisk (fp ++ keyFileName))
Disk fp -> (OnDisk (fp++hashFileName), OnDisk (fp ++ keyFileName))
hashData <- getMem hashLocation startingHashSize
termData <- getMem termLocation startingKeyListSize >>= pad0
return $ HashSet loc
(HashTable (fromIntegral startingHashSize) hashData startingHashSize)
(TermList 1 startingKeyListSize termData (startingKeyListSize - 1))
rehash :: HashSet a -> IO (HashSet a)
rehash (HashSet loc ht@(HashTable sz dat _) tl) = do
let newSize = getHashSize ht * 2 - 1
case getHashLocation loc of
OnDisk fp -> do
let tempHashFile = fp ++ "_"
removeIfExists tempHashFile
xt <- getMem (OnDisk tempHashFile) (fromIntegral newSize)
ht' <- goHash tl (HashTable newSize xt (fromIntegral newSize))
unmapData dat
SD.renameFile tempHashFile fp
return $ HashSet loc ht' tl
InRam -> do
xt <- getMem InRam (fromIntegral newSize)
ht' <- goHash tl (HashTable newSize xt (fromIntegral newSize))
unmapData dat
return $ HashSet loc ht' tl
where
goHash :: TermList a -> HashTable Word32 -> IO (HashTable Word32)
goHash (TermList _ _ kdat _) (HashTable sz' dat' spc') = goHash' 0 (fromIntegral sz) spc'
where
goHash' :: Int -> Int -> Int -> IO (HashTable Word32)
goHash' !p s !sp
| p == s = return (HashTable sz' dat' sp)
| otherwise = do
hd <- VM.read dat p
if hd == 0
then goHash' (p+1) s sp
else do
k <- termAt kdat (fromIntegral hd)
writeHash Nothing k hd
goHash' (p+1) s (sp-1)
where
writeHash :: Maybe Word32 -> Escaped -> Word32 -> IO ()
writeHash mph ek hd = do
let h = (case mph of
Nothing -> hash ek
Just ph -> ph + 1) `mod` sz'
VM.read dat' (fromIntegral h) >>= \x ->
if x == 0
then VM.write dat' (fromIntegral h) hd
else writeHash (Just h) ek hd
{-# RULES "elem/bytestring" forall hs k. elem hs k = elemBs hs k #-}
{-# INLINE[1] elem #-}
elem :: (CE.Serialize a) => HashSet a -> a -> IO Bool
elem hs k = elemBs hs . CE.encode $ k
elemBs :: HashSet a -> C8.ByteString -> IO Bool
elemBs hs k = do
let ek = if C8.any isSpecial k
then fastEscape k
else Escaped $ k `C8.snoc` sepChar
po <- probeForNextSetPosition True hs ek
case po of
KeyFoundAt _ -> return True
FreeAt _ -> return False
x -> error . concat $ ["The impossible happened: lkup received: ", show x]
{-# RULES "storeOne/storeOneBs" storeOne = storeOneBs #-}
{-# INLINE[1] storeOne #-}
storeOne :: (CE.Serialize a) => HashSet a -> a -> IO (HashSet a)
storeOne hs = storeOneBs hs . CE.encode
storeOneBs :: HashSet a -> C8.ByteString -> IO (HashSet a)
storeOneBs hs_ bs =
storeOneIntern hs_ (if C8.any isSpecial bs
then fastEscape bs
else Escaped $ bs `C8.snoc` sepChar)
where
storeOneIntern :: HashSet a -> Escaped -> IO (HashSet a)
storeOneIntern hs@(HashSet loc ht tl) ew =
probeForNextSetPosition False hs ew >>= \po ->
case po of
FreeAt h -> do
let termPos = getPosition tl
VM.write (getHashData ht) (fromIntegral h) (fromIntegral termPos)
termPos' <- writeTerm (getData tl) termPos ew
return (HashSet loc (decrTableSpace ht) (advanceTo tl termPos'))
KeyFoundAt _ -> return hs
TermListFull ->
case getKeysLocation loc of
InRam -> expandRamList tl >>= \tl' -> storeOneIntern (HashSet loc ht tl') ew
OnDisk fp -> expandDiskTermList fp tl >>= \tl' -> storeOneIntern (HashSet loc ht tl') ew
HashTableFull -> rehash hs >>= \hs' -> storeOneIntern hs' ew
probeForNextSetPosition :: Bool -> HashSet a -> Escaped -> IO PositionInfo
probeForNextSetPosition onlyReading (HashSet _ ht tl) ew
| onlyReading = notfull
| getSpace tl < escLen ew = return TermListFull
| isHashFull ht = return HashTableFull
| otherwise = notfull
where
notfull = probeForNextSetPosition' (-1) (hash ew `mod` getHashSize ht)
probeForNextSetPosition' :: Word32 -> Word32 -> IO PositionInfo
probeForNextSetPosition' firstAttempt h
| h == firstAttempt = return HashTableFull
| otherwise = do
hashEntry <- VM.read (getHashData ht) (fromIntegral h) :: IO Word32
if hashEntry == 0
then return $ FreeAt h
else do
matched <- compareTerm (getData tl) (fromIntegral hashEntry) ew
case matched of
Matched -> return (KeyFoundAt h)
_ -> probeForNextSetPosition'
(if firstAttempt == -1 then h else firstAttempt)
(if h + 1 == getHashSize ht then 0 else h + 1)
{-# RULES "terms/Bs" terms = termsBs #-}
{-# INLINE[1] terms #-}
terms :: CE.Serialize k => a -> (a -> k -> IO a) -> HashSet k -> IO a
terms acc f hs = go acc (getData . getSetTerms $ hs) (getPosition . getSetTerms $ hs) f 1
where
go :: CE.Serialize k => a -> VM.IOVector Word8 -> Int -> (a -> k -> IO a) -> Int -> IO a
go !acc dat len f n = do
mn <- getWord dat len n
case mn of
Nothing -> return acc
Just (w,ni) ->
case CE.decode . fastUnescape $ w of
Left l -> error l
Right r -> do
acc' <- f acc r
go acc' dat len f ni
termsBs :: a -> (a -> C8.ByteString -> IO a) -> HashSet C8.ByteString -> IO a
termsBs acc f hs = goBs acc (getData . getSetTerms $ hs) (getPosition . getSetTerms $ hs) f 1
where
goBs :: a -> VM.IOVector Word8 -> Int -> (a -> C8.ByteString -> IO a) -> Int -> IO a
goBs !acc dat len f n = do
mn <- getWord dat len n
case mn of
Nothing -> return acc
Just (w,ni) -> do
acc' <- f acc (fastUnescape w)
goBs acc' dat len f ni
{-# INLINABLE getWord #-}
getWord :: VM.IOVector Word8 -> Int -> Int -> IO (Maybe (Escaped, Int))
getWord vm len a
| a >= VM.length vm = return Nothing
| otherwise = do
z <- nextWord' False a
if z == -1
then return Nothing
else do
buf <- VS.freeze . VM.slice a z $ vm
return (Just (Escaped $ BV.vectorToByteString buf, a + z + 1))
where
nextWord' :: Bool -> Int -> IO Int
nextWord' True z = nextWord' False (z+1)
nextWord' False z
| z >= len = return (-1)
| otherwise =
VM.read vm z >>= \v ->
case v of
10 -> return (z-a)
92 -> nextWord' True (z+1)
_ -> nextWord' False (z+1) | jahaynes/smashy | src/Data/Smashy/Set.hs | mit | 9,747 | 145 | 23 | 3,581 | 3,041 | 1,550 | 1,491 | 204 | 6 |
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
{-# LANGUAGE PatternSynonyms #-}
module Language.Plover.ParserTypes
(IntType(..), FloatType(..), ArgDir(..), Expr, pattern PExpr, wrapPos,
Variable, UnOp(..), BinOp(..), Expr'(..), Arg(..), pattern VoidExpr, integer, float,
)
where
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Pos
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Language
import Control.Monad
import Control.Applicative hiding (many, (<|>))
import Data.Maybe
import Data.Traversable
import Data.Foldable
import Data.Typeable
import Data.Data
import Data.Ratio (numerator, denominator)
import Text.PrettyPrint hiding (integer, float)
import Data.Tag
import Data.Fix
import Language.Plover.Types (IntType(..), FloatType(..), defaultIntType, defaultFloatType, ArgDir(..), PP(..))
type Expr = FixTagged SourcePos Expr'
pattern PExpr tag a = FTag tag a
deriving instance Typeable Fix -- Can't use `Expr` here
deriving instance Data Expr
wrapPos :: SourcePos -> Expr' Expr -> Expr
wrapPos = newTag
type Variable = String
data UnOp = Neg
| Pos
| Deref
| Addr
| Transpose
| Inverse
deriving (Show, Eq, Typeable, Data)
data BinOp = Add
| Sub
| Mul
| Div
| Mod
| Hadamard
| Pow
| Concat
| Type
| And
| Or
| EqualOp
| NEqOp
| LTOp
| LTEOp
| Storing
deriving (Show, Eq, Typeable, Data)
data Expr' a = Vec [(Variable,a)] a
| For [(Variable,a)] a
| While a a
-- Elementary Expressions
| Ref Variable
| T
| Hole
| NoisyHole
| IntLit IntType Integer
| FloatLit FloatType Double
| BoolLit Bool
| StrLit String
| VecLit [a]
| If a a a
| Specialize String [(a, a)]
| Return a
| Assert a
-- Operators
| UnExpr UnOp a
| BinExpr BinOp a a
-- Structures
| Field a String
-- Vectors
| Index a a
| Tuple [a]
| Range (Maybe a) (Maybe a) (Maybe a)
-- Calling
| App a [Arg a]
-- Sequencing
| SeqExpr [a]
-- State
| DefExpr a a
| StoreExpr a a
-- Declarations
| Extern a
| Static a
| Struct Variable [a]
| Typedef Variable a
| Import String
| InlineC String
-- Antiquotation
| Antiquote String
deriving (Eq, Show, Functor, Traversable, Typeable, Foldable, Data)
data Arg a = ImpArg a
| Arg ArgDir a
deriving (Eq, Show, Functor, Traversable, Typeable, Foldable, Data)
pattern VoidExpr = Tuple []
instance Num Expr where
x * y = PExpr NoTag (BinExpr Mul x y)
x + y = PExpr NoTag (BinExpr Add x y)
fromInteger x = PExpr NoTag (IntLit defaultIntType x)
abs = undefined
signum = undefined
negate x = PExpr NoTag (UnExpr Neg x)
instance Fractional Expr where
x / y = PExpr NoTag (BinExpr Div x y)
fromRational x = PExpr NoTag (FloatLit defaultFloatType $ fromIntegral (numerator x) / fromIntegral (denominator x))
integer :: Integer -> Expr' a
integer x = IntLit IDefault x
float :: Double -> Expr' a
float x = FloatLit defaultFloatType x
--instance PP a => PP (PosExpr' a) where
-- pretty (PosExpr' x) = pretty x
instance PP a => PP (Expr' a) where
pretty (Ref v) = text v
pretty T = text "T"
pretty Hole = text "_"
pretty NoisyHole = text "__"
pretty (IntLit t x) = parens $ text $ "IntLit " ++ show t ++ " " ++ show x
pretty (FloatLit t x) = parens $ text $ "(FloatLit " ++ show t ++ " " ++ show x
pretty (BoolLit b) = parens $ text $ "BoolLit " ++ show b
pretty (StrLit s) = parens $ text $ "StrLit " ++ show s
pretty (VecLit xs) = parens $ text "VecLit" <+> sep (map pretty xs)
pretty (If a b c) = parens $ (text "if" <+> nest 3 (pretty a)) $$ (nest 1 (vcat [text "then" <+> pretty b, text "else" <+> pretty c]))
pretty (Specialize v cases) = parens $ (text $ "specialize " ++ v) $$ (nest 1 (vcat [pretty ca <+> text "->" <+> nest 2 (pretty ex) | (ca, ex) <- cases]))
pretty (Return a) = parens $ (text "return" <+> nest 7 (pretty a))
pretty (Assert a) = parens $ (text "assert" <+> nest 7 (pretty a))
pretty (UnExpr op exp) = parens $ hang (text $ show op) 1 (pretty exp)
pretty (BinExpr op a b) = parens $ hang (text $ f op) (length (f op) + 1) $ sep [pretty a, pretty b]
where
f Add = "+"
f Sub = "-"
f Mul = "*"
f Hadamard = ".*"
f Div = "/"
f Mod = "%"
f Pow = "^"
f EqualOp = "=="
f LTOp = "<"
f LTEOp = "<="
f Type = "::"
f op = show op
pretty (Field e field) = parens $ hang (text "Field") 1 $ sep [pretty e, text $ show field]
pretty (Index e ei) = parens $ hang (text "Index") 1 $ sep [nest 5 $ pretty e, pretty ei]
pretty (Tuple []) = text "Void"
pretty (Tuple exps) = parens $ hang (text "Tuple") 1 $ sep (map pretty exps)
pretty (Range a b c) = parens $ hang (text "Range") 1 $
hcat $ punctuate (text ":") [p a, p b, p c]
where p Nothing = text "Nothing"
p (Just x) = pretty x
pretty (Vec vs e) = parens $ hang (text "Vec") 1 $ sep [nest 3 $ sep (map iter vs) <+> text "->", pretty e]
where iter (v, e) = parens $ text v <+> text "in" <+> pretty e
pretty (For vs e) = parens $ hang (text "For") 1 $ sep [nest 3 $ sep (map iter vs) <+> text "->", pretty e]
where iter (v, e) = parens $ text v <+> text "in" <+> pretty e
pretty (While test body) = parens $ hang (text "While") 1 $ sep [nest 5 $ pretty test, pretty body]
pretty (App f args) = parens $ hang (pretty f) 0 $ sep (map pretty args)
pretty (SeqExpr args) = parens $ hang (text "Seq") 4 $ vcat $ punctuate semi (map pretty args)
pretty (DefExpr a b) = parens $ hang (text "Def") 1 $ sep [nest 3 $ pretty a, pretty b]
pretty (StoreExpr a b) = parens $ hang (text "Store") 1 $ sep [nest 5 $ pretty a, pretty b]
pretty (Extern a) = parens $ hang (text "Extern") 1 $ pretty a
pretty (Static a) = parens $ hang (text "Static") 1 $ pretty a
pretty (Struct n a) = parens $ (text "Struct" <+> text n) $$ nest 1 (vcat $ map pretty a)
pretty (Typedef n t) = parens $ (text "Typedef" <+> text n) <+> nest 1 (pretty t)
pretty (Import s) = parens $ text $ "Import " ++ s
pretty (InlineC s) = parens $ text "InlineC" <+> text (show s)
pretty (Antiquote s) = parens $ text "Antiquote" <+> text s
instance PP a => PP (Arg a) where
pretty (Arg dir a) = parens $ text (show dir) <+> pretty a
pretty (ImpArg a) = braces $ pretty a
| swift-nav/plover | src/Language/Plover/ParserTypes.hs | mit | 7,167 | 0 | 15 | 2,161 | 2,861 | 1,478 | 1,383 | 166 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE PatternSynonyms #-}
module Hash where
import Data.Bits (Bits, xor)
import Data.Map.Lazy as Map (Map, fromList, lookup)
import Data.Set (empty, insert, member)
import GameState
import System.Random
import Types (Point (..))
type RandomKey a = (Random a, Bounded a, Ord a)
generateHashes :: (RandomGen g, RandomKey b) => g -> [b]
generateHashes = filterHashes . randomRs (minBound, maxBound)
filterHashes :: Ord b => [b] -> [b]
filterHashes = helpFilter empty
where
helpFilter _ [] = []
helpFilter s (x:xs) = if member x s
then helpFilter s xs
else x : helpFilter (insert x s) xs
data StateElement = SFilledCell Point
| SPiecePos Point
| SPieceRot ACWRotation
| SNumPieces Int
deriving (Eq, Ord, Show, Read)
pattern SFilled x y = SFilledCell (Point x y)
pattern SFloat x y = SPiecePos (Point x y)
generatorKey :: BoardDimensions -> StateElement -> Int
generatorKey (BDim w h) = generatorKey' w h
generatorKey' :: Int -> Int -> StateElement -> Int
generatorKey' w h (SFilled x y) = x + (w * y) `mod` (w * h)
generatorKey' w h (SFloat x y) = (w * h) + (x + (w * y) `mod` (w * h))
generatorKey' w h (SPieceRot r) = (2 * w * h) + fromACWRot r
generatorKey' w h (SNumPieces x) = (2 * w * h) + 6 + x
elems :: BoardDimensions -> GameState -> [StateElement]
elems (BDim w h) gs = pp : pr : np : fc
where
fc = map SFilledCell [Point x y | y <- [0 .. h - 1], x <- [0 .. w - 1]]
pp = SPiecePos $ getPieceLoc gs
pr = SPieceRot $ getPieceOrientation gs
np = SNumPieces $ getPieceCounter gs
populateHashMap :: (RandomGen g, RandomKey b) => g -> Map Int b
populateHashMap gen = fromList $ zip [0..] $ generateHashes gen
hashState :: Bits b => BoardDimensions -> Map Int b -> GameState -> Maybe b
hashState bd m gs = sequence generators >>= (Just . foldl1 xor)
where
generators = map (`Map.lookup` m) genKeys
genKeys = map (generatorKey bd) $ elems bd gs
| sebmathguy/icfp-2015 | library/Hash.hs | mit | 2,166 | 0 | 12 | 635 | 855 | 454 | 401 | 44 | 3 |
module Main where
import Ringo.Parser (eval)
import System.IO (hFlush, stdout)
main :: IO ()
main = do welcomeMes
repl
welcomeMes :: IO ()
welcomeMes = putStr "Welcome!\n"
repl :: IO ()
repl = do putStr "$ "
hFlush stdout
line <- getLine
(putStrLn.eval) line
repl
| gogotanaka/Ringo | src/Interpreter.hs | mit | 317 | 0 | 9 | 98 | 114 | 57 | 57 | 14 | 1 |
module Pivotal.Utilities
(
apiToken
) where
import System.Environment (getEnv)
apiToken :: IO String
apiToken = getEnv "PIVOTAL_TRACKER_API_TOKEN"
| toddmohney/tracker_radiator | Pivotal/Utilities.hs | mit | 165 | 0 | 5 | 35 | 37 | 21 | 16 | 6 | 1 |
module SudokuAmb where
import Data.List
import Control.Monad
numlist = [1..9]
allp (i,j) = concat [block,line,col]
where block = [(i + dx - mod i 3,j + dy - mod j 3) |dx<-[0..2],dy<-[0..2]]
line = [(i,dy)| dy <- [0..9]]
col = [(dx,j)| dx<-[0..9]]
get pos all = (map head).group.sort $ [ k | (xy,k)<- all, elem xy $ allp pos ]
refresh pos k all = [ if (not $ elem xy $ allp pos) || elem k ks then (xy,ks) else (xy,k:ks) | (xy,ks) <- all]
solve ([],taken) = [taken]
solve (empty,taken) = concat $ do
i<-numlist
guard $ (not $ elem i used)
return $ solve (refresh pos i rst,(pos,i):taken)
where (pos,used):rst = sortBy (\a b -> compare (length.snd $ b) (length.snd $ a)) empty
solveStr :: [Int] -> [Int]
solveStr = (getout 0). head . solve . fill . (getin 0)
fill (empty,taken) = ([(pos,get pos taken) | pos <- empty],taken)
getin i [] = ([],[])
getin i (x:xs) = if x/=0 then (empty,(pos,x):taken)
else (pos:empty,taken)
where (empty,taken) = getin (i+1) xs
pos = (div i 9, mod i 9)
getout 81 taken = []
getout i taken = k:(getout (i+1) taken)
where pos = (div i 9, mod i 9)
k = head [ k|(xy,k)<-taken,xy==pos]
| ztuowen/sudoku | SudokuAmb.hs | mit | 1,196 | 0 | 13 | 296 | 769 | 419 | 350 | 28 | 2 |
{-# LANGUAGE CPP, TypeFamilies, DeriveDataTypeable #-}
module PGIP.GraphQL.Result.OMS where
import PGIP.GraphQL.Result.ConservativityStatus
import PGIP.GraphQL.Result.FileRange
import PGIP.GraphQL.Result.IdReference
import PGIP.GraphQL.Result.Language
import PGIP.GraphQL.Result.LocIdReference
import PGIP.GraphQL.Result.Logic
import PGIP.GraphQL.Result.Mapping
import PGIP.GraphQL.Result.ReasoningAttempt
import PGIP.GraphQL.Result.Sentence
import PGIP.GraphQL.Result.StringReference
import Data.Data
data OMS = OMS { conservativityStatus :: ConservativityStatus
, consistencyCheckAttempts :: [ReasoningAttempt]
, description :: Maybe String
, displayName :: String
, freeNormalForm :: Maybe LocIdReference
, freeNormalFormSignatureMorphism :: Maybe IdReference
, labelHasFree :: Bool
, labelHasHiding :: Bool
, language :: Language
, locId :: String
, logic :: Logic
, mappingsSource :: [Mapping]
, mappingsTarget :: [Mapping]
, name :: String
, nameExtension :: String
, nameExtensionIndex :: Int
, nameFileRange :: Maybe FileRange
, normalForm :: Maybe LocIdReference
, normalFormSignatureMorphism :: Maybe IdReference
, origin :: String
, sentences :: [Sentence]
, serialization :: Maybe StringReference
, omsSignature :: IdReference
} deriving (Show, Typeable, Data)
| spechub/Hets | PGIP/GraphQL/Result/OMS.hs | gpl-2.0 | 1,622 | 0 | 9 | 488 | 279 | 180 | 99 | 37 | 0 |
{-# OPTIONS -w -O0 #-}
{- |
Module : ATC/Id.der.hs
Description : generated Typeable, ShATermConvertible instances
Copyright : (c) DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable(overlapping Typeable instances)
Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible
for the type(s):
'Common.Id.Pos'
'Common.Id.Range'
'Common.Id.Token'
'Common.Id.Id'
-}
{-
Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!!
dependency files:
Common/Id.hs
-}
module ATC.Id () where
import ATerm.Lib
import Common.Id
import Data.Char
import Data.List (isPrefixOf)
import Data.Typeable
import qualified Data.Set as Set
{-! for Common.Id.Pos derive : Typeable !-}
{-! for Common.Id.Range derive : Typeable !-}
{-! for Common.Id.Token derive : Typeable !-}
{-! for Common.Id.Id derive : Typeable !-}
{-! for Common.Id.Pos derive : ShATermConvertible !-}
{-! for Common.Id.Range derive : ShATermConvertible !-}
{-! for Common.Id.Token derive : ShATermConvertible !-}
{-! for Common.Id.Id derive : ShATermConvertible !-}
| nevrenato/Hets_Fork | ATC/Id.der.hs | gpl-2.0 | 1,180 | 0 | 5 | 181 | 58 | 41 | 17 | 8 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Sepa.Debtor
( -- Debtor
mkDebtor,
Debtor, DebtorId,
firstName,
lastName,
mandates,
registrationDate,
validDebtor,
validDebtorName,
getActiveMandate,
-- Mandate
mkMandate,
Mandate, MandateId,
mandateRef,
iban,
signatureDate,
lastTimeActive,
isNew,
validMandate,
updateMandatesLastTimeActive,
-- SpanishBank
mkSpanishBank,
SpanishBank, SpanishBankId,
fourDigitsCode,
bic,
bankName,
validSpanishBank,
validSpanishBankBic
) where
import ClassyPrelude
import Control.Lens
import qualified Data.Char as CH (isDigit, isUpper)
import qualified Data.List as LT
import qualified Data.Map as M
import qualified Data.Time.Calendar as T
import Database.Persist ((=.))
import Database.Persist.MongoDB (nestEq, (->.))
import qualified Database.Persist.MongoDB as DB
import qualified Database.Persist.Quasi as DB (upperCaseSettings)
import qualified Database.Persist.TH as DB (mkPersist, mpsGenerateLenses,
mpsPrefixFields,
persistFileWith, share)
import Sepa.MongoSettings
import Sepa.SpanishIban
-- WARNING: the use of lenses (setters) can violate the invariants of the Abstract Data
-- Types in this module.
DB.share [DB.mkPersist mongoSettings { DB.mpsGenerateLenses = True
, DB.mpsPrefixFields = False }]
$(DB.persistFileWith DB.upperCaseSettings "Sepa/Debtor.persistent")
-- Debtors
mkDebtor :: Text -> Text -> [Mandate] -> T.Day -> Debtor
mkDebtor firstName_ lastName_ mandates_ registrationDate_ =
assert (validDebtor firstName_ lastName_ mandates_ registrationDate_)
$ Debtor firstName_ lastName_ mandates_ registrationDate_
validDebtor :: Text -> Text -> [Mandate] -> T.Day -> Bool
validDebtor firstName_ lastName_ mandates_ _registrationDate_ =
validDebtorName firstName_ lastName_
&& validMandateList mandates_
validDebtorName :: Text -> Text -> Bool
validDebtorName firstName_ lastName_ =
not (null firstName_) && length firstName_ <= maxLengthFirstName
&& not (null lastName_) && length lastName_ <= maxLengthLastName
&& length lastName_ + length firstName_ <= maxLengthFullName
where maxLengthFirstName = 40
maxLengthLastName = 60
maxLengthFullName = 68 -- SEPA constraint (2.72) is 70, keep room for ", "
-- | We want mandates ordered from more recent to oldest.
validMandateList :: [Mandate] -> Bool
validMandateList mandates_ = LT.and lastTimePairs
where
lastTimeActiveList = map (^. lastTimeActive) mandates_
lastTimeActiveList' = Nothing : Nothing : lastTimeActiveList
lastTimeActiveList'' = Nothing : lastTimeActiveList'
lastTimePairs = LT.zipWith newerThan lastTimeActiveList'' lastTimeActiveList'
newerThan Nothing _ = True
newerThan (Just _) Nothing = False
newerThan (Just d1) (Just d2) = T.diffDays d1 d2 >= 0
getActiveMandate :: T.Day -> Debtor -> Maybe Mandate
getActiveMandate today debtor =
-- Better pass today as an argument, to not make a lot of system calls.
-- zonedTime <- T.getZonedTime
-- let today = T.localDay (T.zonedTimeToLocalTime zonedTime)
-- Mandates are ordered, with most recently active first
case debtor ^. mandates of
(mandate : _) -> case mandate ^. lastTimeActive of
-- 36 months == 3 years
Just lta -> if T.addDays (3 * 365) lta > today then Just mandate else Nothing
Nothing -> Just mandate
[] -> Nothing -- No mandates yet
-- Mandates
mkMandate :: Text -> Text -> T.Day -> Maybe T.Day -> Mandate
mkMandate ref iban_ signatureDate_ lastTimeActive_ =
assert (validMandate ref iban_ signatureDate_ lastTimeActive_)
$ Mandate ref iban_ signatureDate_ lastTimeActive_
-- In fact more characters are allowed in mandate reference code (but not all), but for
-- simplicity we constraint us to digits + space.
validMandate :: Text -> Text -> T.Day -> Maybe T.Day -> Bool
validMandate ref iban_ _signatureDate_ _lastTimeActive_ =
length ref == 35 && all (\c -> CH.isDigit c || c == ' ') ref
&& validSpanishIban iban_
isNew :: (Contravariant f, Functor f, Conjoined p) => p Bool (f Bool) -> p Mandate (f Mandate)
isNew = to _isNew
_isNew :: Mandate -> Bool
_isNew = isNothing . (^. lastTimeActive)
--updateMandateLastTimeActive :: DB.ConnectionPool -> Text -> T.Day -> IO ()
updateMandatesLastTimeActive mandateRefs newDay = do
debtors <- DB.selectList ([] :: [DB.Filter Debtor]) []
let mandateAL = concatMap (\(DB.Entity k d) -> fmap (\m -> (m ^. mandateRef, (k, d))) (d ^. mandates)) debtors
let debtorsMap = M.fromList mandateAL
forM_ mandateRefs $ \ref ->
case M.lookup ref debtorsMap of
Nothing -> error "updateMandatesLastTimeActive: no debtor"
Just (k, d) -> do
let updateMandate m = if m ^. mandateRef == ref
then m & lastTimeActive .~ Just newDay
else m
let mandates' = map updateMandate (d ^. mandates)
DB.update k [Mandates =. mandates']
-- forM_ mandateRefs $ \ref -> do
-- mDebtorE <- DB.selectFirst [Mandates ->. MandateRef `nestEq` ref] []
-- case mDebtorE of
-- Nothing -> error "updateMandateLastTimeActive: no debtor"
-- Just (DB.Entity debtorKey debtor) -> do
-- let mandates' = case debtor ^. mandates of
-- (m : ms) -> (m & lastTimeActive .~ Just newDay) : ms
-- [] -> error "updateMandateLastTimeActive: debtor with no mandates"
-- DB.update debtorKey [Mandates =. mandates']
-- Spanish banks
mkSpanishBank :: Text -> Text -> Text -> SpanishBank
mkSpanishBank fourDigitsCode_ bic_ bankName_ =
assert (validSpanishBank fourDigitsCode_ bic_ bankName_)
$ SpanishBank fourDigitsCode_ bic_ bankName_
validSpanishBank :: Text -> Text -> Text -> Bool
validSpanishBank fourDigitsCode_ bic_ bankName_ =
length fourDigitsCode_ == 4 && all CH.isDigit fourDigitsCode_
&& validSpanishBankBic bic_
&& length bankName_ <= maxLengthBankName
where maxLengthBankName = 100
validSpanishBankBic :: Text -> Bool
validSpanishBankBic bic_ = length bic_ == 11
&& all CH.isUpper institution
&& country == "ES"
&& all isDigitOrUpper location
&& all isDigitOrUpper branch
where (institution, suffix) = splitAt 4 bic_
(country, suffix') = splitAt 2 suffix
(location, branch) = splitAt 2 suffix'
isDigitOrUpper c = CH.isDigit c || CH.isUpper c
| gmarpons/sepa-debits | Sepa/Debtor.hs | gpl-3.0 | 7,132 | 19 | 15 | 1,944 | 1,496 | 815 | 681 | 127 | 4 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
-- |
-- Copyright : (c) 2011 Benedikt Schmidt & Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <beschmi@gmail.com>
-- Portability : GHC only
--
-- Guarded formulas.
module Theory.Constraint.System.Guarded (
-- * Guarded formulas
Guarded(..)
, LGuarded
, LNGuarded
, GAtom(..)
-- ** Smart constructors
, gfalse
, gtrue
, gdisj
, gconj
, gex
, gall
, gnot
, ginduct
, formulaToGuarded
, formulaToGuarded_
-- ** Transformation
, simplifyGuarded
, simplifyGuardedOrReturn
, mapGuardedAtoms
, atomToGAtom
, sortGAtoms
-- ** Queries
, isConjunction
, isDisjunction
, isAllGuarded
, isExGuarded
, isSafetyFormula
, guardFactTags
-- ** Conversions to non-bound representations
, bvarToLVar
-- , unbindAtom
, openGuarded
-- ** Substitutions
, substBound
, substBoundAtom
, substFree
, substFreeAtom
-- ** Skolemization
, unskolemizeLNGuarded
, applySkGuarded
, skolemizeGuarded
, skolemizeTerm
, skolemizeFact
, matchAction
, matchTerm
, applySkAction
, applySkTerm
-- ** Pretty-printing
, prettyGuarded
) where
import Control.Applicative
import Control.Arrow
import Control.DeepSeq
import Control.Monad.Except
import Control.Monad.Fresh (MonadFresh, scopeFreshness)
import qualified Control.Monad.Trans.PreciseFresh as Precise (Fresh, evalFresh, evalFreshT)
import Debug.Trace
import GHC.Generics (Generic)
import Data.Data
import Data.Binary
import Data.Either (partitionEithers)
-- import Data.Foldable (Foldable(..), foldMap)
import Data.List
import qualified Data.DList as D
-- import Data.Monoid (Monoid(..))
-- import Data.Traversable hiding (mapM, sequence)
import Logic.Connectives
import Text.PrettyPrint.Highlight
import Theory.Model
-- Control.Monad.Fail import will become redundant in GHC 8.8+
import qualified Control.Monad.Fail as Fail
import Data.Functor.Identity
instance Fail.MonadFail Identity where
fail = Fail.fail
------------------------------------------------------------------------------
-- Types
------------------------------------------------------------------------------
data Guarded s c v = GAto (Atom (VTerm c (BVar v)))
| GDisj (Disj (Guarded s c v))
| GConj (Conj (Guarded s c v))
| GGuarded Quantifier [s] [Atom (VTerm c (BVar v))] (Guarded s c v)
-- ^ Denotes @ALL xs. as => gf@ or @Ex xs. as & gf&
-- depending on the 'Quantifier'.
-- We assume that all bound variables xs occur in
-- f@i atoms in as.
deriving (Eq, Ord, Show, Generic)
instance (NFData s, NFData c, NFData v) => NFData (Guarded s c v)
instance (Binary s, Binary c, Binary v) => Binary (Guarded s c v)
isConjunction :: Guarded s c v -> Bool
isConjunction (GConj _) = True
isConjunction _ = False
isDisjunction :: Guarded s c v -> Bool
isDisjunction (GDisj _) = True
isDisjunction _ = False
isExGuarded :: Guarded s c v -> Bool
isExGuarded (GGuarded Ex _ _ _) = True
isExGuarded _ = False
isAllGuarded :: Guarded s c v -> Bool
isAllGuarded (GGuarded All _ _ _) = True
isAllGuarded _ = False
-- | Check whether the guarded formula is closed and does not contain an
-- existential quantifier. This under-approximates the question whether the
-- formula is a safety formula. A safety formula @phi@ has the property that a
-- trace violating it can never be extended to a trace satisfying it.
isSafetyFormula :: HasFrees (Guarded s c v) => Guarded s c v -> Bool
isSafetyFormula gf0 =
null (frees [gf0]) && noExistential gf0
where
noExistential (GAto _ ) = True
noExistential (GGuarded Ex _ _ _) = False
noExistential (GGuarded All _ _ gf) = noExistential gf
noExistential (GDisj disj) = all noExistential $ getDisj disj
noExistential (GConj conj) = all noExistential $ getConj conj
-- | All 'FactTag's that are used in guards.
guardFactTags :: Guarded s c v -> [FactTag]
guardFactTags =
D.toList .
foldGuarded mempty (mconcat . getDisj) (mconcat . getConj) getTags
where
getTags _qua _ss atos inner =
mconcat [ D.singleton tag | Action _ (Fact tag _ _) <- atos ] <> inner
-- | Atoms that are allowed as guards.
data GAtom t = GEqE t t | GAction t (Fact t)
deriving (Eq, Show, Ord)
isGAction :: GAtom t -> Bool
isGAction (GAction _ _) = True
isGAction _ = False
-- | Convert 'Atom's to 'GAtom's, if possible.
atomToGAtom :: Show t => Atom t -> GAtom t
atomToGAtom = conv
where conv (EqE s t) = GEqE s t
conv (Action i f) = GAction i f
conv a = error $ "atomsToGAtom: "++ show a
++ "is not a guarded atom."
-- | Stable sort that ensures that actions occur before equations.
sortGAtoms :: [GAtom t] -> [GAtom t]
sortGAtoms = uncurry (++) . partition isGAction
------------------------------------------------------------------------------
-- Folding
------------------------------------------------------------------------------
-- | Fold a guarded formula.
foldGuarded :: (Atom (VTerm c (BVar v)) -> b)
-> (Disj b -> b)
-> (Conj b -> b)
-> (Quantifier -> [s] -> [Atom (VTerm c (BVar v))] -> b -> b)
-> Guarded s c v
-> b
foldGuarded fAto fDisj fConj fGuarded =
go
where
go (GAto a) = fAto a
go (GDisj disj) = fDisj $ fmap go disj
go (GConj conj) = fConj $ fmap go conj
go (GGuarded qua ss as gf) = fGuarded qua ss as (go gf)
-- | Fold a guarded formula with scope info.
-- The Integer argument denotes the number of
-- quantifiers that have been encountered so far.
foldGuardedScope :: (Integer -> Atom (VTerm c (BVar v)) -> b)
-> (Disj b -> b)
-> (Conj b -> b)
-> (Quantifier -> [s] -> Integer -> [Atom (VTerm c (BVar v))] -> b -> b)
-> Guarded s c v
-> b
foldGuardedScope fAto fDisj fConj fGuarded =
go 0
where
go !i (GAto a) = fAto i a
go !i (GDisj disj) = fDisj $ fmap (go i) disj
go !i (GConj conj) = fConj $ fmap (go i) conj
go !i (GGuarded qua ss as gf) =
fGuarded qua ss i' as (go i' gf)
where
i' = i + fromIntegral (length ss)
-- | Map a guarded formula with scope info.
-- The Integer argument denotes the number of
-- quantifiers that have been encountered so far.
mapGuardedAtoms :: (Integer -> Atom (VTerm c (BVar v))
-> Atom (VTerm d (BVar w)))
-> Guarded s c v
-> Guarded s d w
mapGuardedAtoms f =
foldGuardedScope (\i a -> GAto $ f i a) GDisj GConj
(\qua ss i as gf -> GGuarded qua ss (map (f i) as) gf)
------------------------------------------------------------------------------
-- Instances
------------------------------------------------------------------------------
{-
instance Functor (Guarded s c) where
fmap f = foldGuarded (GAto . fmap (fmapTerm (fmap (fmap f)))) GDisj GConj
(\qua ss as gf -> GGuarded qua ss (map (fmap (fmapTerm (fmap (fmap f)))) as) gf)
-}
instance Foldable (Guarded s c) where
foldMap f = foldGuarded (foldMap (foldMap (foldMap (foldMap f))))
(mconcat . getDisj)
(mconcat . getConj)
(\_qua _ss as b -> foldMap (foldMap (foldMap (foldMap (foldMap f)))) as `mappend` b)
traverseGuarded :: (Applicative f, Ord c, Ord v, Ord a)
=> (a -> f v) -> Guarded s c a -> f (Guarded s c v)
traverseGuarded f = foldGuarded (liftA GAto . traverse (traverseTerm (traverse (traverse f))))
(liftA GDisj . sequenceA)
(liftA GConj . sequenceA)
(\qua ss as gf -> GGuarded qua ss <$> traverse (traverse (traverseTerm (traverse (traverse f)))) as <*> gf)
instance Ord c => HasFrees (Guarded (String, LSort) c LVar) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc _ _ = const mempty
mapFrees f = traverseGuarded (mapFrees f)
-- FIXME: remove name hints for variables for saturation?
type LGuarded c = Guarded (String, LSort) c LVar
------------------------------------------------------------------------------
-- Substitutions of bound for free and vice versa
------------------------------------------------------------------------------
-- | @substBoundAtom s a@ substitutes each occurence of a bound variables @i@
-- in @dom(s)@ with the corresponding free variable @x=s(i)@ in the atom @a@.
substBoundAtom :: Ord c => [(Integer,LVar)] -> Atom (VTerm c (BVar LVar)) -> Atom (VTerm c (BVar LVar))
substBoundAtom s = fmap (fmapTerm (fmap subst))
where subst bv@(Bound i') = case lookup i' s of
Just x -> Free x
Nothing -> bv
subst fv = fv
-- | @substBound s gf@ substitutes each occurence of a bound
-- variable @i@ in @dom(s)@ with the corresponding free variable
-- @s(i)=x@ in all atoms in @gf@.
substBound :: Ord c => [(Integer,LVar)] -> LGuarded c -> LGuarded c
substBound s = mapGuardedAtoms (\j a -> substBoundAtom [(i+j,v) | (i,v) <- s] a)
-- | @substFreeAtom s a@ substitutes each occurence of a free variables @v@
-- in @dom(s)@ with the bound variables @i=s(v)@ in the atom @a@.
substFreeAtom :: Ord c
=> [(LVar,Integer)]
-> Atom (VTerm c (BVar LVar)) -> Atom (VTerm c (BVar LVar))
substFreeAtom s = fmap (fmapTerm (fmap subst))
where subst fv@(Free x) = case lookup x s of
Just i -> Bound i
Nothing -> fv
subst bv = bv
-- | @substFreeAtom s gf@ substitutes each occurence of a free variables
-- @v in dom(s)@ with the correpsonding bound variables @i=s(v)@
-- in all atoms in @gf@.
substFree :: Ord c => [(LVar,Integer)] -> LGuarded c -> LGuarded c
substFree s = mapGuardedAtoms (\j a -> substFreeAtom [(v,i+j) | (v,i) <- s] a)
-- | Assuming that there are no more bound variables left in an atom of a
-- formula, convert it to an atom with free variables only.
bvarToLVar :: Ord c => Atom (VTerm c (BVar LVar)) -> Atom (VTerm c LVar)
bvarToLVar =
fmap (fmapTerm (fmap (foldBVar boundError id)))
where
boundError v = error $ "bvarToLVar: left-over bound variable '"
++ show v ++ "'"
-- | Assuming that there are no more bound variables left in an atom of a
-- formula, convert it to an atom with free variables only.
--bvarToMaybeLVar :: Ord c => Atom (VTerm c (BVar LVar)) -> Maybe (Atom (VTerm c LVar))
--bvarToMaybeLVar =
-- fmap (fmapTerm (fmap (foldBVar ??? id)))
-- | Provided an 'Atom' does not contain a bound variable, it is converted to
-- the type of atoms without bound varaibles.
unbindAtom :: (Ord c, Ord v) => Atom (VTerm c (BVar v)) -> Maybe (Atom (VTerm c v))
unbindAtom = traverse (traverseTerm (traverse (foldBVar (const Nothing) Just)))
------------------------------------------------------------------------------
-- Opening and Closing
------------------------------------------------------------------------------
-- | @openGuarded gf@ returns @Just (qua,vs,ats,gf')@ if @gf@ is a guarded
-- clause and @Nothing@ otherwise. In the first case, @qua@ is the quantifier,
-- @vs@ is a list of fresh variables, @ats@ is the antecedent, and @gf'@ is the
-- succedent. In both antecedent and succedent, the bound variables are
-- replaced by @vs@.
openGuarded :: (Ord c, MonadFresh m)
=> LGuarded c -> m (Maybe (Quantifier, [LVar], [Atom (VTerm c LVar)], LGuarded c))
openGuarded (GGuarded qua vs as gf) = do
xs <- mapM (\(n,s) -> freshLVar n s) vs
return $ Just (qua, xs, openas xs, opengf xs)
where
openas xs = map (bvarToLVar . substBoundAtom (subst xs)) as
opengf xs = substBound (subst xs) gf
subst xs = zip [0..] (reverse xs)
openGuarded _ = return Nothing
-- | @closeGuarded vs ats gf@ is a smart constructor for @GGuarded@.
closeGuarded :: Ord c => Quantifier -> [LVar] -> [Atom (VTerm c LVar)]
-> LGuarded c -> LGuarded c
closeGuarded qua vs as gf =
(case qua of Ex -> gex; All -> gall) vs' as' gf'
where
as' = map (substFreeAtom s . fmap (fmapTerm (fmap Free))) as
gf' = substFree s gf
s = zip (reverse vs) [0..]
vs' = map (lvarName &&& lvarSort) vs
------------------------------------------------------------------------------
-- Conversion and negation
------------------------------------------------------------------------------
type LNGuarded = Guarded (String,LSort) Name LVar
instance Apply LNGuarded where
apply subst = mapGuardedAtoms (const $ apply subst)
-- | @gtf b@ returns the guarded formula f with @b <-> f@.
gtf :: Bool -> Guarded s c v
gtf False = GDisj (Disj [])
gtf True = GConj (Conj [])
-- | @gfalse@ returns the guarded formula f with @False <-> f@.
gfalse :: Guarded s c v
gfalse = gtf False
-- | @gtrue@ returns the guarded formula f with @True <-> f@.
gtrue :: Guarded s c v
gtrue = gtf True
-- | @gnotAtom a@ returns the guarded formula f with @not a <-> f@.
gnotAtom :: Atom (VTerm c (BVar v)) -> Guarded s c v
gnotAtom a = GGuarded All [] [a] gfalse
-- | @gconj gfs@ smart constructor for the conjunction of gfs.
gconj :: (Ord s, Ord c, Ord v) => [Guarded s c v] -> Guarded s c v
gconj gfs0 = case concatMap flatten gfs0 of
[gf] -> gf
gfs | any (gfalse ==) gfs -> gfalse
-- FIXME: See 'sortednub' below.
| otherwise -> GConj $ Conj $ nub gfs
where
flatten (GConj conj) = concatMap flatten $ getConj conj
flatten gf = [gf]
-- | @gdisj gfs@ smart constructor for the disjunction of gfs.
gdisj :: (Ord s, Ord c, Ord v) => [Guarded s c v] -> Guarded s c v
gdisj gfs0 = case concatMap flatten gfs0 of
[gf] -> gf
gfs | any (gtrue ==) gfs -> gtrue
-- FIXME: Consider using 'sortednub' here. This yields stronger
-- normalizaton for formulas. However, it also means that we loose
-- invariance under renaming of free variables, as the order changes,
-- when they are renamed.
| otherwise -> GDisj $ Disj $ nub gfs
where
flatten (GDisj disj) = concatMap flatten $ getDisj disj
flatten gf = [gf]
-- @ A smart constructor for @GGuarded Ex@ that removes empty quantifications
-- and conjunctions with 'gfalse'.
gex :: (Ord s, Ord c, Ord v)
=> [s] -> [Atom (VTerm c (BVar v))] -> Guarded s c v -> Guarded s c v
gex [] as gf = gconj (map GAto as ++ [gf])
gex _ _ gf | gf == gfalse = gfalse
gex ss as gf = GGuarded Ex ss as gf
-- @ A smart constructor for @GGuarded All@ that drops implications to 'gtrue'
-- and removes empty premises.
gall :: (Eq s, Eq c, Eq v)
=> [s] -> [Atom (VTerm c (BVar v))] -> Guarded s c v -> Guarded s c v
gall _ [] gf = gf
gall _ _ gf | gf == gtrue = gtrue
gall ss atos gf = GGuarded All ss atos gf
-- Conversion of formulas to guarded formulas
---------------------------------------------
-- | Local newtype to avoid orphan instance.
newtype ErrorDoc d = ErrorDoc { unErrorDoc :: d }
deriving( Monoid, Semigroup, NFData, Document, HighlightDocument )
-- | @formulaToGuarded fm@ returns a guarded formula @gf@ that is
-- equivalent to @fm@ under the assumption that this is possible.
-- If not, then 'error' is called.
formulaToGuarded_ :: LNFormula -> LNGuarded
formulaToGuarded_ = either (error . render) id . formulaToGuarded
-- | @formulaToGuarded fm@ returns a guarded formula @gf@ that is
-- equivalent to @fm@ if possible.
formulaToGuarded :: HighlightDocument d => LNFormula -> Either d LNGuarded
formulaToGuarded fmOrig =
either (Left . ppError . unErrorDoc) Right
$ Precise.evalFreshT (convert False fmOrig) (avoidPrecise fmOrig)
where
ppFormula :: HighlightDocument a => LNFormula -> a
ppFormula = nest 2 . doubleQuotes . prettyLNFormula
ppError d = d $-$ text "in the formula" $-$ ppFormula fmOrig
convert True (Ato a) = pure $ gnotAtom a
convert False (Ato a) = pure $ GAto a
convert polarity (Not f) = convert (not polarity) f
convert True (Conn And f g) = gdisj <$> mapM (convert True) [f, g]
convert False (Conn And f g) = gconj <$> mapM (convert False) [f, g]
convert True (Conn Or f g) = gconj <$> mapM (convert True) [f, g]
convert False (Conn Or f g) = gdisj <$> mapM (convert False) [f, g]
convert True (Conn Imp f g ) =
gconj <$> sequence [convert False f, convert True g]
convert False (Conn Imp f g ) =
gdisj <$> sequence [convert True f, convert False g]
convert polarity (TF b) = pure $ gtf (polarity /= b)
convert polarity f0@(Qua qua0 _ _) =
-- The quantifier switch stems from our implicit negation of the formula.
case (qua0, polarity) of
(All, True ) -> convAll Ex
(All, False) -> convAll All
(Ex, True ) -> convEx All
(Ex, False) -> convEx Ex
where
noUnguardedVars [] = return ()
noUnguardedVars unguarded = throwError $ vcat
[ fsep $ text "unguarded variable(s)"
: (punctuate comma $
map (quotes . text . show) unguarded)
++ map text ["in", "the", "subformula"]
, ppFormula f0
]
conjActionsEqs (Conn And f1 f2) = conjActionsEqs f1 ++ conjActionsEqs f2
conjActionsEqs (Ato a@(Action _ _)) = [Left $ bvarToLVar a]
conjActionsEqs (Ato e@(EqE _ _)) = [Left $ bvarToLVar e]
conjActionsEqs f = [Right f]
-- Given a list of unguarded variables and a list of atoms, compute the
-- remaining unguarded variables that are not guarded by the given atoms.
remainingUnguarded ug0 atoms =
go ug0 (sortGAtoms . map atomToGAtom $ atoms)
where go ug [] = ug
go ug ((GAction a fa) :gatoms) = go (ug \\ frees (a, fa)) gatoms
-- FIXME: We do not consider the terms, e.g., for ug=[x,y],
-- s=pair(x,a), and t=pair(b,y), we could define ug'=[].
go ug ((GEqE s t):gatoms) = go ug' gatoms
where ug' | covered s ug = ug \\ frees t
| covered t ug = ug \\ frees s
| otherwise = ug
covered a vs = frees a `intersect` vs == []
convEx qua = do
(xs,_,f) <- openFormulaPrefix f0
let (as_eqs, fs) = partitionEithers $ conjActionsEqs f
-- all existentially quantified variables must be guarded
noUnguardedVars (remainingUnguarded xs as_eqs)
-- convert all other formulas
gf <- (if polarity then gdisj else gconj)
<$> mapM (convert polarity) fs
return $ closeGuarded qua xs (as_eqs) gf
convAll qua = do
(xs,_,f) <- openFormulaPrefix f0
case f of
Conn Imp ante suc -> do
let (as_eqs, fs) = partitionEithers $ conjActionsEqs ante
-- all universally quantified variables must be guarded
noUnguardedVars (remainingUnguarded xs (as_eqs))
-- negate formulas in antecedent and combine with body
gf <- (if polarity then gconj else gdisj)
<$> sequence ( map (convert (not polarity)) fs ++
[convert polarity suc] )
return $ closeGuarded qua xs as_eqs gf
_ -> throwError $
text "universal quantifier without toplevel implication" $-$
ppFormula f0
convert polarity (Conn Iff f1 f2) =
gconj <$> mapM (convert polarity) [Conn Imp f1 f2, Conn Imp f2 f1]
------------------------------------------------------------------------------
-- Induction over the trace
------------------------------------------------------------------------------
-- | Negate a guarded formula.
gnot :: (Ord s, Ord c, Ord v)
=> Guarded s c v -> Guarded s c v
gnot =
go
where
go (GGuarded All ss as gf) = gex ss as $ go gf
go (GGuarded Ex ss as gf) = gall ss as $ go gf
go (GAto ato) = gnotAtom ato
go (GDisj disj) = gconj $ map go (getDisj disj)
go (GConj conj) = gdisj $ map go (getConj conj)
-- | Checks if a doubly guarded formula is satisfied by the empty trace;
-- returns @'Left' errMsg@ if the formula is not doubly guarded.
satisfiedByEmptyTrace :: Guarded s c v -> Either String Bool
satisfiedByEmptyTrace =
foldGuarded
(\_ato -> throwError "atom outside the scope of a quantifier")
(liftM or . sequence . getDisj)
(liftM and . sequence . getConj)
(\qua _ss _as _gf -> return $ qua == All)
-- the empty trace always satisfies guarded all-quantification
-- and always dissatisfies guarded ex-quantification
-- | Tries to convert a doubly guarded formula to an induction hypothesis.
-- Returns @'Left' errMsg@ if the formula is not last-free or not doubly
-- guarded.
toInductionHypothesis :: Ord c => LGuarded c -> Either String (LGuarded c)
toInductionHypothesis =
go
where
go (GGuarded qua ss as gf)
| any isLastAtom as = throwError "formula not last-free"
| otherwise = do
gf' <- go gf
return $ case qua of
All -> gex ss as (gconj $ (gnotAtom <$> lastAtos) ++ [gf'])
Ex -> gall ss as (gdisj $ (GAto <$> lastAtos) ++ [gf'])
where
lastAtos :: [Atom (VTerm c (BVar LVar))]
lastAtos = do
(j, (_, LSortNode)) <- zip [0..] $ reverse ss
return $ Last (varTerm (Bound j))
go (GAto (Less i j)) = return $ gdisj [GAto (EqE i j), GAto (Less j i)]
go (GAto (Last _)) = throwError "formula not last-free"
go (GAto ato) = return $ gnotAtom ato
go (GDisj disj) = gconj <$> traverse go (getDisj disj)
go (GConj conj) = gdisj <$> traverse go (getConj conj)
-- | Try to prove the formula by applying induction over the trace.
-- Returns @'Left' errMsg@ if this is not possible. Returns a tuple of
-- formulas: one formalizing the proof obligation of the base-case and one
-- formalizing the proof obligation of the step-case.
ginduct :: Ord c => LGuarded c -> Either String (LGuarded c, LGuarded c)
ginduct gf = do
unless (null $ frees gf) (throwError "formula not closed")
unless (containsAction gf) (throwError "formula contains no action atom")
baseCase <- satisfiedByEmptyTrace gf
gfIH <- toInductionHypothesis gf
return (gtf baseCase, gconj [gf, gfIH])
where
containsAction = foldGuarded (const True) (or . getDisj) (or . getConj)
(\_ _ as body -> not (null as) || body)
------------------------------------------------------------------------------
-- Formula Simplification
------------------------------------------------------------------------------
-- | Simplify a 'Guarded' formula by replacing atoms with their truth value,
-- if it can be determined.
simplifyGuarded :: (LNAtom -> Maybe Bool)
-- ^ Partial assignment for truth value of atoms.
-> LNGuarded
-- ^ Original formula
-> Maybe LNGuarded
-- ^ Simplified formula, provided some simplification was
-- performed.
simplifyGuarded valuation fm0
| fm1 /= fm0 = trace (render $ ppMsg) (Just fm1)
| otherwise = Nothing
where
fm1 = simplifyGuardedOrReturn valuation fm0
ppFm = nest 2 . doubleQuotes . prettyGuarded
ppMsg = nest 2 $ text "simplified formula:" $-$
nest 2 (vcat [ ppFm fm0, text "to", ppFm fm1])
-- | Simplify a 'Guarded' formula by replacing atoms with their truth value,
-- if it can be determined. If nothing is simplified, returns the initial formula.
simplifyGuardedOrReturn :: (LNAtom -> Maybe Bool)
-- ^ Partial assignment for truth value of atoms.
-> LNGuarded
-- ^ Original formula
-> LNGuarded
-- ^ Simplified formula.
simplifyGuardedOrReturn valuation fm0 = {-trace (render ppMsg)-} fm1
where
-- ppFm = nest 2 . doubleQuotes . prettyGuarded
-- ppMsg = nest 2 $ text "simplified formula:" $-$
-- nest 2 (vcat [ ppFm fm0, text "to", ppFm fm1])
fm1 = simp fm0
simp fm@(GAto ato) = maybe fm gtf {-(trace (show (valuation =<< unbindAtom ato))-} (valuation =<< unbindAtom ato){-)-}
simp (GDisj fms) = gdisj $ map simp $ getDisj fms
simp (GConj fms) = gconj $ map simp $ getConj fms
simp (GGuarded All [] atos gf)
| any ((Just False ==) . snd) annAtos = gtrue
| otherwise =
-- keep all atoms that we cannot evaluate yet.
-- NOTE: Here we are missing the opportunity to change the valuation
-- for evaluating the body 'gf'. We could add all atoms that we have
-- as a premise.
gall [] (fst <$> filter ((Nothing ==) . snd) annAtos) (simp gf)
where
-- cache the possibly expensive evaluation of the valuation
annAtos = (\x -> (x, {-(trace (show (valuation =<< unbindAtom x))-} (valuation =<< unbindAtom x){-)-})) <$> atos
-- Note that existentials without quantifiers are already eliminated by
-- 'gex'. Moreover, we delay simplification inside guarded all
-- quantification and guarded existential quantifiers. Their body will be
-- simplified once the quantifiers are gone.
simp fm@(GGuarded _ _ _ _) = fm
------------------------------------------------------------------------------
-- Terms, facts, and formulas with skolem constants
------------------------------------------------------------------------------
-- | A constant type that supports names and skolem constants. We use the
-- skolem constants to represent fixed free variables from the constraint
-- system during matching the atoms of a guarded clause to the atoms of the
-- constraint system.
data SkConst = SkName Name
| SkConst LVar
deriving( Eq, Ord, Show, Data, Typeable )
type SkTerm = VTerm SkConst LVar
type SkFact = Fact SkTerm
type SkSubst = Subst SkConst LVar
type SkGuarded = LGuarded SkConst
-- | A term with skolem constants and bound variables
type BSkTerm = VTerm SkConst BLVar
-- | An term with skolem constants and bound variables
type BSkAtom = Atom BSkTerm
instance IsConst SkConst
-- Skolemization of terms without bound variables.
--------------------------------------------------
skolemizeTerm :: LNTerm -> SkTerm
skolemizeTerm = fmapTerm conv
where
conv :: Lit Name LVar -> Lit SkConst LVar
conv (Var v) = Con (SkConst v)
conv (Con n) = Con (SkName n)
skolemizeFact :: LNFact -> Fact SkTerm
skolemizeFact = fmap skolemizeTerm
skolemizeAtom :: BLAtom -> BSkAtom
skolemizeAtom = fmap skolemizeBTerm
skolemizeGuarded :: LNGuarded -> SkGuarded
skolemizeGuarded = mapGuardedAtoms (const skolemizeAtom)
applySkTerm :: SkSubst -> SkTerm -> SkTerm
applySkTerm subst t = applyVTerm subst t
applySkFact :: SkSubst -> SkFact -> SkFact
applySkFact subst = fmap (applySkTerm subst)
applySkAction :: SkSubst -> (SkTerm,SkFact) -> (SkTerm,SkFact)
applySkAction subst (t,f) = (applySkTerm subst t, applySkFact subst f)
-- Skolemization of terms with bound variables.
-----------------------------------------------
skolemizeBTerm :: VTerm Name BLVar -> BSkTerm
skolemizeBTerm = fmapTerm conv
where
conv :: Lit Name BLVar -> Lit SkConst BLVar
conv (Var (Free x)) = Con (SkConst x)
conv (Var (Bound b)) = Var (Bound b)
conv (Con n) = Con (SkName n)
unskolemizeBTerm :: BSkTerm -> VTerm Name BLVar
unskolemizeBTerm t = fmapTerm conv t
where
conv :: Lit SkConst BLVar -> Lit Name BLVar
conv (Con (SkConst x)) = Var (Free x)
conv (Var (Bound b)) = Var (Bound b)
conv (Var (Free v)) = error $ "unskolemizeBTerm: free variable " ++
show v++" found in "++show t
conv (Con (SkName n)) = Con n
unskolemizeBLAtom :: BSkAtom -> BLAtom
unskolemizeBLAtom = fmap unskolemizeBTerm
unskolemizeLNGuarded :: SkGuarded -> LNGuarded
unskolemizeLNGuarded = mapGuardedAtoms (const unskolemizeBLAtom)
applyBSkTerm :: SkSubst -> VTerm SkConst BLVar -> VTerm SkConst BLVar
applyBSkTerm subst =
go
where
go t = case viewTerm t of
Lit l -> applyBLLit l
FApp o as -> fApp o (map go as)
applyBLLit :: Lit SkConst BLVar -> VTerm SkConst BLVar
applyBLLit l@(Var (Free v)) =
maybe (lit l) (fmapTerm (fmap Free)) (imageOf subst v)
applyBLLit l = lit l
applyBSkAtom :: SkSubst -> Atom (VTerm SkConst BLVar) -> Atom (VTerm SkConst BLVar)
applyBSkAtom subst = fmap (applyBSkTerm subst)
applySkGuarded :: SkSubst -> LGuarded SkConst -> LGuarded SkConst
applySkGuarded subst = mapGuardedAtoms (const $ applyBSkAtom subst)
-- Matching
-----------
matchAction :: (SkTerm, SkFact) -> (SkTerm, SkFact) -> WithMaude [SkSubst]
matchAction (i1, fa1) (i2, fa2) =
solveMatchLTerm sortOfSkol (i1 `matchWith` i2 <> fa1 `matchFact` fa2)
where
sortOfSkol (SkName n) = sortOfName n
sortOfSkol (SkConst v) = lvarSort v
matchTerm :: SkTerm -> SkTerm -> WithMaude [SkSubst]
matchTerm s t =
solveMatchLTerm sortOfSkol (s `matchWith` t)
where
sortOfSkol (SkName n) = sortOfName n
sortOfSkol (SkConst v) = lvarSort v
------------------------------------------------------------------------------
-- Pretty Printing
------------------------------------------------------------------------------
-- | Pretty print a formula.
prettyGuarded :: HighlightDocument d
=> LNGuarded -- ^ Guarded Formula.
-> d -- ^ Pretty printed formula.
prettyGuarded fm =
Precise.evalFresh (pp fm) (avoidPrecise fm)
where
pp :: HighlightDocument d => LNGuarded -> Precise.Fresh d
pp (GAto a) = return $ prettyNAtom $ bvarToLVar a
pp (GDisj (Disj [])) = return $ operator_ "⊥" -- "F"
pp (GDisj (Disj xs)) = do
ps <- mapM (\x -> opParens <$> pp x) xs
return $ parens $ sep $ punctuate (operator_ " ∨") ps
-- return $ sep $ punctuate (operator_ " |") ps
pp (GConj (Conj [])) = return $ operator_ "⊤" -- "T"
pp (GConj (Conj xs)) = do
ps <- mapM (\x -> opParens <$> pp x) xs
return $ sep $ punctuate (operator_ " ∧") ps --- " &") ps
pp gf0@(GGuarded _ _ _ _) =
-- variable names invented here can be reused otherwise
scopeFreshness $ do
Just (qua, vs, atoms, gf) <- openGuarded gf0
let antecedent = (GAto . fmap (fmapTerm (fmap Free))) <$> atoms
connective = operator_ (case qua of All -> "⇒"; Ex -> "∧")
-- operator_ (case qua of All -> "==>"; Ex -> "&")
quantifier = operator_ (ppQuant qua) <-> ppVars vs <> operator_ "."
dante <- nest 1 <$> pp (GConj (Conj antecedent))
case (qua, vs, gf) of
(Ex, _, GConj (Conj [])) ->
return $ sep $ [ quantifier, dante ]
(All, [], GDisj (Disj [])) | gf == gfalse ->
return $ operator_ "¬" <> dante
_ -> do
dsucc <- nest 1 <$> pp gf
return $ sep [ quantifier, sep [dante, connective, dsucc] ]
where
ppVars = fsep . map (text . show)
ppQuant All = "∀" -- "All "
ppQuant Ex = "∃" -- "Ex "
| kmilner/tamarin-prover | lib/theory/src/Theory/Constraint/System/Guarded.hs | gpl-3.0 | 32,653 | 1 | 31 | 9,181 | 8,808 | 4,531 | 4,277 | 484 | 24 |
#! /usr/bin/env runghc
module Collatz where
import Control.Monad (ap, when)
import Control.Monad.Instances (Monad)
import Data.Numbers.Primes (isPrime)
import System.Environment (getArgs)
main :: IO ()
main = getArgs >>= ap (when . (> 0) . length) (printLines . tail . collatz . read . head)
collatz :: Integral a => a -> [a]
collatz 1 = [1]
collatz n | even n = n : collatz (n `div` 2)
| odd n = n : collatz (3 * n + 1)
printLines :: Show a => [a] -> IO ()
printLines = foldr ((>>) . print) (return ())
| CS-CLUB/contests | 2012/submissions/Khalil Fazal/3/a/Collatz.hs | gpl-3.0 | 568 | 0 | 11 | 160 | 252 | 136 | 116 | 13 | 1 |
class X a where
f :: a -> Int
class Y a where
g :: a -> Bool
g = f | Helium4Haskell/helium | test/typeClasses/ClassInstaneError13.hs | gpl-3.0 | 79 | 0 | 7 | 33 | 42 | 21 | 21 | 5 | 0 |
module HEP.Automation.MadGraph.Dataset.Set20110404set1 where
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.Cluster
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Dataset.Common
import HEP.Automation.MadGraph.Dataset.SUSY
processTB :: [Char]
processTB =
"\ngenerate P P > t b / g a z h w+ w- QED=99 @1\nadd process P P > t~ b~ / g a z h w+ w- QED=99 @2\n"
psetup_wpzpfull_bb :: ProcessSetup
psetup_wpzpfull_bb = PS {
mversion = MadGraph4
, model = WpZpFull
, process = processTB
, processBrief = "tb"
, workname = "404WpZpFull"
}
my_csetup :: ClusterSetup
my_csetup = CS { cluster = Parallel 3 }
wpzpparamset :: [Param]
wpzpparamset = [ WpZpFullParam m m gW gW gZ gZ gZ gZ
| m <-[150.0]
, gW <- [0.5*sqrt 2]
, gZ <- [0.5] ]
psetuplist :: [ProcessSetup]
psetuplist = [ psetup_wpzpfull_bb ]
sets :: [Int]
sets = [1]
wpzptasklist :: [WorkSetup]
wpzptasklist = [ WS my_ssetup (psetup_wpzpfull_bb)
(rsetupGen p NoMatch NoUserCutDef NoPGS 20000 num)
my_csetup
| p <- wpzpparamset , num <- sets ]
wpzptasklist2 :: [WorkSetup]
wpzptasklist2 = [ WS my_ssetup (psetup_wpzpfull_bb)
(rsetupLHC p NoMatch NoUserCutDef NoPGS 20000 num)
my_csetup
| p <- wpzpparamset , num <- sets ]
totaltasklist :: [WorkSetup]
totaltasklist = wpzptasklist ++ wpzptasklist2
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110404set1.hs | gpl-3.0 | 1,649 | 0 | 10 | 475 | 378 | 224 | 154 | 41 | 1 |
{-
This file is part of artgen.
Foobar is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
Copyright (c) 2015 Chad Dettmering
Authors:
Chad Dettmering chad.dettmering@gmail.com
-}
module Chainer.Histogram where
import qualified Data.Map.Strict as Map
import Data.List (foldl')
-- Maps an element to the number of occurrences of that element.
type Histogram a = Map.Map a Integer
{-
- Creates an empty Histogram
-}
emptyH :: Histogram a
emptyH = Map.empty :: Map.Map a Integer
{-
- Creates a Histogram from a list
-}
fromListH :: Ord a => [a] -> Histogram a
fromListH lst = foldl' (\acc x -> addH x acc) emptyH lst
{-
- Merges 2 Histograms together adding their occurrences
-}
mergeH :: Ord a => Histogram a -> Histogram a -> Histogram a
mergeH h1 h2 = Map.unionWith (+) h1 h2
{-
- addHs a value to the Histogram, or adjust the value
- +1 if it already exists in the Histogram
-}
addH :: Ord a => a -> Histogram a -> Histogram a
addH value histogram = adjustOrInsertH (\x -> x + 1) value histogram
{-
- Gets the number of occurrences of the element within
- the Histogram
-}
occurrences :: Ord k => k -> Histogram k -> Integer
occurrences element histogram = case (Map.lookup element histogram) of
Just found -> found
Nothing -> 0
{-
- Total sum of all Histogram occurrences
-}
sumOccurrences :: Histogram a -> Integer
sumOccurrences histogram = Map.foldl' (+) 0 histogram
{-
- Inserts element into the Histogram if it doesn't exist, otherwise adjusts
- the value of element by applying f to it.
-}
adjustOrInsertH :: Ord k => (Integer -> Integer) -> k -> Histogram k -> Histogram k
adjustOrInsertH f element histogram = case (Map.lookup element histogram) of
Just found -> Map.adjust f element histogram
Nothing -> Map.insert element (f 0) histogram
| cdettmering/artgen | Chainer/Histogram.hs | gpl-3.0 | 2,469 | 0 | 10 | 584 | 425 | 219 | 206 | 22 | 2 |
{-|
Module : Bench
Description : Benchmark of Multilinear library
Copyright : (c) Artur M. Brodzki, 2018
License : BSD3
Maintainer : artur@brodzki.org
Stability : experimental
Portability : Windows/POSIX
-}
module Main (
main
) where
import Criterion.Main
import Criterion.Types
import Multilinear.Generic.MultiCore
import qualified Multilinear.Matrix as Matrix
-- | Simple generator function for bencharking matrices
gen :: Int -> Int -> Double
gen j k = sin (fromIntegral j) + cos (fromIntegral k)
-- | Generate benchmark of matrix multiplication
sizedMatrixMultBench ::
Int -- ^ size of square matrix to multiplicate
-> Benchmark
sizedMatrixMultBench s =
bench (show s ++ "x" ++ show s) $
nf ((Matrix.fromIndices "ij" s s gen :: Tensor Double) *) (Matrix.fromIndices "jk" s s gen :: Tensor Double)
-- | Generate benchmark of matrix addition
sizedMatrixAddBench ::
Int -- ^ size of square matrix to add
-> Benchmark
sizedMatrixAddBench s =
bench (show s ++ "x" ++ show s) $
nf ((Matrix.fromIndices "ij" s s gen :: Tensor Double) +) (Matrix.fromIndices "ij" s s gen :: Tensor Double)
-- | ENTRY POINT
main :: IO ()
main = defaultMainWith defaultConfig { reportFile = Just "benchmark/2-cores-bench.html" } [
bgroup "matrix addition" $ sizedMatrixAddBench <$> [64, 128, 256, 512, 1024],
bgroup "matrix multiplication" $ sizedMatrixMultBench <$> [64, 128, 256, 512, 1024]
]
| ArturB/Multilinear | benchmark/2-cores/time/Bench.hs | gpl-3.0 | 1,496 | 0 | 10 | 339 | 354 | 191 | 163 | 24 | 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.Games.Events.Record
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Records a batch of changes to the number of times events have occurred
-- for the currently authenticated user of this application.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Reference> for @games.events.record@.
module Network.Google.Resource.Games.Events.Record
(
-- * REST Resource
EventsRecordResource
-- * Creating a Request
, eventsRecord
, EventsRecord
-- * Request Lenses
, erXgafv
, erUploadProtocol
, erAccessToken
, erUploadType
, erPayload
, erLanguage
, erCallback
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.events.record@ method which the
-- 'EventsRecord' request conforms to.
type EventsRecordResource =
"games" :>
"v1" :>
"events" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "language" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] EventRecordRequest :>
Post '[JSON] EventUpdateResponse
-- | Records a batch of changes to the number of times events have occurred
-- for the currently authenticated user of this application.
--
-- /See:/ 'eventsRecord' smart constructor.
data EventsRecord =
EventsRecord'
{ _erXgafv :: !(Maybe Xgafv)
, _erUploadProtocol :: !(Maybe Text)
, _erAccessToken :: !(Maybe Text)
, _erUploadType :: !(Maybe Text)
, _erPayload :: !EventRecordRequest
, _erLanguage :: !(Maybe Text)
, _erCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EventsRecord' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'erXgafv'
--
-- * 'erUploadProtocol'
--
-- * 'erAccessToken'
--
-- * 'erUploadType'
--
-- * 'erPayload'
--
-- * 'erLanguage'
--
-- * 'erCallback'
eventsRecord
:: EventRecordRequest -- ^ 'erPayload'
-> EventsRecord
eventsRecord pErPayload_ =
EventsRecord'
{ _erXgafv = Nothing
, _erUploadProtocol = Nothing
, _erAccessToken = Nothing
, _erUploadType = Nothing
, _erPayload = pErPayload_
, _erLanguage = Nothing
, _erCallback = Nothing
}
-- | V1 error format.
erXgafv :: Lens' EventsRecord (Maybe Xgafv)
erXgafv = lens _erXgafv (\ s a -> s{_erXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
erUploadProtocol :: Lens' EventsRecord (Maybe Text)
erUploadProtocol
= lens _erUploadProtocol
(\ s a -> s{_erUploadProtocol = a})
-- | OAuth access token.
erAccessToken :: Lens' EventsRecord (Maybe Text)
erAccessToken
= lens _erAccessToken
(\ s a -> s{_erAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
erUploadType :: Lens' EventsRecord (Maybe Text)
erUploadType
= lens _erUploadType (\ s a -> s{_erUploadType = a})
-- | Multipart request metadata.
erPayload :: Lens' EventsRecord EventRecordRequest
erPayload
= lens _erPayload (\ s a -> s{_erPayload = a})
-- | The preferred language to use for strings returned by this method.
erLanguage :: Lens' EventsRecord (Maybe Text)
erLanguage
= lens _erLanguage (\ s a -> s{_erLanguage = a})
-- | JSONP
erCallback :: Lens' EventsRecord (Maybe Text)
erCallback
= lens _erCallback (\ s a -> s{_erCallback = a})
instance GoogleRequest EventsRecord where
type Rs EventsRecord = EventUpdateResponse
type Scopes EventsRecord =
'["https://www.googleapis.com/auth/games"]
requestClient EventsRecord'{..}
= go _erXgafv _erUploadProtocol _erAccessToken
_erUploadType
_erLanguage
_erCallback
(Just AltJSON)
_erPayload
gamesService
where go
= buildClient (Proxy :: Proxy EventsRecordResource)
mempty
| brendanhay/gogol | gogol-games/gen/Network/Google/Resource/Games/Events/Record.hs | mpl-2.0 | 4,916 | 0 | 18 | 1,207 | 789 | 459 | 330 | 112 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.InstanceGroupManagers.DeleteInstances
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Flags the specified instances in the managed instance group for
-- immediate deletion. The instances are also removed from any target pools
-- of which they were a member. This method reduces the targetSize of the
-- managed instance group by the number of instances that you delete. This
-- operation is marked as DONE when the action is scheduled even if the
-- instances are still being deleted. You must separately verify the status
-- of the deleting action with the listmanagedinstances method. If the
-- group is part of a backend service that has enabled connection draining,
-- it can take up to 60 seconds after the connection draining duration has
-- elapsed before the VM instance is removed or deleted. You can specify a
-- maximum of 1000 instances with this method per request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instanceGroupManagers.deleteInstances@.
module Network.Google.Resource.Compute.InstanceGroupManagers.DeleteInstances
(
-- * REST Resource
InstanceGroupManagersDeleteInstancesResource
-- * Creating a Request
, instanceGroupManagersDeleteInstances
, InstanceGroupManagersDeleteInstances
-- * Request Lenses
, igmdiRequestId
, igmdiProject
, igmdiInstanceGroupManager
, igmdiZone
, igmdiPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instanceGroupManagers.deleteInstances@ method which the
-- 'InstanceGroupManagersDeleteInstances' request conforms to.
type InstanceGroupManagersDeleteInstancesResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instanceGroupManagers" :>
Capture "instanceGroupManager" Text :>
"deleteInstances" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON]
InstanceGroupManagersDeleteInstancesRequest
:> Post '[JSON] Operation
-- | Flags the specified instances in the managed instance group for
-- immediate deletion. The instances are also removed from any target pools
-- of which they were a member. This method reduces the targetSize of the
-- managed instance group by the number of instances that you delete. This
-- operation is marked as DONE when the action is scheduled even if the
-- instances are still being deleted. You must separately verify the status
-- of the deleting action with the listmanagedinstances method. If the
-- group is part of a backend service that has enabled connection draining,
-- it can take up to 60 seconds after the connection draining duration has
-- elapsed before the VM instance is removed or deleted. You can specify a
-- maximum of 1000 instances with this method per request.
--
-- /See:/ 'instanceGroupManagersDeleteInstances' smart constructor.
data InstanceGroupManagersDeleteInstances =
InstanceGroupManagersDeleteInstances'
{ _igmdiRequestId :: !(Maybe Text)
, _igmdiProject :: !Text
, _igmdiInstanceGroupManager :: !Text
, _igmdiZone :: !Text
, _igmdiPayload :: !InstanceGroupManagersDeleteInstancesRequest
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstanceGroupManagersDeleteInstances' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'igmdiRequestId'
--
-- * 'igmdiProject'
--
-- * 'igmdiInstanceGroupManager'
--
-- * 'igmdiZone'
--
-- * 'igmdiPayload'
instanceGroupManagersDeleteInstances
:: Text -- ^ 'igmdiProject'
-> Text -- ^ 'igmdiInstanceGroupManager'
-> Text -- ^ 'igmdiZone'
-> InstanceGroupManagersDeleteInstancesRequest -- ^ 'igmdiPayload'
-> InstanceGroupManagersDeleteInstances
instanceGroupManagersDeleteInstances pIgmdiProject_ pIgmdiInstanceGroupManager_ pIgmdiZone_ pIgmdiPayload_ =
InstanceGroupManagersDeleteInstances'
{ _igmdiRequestId = Nothing
, _igmdiProject = pIgmdiProject_
, _igmdiInstanceGroupManager = pIgmdiInstanceGroupManager_
, _igmdiZone = pIgmdiZone_
, _igmdiPayload = pIgmdiPayload_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
igmdiRequestId :: Lens' InstanceGroupManagersDeleteInstances (Maybe Text)
igmdiRequestId
= lens _igmdiRequestId
(\ s a -> s{_igmdiRequestId = a})
-- | Project ID for this request.
igmdiProject :: Lens' InstanceGroupManagersDeleteInstances Text
igmdiProject
= lens _igmdiProject (\ s a -> s{_igmdiProject = a})
-- | The name of the managed instance group.
igmdiInstanceGroupManager :: Lens' InstanceGroupManagersDeleteInstances Text
igmdiInstanceGroupManager
= lens _igmdiInstanceGroupManager
(\ s a -> s{_igmdiInstanceGroupManager = a})
-- | The name of the zone where the managed instance group is located.
igmdiZone :: Lens' InstanceGroupManagersDeleteInstances Text
igmdiZone
= lens _igmdiZone (\ s a -> s{_igmdiZone = a})
-- | Multipart request metadata.
igmdiPayload :: Lens' InstanceGroupManagersDeleteInstances InstanceGroupManagersDeleteInstancesRequest
igmdiPayload
= lens _igmdiPayload (\ s a -> s{_igmdiPayload = a})
instance GoogleRequest
InstanceGroupManagersDeleteInstances
where
type Rs InstanceGroupManagersDeleteInstances =
Operation
type Scopes InstanceGroupManagersDeleteInstances =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient
InstanceGroupManagersDeleteInstances'{..}
= go _igmdiProject _igmdiZone
_igmdiInstanceGroupManager
_igmdiRequestId
(Just AltJSON)
_igmdiPayload
computeService
where go
= buildClient
(Proxy ::
Proxy InstanceGroupManagersDeleteInstancesResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/InstanceGroupManagers/DeleteInstances.hs | mpl-2.0 | 7,613 | 0 | 19 | 1,619 | 656 | 398 | 258 | 107 | 1 |
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Network.Kafka.Protocol.Fetch
( FetchRequest
, FetchRequestFields
, FetchResponse
, FetchResponseFields
, FetchResponsePayload
, FetchResponsePayloadFields
, FMaxBytes
, FMaxWaitTime
, FMinBytes
, maxBytes
, maxWaitTime
, minBytes
)
where
import Control.Lens
import Data.Proxy
import Data.Serialize
import Data.Vinyl
import Data.Word
import GHC.Generics
import Network.Kafka.Protocol.Instances ()
import Network.Kafka.Protocol.Universe
type FMaxBytes = '("max_bytes" , Word32)
type FMaxWaitTime = '("max_wait_time", Word32)
type FMinBytes = '("min_bytes" , Word32)
maxBytes :: Proxy FMaxBytes
maxBytes = Proxy
maxWaitTime :: Proxy FMaxWaitTime
maxWaitTime = Proxy
minBytes :: Proxy FMinBytes
minBytes = Proxy
type FetchRequestFields
= '[ FReplicaId
, FMaxWaitTime
, FMinBytes
, FTopic
, FPartition
, FOffset
, FMaxBytes
]
type FetchRequest = Req 1 0 FetchRequestFields
type FetchResponseFields = '[ FPayload FetchResponsePayload ]
type FetchResponse = Resp FetchResponseFields
type FetchResponsePayloadFields
= '[ FPartition
, FErrorCode
, FOffset
, FSize
, FMessageSet
]
newtype FetchResponsePayload
= FetchResponsePayload (FieldRec FetchResponsePayloadFields)
deriving (Eq, Show, Generic)
instance Serialize FetchResponsePayload
makeWrapped ''FetchResponsePayload
| kim/kafka-protocol | src/Network/Kafka/Protocol/Fetch.hs | mpl-2.0 | 1,897 | 0 | 7 | 438 | 315 | 194 | 121 | 58 | 1 |
module Typekwondo2 where
chk :: Eq b => (a -> b) -> a -> b -> Bool
chk f x y = (f x) == y
arith :: Num b => (a -> b) -> Integer -> a -> b
arith f x y = (f y) + fromInteger x
| logistark/haskellbookexercises | 6 - Typeclasses/typekwondo2.hs | apache-2.0 | 184 | 0 | 8 | 60 | 113 | 58 | 55 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module CodeWorld.Compile.Requirements.Language (parseRequirement) where
import CodeWorld.Compile.Framework
import CodeWorld.Compile.Requirements.LegacyLanguage
import CodeWorld.Compile.Requirements.Types
import Control.Applicative
import Data.Aeson
import Data.Aeson.Types (explicitParseFieldMaybe)
import qualified Data.Aeson.Types as Aeson
import Data.Either
import Data.Foldable
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Yaml as Yaml
import Language.Haskell.Exts.SrcLoc
instance FromJSON Requirement where
parseJSON = withObject "Requirement" $ \v ->
Requirement <$> v .: "Description"
<*> v .: "Rules"
instance FromJSON Rule where
parseJSON = withObject "Rule" $ \o -> do
choices <- sequence
[ explicitParseFieldMaybe definedByFunction o "definedByFunction"
, explicitParseFieldMaybe matchesExpected o "matchesExpected"
, explicitParseFieldMaybe hasSimpleParams o "hasSimpleParams"
, explicitParseFieldMaybe usesAllParams o "usesAllParams"
, explicitParseFieldMaybe notDefined o "notDefined"
, explicitParseFieldMaybe notUsed o "notUsed"
, explicitParseFieldMaybe containsMatch o "containsMatch"
, explicitParseFieldMaybe matchesRegex o "matchesRegex"
, explicitParseFieldMaybe ifThen o "ifThen"
, explicitParseFieldMaybe allOf o "all"
, explicitParseFieldMaybe anyOf o "any"
, explicitParseFieldMaybe notThis o "not"
, explicitParseFieldMaybe maxLineLength o "maxLineLength"
, explicitParseFieldMaybe noWarningsExcept o "noWarningsExcept"
, explicitParseFieldMaybe typeSignatures o "typeSignatures"
, explicitParseFieldMaybe blacklist o "blacklist"
, explicitParseFieldMaybe whitelist o "whitelist"
]
case catMaybes choices of
[r] -> decorateWith o r
[] -> fail "No recognized rule type was defined."
_ -> fail "More than one type was found for a single rule."
decorateWith :: Aeson.Object -> Rule -> Aeson.Parser Rule
decorateWith obj = wrapCustomMessage
where wrapCustomMessage rule = do
msg <- obj .:? "explanation"
case msg of Just str -> return (OnFailure str rule)
_ -> return rule
definedByFunction :: Aeson.Value -> Aeson.Parser Rule
definedByFunction = withObject "definedByFunction" $ \o ->
DefinedByFunction <$> o .: "variable"
<*> o .: "function"
matchesExpected :: Aeson.Value -> Aeson.Parser Rule
matchesExpected = withObject "matchesExpected" $ \o ->
MatchesExpected <$> o .: "variable"
<*> o .: "hash"
hasSimpleParams :: Aeson.Value -> Aeson.Parser Rule
hasSimpleParams = withText "hasSimpleParams" $ \t ->
return $ HasSimpleParams $ T.unpack t
usesAllParams :: Aeson.Value -> Aeson.Parser Rule
usesAllParams = withText "usesAllParams" $ \t ->
return $ UsesAllParams $ T.unpack t
notDefined :: Aeson.Value -> Aeson.Parser Rule
notDefined = withText "notDefined" $ \t ->
return $ NotDefined $ T.unpack t
notUsed :: Aeson.Value -> Aeson.Parser Rule
notUsed = withText "notUsed" $ \t ->
return $ NotUsed $ T.unpack t
containsMatch :: Aeson.Value -> Aeson.Parser Rule
containsMatch = withObject "containsMatch" $ \o ->
ContainsMatch <$> o .: "template"
<*> o .:? "topLevel" .!= True
<*> o .:? "cardinality" .!= atLeastOne
matchesRegex :: Aeson.Value -> Aeson.Parser Rule
matchesRegex = withObject "matchesRegex" $ \o ->
MatchesRegex <$> o .: "pattern"
<*> o .:? "cardinality" .!= atLeastOne
ifThen :: Aeson.Value -> Aeson.Parser Rule
ifThen = withObject "ifThen" $ \o ->
OnFailure <$> o .: "if"
<*> o .: "then"
allOf :: Aeson.Value -> Aeson.Parser Rule
allOf v = AllOf <$> withArray "all" (mapM parseJSON . toList) v
anyOf :: Aeson.Value -> Aeson.Parser Rule
anyOf v = AnyOf <$> withArray "any" (mapM parseJSON . toList) v
notThis :: Aeson.Value -> Aeson.Parser Rule
notThis v = NotThis <$> parseJSON v
maxLineLength :: Aeson.Value -> Aeson.Parser Rule
maxLineLength v = MaxLineLength <$> parseJSON v
noWarningsExcept :: Aeson.Value -> Aeson.Parser Rule
noWarningsExcept v = NoWarningsExcept <$> withArray "exceptions" (mapM parseJSON . toList) v
typeSignatures :: Aeson.Value -> Aeson.Parser Rule
typeSignatures v = TypeSignatures <$> parseJSON v
blacklist :: Aeson.Value -> Aeson.Parser Rule
blacklist v = Blacklist <$> withArray "blacklist" (mapM parseJSON . toList) v
whitelist :: Aeson.Value -> Aeson.Parser Rule
whitelist v = Whitelist <$> withArray "whitelist" (mapM parseJSON . toList) v
instance FromJSON Cardinality where
parseJSON val = parseAsNum val <|> parseAsObj val
where parseAsNum val = do
n <- parseJSON val
return (Cardinality (Just n) (Just n))
parseAsObj = withObject "cardinality" $ \o -> do
exactly <- o .:? "exactly"
mini <- o .:? "atLeast"
maxi <- o .:? "atMost"
case (exactly, mini, maxi) of
(Just n, Nothing, Nothing) ->
return (Cardinality (Just n) (Just n))
(Nothing, Nothing, Nothing) ->
fail "Missing cardinality"
(Nothing, m, n) ->
return (Cardinality m n)
parseRequirement :: Int -> Int -> Text -> Either String Requirement
parseRequirement ln col txt
| isLegacyFormat txt = parseLegacyRequirement ln col txt
| otherwise = either (Left . prettyPrintYamlParseException ln col) Right $
Yaml.decodeEither' (T.encodeUtf8 txt)
prettyPrintYamlParseException ln col e =
formatLocation srcSpan ++ ": " ++ Yaml.prettyPrintParseException e
where srcSpan = SrcSpanInfo loc []
loc = SrcSpan "program.hs" ln col ln col
| alphalambda/codeworld | codeworld-compiler/src/CodeWorld/Compile/Requirements/Language.hs | apache-2.0 | 6,745 | 0 | 19 | 1,644 | 1,639 | 832 | 807 | 126 | 2 |
-- |Javascript pretty-printer.
module Main where
import Ovid.Net (getPageJavascript)
import Javascript.Javascript (parseJavascriptFromFile)
import Html.PermissiveParser (parseHtmlFromFile)
import System.Environment (getArgs)
import Data.List (isSuffixOf)
import Control.Monad
import Framework
buildTime =
#ifdef __TIME__
__TIME__
#else
#error "__TIME__ is not defined"
#endif
buildDate =
#ifdef __DATE__
__DATE__
#else
#error "__DATE__ is not defined"
#endif
main = do
rawArgs <- getArgs
case rawArgs of
[arg] -> main' arg
otherwise -> fail "Expected a single file name as a command-line argument"
main' path | (".html" `isSuffixOf` path || ".lhs" `isSuffixOf` path) = do
eitherS <- parseHtmlFromFile path
case eitherS of
Left parseError -> fail (show parseError)
Right (html,warnings) -> do
unless (null warnings)
(warn $ show warnings)
stmts <- getPageJavascript html
putStr (show stmts)
main' path = do
stmts <- parseJavascriptFromFile path
putStr (show stmts)
| brownplt/ovid | src/Jspp.hs | bsd-2-clause | 1,032 | 0 | 16 | 196 | 278 | 144 | 134 | -1 | -1 |
module Orders where
import GPS
import Facing
import Unit
data Order = OrderMove UnitId [GPS]
| OrderFace UnitId Facing
| OrderNAI Int GPS
deriving (Show, Eq)
type Orders = [Order]
| nbrk/ld | library/Orders.hs | bsd-2-clause | 209 | 0 | 7 | 59 | 61 | 37 | 24 | 9 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Data.Char
import Data.String
import Data.Monoid
import Data.Maybe
import Data.List (intercalate, isSuffixOf, groupBy, nub, sort)
import Data.List.Split (splitOn, splitOneOf)
import Data.Time.Format as Time
import Control.Arrow ((***), (&&&))
import Control.Applicative ((<$>), (<*>))
import Network.URI as URI
import System.IO (hPutStr, hClose)
import System.FilePath (dropExtension, (</>))
import System.Time
import System.Directory
import Text.Blaze.Html
import Text.Blaze.Html.Renderer.String
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.RSS as RSS
import Cheapskate (markdown, def)
import Cheapskate.Html (renderDoc)
import Cheapskate.Types
data Post = Post
{ filename :: String
, tags :: [(String, String)]
, content :: String
} deriving (Show, Eq)
copyright :: String
copyright = "© Phil Freeman 2010-2021"
readTags :: String -> ([(String, String)], [String])
readTags = readTags' False [] . splitOneOf "\n\r" where
readTags' :: Bool -> [(String, String)] -> [String] -> ([(String, String)], [String])
readTags' _ ts [] = (ts, [])
readTags' False ts (('-':'-':'-':_):ss) = readTags' True ts ss
readTags' True ts (('-':'-':'-':_):ss) = (ts, ss)
readTags' False ts (_:ss) = readTags' False ts ss
readTags' True ts (s:ss) = readTags' True (readTag s:ts) ss
readTag :: String -> (String, String)
readTag s = let (key:rest) = splitOn ":" s in (key, dropWhile isSpace $ intercalate ":" rest)
getAllPosts :: FilePath -> IO [Post]
getAllPosts path = do
posts <- reverse . sort . filter (isSuffixOf ".markdown") <$> getDirectoryContents path
flip mapM posts $ \filename -> do
content <- readFile $ path </> filename
let split = readTags content
return $ Post
{ filename = filename
, tags = fst split
, content = intercalate "\n" $ snd split }
markdownToHtml :: String -> H.Html
markdownToHtml = renderDoc . markdown def { allowRawHtml = True, sanitize = False } . fromString
postFilename :: String -> String
postFilename = (++ ".html") . dropExtension
collectTags :: [Post] -> [(String, [Post])]
collectTags posts =
map (id &&& postsFor posts) $ allTags posts
where
postsFor posts tag = filter (elem tag . tagsFor) posts
tagsFor = map (dropWhile isSpace) . filter (not . null) . splitOneOf ",". fromJust . lookup "tags" . tags
allTags = sort . nub . concatMap tagsFor
defaultTemplate :: String -> String -> String -> H.Html -> H.Html
defaultTemplate title subtitle rootPrefix body = do
H.docType
H.html $ do
H.head $ do
H.title $ H.toHtml $ "Functorial Blog - " ++ title
H.link ! A.rel "stylesheet"
! A.type_ "text/css"
! A.href "//fonts.googleapis.com/css?family=Roboto+Slab:300"
H.link ! A.rel "stylesheet"
! A.type_ "text/css"
! A.href "//fonts.googleapis.com/css?family=Roboto+Mono:300"
H.link ! A.rel "stylesheet"
! A.type_ "text/css"
! A.href (fromString $ rootPrefix </> "assets" </> "default.css")
H.meta ! A.name "viewport" ! A.content "width=device-width, initial-scale=1"
H.script ! A.type_ "text/javascript" ! A.src (fromString $ rootPrefix </> "assets" </> "gaq.js") $ mempty
H.body $ do
H.header $ do
H.h1 $ fromString title
H.p $ fromString subtitle
H.hr
H.main body
H.footer $ do
H.hr
H.p ! A.class_ "text-muted" $ H.small $ fromString copyright
renderPost :: Post -> H.Html
renderPost Post{..} = do
let title = maybe "" id $ lookup "title" tags
author = maybe "" id $ lookup "author" tags
date = maybe "" id $ lookup "date" tags
defaultTemplate title ("by " ++ author ++ " on " ++ date) ".." (markdownToHtml content)
renderPostLink :: String -> Post -> H.Html
renderPostLink rootPrefix Post{..} = do
let title = maybe "" id $ lookup "title" tags
date = maybe "" id $ lookup "date" tags
H.li $ do
H.a ! A.href (fromString $ rootPrefix </> "posts/" </> postFilename filename) $ fromString title
H.em ! A.class_ "text-muted" $ do
fromString " ("
fromString date
fromString ")"
renderIndex :: [Post] -> H.Html
renderIndex posts = defaultTemplate "Functorial Blog" "A blog about functional programming" "./" $ do
H.h2 "Posts"
H.ul $ mapM_ (renderPostLink ".") posts
H.p $ H.small $ H.a ! A.href "feed.rss" $ fromString "RSS Feed"
renderFeed :: [Post] -> RSS.RSS
renderFeed posts =
RSS.RSS "Functorial Blog"
(URI.URI
"https:"
(Just (URI.URIAuth "" "blog.functorial.com" ""))
"/feed.rss"
""
"")
"A blog about functional programming"
[ RSS.Language "English"
, RSS.Copyright copyright
, RSS.WebMaster "freeman.phil@gmail.com"
]
(map renderFeedPost posts)
renderFeedPost :: Post -> RSS.Item
renderFeedPost post =
[ RSS.Title title
, RSS.Link $
URI.URI
"https:"
(Just (URI.URIAuth "" "blog.functorial.com" ""))
("/posts/" ++ postFilename (filename post))
""
""
, RSS.PubDate (Time.parseTimeOrError True Time.defaultTimeLocale "%Y/%m/%d" date)
]
where
title = maybe "" id $ lookup "title" (tags post)
date = maybe "" id $ lookup "date" (tags post)
writeHtml :: FilePath -> H.Html -> IO ()
writeHtml fp = writeFile fp . renderHtml
writeRSS :: FilePath -> RSS.RSS -> IO ()
writeRSS fp = writeFile fp . RSS.showXML . RSS.rssToXML
main :: IO ()
main = do
dir <- getCurrentDirectory
let
dirOutput = dir </> "output"
dirPosts = dir </> "output" </> "posts"
dirAssets = dir </> "output" </> "assets"
assets <- filter (\f -> isSuffixOf ".js" f || isSuffixOf ".css" f) <$> getDirectoryContents (dir </> "assets")
posts <- getAllPosts $ dir </> "posts"
mapM_ (createDirectoryIfMissing False) [ dirOutput, dirAssets, dirPosts ]
mapM_ (\f -> copyFile (dir </> "assets" </> f) (dirAssets </> f)) assets
mapM_ (\post -> writeHtml (dirPosts </> postFilename (filename post)) (renderPost post)) posts
writeHtml (dirOutput </> "index.html") (renderIndex posts)
writeRSS (dirOutput </> "feed.rss") (renderFeed posts)
| functorial/blog-source | Main.hs | bsd-3-clause | 6,344 | 0 | 20 | 1,452 | 2,273 | 1,164 | 1,109 | 154 | 5 |
-- © 2002-2005 Peter Thiemann
-- |Haskell98 version of the submission functions.
module WASH.CGI.Submit98
( InputHandle, HasValue (value)
, F0 (F0), F1 (F1), F2 (F2), F3 (F3), F4 (F4), F5 (F5), F6 (F6), F7 (F7), F8 (F8)
, FL (FL), FA (FA)
, deF0, deF1, deF2, deF3, deF4, deF5, deF6, deF7, deF8
, deFL, deFA
, deValueF0, deValueF1, deValueF2, deValueF3, deValueF4, deValueF5, deValueF6, deValueF7, deValueF8
, deValueFL, deValueFA
, submit, submit0, defaultSubmit, DTree, submitx, dtleaf, dtnode
, submitLink, submitLink0, defaultSubmitLink
, activate
)
where
import WASH.CGI.AbstractSelector
import WASH.CGI.CGIInternals
import WASH.CGI.CGIMonad
import WASH.CGI.EventHandlers
import qualified WASH.CGI.HTMLWrapper as H
import WASH.CGI.InputHandle
import Control.Monad
instance HasValue InputField where
value inf = valueInputField inf
instance InputHandle (InputField a) where
validate inf = validateInputField inf
isBound inf = ifBound inf
ihNames inf = [ifName inf]
data F0 x = F0
deF0 :: r -> (F0 x -> r)
deF0 r F0 = r
deValueF0 r F0 = r
instance InputHandle F0 where
validate F0 = Right F0
isBound F0 = True
ihNames F0 = []
data F1 a x = F1 (a x)
deF1 :: (a x -> r) -> (F1 a x -> r)
deF1 g (F1 ax) = g ax
deValueF1 g (F1 ax) = g (value ax)
instance InputHandle a => InputHandle (F1 a) where
validate (F1 ainv) =
feither id F1 (validate ainv)
isBound (F1 ainv) = isBound ainv
ihNames (F1 ainv) = ihNames ainv
data F2 a b x = F2 (a x) (b x)
deF2 :: (a x -> b x -> r) -> (F2 a b x -> r)
deF2 g (F2 ax bx) = g ax bx
deValueF2 g (F2 ax bx) = g (value ax) (value bx)
instance (InputHandle a, InputHandle b) => InputHandle (F2 a b) where
validate (F2 ainv binv) =
feither id (uncurry F2)
(propagate (validate ainv) (validate binv))
isBound (F2 ainv binv) =
isBound ainv && isBound binv
ihNames (F2 ainv binv) =
ihNames ainv ++ ihNames binv
data F3 a b c x = F3 (a x) (b x) (c x)
deF3 :: (a x -> b x -> c x -> r) -> (F3 a b c x -> r)
deF3 g (F3 ax bx cx) = g ax bx cx
deValueF3 g (F3 ax bx cx) = g (value ax) (value bx) (value cx)
instance (InputHandle a, InputHandle b, InputHandle c) => InputHandle (F3 a b c) where
validate (F3 ainv binv cinv) =
feither id (\ (aval,(bval,cval)) -> F3 aval bval cval)
(propagate (validate ainv)
(propagate (validate binv) (validate cinv)))
isBound (F3 ainv binv cinv) =
isBound ainv && isBound binv && isBound cinv
ihNames (F3 ainv binv cinv) =
ihNames ainv ++ ihNames binv ++ ihNames cinv
data F4 a b c d x = F4 (a x) (b x) (c x) (d x)
deF4 :: (a x -> b x -> c x -> d x -> r) -> (F4 a b c d x -> r)
deF4 g (F4 ax bx cx dx) = g ax bx cx dx
deValueF4 g (F4 ax bx cx dx) = g (value ax) (value bx) (value cx) (value dx)
instance (InputHandle a, InputHandle b, InputHandle c, InputHandle d)
=> InputHandle (F4 a b c d) where
validate (F4 ainv binv cinv dinv) =
feither id (\ (aval,(bval,(cval,dval))) -> F4 aval bval cval dval)
(propagate (validate ainv)
(propagate (validate binv)
(propagate (validate cinv) (validate dinv))))
isBound (F4 ainv binv cinv dinv) =
isBound ainv && isBound binv && isBound cinv && isBound dinv
ihNames (F4 ainv binv cinv dinv) =
ihNames ainv ++ ihNames binv ++ ihNames cinv ++ ihNames dinv
data F5 a b c d e x = F5 (a x) (b x) (c x) (d x) (e x)
deF5 :: (a x -> b x -> c x -> d x -> e x -> r) -> (F5 a b c d e x -> r)
deF5 g (F5 ax bx cx dx ex) = g ax bx cx dx ex
deValueF5 g (F5 ax bx cx dx ex) = g (value ax) (value bx) (value cx) (value dx) (value ex)
instance (InputHandle a, InputHandle b, InputHandle c, InputHandle d, InputHandle e)
=> InputHandle (F5 a b c d e) where
validate (F5 ainv binv cinv dinv einv) =
feither id (\ (aval,(bval,(cval,(dval,eval)))) -> F5 aval bval cval dval eval)
(propagate (validate ainv)
(propagate (validate binv)
(propagate (validate cinv)
(propagate (validate dinv) (validate einv)))))
isBound (F5 ainv binv cinv dinv einv) =
isBound ainv && isBound binv && isBound cinv && isBound dinv && isBound einv
ihNames (F5 ainv binv cinv dinv einv) =
ihNames ainv ++ ihNames binv ++ ihNames cinv ++ ihNames dinv ++ ihNames einv
data F6 a b c d e f x = F6 (a x) (b x) (c x) (d x) (e x) (f x)
deF6 :: (a x -> b x -> c x -> d x -> e x -> f x -> r) -> (F6 a b c d e f x -> r)
deF6 g (F6 ax bx cx dx ex fx) = g ax bx cx dx ex fx
deValueF6 g (F6 ax bx cx dx ex fx) = g (value ax) (value bx) (value cx) (value dx) (value ex) (value fx)
instance (InputHandle a, InputHandle b, InputHandle c, InputHandle d, InputHandle e, InputHandle f)
=> InputHandle (F6 a b c d e f) where
validate (F6 ainv binv cinv dinv einv finv) =
feither id (\ (aval,(bval,(cval,(dval,(eval, fval))))) -> F6 aval bval cval dval eval fval)
(propagate (validate ainv)
(propagate (validate binv)
(propagate (validate cinv)
(propagate (validate dinv)
(propagate (validate einv) (validate finv))))))
isBound (F6 ainv binv cinv dinv einv finv) =
isBound ainv && isBound binv && isBound cinv && isBound dinv && isBound einv && isBound finv
ihNames (F6 ainv binv cinv dinv einv finv) =
ihNames ainv ++ ihNames binv ++ ihNames cinv ++ ihNames dinv ++ ihNames einv ++ ihNames finv
data F7 a b c d e f g x = F7 (a x) (b x) (c x) (d x) (e x) (f x) (g x)
deF7 :: (a x -> b x -> c x -> d x -> e x -> f x -> g x -> r) -> (F7 a b c d e f g x -> r)
deF7 g (F7 ax bx cx dx ex fx gx) = g ax bx cx dx ex fx gx
deValueF7 g (F7 ax bx cx dx ex fx gx) = g (value ax) (value bx) (value cx) (value dx) (value ex) (value fx) (value gx)
instance (InputHandle a, InputHandle b, InputHandle c, InputHandle d, InputHandle e, InputHandle f, InputHandle g)
=> InputHandle (F7 a b c d e f g) where
validate (F7 ainv binv cinv dinv einv finv ginv) =
feither id (\ (aval,(bval,(cval,(dval,(eval, (fval, gval)))))) -> F7 aval bval cval dval eval fval gval)
(propagate (validate ainv)
(propagate (validate binv)
(propagate (validate cinv)
(propagate (validate dinv)
(propagate (validate einv)
(propagate (validate finv) (validate ginv)))))))
isBound (F7 ainv binv cinv dinv einv finv ginv) =
isBound ainv && isBound binv && isBound cinv && isBound dinv && isBound einv && isBound finv && isBound ginv
ihNames (F7 ainv binv cinv dinv einv finv ginv) =
ihNames ainv ++ ihNames binv ++ ihNames cinv ++ ihNames dinv ++ ihNames einv ++ ihNames finv ++ ihNames ginv
data F8 a b c d e f g h x = F8 (a x) (b x) (c x) (d x) (e x) (f x) (g x) (h x)
deF8 :: (a x -> b x -> c x -> d x -> e x -> f x -> g x -> h x -> r) -> (F8 a b c d e f g h x -> r)
deF8 g (F8 ax bx cx dx ex fx gx hx) = g ax bx cx dx ex fx gx hx
deValueF8 g (F8 ax bx cx dx ex fx gx hx) = g (value ax) (value bx) (value cx) (value dx) (value ex) (value fx) (value gx) (value hx)
instance (InputHandle a, InputHandle b, InputHandle c, InputHandle d, InputHandle e, InputHandle f, InputHandle g, InputHandle h)
=> InputHandle (F8 a b c d e f g h) where
validate (F8 ainv binv cinv dinv einv finv ginv hinv) =
feither id (\ (aval,(bval,(cval,(dval,(eval, (fval, (gval, hval))))))) -> F8 aval bval cval dval eval fval gval hval)
(propagate (validate ainv)
(propagate (validate binv)
(propagate (validate cinv)
(propagate (validate dinv)
(propagate (validate einv)
(propagate (validate finv)
(propagate (validate ginv) (validate hinv))))))))
isBound (F8 ainv binv cinv dinv einv finv ginv hinv) =
isBound ainv && isBound binv && isBound cinv && isBound dinv && isBound einv && isBound finv && isBound ginv && isBound hinv
ihNames (F8 ainv binv cinv dinv einv finv ginv hinv) =
ihNames ainv ++ ihNames binv ++ ihNames cinv ++ ihNames dinv ++ ihNames einv ++ ihNames finv ++ ihNames ginv ++ ihNames hinv
-- |'FL' is required to pass an unknown number of handles of the same
-- type need to the callback function in a form submission. The
-- handles need to be collected in a list and then wrapped in the 'FL' data constructor
data FL a x = FL [a x]
deFL :: ([a x] -> r) -> (FL a x -> r)
deFL g (FL axs) = g axs
deValueFL g (FL axs) = g (map value axs)
instance InputHandle a => InputHandle (FL a) where
validate (FL ainvs) =
g (map validate ainvs) -- [Either [ValidationError] (h VALID)]
where
g = foldr h (Right (FL []))
h ev evs = feither id (\ (v, FL vs) -> FL (v : vs)) (propagate ev evs)
isBound (FL ainvs) =
all isBound ainvs
ihNames (FL ainvs) =
concatMap ihNames ainvs
-- |'FA' comes handy when you want to tag an input handle with some extra
-- information, which is not itsefl an input handle and which is not validated
-- by a form submission. The tag is the first argument and the handle is the
-- second argument of the data constructor.
data FA a b x = FA a (b x)
deFA :: (a -> b x -> r) -> (FA a b x -> r)
deFA g (FA a bx) = g a bx
deValueFA g (FA a bx) = g a (value bx)
instance InputHandle b => InputHandle (FA a b) where
validate (FA a binv) =
feither id (FA a) (validate binv)
isBound (FA a binv) =
isBound binv
ihNames (FA a binv) =
ihNames binv
-- |Create a submission button with attached action.
submit :: (CGIMonad cgi, InputHandle h)
=> h INVALID -- ^input field handles to be validated and passed to callback action
-> (h VALID -> cgi ()) -- ^callback maps valid input handles to a CGI action
-> HTMLField cgi x y () -- ^returns a field so that attributes can be attached
submit = submitInternal False
-- |Create a continuation button that takes no parameters.
submit0 :: (CGIMonad cgi) => cgi () -> HTMLField cgi x y ()
submit0 cont = submit F0 (\F0 -> cont)
-- |Create a submission button whose attached action is fired whenever the form
-- is submitted without explicitly clicking any submit button. This can happen if
-- an input field has an attached onclick="submit()" action.
defaultSubmit :: (CGIMonad cgi, InputHandle h) =>
h INVALID -> (h VALID -> cgi ()) -> HTMLField cgi x y ()
defaultSubmit = submitInternal True
-- |Create an ordinary link serving as a submission button.
submitLink :: (CGIMonad cgi, InputHandle h) =>
h INVALID -> (h VALID -> cgi ()) -> H.HTMLCons x y cgi ()
submitLink = submitInternalLink False
-- |Create a continuation link.
submitLink0 :: (CGIMonad cgi) => cgi () -> H.HTMLCons x y cgi ()
submitLink0 cont = submitLink F0 (const cont)
defaultSubmitLink :: (CGIMonad cgi, InputHandle h) =>
h INVALID -> (h VALID -> cgi ()) -> H.HTMLCons x y cgi ()
defaultSubmitLink = submitInternalLink True
-- |Abstract type of decisions trees. These trees provide structured validation.
newtype DTree cgi x y = DTree { unDTree :: HTMLField cgi x y () }
-- |Create a submission button whose validation proceeds according to a decision
-- tree. Trees are built using 'dtleaf' and 'dtnode'.
submitx :: DTree cgi x y -> HTMLField cgi x y ()
submitx = unDTree
-- |Create a leaf in a decision tree from a CGI action.
dtleaf :: (CGIMonad cgi) => cgi () -> DTree cgi x y
dtleaf action = DTree $ submit0 action
-- |Create a node in a decision tree. Takes an invalid input field and a
-- continuation. Validates the input field and passes it to the continuation if
-- the validation was successful. The continuation can dispatch on the value of
-- the input field and produces a new decision tree.
dtnode :: (CGIMonad cgi, InputHandle h) =>
h INVALID -> (h VALID -> DTree cgi x y) -> DTree cgi x y
dtnode hinv next =
if isBound hinv then
case validate hinv of
Right hval ->
next hval
Left ss ->
DTree $ internalSubmitField False (Left ss)
else
DTree $ internalSubmitField False (Left [])
submitInternal isDefault hinv g =
internalSubmitField isDefault (validator hinv g)
validator hinv g =
either Left (Right . g) (validate hinv)
submitInternalLink isDefault hinv g =
internalSubmitLink isDefault (validator hinv g)
instance HasValue RadioGroup where
value rg = valueRadioGroup rg
instance InputHandle (RadioGroup a) where
validate rg = validateRadioGroup rg
isBound rg = radioBound rg
ihNames rg = [radioName rg]
instance HasValue SelectionGroup where
value sg = valueSelectionGroup sg
instance InputHandle (SelectionGroup a) where
validate sg = validateSelectionGroup sg
isBound sg = selectionBound sg
ihNames sg = [selectionName sg]
-- |Attach a CGI action to the value returned by the input field. Activation
-- means that data is submitted as soon as it is entered.
activate :: (CGIMonad cgi, InputHandle (i a), HasValue i) =>
(a -> cgi ()) -> HTMLField cgi x y (i a INVALID) -> HTMLField cgi x y (i a INVALID)
activate actionFun inputField attrs =
do invalid_inf <- inputField (do attrs
onChange $ "WASHSubmit(this.name);")
let r = validate invalid_inf
rv = either Left (Right . value) r
when (isBound invalid_inf) $
activateInternal actionFun (head $ ihNames invalid_inf) rv
return invalid_inf
| nh2/WashNGo | WASH/CGI/Submit98.hs | bsd-3-clause | 12,973 | 19 | 22 | 2,961 | 5,687 | 2,895 | 2,792 | 260 | 3 |
{-# LANGUAGE DeriveFunctor #-}
module Crossword.Description where
import Text.Parsec hiding ((<|>))
import Crossword.Parser (Parser)
import Crossword.Regex
import qualified Crossword.Parser as P
data Description = Description
{ horizontal :: [Clue Regex]
, vertical :: [Clue Regex]
, diagonal :: [Clue Regex]
} deriving Show
description :: Parser Description
description = Description <$> (string "Horizontal" *> newline *> many1 (pClue <* newline))
<* newline
<*> (string "Vertical" *> newline *> many1 (pClue <* newline))
<* newline
<*> (string "Diagonal" *> newline *> many1 (pClue <* newline))
type Position = (Int, Int)
type Length = Int
data Clue a = Clue
{ position :: Position
, len :: Length
, clue :: a
} deriving (Show, Functor)
pClue :: Parser (Clue Regex)
pClue = Clue <$> pPosition <* spaces <*> number <* spaces <*> P.regex
pPosition :: Parser (Int, Int)
pPosition = (,) <$ char '(' <*> number <* char ',' <*> number <* char ')'
number :: Parser Int
number = read <$> many1 digit
| hesselink/regex-crossword | src/Crossword/Description.hs | bsd-3-clause | 1,144 | 0 | 14 | 312 | 365 | 203 | 162 | 30 | 1 |
--------------------------------------------------
-- Copyright 1994 by Peter Thiemann
-- $Log: Parsers.hs,v $
-- Revision 1.1.1.1 1998/12/09 13:34:08 pjt
-- Imported sources
--
-- Revision 1.3 1994/03/15 15:34:53 thiemann
-- minor revisions
--
--Revision 1.2 1993/08/31 12:31:32 thiemann
--reflect changes in type FONT
--
--Revision 1.1 1993/08/17 12:34:29 thiemann
--Initial revision
--
-- $Locker: $
--------------------------------------------------
module Parsers where
infixl 6 `using`, `using2`
infixr 7 `alt`
infixr 8 `thn`, `xthn`, `thnx`
type Parser a b = [a] -> [(b, [a])]
succeed :: beta -> Parser alpha beta
succeed value tokens = [(value, tokens)]
-- the parser
-- satisfy p
-- accepts the language { token | p(token) }
satisfy :: (alpha -> Bool) -> Parser alpha alpha
satisfy p [] = []
satisfy p (token:tokens) | p token = succeed token tokens
| otherwise = []
-- the parser
-- literal word
-- accepts { word }
literal :: Eq alpha => alpha -> Parser alpha alpha
literal token = satisfy (== token)
-- if p1 and p2 are parsers accepting L1 and L2 then
-- then p1 p2
-- accepts L1.L2
thn :: Parser alpha beta -> Parser alpha gamma -> Parser alpha (beta, gamma)
thn p1 p2 =
concat
. map (\ (v1, tokens1) -> map (\ (v2, tokens2) -> ((v1,v2), tokens2)) (p2 tokens1))
. p1
thnx :: Parser alpha beta -> Parser alpha gamma -> Parser alpha beta
thnx p1 p2 =
concat
. map (\ (v1, tokens1) -> map (\ (v2, tokens2) -> (v1, tokens2)) (p2 tokens1))
. p1
xthn :: Parser alpha beta -> Parser alpha gamma -> Parser alpha gamma
xthn p1 p2 =
concat
. map (\ (v1, tokens1) -> map (\ (v2, tokens2) -> (v2, tokens2)) (p2 tokens1))
. p1
-- if p1 and p2 are parsers accepting L1 and L2 then
-- alt p1 p2
-- accepts L1 \cup L2
alt :: Parser alpha beta -> Parser alpha beta -> Parser alpha beta
alt p1 p2 tokens = p1 tokens ++ p2 tokens
-- if p1 is a parser then
-- using p1 f
-- is a parser that accepts the same language as p1
-- but mangles the semantic value with f
using :: Parser alpha beta -> (beta -> gamma) -> Parser alpha gamma
using p1 f = map (\ (v, tokens) -> (f v, tokens)) . p1
using2 :: Parser a (b,c) -> (b -> c -> d) -> Parser a d
using2 p f = map ( \((v,w), tokens) -> (f v w, tokens)) . p
-- if p accepts L then plus p accepts L+
plus :: Parser alpha beta -> Parser alpha [beta]
plus p = (p `thn` rpt p) `using2` (:)
-- if p accepts L then rpt p accepts L*
rpt :: Parser alpha beta -> Parser alpha [beta]
rpt p = plus p `alt` succeed []
-- if p accepts L then opt p accepts L?
opt :: Parser alpha beta -> Parser alpha [beta]
opt p = (p `using` \x -> [x]) `alt` succeed []
-- followedBy p1 p2 recognizes L(p1) if followed by a word in L (p2)
followedBy :: Parser a b -> Parser a c -> Parser a b
followedBy p q tks = [(v, rest) | (v, rest) <- p tks, x <- q rest]
| FranklinChen/Ebnf2ps | src/Parsers.hs | bsd-3-clause | 2,821 | 6 | 14 | 598 | 987 | 548 | 439 | 42 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | scan a local index downloaded from Hackage
module Hackage where
import Edit.Types
import Edit.Parser
import Control.Exception
import Control.Monad
import Data.Data
import Data.Either (rights)
import Data.Foldable
import Data.Monoid
import Data.Ord (comparing)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Lazy (toStrict)
import qualified Data.Text.Lazy.Builder as TB
import qualified Data.Text.Read as T
import Data.Typeable
import Shelly
import System.Environment
import Text.Parsec
import Data.Traversable
import Shelly
import Text.Parsec
import Prelude hiding
(foldl, foldl1, foldr, foldr1
, mapM, mapM_, sequence, sequence_
, head, tail, last, init, map, (++), (!!), FilePath, lines
, maximum, maximumBy, readFile, writeFile)
-- | parse the .cabal file for the most recent version of each package.
scanHackage :: FilePath -> Maybe Int -> Sh [Either ParseError [DetailedPackage]]
scanHackage hackagePath limit = do
paths <- ls hackagePath
packages <- filterM test_d paths
traverse parseLatest (case limit of
Nothing -> packages
Just n -> take n packages)
parseLatest :: FilePath -> Sh (Either ParseError [DetailedPackage])
parseLatest dir = do
versions <- traverse toTextWarn =<< ls dir
let newest = newestVersion versions
fns <- traverse toTextWarn =<< filter (hasExt "cabal") <$> ls (dir </> newest)
let cabalFileName = case fns of
[] -> throw . IndexLayoutError $ "packageStat: expected .cabal file in " <> newest
[c] -> c
_ -> throw . IndexLayoutError $ "packageStat: only expected one .cabal file in " <> newest
cabal <- readfile (dir </> newest </> cabalFileName)
return $ parse detailedParser (T.unpack cabalFileName) cabal
-- | Pick newest version based on standard package numbering. If we
-- can't make sense of the version number, fall back to lexicographic
-- ordering.
newestVersion :: [Text] -> Text
newestVersion [] = throw $ IndexLayoutError "newestVersion: Cannot pick one from an empty list"
newestVersion vs = case rights $ fmap splitVersion vs of
[] -> maximum vs
vs' -> fst . maximumBy (comparing snd) $ zip vs vs'
splitVersion :: Text -> Either String [Int]
splitVersion = traverse (fmap fst . T.decimal) . T.splitOn "."
data HackageError =
IndexLayoutError Text
deriving (Typeable, Data, Show)
instance Exception HackageError
| bergey/cabal-edit | executables/Hackage.hs | bsd-3-clause | 2,708 | 0 | 15 | 697 | 681 | 368 | 313 | 58 | 3 |
module Cis194.Hw.Week1Spec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Cis194.Hw.Week1
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "toDigits" $ do
it "should split digits of integer into a list" $ do
toDigits 1234 `shouldBe` [1,2,3,4]
it "should return an empty list for zero" $ do
toDigits 0 `shouldBe` []
-- uses QuickCheck - need to learn how to generate constrained inputs
it "should return an empty list for negative numbers" $ property $
\x -> (if x < 0 then (toDigits x) else []) == ([] :: [Integer])
describe "toDigitsRev" $ do
it "should return an empty list for zero" $ do
toDigitsRev 0 `shouldBe` []
it "should return an empty list for negative numbers" $ do
toDigitsRev (-1) `shouldBe` []
toDigitsRev (-22222) `shouldBe` []
it "should split digits of integer into a list in reverse order" $ do
toDigitsRev 123 `shouldBe` [3,2,1]
toDigitsRev 431 `shouldBe` [1,3,4]
toDigitsRev 12 `shouldBe` [2,1]
toDigitsRev 2 `shouldBe` [2]
describe "doubleEveryOther" $ do
it "should return an empty list given an empty list" $ do
doubleEveryOther [] `shouldBe` []
it "should double every other int in the list, from right to left" $ do
doubleEveryOther [8,7,6,5] `shouldBe`[16,7,12,5]
doubleEveryOther [1,2,3] `shouldBe` [1,4,3]
describe "sumDigits" $ do
it "should return zero for an empty list" $ do
sumDigits [] `shouldBe` 0
it "should sum all digits in the list" $ do
sumDigits [16,7,12,5] `shouldBe` 22
sumDigits [18,7,33,5] `shouldBe` 27
describe "validate" $ do
it "should return True for valid card number" $ do
validate 4012888888881881 `shouldBe` True
it "should return False for invalid card number" $ do
validate 4012888888881882 `shouldBe` False
describe "hanoi" $ do
it "should return an empty list for zero discs" $ do
hanoi 0 "a" "b" "c" `shouldBe` []
it "should solve for 1 disc" $ do
hanoi 1 "a" "b" "c" `shouldBe` [("a", "b")]
| halarnold2000/cis194 | test/Cis194/Hw/Week1Spec.hs | bsd-3-clause | 2,095 | 0 | 16 | 520 | 687 | 353 | 334 | 48 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP #-}
module Cauterize.GHC7.Support.Result
( Trace(..)
, CautResult(..)
, CautError(..)
, failWithTrace
, withTrace
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Monad.Morph
import Control.Monad.Trans.Reader
import qualified Data.Text as T
data CautError
= CautError { errorMsg :: T.Text -- Description of the error.
, errorTrace :: [Trace] -- Trace to the error. Head of the list is most recent trace.
} deriving (Show, Eq)
-- Identifies the path through the cauterize structure.
data Trace = TBuiltIn T.Text
| TSynonym T.Text
| TRange T.Text
| TArray T.Text
| TArrayIndex Int
| TVector T.Text
| TVectorTag
| TVectorIndex Int
| TEnumeration T.Text
| TRecord T.Text
| TRecordField T.Text
| TCombination T.Text
| TCombinationTag
| TCombinationField T.Text
| TUnion T.Text
| TUnionTag
| TUnionField T.Text
deriving (Show, Eq)
-- Insert information into the trace stack and fail.
failWithTrace :: (MonadTrans t, Monad (t CautResult))
=> T.Text -> t CautResult a
failWithTrace msg = do
currentTrace <- lift $ CautResult ask
lift $ CautResult $ lift $ Left $ CautError msg currentTrace
-- Insert new information into the trace stack.
withTrace :: (MonadTrans t, Monad (t CautResult), MFunctor t)
=> Trace -> t CautResult a -> t CautResult a
withTrace trace = hoist (CautResult . local (trace:) . unCautResult)
newtype CautResult a =
CautResult {
unCautResult :: ReaderT [Trace] (Either CautError) a
} deriving (Functor, Applicative, Monad)
| cauterize-tools/caut-ghc7-ref | lib/Cauterize/GHC7/Support/Result.hs | bsd-3-clause | 1,793 | 0 | 10 | 502 | 433 | 248 | 185 | 45 | 1 |
module Sexy.Instances.Nil.Maybe () where
import Sexy.Data (Maybe(..))
import Sexy.Classes (Nil(..))
instance Nil (Maybe a) where
nil = Nothing
| DanBurton/sexy | src/Sexy/Instances/Nil/Maybe.hs | bsd-3-clause | 147 | 0 | 7 | 22 | 58 | 36 | 22 | 5 | 0 |
module Deprecated.DiGraph.TreeMonoidFoldOnSimpleGraph where
----------------------------------------------------------------------
-- test experiments
import Data.Hashable
import PolyGraph.ReadOnly.DiGraph
import PolyGraph.Common
import PolyGraph.ReadOnly.DiGraph.Fold.TAMonoidFold
import qualified Data.HashSet as HS
import Deprecated.DiGraph.SampleData (playTwoDiamonds)
-- | Numbers as Monoids under addition.
newtype Sum a = Sum { getSum :: a } deriving Show
instance Num a => Monoid (Sum a) where
mempty = Sum 0
Sum x `mappend` Sum y = Sum (x + y)
--
-- example aggregator (polymorphic for arbitrary v and e types but to count a needs to be an Int or something of that sort)
--
countTreeEdges :: MonoidFoldAccLogic v e (Sum Int)
countTreeEdges = defaultMonoidFoldAccLogic {
applyEdge = const (Sum 1)
}
testDimongGraphEdgeCount:: Int
testDimongGraphEdgeCount = getSum $ (dfsFold playTwoDiamonds (countTreeEdges :: MonoidFoldAccLogic v (OPair v) (Sum Int)) "a0") -- :: tells compiler how to specialize polymorphic aggregator
-- prints 4
--
-- NOTE if I used [] instead of HashSet this aggregator would not scale (would have exp cost)
--
listChildVertices :: forall v e . (Hashable v, Eq v) => MonoidFoldAccLogic v e (HS.HashSet v)
listChildVertices = defaultMonoidFoldAccLogic {
applyVertex = (\ v -> HS.singleton v)
}
testDimongVerices:: [String]
testDimongVerices = HS.toList (dfsFold playTwoDiamonds (listChildVertices :: MonoidFoldAccLogic String (OPair String) (HS.HashSet String)) "a0")
-- :: Note need to tell compiler how to specialize polymorphic aggreagator
-- prints all vertices
--
-- One more polymorphic aggregator
--
countDepth :: MonoidFoldAccLogic v e (Sum Int)
countDepth = defaultMonoidFoldAccLogic {
applyEdge = const( Sum 1)
}
testDimongGraphDepthCount:: Int
testDimongGraphDepthCount = getSum $ (dfsFold playTwoDiamonds (countDepth :: MonoidFoldAccLogic v (OPair v) (Sum Int)) "a0") -- :: needs to define edge type
-- prints 2
experiments = [show testDimongGraphDepthCount, show testDimongGraphEdgeCount, show testDimongVerices]
-- prints all examples
| rpeszek/GraphPlay | play/Deprecated/DiGraph/TreeMonoidFoldOnSimpleGraph.hs | bsd-3-clause | 2,217 | 0 | 12 | 419 | 467 | 265 | 202 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Graphics.GPipe
import qualified Data.Vec as Vec
import Data.Vec.Nat
import Data.Monoid
import Data.IORef
import Graphics.UI.GLUT
(Window,
mainLoop,
postRedisplay,
idleCallback,
getArgsAndInitialize,
($=))
main :: IO ()
main = do
getArgsAndInitialize
angleRef <- newIORef 0.0
newWindow "Spinning box" (100:.100:.()) (800:.600:.()) (renderFrame angleRef) initWindow
mainLoop
renderFrame :: IORef Float -> Vec2 Int -> IO (FrameBuffer RGBFormat () ())
renderFrame angleRef size = do
angle <- readIORef angleRef
writeIORef angleRef ((angle + 0.005) `mod'` (2*pi))
return $ cubeFrameBuffer angle size
initWindow :: Window -> IO ()
initWindow win = idleCallback $= Just (postRedisplay (Just win))
cube :: PrimitiveStream Triangle (Vec3 (Vertex Float), Vec3 (Vertex Float), Vec2 (Vertex Float))
cube = mconcat [sidePosX, sideNegX, sidePosY, sideNegY, sidePosZ, sideNegZ]
sidePosX = toGPUStream TriangleStrip $ zip3 [1:.0:.0:.(), 1:.1:.0:.(), 1:.0:.1:.(), 1:.1:.1:.()] (repeat (1:.0:.0:.())) uvCoords
sideNegX = toGPUStream TriangleStrip $ zip3 [0:.0:.1:.(), 0:.1:.1:.(), 0:.0:.0:.(), 0:.1:.0:.()] (repeat ((-1):.0:.0:.())) uvCoords
sidePosY = toGPUStream TriangleStrip $ zip3 [0:.1:.1:.(), 1:.1:.1:.(), 0:.1:.0:.(), 1:.1:.0:.()] (repeat (0:.1:.0:.())) uvCoords
sideNegY = toGPUStream TriangleStrip $ zip3 [0:.0:.0:.(), 1:.0:.0:.(), 0:.0:.1:.(), 1:.0:.1:.()] (repeat (0:.(-1):.0:.())) uvCoords
sidePosZ = toGPUStream TriangleStrip $ zip3 [1:.0:.1:.(), 1:.1:.1:.(), 0:.0:.1:.(), 0:.1:.1:.()] (repeat (0:.0:.1:.())) uvCoords
sideNegZ = toGPUStream TriangleStrip $ zip3 [0:.0:.0:.(), 0:.1:.0:.(), 1:.0:.0:.(), 1:.1:.0:.()] (repeat (0:.0:.(-1):.())) uvCoords
uvCoords = [0:.0:.(), 0:.1:.(), 1:.0:.(), 1:.1:.()]
transformedCube :: Float -> Vec2 Int -> PrimitiveStream Triangle (Vec4 (Vertex Float), (Vec3 (Vertex Float), Vec2 (Vertex Float)))
transformedCube angle size = fmap (transform angle size) cube
transform :: Float
-> Vec2 Int
-> (Vec3 (Vertex Float),Vec3 (Vertex Float),Vec2 (Vertex Float))
-> (Vec4 (Vertex Float),(Vec3 (Vertex Float),Vec2 (Vertex Float)))
transform angle (width:.height:.()) (pos, norm, uv) = (transformedPos, (transformedNorm, uv))
where
modelMat = rotationVec (normalize (1:.0.5:.0.3:.())) angle `multmm` translation (-0.5)
viewMat = translation (-(0:.0:.2:.()))
projMat = perspective 1 100 (pi/3) (fromIntegral width / fromIntegral height)
viewProjMat = projMat `multmm` viewMat
transformedPos = toGPU (viewProjMat `multmm` modelMat) `multmv` (homPoint pos :: Vec4 (Vertex Float))
transformedNorm = toGPU (Vec.map (Vec.take n3) $ Vec.take n3 modelMat) `multmv` norm
rasterizedCube :: Float -> Vec2 Int -> FragmentStream (Vec3 (Fragment Float), Vec2 (Fragment Float))
rasterizedCube angle size = rasterizeFront $ transformedCube angle size
litCube :: Float -> Vec2 Int -> FragmentStream (Color RGBFormat (Fragment Float))
litCube angle size = fmap enlight $ rasterizedCube angle size
enlight :: (Vec3 (Fragment Float), Vec2 (Fragment Float)) -> Color RGBFormat (Fragment Float)
enlight (norm, uv) = RGB (0:.2:.0:. ())
cubeFrameBuffer :: Float -> Vec2 Int -> FrameBuffer RGBFormat () ()
cubeFrameBuffer angle size = paintSolid (litCube angle size) emptyFrameBuffer
paintSolid = paintColor NoBlending (RGB $ Vec.vec True)
emptyFrameBuffer = newFrameBufferColor (RGB 0)
| robgssp/strobe | Test2.hs | bsd-3-clause | 3,512 | 0 | 14 | 585 | 1,794 | 932 | 862 | 59 | 1 |
module TUDMensa.Get (getWeekly) where
import Control.Applicative
import Data.Char
import TUDMensa.Types
import Network.HTTP
import Text.HTML.TagSoup
baseUrl :: String
baseUrl = "http://www.studentenwerkdarmstadt.de/index.php?option=com_spk&task="
weeklyUrl :: Date -> Location -> Request String
weeklyUrl NextWeek loc = getRequest $ baseUrl ++ tell loc ++ "&view=nextweek"
weeklyUrl _ loc = getRequest $ baseUrl ++ tell loc ++ "&view=week"
tell = map toLower . show
getWeekly :: Date -> Location -> IO [Tag String]
getWeekly =
(.) (fmap (parseTags . either (const []) rspBody) . simpleHTTP) . weeklyUrl
| dschoepe/tud-mensa | TUDMensa/Get.hs | bsd-3-clause | 610 | 0 | 15 | 88 | 191 | 101 | 90 | 15 | 1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Prelude hiding (repeat, take)
data L a = N | C a (L a)
[lq|
data L a <p :: (L a) -> Prop>
= N
| C (x::a) (xs::L <p> a <<p>>)
|]
[lq|
measure isCons :: L a -> Prop
isCons (N) = false
isCons (C a l) = true
|]
[lq| type Stream a = {v: L <{\v -> (isCons v)}> a | (isCons v)} |]
[lq| Lazy repeat |]
[lq| repeat :: a -> Stream a |]
repeat :: a -> L a
repeat x = C x (repeat x)
[lq| take :: Nat -> Stream a -> L a |]
take :: Int -> L a -> L a
take 0 _ = N
take n ys@(C x xs) = x `C` take (n-1) xs
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/Repeat.hs | bsd-3-clause | 575 | 0 | 8 | 165 | 179 | 103 | 76 | 15 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Module : $Header$
Copyright : (c) 2015 Swinburne Software Innovation Lab
License : BSD3
Maintainer : Rhys Adams <rhysadams@swin.edu.au>
Stability : unstable
Portability : portable
Entry point for the subexecutor, called by the executor on compute slaves.
-}
module Main where
import Prelude hiding (writeFile)
import qualified Eclogues.Job as Job
import Eclogues.Paths (runResult, specFile)
import Eclogues.Util (
AbsDir (..), RunResult (..), readJSON, orError, dirName, getOutputPath)
import Control.Arrow ((&&&))
import Control.Monad (when)
import Data.Aeson (encode)
import Data.Aeson.TH (deriveFromJSON, defaultOptions)
import Data.Maybe (fromMaybe)
import Data.Metrology.SI (Second (Second))
import Data.Metrology.Computing ((#>), Time)
import Data.Scientific.Suspicious (toBoundedInteger)
import qualified Data.Text as T
import Lens.Micro ((^.))
import Path ( Path, Abs, Dir, (</>), toFilePath
, parseAbsFile, mkRelFile, mkRelDir )
import Path.IO (getCurrentDirectory, createDirectoryIfMissing, copyFile, writeFile)
import System.Environment (getArgs)
import System.Exit (ExitCode (..))
import System.FilePath.Glob (glob)
import System.Process (callProcess, spawnProcess, waitForProcess)
-- | JSON configuration type.
data SubexecutorConfig = SubexecutorConfig { jobsDir :: AbsDir }
$(deriveFromJSON defaultOptions ''SubexecutorConfig)
-- | Run a bash command with a time limit.
runCommand :: Time -> Job.Command -> IO RunResult
runCommand timeout cmd = do
let time = fromMaybe maxBound . toBoundedInteger $ timeout #> Second :: Int
proc <- spawnProcess "/usr/bin/timeout" [show time, "/bin/bash", "-c", T.unpack cmd]
code <- waitForProcess proc
pure $ case code of
ExitFailure 124 -> Overtime
c -> Ended c
-- | Copy the contents of a directory into another.
copyDirContents :: Path Abs Dir -> Path Abs Dir -> IO ()
copyDirContents from to = callProcess "/bin/cp" ["-r", toFilePath from ++ ".", toFilePath to]
-- | Run a job from its spec.
runJob :: AbsDir -- ^ Shared jobs directory
-> Job.Name -- ^ Job name
-> IO ()
runJob (AbsDir shared) name = do
cwd <- getCurrentDirectory
let inputDir = cwd </> $(mkRelDir "virgil-dependencies/")
copyDep = uncurry copyDirContents . (outputDir &&& (inputDir </>)) . dirName
copyOutput f = copyFile (getOutputPath cwd f)
(getOutputPath (outputDir jobDirName) f)
spec <- orError =<< readJSON (toFilePath $ specDir </> specFile) :: IO Job.Spec
createDirectoryIfMissing False inputDir
mapM_ copyDep $ spec ^. Job.dependsOn
runRes <- runCommand (spec ^. Job.time) (spec ^. Job.command)
-- TODO: Trigger Failed state when output doesn't exist
mapM_ copyOutput $ spec ^. Job.outputFiles
writeFile (specDir </> runResult) $ encode runRes
when (spec ^. Job.captureStdout) $ glob ".logs/*/0/stdout" >>= \case
[fp] | Just fn <- parseAbsFile fp
-> copyFile fn $ outputDir jobDirName </> $(mkRelFile "stdout")
_ -> error "Stdout log file missing"
where
specDir = shared </> jobDirName
outputDir n = shared </> n </> $(mkRelDir "output/")
jobDirName = dirName name
main :: IO ()
main = do
conf <- orError =<< readJSON "/etc/xdg/eclogues/subexecutor.json"
(nameStr:_) <- getArgs
case Job.mkName $ T.pack nameStr of
Nothing -> error "Invalid job name"
Just name -> runJob (jobsDir conf) name
| futufeld/eclogues | eclogues-impl/app/subexecutor/Main.hs | bsd-3-clause | 3,574 | 0 | 15 | 735 | 976 | 521 | 455 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Web.Spock.Internal.SessionVault where
#if MIN_VERSION_base(4,8,0)
#else
import Control.Applicative
#endif
import Control.Concurrent.STM (STM, atomically)
import Control.Monad
import Data.Hashable
import qualified Data.Text as T
import Focus as F
import qualified ListT as L
import qualified StmContainers.Map as STMMap
import Web.Spock.Internal.Types
class (Eq (SessionKey s), Hashable (SessionKey s)) => IsSession s where
type SessionKey s :: *
getSessionKey :: s -> SessionKey s
instance IsSession (Session conn sess st) where
type SessionKey (Session conn sess st) = T.Text
getSessionKey = sess_id
newtype SessionVault s = SessionVault {unSessionVault :: STMMap.Map (SessionKey s) s}
-- | Create a new session vault
newSessionVault :: STM (SessionVault s)
newSessionVault = SessionVault <$> STMMap.new
-- | Load a session
loadSession :: IsSession s => SessionKey s -> SessionVault s -> STM (Maybe s)
loadSession key (SessionVault smap) = STMMap.lookup key smap
-- | Store a session, overwriting any previous values
storeSession :: IsSession s => s -> SessionVault s -> STM ()
storeSession v (SessionVault smap) = STMMap.insert v (getSessionKey v) smap
-- | Removea session
deleteSession :: IsSession s => SessionKey s -> SessionVault s -> STM ()
deleteSession k (SessionVault smap) = STMMap.delete k smap
-- | Get all sessions as list
toList :: SessionVault s -> STM [s]
toList = liftM (map snd) . L.toList . STMMap.listT . unSessionVault
-- | Remove all sessions that do not match the predicate
filterSessions :: IsSession s => (s -> Bool) -> SessionVault s -> STM ()
filterSessions cond sv =
do
allVals <- toList sv
let deleteKeys =
map getSessionKey $
filter (not . cond) allVals
forM_ deleteKeys $ flip deleteSession sv
-- | Perform action on all sessions
mapSessions :: IsSession s => (s -> STM s) -> SessionVault s -> STM ()
mapSessions f sv@(SessionVault smap) =
do
allVals <- toList sv
forM_ allVals $ \sess ->
STMMap.focus (F.adjustM f) (getSessionKey sess) smap
newStmSessionStore' :: IO (SessionStore (Session conn sess st) STM)
newStmSessionStore' =
do
vault <- atomically newSessionVault
return $
SessionStore
{ ss_runTx = atomically,
ss_loadSession = flip loadSession vault,
ss_deleteSession = flip deleteSession vault,
ss_storeSession = flip storeSession vault,
ss_toList = toList vault,
ss_filterSessions = flip filterSessions vault,
ss_mapSessions = flip mapSessions vault
}
newStmSessionStore :: IO (SessionStoreInstance (Session conn sess st))
newStmSessionStore = SessionStoreInstance <$> newStmSessionStore'
| agrafix/Spock | Spock/src/Web/Spock/Internal/SessionVault.hs | bsd-3-clause | 2,790 | 0 | 13 | 552 | 805 | 420 | 385 | 59 | 1 |
module CheckedLang.TypeChecker
( typeOf
, typeOfProgram
, typeOfExpression
, checkProgramType
, checkExpressionType
) where
import CheckedLang.Data
import Control.Arrow (second)
type TypeTry = Either TypeError
type TypeResult = TypeTry Type
checkProgramType :: Program -> Type -> TypeResult
checkProgramType (Prog expr) = checkExpressionType expr
checkExpressionType :: Expression -> Type -> TypeResult
checkExpressionType expr typ = checkType expr typ empty
typeOfProgram :: Program -> TypeResult
typeOfProgram (Prog expr) = typeOfExpression expr
typeOfExpression :: Expression -> TypeResult
typeOfExpression expr = typeOf expr empty
liftMaybe :: TypeError -> Maybe a -> TypeTry a
liftMaybe _ (Just x) = return x
liftMaybe y Nothing = throwTypeError y
throwTypeError :: TypeError -> TypeTry a
throwTypeError = Left
checkType :: Expression -> Type -> TypeEnvironment -> TypeResult
checkType expr expect tenv = do
actual <- typeOf expr tenv
if expect == actual
then return expect
else throwTypeError (TypeMismatch expect actual expr)
typeOf :: Expression -> TypeEnvironment -> TypeResult
typeOf (ConstExpr val) _ = typeOfConstExpr val
typeOf (VarExpr name) tenv = typeOfVarExpr name tenv
typeOf (LetExpr binds body) tenv = typeOfLetExpr binds body tenv
typeOf (BinOpExpr op e1 e2) tenv = typeOfBinOpExpr op e1 e2 tenv
typeOf (UnaryOpExpr op e) tenv = typeOfUnaryOpExpr op e tenv
typeOf (CondExpr branches) tenv = typeOfCondExpr branches tenv
typeOf (ProcExpr params body) tenv = typeOfProcExpr params body tenv
typeOf (CallExpr proc args) tenv = typeOfCallExpr proc args tenv
typeOf (LetRecExpr binds body) tenv = typeOfLetRecExpr binds body tenv
typeOfConstExpr :: ExpressedValue -> TypeResult
typeOfConstExpr (ExprNum n) = return TypeInt
typeOfConstExpr (ExprBool b) = return TypeBool
typeOfVarExpr :: String -> TypeEnvironment -> TypeResult
typeOfVarExpr name tenv = liftMaybe err $ apply tenv name
where err = UnboundVar name
typeOfLetExpr :: [(String, Expression)] -> Expression -> TypeEnvironment
-> TypeResult
typeOfLetExpr binds body tenv = do
typeBinds <- reverse <$> foldl func (return []) binds
typeOf body (extendMany typeBinds tenv)
where
func acc (name, expr) = do
typeBinds <- acc
typ <- typeOf expr tenv
return $ (name, typ) : typeBinds
typedBinOps :: [(BinOp, (Type, Type, Type))]
typedBinOps = concat
[ attachTypes binBoolOps TypeBool TypeBool TypeBool
, attachTypes binNumToNumOps TypeInt TypeInt TypeInt
, attachTypes binNumToBoolOps TypeInt TypeInt TypeBool
]
where
attachTypes ops t1 t2 tres = fmap (\op -> (op, (t1, t2, tres))) ops
binBoolOps = []
binNumToNumOps = [ Add, Sub, Mul, Div ]
binNumToBoolOps = [ Gt, Le, Eq ]
typedUnaryOps :: [(UnaryOp, (Type, Type))]
typedUnaryOps = concat
[ attachTypes unaryBoolOps TypeBool TypeBool
, attachTypes unaryNumToNumOps TypeInt TypeInt
, attachTypes unaryNumToBoolOps TypeInt TypeBool
]
where
attachTypes ops t tres = fmap (\op -> (op, (t, tres))) ops
unaryBoolOps = []
unaryNumToNumOps = [ Minus ]
unaryNumToBoolOps = [ IsZero ]
typeOfBinOpExpr :: BinOp -> Expression -> Expression -> TypeEnvironment
-> TypeResult
typeOfBinOpExpr op e1 e2 tenv = do
types <- liftMaybe (UnknownOperator (show op)) (lookup op typedBinOps)
let (t1, t2, tres) = types
checkType e1 t1 tenv
checkType e2 t2 tenv
return tres
typeOfUnaryOpExpr :: UnaryOp -> Expression -> TypeEnvironment -> TypeResult
typeOfUnaryOpExpr op e tenv = do
types <- liftMaybe (UnknownOperator (show op)) (lookup op typedUnaryOps)
let (t, tres) = types
checkType e t tenv
return tres
typeOfCondExpr :: [(Expression, Expression)] -> TypeEnvironment -> TypeResult
typeOfCondExpr [] tenv = throwTypeError . TypeDefaultError $
"Condition expression should contain at least one sub-expressions."
typeOfCondExpr ((cond, expr) : remain) tenv = do
checkType cond TypeBool tenv
typ <- typeOf expr tenv
checkRemainTypes remain typ
where
checkRemainTypes [] typ = return typ
checkRemainTypes ((cond, expr) : remain) typ = do
checkType cond TypeBool tenv
checkType expr typ tenv
checkRemainTypes remain typ
typeOfProcExpr :: [(String, Type)] -> Expression -> TypeEnvironment
-> TypeResult
typeOfProcExpr params body tenv = do
resType <- typeOf body (extendMany params tenv)
let paramTypes = fmap snd params
return $ TypeProc paramTypes resType
typeOfExprs :: [Expression] -> TypeEnvironment -> TypeTry [Type]
typeOfExprs exprs tenv = reverse <$> foldl func (return []) exprs
where
func acc expr = do
types <- acc
typ <- typeOf expr tenv
return $ typ : types
typeOfCallExpr :: Expression -> [Expression] -> TypeEnvironment -> TypeResult
typeOfCallExpr proc args tenv = do
procType <- typeOf proc tenv
argTypes <- typeOfExprs args tenv
checkParamsType procType argTypes
where
checkParamsType (TypeProc paramTypes resType) argTypes =
if paramTypes == argTypes
then return resType
else throwTypeError $ ParamsTypeMismatch paramTypes argTypes proc
checkParamsType wrongType _ = throwTypeError $ CallNotProcVal wrongType
typeOfLetRecExpr :: [(Type, String, [(String, Type)], Expression)]
-> Expression -> TypeEnvironment
-> TypeResult
typeOfLetRecExpr binds body tenv = checkAllBinds binds >> typeOf body bodyEnv
where
recBinds = [ (name, TypeProc (fmap snd paramTs) resT)
| (resT, name, paramTs, _) <- binds ]
bodyEnv = extendMany recBinds tenv
checkAllBinds [] = return ()
checkAllBinds ((res, name, params, body) : remain) =
checkType body res (extendMany params bodyEnv) >> checkAllBinds remain
| li-zhirui/EoplLangs | src/CheckedLang/TypeChecker.hs | bsd-3-clause | 5,822 | 0 | 12 | 1,204 | 1,883 | 956 | 927 | 130 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module NumHask.Array.Constraints
( IsValidConcat
, Squeeze
, Concatenate
, IsValidTranspose
, DimShuffle
, dimShuffle
, Fold
, FoldAlong
, TailModule
, HeadModule
, Transpose
) where
import Data.Singletons.Prelude hiding (Max)
import Data.Singletons.Prelude.List
((:!!$), Drop, Filter, Head, Insert,
Length, Minimum, SplitAt, Sum, Take, ZipWith,)
import Data.Singletons.Prelude.Tuple (Fst, Snd)
import Data.Singletons.TH (promote)
import Data.Singletons.TypeLits (Nat)
import qualified Protolude as P
import GHC.Err (error)
#if ( __GLASGOW_HASKELL__ < 801 )
instance P.Eq Nat where
x == y = P.not (x P./= y)
x /= y = P.not (x P.== y)
instance P.Ord Nat where
x > y = P.not (x P./= y) P.&& P.not (x P.< y)
x < y = P.not (x P./= y) P.&& P.not (x P.> y)
x <= y = (x P.== y) P.|| P.not (x P.> y)
x >= y = (x P.== y) P.|| P.not (x P.< y)
#endif
(!!) :: [a] -> Nat -> a
[] !! _ = error "Data.Singletons.List.!!: index too large"
(x:xs) !! n =
if n P.== 0
then x
else xs !! (n P.- 1)
type family DropDim d a :: [b] where
DropDim 0 xs = Drop 1 xs
DropDim d xs = Take (d :- 1) (Fst (SplitAt d xs)) :++ Snd (SplitAt d xs)
type family IsValidConcat i (a :: [Nat]) (b :: [Nat]) :: P.Bool where
IsValidConcat _ '[] _ = 'P.False
IsValidConcat _ _ '[] = 'P.False
IsValidConcat i a b = And (ZipWith (:==$) (DropDim i a) (DropDim i b))
type family Squeeze (a :: [Nat]) where
Squeeze '[] = '[]
Squeeze a = Filter ((:/=$$) 1) a
type family IsValidTranspose (p :: [Nat]) (a :: [Nat]) :: P.Bool where
IsValidTranspose p a =
(Minimum p :>= 0) :&& (Minimum a :>= 0) :&& (Sum a :== Sum p) :&& Length p :== Length a
type family Transpose a where
Transpose a = Reverse a
type family AddDimension (d :: Nat) t :: [Nat] where
AddDimension d t = Insert d t
type family Concatenate i (a :: [Nat]) (b :: [Nat]) :: [Nat] where
Concatenate i a b =
Take i (Fst (SplitAt (i :+ 1) a)) :++
('[ Head (Drop i a) :+ Head (Drop i b)]) :++
Snd (SplitAt (i :+ 1) b)
-- | Reduces axis i in shape s. Maintains singlton dimension
type family FoldAlong i (s :: [Nat]) where
FoldAlong _ '[] = '[]
FoldAlong d xs = Take d (Fst (SplitAt (d :+ 1) xs)) :++ '[ 1] :++ Snd (SplitAt (d :+ 1) xs)
-- | Reduces axis i in shape s. Does not maintain singlton dimension.
type family Fold i (s :: [Nat]) where
Fold _ '[] = '[]
Fold d xs = Take d (Fst (SplitAt (d :+ 1) xs)) :++ Snd (SplitAt (d :+ 1) xs)
type family TailModule i (s :: [Nat]) where
TailModule _ '[] = '[]
TailModule d xs = (Snd (SplitAt d xs))
type family HeadModule i (s :: [Nat]) where
HeadModule _ '[] = '[]
HeadModule d xs = (Fst (SplitAt d xs))
$(promote
[d|
dimShuffle :: P.Eq a => [a] -> [Nat] -> [a]
dimShuffle _ [] = []
dimShuffle [] _ = []
dimShuffle (x : xs) (b : bs)
= if b P.== 0 then x : dimShuffle xs bs else
(xs !! (b P.- 1)) : dimShuffle xs bs
|])
| tonyday567/naperian | src/NumHask/Array/Constraints.hs | bsd-3-clause | 3,524 | 0 | 14 | 790 | 1,349 | 755 | 594 | 96 | 2 |
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PartialTypeSignatures #-}
module Haskell.Ide.ExamplePluginAsync where
import Control.Concurrent
import Control.Concurrent.STM.TChan
import Control.Monad.IO.Class
import Control.Monad.STM
import Data.Monoid
import qualified Data.Text as T
import Haskell.Ide.Engine.ExtensibleState
import Haskell.Ide.Engine.MonadFunctions
import Haskell.Ide.Engine.PluginDescriptor
-- ---------------------------------------------------------------------
exampleAsyncDescriptor :: TaggedPluginDescriptor _
exampleAsyncDescriptor = PluginDescriptor
{
pdUIShortName = "Async Example"
, pdUIOverview = "An example HIE plugin using multiple/async processes"
, pdCommands =
buildCommand (longRunningCmdSync Cmd1) (Proxy :: Proxy "cmd1")
"Long running synchronous command" [] (SCtxNone :& RNil) RNil
:& buildCommand (longRunningCmdSync Cmd2) (Proxy :: Proxy "cmd2")
"Long running synchronous command" [] (SCtxNone :& RNil) RNil
:& buildCommand (streamingCmdAsync (CmdA 3 100)) (Proxy :: Proxy "cmdA3") "Long running async/streaming command" [] (SCtxNone :& RNil) RNil
:& RNil
, pdExposedServices = []
, pdUsedServices = []
}
-- ---------------------------------------------------------------------
data WorkerCmd = Cmd1 | Cmd2
deriving Show
data WorkerCmdAsync = CmdA
Int -- Number of times to repeat
Int -- delay between repeats
deriving Show
-- | Keep track of the communication channesl to the remote process.
data SubProcess = SubProcess
{ spChIn :: TChan WorkerCmd
, spChOut :: TChan T.Text
, spProcess :: ThreadId
}
-- | Wrap it in a Maybe for pure initialisation
data AsyncPluginState = APS (Maybe SubProcess)
-- | Tag the state variable to enable it to be stored in the dispatcher state,
-- accessible to all plugins, provided they know the type, as it is accessed via
-- a @cast@
instance ExtensionClass AsyncPluginState where
initialValue = APS Nothing
-- ---------------------------------------------------------------------
-- | This command manages interaction with a separate process, doing stuff.
longRunningCmdSync :: WorkerCmd -> CommandFunc T.Text
longRunningCmdSync cmd = CmdSync $ \_ctx _req -> do
SubProcess cin cout _tid <- ensureProcessRunning
liftIO $ atomically $ writeTChan cin cmd
res <- liftIO $ atomically $ readTChan cout
return (IdeResponseOk $ "res=" <> res)
-- ---------------------------------------------------------------------
-- | If there is already a @SubProcess@ value in the plugin state return it,
-- else create a new set of @TChan@ and fork the worker with them, storing the
-- new @SubProcess@ value in the plugin state.
ensureProcessRunning :: IdeM SubProcess
ensureProcessRunning = do
(APS v) <- get -- from extensible state
sp <- case v of
Nothing -> do
cin <- liftIO $ atomically newTChan
cout <- liftIO $ atomically newTChan
tid <- liftIO $ forkIO (workerProc cin cout)
let v' = SubProcess cin cout tid
put (APS (Just v')) -- into extensible state
return v'
Just v' -> return v'
return sp
-- ---------------------------------------------------------------------
-- | Long running worker process, can be doing commands in an async manner
workerProc :: TChan WorkerCmd -> TChan T.Text -> IO ()
workerProc cin cout = loop 1
where
loop :: Integer -> IO ()
loop cnt = do
debugm "workerProc:top of loop"
req <- liftIO $ atomically $ readTChan cin
debugm $ "workerProc loop:got:" ++ show req
case req of
Cmd1 -> do
liftIO $ atomically $ writeTChan cout (T.pack $ "wp cmd1:cnt=" ++ show cnt)
loop (cnt + 1)
Cmd2 -> do
liftIO $ atomically $ writeTChan cout (T.pack $ "wp cmd2:cnt=" ++ show cnt)
loop (cnt + 1)
-- ---------------------------------------------------------------------
-- | This command manages interaction with a separate process, doing stuff.
streamingCmdAsync :: WorkerCmdAsync -> CommandFunc T.Text
streamingCmdAsync cmd = CmdAsync $ \replyFunc _ctx _req -> do
tid <- liftIO $ forkIO (workerProcAsync cmd replyFunc)
debugm $ "streamingCmdAsync:launched worker as " ++ show tid
let tidStr = T.pack (show tid ++ ":")
liftIO $ replyFunc (IdeResponseOk $ tidStr <> "started from streamingCmdAsync")
-- | This command manages interaction with a separate process, doing stuff.
workerProcAsync :: WorkerCmdAsync -> (IdeResponse T.Text -> IO ()) -> IO ()
workerProcAsync (CmdA num delayMs) replyFunc = do
tid <- myThreadId
let tidStr = show tid ++ ":"
replyFunc (IdeResponseOk $ T.pack $ tidStr <> "starting")
let
go n = do
replyFunc (IdeResponseOk $ T.pack $ tidStr <> "iteration " <> show n)
threadDelay (delayMs * 1000)
mapM_ go [1..num]
replyFunc (IdeResponseOk $ T.pack $ tidStr <> "done")
-- ---------------------------------------------------------------------
| JPMoresmau/haskell-ide-engine | hie-eg-plugin-async/Haskell/Ide/ExamplePluginAsync.hs | bsd-3-clause | 5,215 | 0 | 19 | 1,135 | 1,132 | 577 | 555 | 91 | 2 |
module HaskellEditor.Configuration
where
import HaskellEditor.Configuration.Types
import qualified HaskellEditor.Files
import qualified Data.ByteString
import qualified Data.ByteString.Lazy
import System.IO
import Data.Yaml
loadConfigFile :: FilePath -> IO (Maybe Configuration)
loadConfigFile path = do
maybeConfiguration <- parseConfig path
return maybeConfiguration
parseConfig :: FilePath -> IO (Maybe HaskellEditor.Configuration.Types.Configuration)
parseConfig filePath = do
lazyContents <- withFile filePath ReadMode $ HaskellEditor.Files.getFile
let strictContents = Data.ByteString.concat $ Data.ByteString.Lazy.toChunks lazyContents
case (Data.Yaml.decodeEither' strictContents) of
Left parseException -> do
putStrLn $ show parseException
return Nothing
Right configuration -> return $ Just configuration
getCanonicalRootPath :: Configuration -> FilePath -> IO FilePath
getCanonicalRootPath config filepath = do
let configRootFolder = rootFolder config
HaskellEditor.Files.getCanonicalRootPathFromPath configRootFolder filepath
| stevechy/haskellEditor | src/HaskellEditor/Configuration.hs | bsd-3-clause | 1,122 | 0 | 13 | 186 | 261 | 131 | 130 | 24 | 2 |
{-# LANGUAGE FlexibleInstances, OverlappingInstances, TypeSynonymInstances,
OverloadedStrings #-}
module Database.Redis.Types where
import Control.Applicative
import Control.DeepSeq
import Data.ByteString.Char8 (ByteString, pack)
import qualified Data.ByteString.Lex.Fractional as F (readSigned, readDecimal)
import qualified Data.ByteString.Lex.Integral as I (readSigned, readDecimal)
import Database.Redis.Protocol
------------------------------------------------------------------------------
-- Classes of types Redis understands
--
class RedisArg a where
encode :: a -> ByteString
class RedisResult a where
decode :: Reply -> Either Reply a
------------------------------------------------------------------------------
-- RedisArg instances
--
instance RedisArg ByteString where
encode = id
instance RedisArg Integer where
encode = pack . show
instance RedisArg Double where
encode = pack . show
------------------------------------------------------------------------------
-- RedisResult instances
--
data Status = Ok | Pong | Status ByteString
deriving (Show, Eq)
instance NFData Status
data RedisType = None | String | Hash | List | Set | ZSet
deriving (Show, Eq)
instance RedisResult Reply where
decode = Right
instance RedisResult ByteString where
decode (SingleLine s) = Right s
decode (Bulk (Just s)) = Right s
decode r = Left r
instance RedisResult Integer where
decode (Integer n) = Right n
decode r =
maybe (Left r) (Right . fst) . I.readSigned I.readDecimal =<< decode r
instance RedisResult Double where
decode r = maybe (Left r) (Right . fst) . F.readSigned F.readDecimal =<< decode r
instance RedisResult Status where
decode (SingleLine s) = Right $ case s of
"OK" -> Ok
"PONG" -> Pong
_ -> Status s
decode r = Left r
instance RedisResult RedisType where
decode (SingleLine s) = Right $ case s of
"none" -> None
"string" -> String
"hash" -> Hash
"list" -> List
"set" -> Set
"zset" -> ZSet
_ -> error $ "Hedis: unhandled redis type: " ++ show s
decode r = Left r
instance RedisResult Bool where
decode (Integer 1) = Right True
decode (Integer 0) = Right False
decode (Bulk Nothing) = Right False -- Lua boolean false = nil bulk reply
decode r = Left r
instance (RedisResult a) => RedisResult (Maybe a) where
decode (Bulk Nothing) = Right Nothing
decode (MultiBulk Nothing) = Right Nothing
decode r = Just <$> decode r
instance (RedisResult a) => RedisResult [a] where
decode (MultiBulk (Just rs)) = mapM decode rs
decode r = Left r
instance (RedisResult a, RedisResult b) => RedisResult (a,b) where
decode (MultiBulk (Just [x, y])) = (,) <$> decode x <*> decode y
decode r = Left r
instance (RedisResult k, RedisResult v) => RedisResult [(k,v)] where
decode r = case r of
(MultiBulk (Just rs)) -> pairs rs
_ -> Left r
where
pairs [] = Right []
pairs (_:[]) = Left r
pairs (r1:r2:rs) = do
k <- decode r1
v <- decode r2
kvs <- pairs rs
return $ (k,v) : kvs
| bitemyapp/hedis | src/Database/Redis/Types.hs | bsd-3-clause | 3,400 | 0 | 12 | 968 | 1,045 | 539 | 506 | 78 | 0 |
module Test.Rebuild(main) where
import Development.Shake
import Test.Type
import Text.Read
import Data.List.Extra
import Control.Monad
import General.GetOpt
data Opt = Timestamp String | Pattern Pat
opts = [Option "" ["timestamp"] (ReqArg (Right . Timestamp) "VALUE") "Value used to detect what has rebuilt when"
,Option "" ["pattern"] (ReqArg (fmap Pattern . readEither) "PATTERN") "Which file rules to use (%>, &?> etc)"]
main = testBuildArgs test opts $ \args -> do
let timestamp = concat [x | Timestamp x <- args]
let p = lastDef PatWildcard [x | Pattern x <- args]
want ["a.txt"]
pat p "a.txt" $ \out -> do
src <- readFile' "b.txt"
writeFile' out $ src ++ timestamp
pat p "b.txt" $ \out -> do
src <- readFile' "c.txt"
writeFile' out $ src ++ timestamp
test build =
forM_ [minBound..maxBound :: Pat] $ \pat -> do
build ["clean"]
let go arg c b a flags = do
writeFileChanged "c.txt" c
build $ ["--timestamp=" ++ arg, "--sleep","--no-reports","--pattern=" ++ show pat] ++ flags
assertContents "b.txt" b
assertContents "a.txt" a
-- check rebuild works
go "1" "x" "x1" "x11" []
go "2" "x" "x1" "x11" []
go "3" "x" "x1" "x13" ["--rebuild=a.*"]
go "4" "x" "x1" "x13" []
go "5" "x" "x5" "x55" ["--rebuild=b.*"]
go "6" "x" "x6" "x66" ["--rebuild"]
go "7" "x" "x6" "x66" []
go "8" "y" "y8" "y88" []
-- check skip works
go "1" "x" "x1" "x11" []
go "2" "y" "y2" "x11" ["--skip=a.*"]
go "3" "y" "y2" "y23" []
go "4" "z" "y2" "y23" ["--skip=b.*"]
go "5" "z" "y2" "y23" ["--skip=b.*"]
go "6" "z" "z6" "z66" []
go "7" "a" "z6" "z66" ["--skip=c.*"]
go "8" "a" "z6" "z66" ["--skip=b.*"]
go "9" "a" "a9" "z66" ["--skip=a.*"]
go "0" "a" "a9" "a90" []
{-
-- check skip-forever works
-- currently it does not work properly
go "1" "x" "x1" "x11" []
go "2" "y" "y2" "x11" ["--skip-forever=a.*"]
go "3" "y" "y2" "x11" []
go "4" "z" "z4" "z44" []
-}
| ndmitchell/shake | src/Test/Rebuild.hs | bsd-3-clause | 2,199 | 0 | 18 | 689 | 703 | 338 | 365 | 46 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
-- module Test where
import Foreign.C.Types
-- import Data.Map
import Maybe
-- main = putStrLn "11"
fibonacci :: Int -> Int
fibonacci n = fibs !! n
where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
-- local_map = Data.Map.fromList [(1,2), (3,4)]
-- lookup_hs ::CInt -> CInt
-- lookup_hs = fromIntegral . Maybe.fromJust . ((flip Data.Map.lookup) local_map) . fromIntegral
-- foreign export ccall lookup_hs :: CInt -> CInt
fibonacci_hs :: CInt -> CInt
fibonacci_hs = fromIntegral . fibonacci . fromIntegral
foreign export ccall fibonacci_hs :: CInt -> CInt
-- main = putStrLn "foo"
| mwotton/Hubris-Haskell | sample/Test.hs | mit | 635 | 0 | 10 | 113 | 106 | 62 | 44 | 9 | 1 |
import Geometry
import Drawing
main = drawPicture myPicture
myPicture points =
red (drawSegment (b,c) & drawPointsLabels [a,b,c] ["A","B","C"] ) &
faint (drawSegment (a,b) & drawPointLabel o "O"
& drawSegment (o,a) & drawSegment (o,c')
& drawPointLabel c' "C'"
& drawArc (a,b,o) & drawArc (b,a,o)
& drawArc (c,b,c') & drawArc (c',o,d) ) &
drawPointLabel d "D" & drawSegment (a,d) &
message $ "Euclid 1_2 "
++ " AD=" ++ shownum (dist a d)
++ ", BC=" ++ shownum (dist b c)
where { [a,b,c] = take 3 points;
Just o = find (across c (a,b)) $ circle_circle (a,b) (b,a);
Just c' = find (beyond (o,b)) $ line_circle (o,b) (b,c);
Just d = find (beyond (o,a)) $ line_circle (o,a) (o,c');
}
| alphalambda/hsmath | src/Learn/Geometry/demo08euclid1_2.hs | gpl-2.0 | 823 | 0 | 25 | 261 | 425 | 228 | 197 | 18 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.