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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Main
where
import Test.Tasty ( defaultMain
, testGroup
)
import HFlint.Test.FMPQ as FMPQ
import HFlint.Test.FMPZ as FMPZ
import HFlint.Test.FMPQPoly as FMPQPoly
import HFlint.Test.FMPZPoly as FMPZPoly
import HFlint.Test.Primes as Primes
main = defaultMain $ testGroup "HFlint tests"
[ FMPQ.tests
, FMPZ.tests
, FMPQPoly.tests
, FMPZPoly.tests
, Primes.tests
]
|
martinra/hflint
|
test/HFlint/Test.hs
|
gpl-3.0
| 459 | 0 | 8 | 140 | 96 | 63 | 33 | 14 | 1 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
-- |
-- Copyright : (c) 2010-2012 Benedikt Schmidt
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <[email protected]>
--
-- Standard and fresh substitutions.
module Term.Substitution (
-- ** Composition of fresh and free substitutions
composeVFresh
-- ** Conversion between fresh and free
, freshToFree
, freshToFreeAvoiding
, freshToFreeAvoidingFast
, freeToFreshRaw
-- ** Convenience exports
, module Term.LTerm
, module Term.Substitution.SubstVFree
, module Term.Substitution.SubstVFresh
) where
import Term.LTerm
import Term.Substitution.SubstVFree
import Term.Substitution.SubstVFresh
import Extension.Prelude
import Control.Monad.Bind
import Control.Basics
-- Composition of VFresh and VFresh substitutions
----------------------------------------------------------------------
-- | @composeVFresh s1 s2@ composes the fresh substitution s1 and the free substitution s2.
-- The result is the fresh substitution s = s1.s2.
composeVFresh :: (IsConst c, Show (Lit c LVar))
=> LSubstVFresh c -> LSubst c -> LSubstVFresh c
composeVFresh s1_0 s2 =
-- all variables in vrange(s1.s2) originate from s1 and can be considered fresh.
freeToFreshRaw (s1 `compose` s2)
where
s1 = freshToFreeAvoidingFast (extendWithRenaming (varsRange s2) s1_0) (s2,s1_0)
-- Conversion between substitutions
----------------------------------------------------------------------
-- | @freshToFree s@ converts the bound variables in @s@ to free variables
-- using fresh variable names. We try to preserve variables names if possible.
freshToFree :: (MonadFresh m, IsConst c)
=> SubstVFresh c LVar -> m (Subst c LVar)
freshToFree subst = (`evalBindT` noBindings) $ do
let slist = sortOn (size . snd) $ substToListVFresh subst
-- import oldvar ~> newvar mappings first, keep namehint from oldvar
substFromList <$> mapM convertMapping slist
where
convertMapping (lv,t) = (lv,) <$> mapFrees (Arbitrary importVar) t
where
importVar v = importBinding (\s i -> LVar s (lvarSort v) i) v (namehint v)
namehint v = case viewTerm t of
Lit (Var _) -> lvarName lv -- keep name of oldvar
_ -> lvarName v
-- | @freshToFreeAvoiding s t@ converts all fresh variables in the range of
-- @s@ to free variables avoiding free variables in @t@. This function tries
-- to reuse variable names from the domain of the substitution if possible.
freshToFreeAvoiding :: (HasFrees t, IsConst c) => SubstVFresh c LVar -> t -> Subst c LVar
freshToFreeAvoiding s t = freshToFree s `evalFreshAvoiding` t
-- | @freshToFreeAvoidingFast s t@ converts all fresh variables in the range of
-- @s@ to free variables avoiding free variables in @t@. This function does
-- not try to reuse variable names from the domain of the substitution.
freshToFreeAvoidingFast :: (HasFrees t, Ord c) => LSubstVFresh c -> t -> LSubst c
freshToFreeAvoidingFast s t =
substFromList . renameMappings . substToListVFresh $ s
where
renameMappings l = zip (map fst l) (rename (map snd l) `evalFreshAvoiding` t)
-- | @freeToFreshRaw s@ considers all variables in the range of @s@ as fresh.
freeToFreshRaw :: Subst c LVar -> SubstVFresh c LVar
freeToFreshRaw s@(Subst _) = substFromListVFresh $ substToList s
|
ekr/tamarin-prover
|
lib/term/src/Term/Substitution.hs
|
gpl-3.0
| 3,395 | 0 | 14 | 657 | 623 | 340 | 283 | 40 | 2 |
module XMonad.Prompt.VpnPrompt (
vpnPrompt
) where
import Data.List
import XMonad
import XMonad.Prompt hiding ( pasteString )
import XMonad.Prompt.Common
import System.FilePath
import System.Directory
import Control.Monad
data Vpn = Vpn
data StopVpn = StopVpn
instance XPrompt Vpn where
showXPrompt Vpn = "Vpn: "
nextCompletion _ = getNextCompletion
instance XPrompt StopVpn where
showXPrompt StopVpn = "Stop Vpn: "
nextCompletion _ = getNextCompletion
vpnPrompt :: XPConfig -> X ()
vpnPrompt c = do
running <- liftIO isVpnRunning
if running
then mkXPrompt StopVpn c (mkComplFunFromList ["y", "yes", "n", "no"]) stopVpn
else mkXPrompt Vpn c vpnCompl startVpn
vpnDir :: FilePath
vpnDir = "/etc/openvpn/client/"
vpnCompl :: ComplFunction
vpnCompl = makeCompletionFunc getVpnList
getVpnList :: IO [String]
getVpnList = do
contents <- getDirectoryContents vpnDir
let files = filter (\file -> takeExtension file == ".conf") contents
filterVpnList files
filterVpnList :: [FilePath] -> IO [String]
filterVpnList files = return $ fmap dropExtension files
startVpn :: String -> X ()
startVpn input = do
completions <- liftIO $ vpnCompl input
unless (null completions) $ do
let vpnFile = head completions
liftIO $ spawn $
"sudo systemctl start openvpn-client@" ++ vpnFile ++ ".service"
stopVpn :: String -> X ()
stopVpn s = if s `elem` ["y", "yes"]
then liftIO $ do
vpn <- getRunningVpn
case vpn of
Just s -> spawn $ "sudo systemctl stop openvpn-client@" ++ s ++ ".service"
else spawn "notify-send -u critical Not found"
isVpnRunning :: IO Bool
isVpnRunning = do
vpn <- getRunningVpn
case vpn of
Just _ -> return True
Nothing -> return False
getRunningVpn :: IO (Maybe String)
getRunningVpn = do
names <- getDirectoryContents "/run"
let xs = filter (\name -> isPrefixOf "openvpn-client@" name &&
isSuffixOf ".pid" name) names
if length xs == 1
then return $ stripPrefix "openvpn-client@" $ takeBaseName $ head xs
else return Nothing
|
akermu/akermu-xmonad
|
src/XMonad/Prompt/VpnPrompt.hs
|
gpl-3.0
| 2,147 | 0 | 14 | 514 | 631 | 317 | 314 | 62 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Jobs.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Jobs.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | Required. Type of filter.
data CompensationFilterType
= FilterTypeUnspecified
-- ^ @FILTER_TYPE_UNSPECIFIED@
-- Filter type unspecified. Position holder, INVALID, should never be used.
| UnitOnly
-- ^ @UNIT_ONLY@
-- Filter by \`base compensation entry\'s\` unit. A job is a match if and
-- only if the job contains a base CompensationEntry and the base
-- CompensationEntry\'s unit matches provided units. Populate one or more
-- units. See CompensationInfo.CompensationEntry for definition of base
-- compensation entry.
| UnitAndAmount
-- ^ @UNIT_AND_AMOUNT@
-- Filter by \`base compensation entry\'s\` unit and amount \/ range. A job
-- is a match if and only if the job contains a base CompensationEntry, and
-- the base entry\'s unit matches provided CompensationUnit and amount or
-- range overlaps with provided CompensationRange. See
-- CompensationInfo.CompensationEntry for definition of base compensation
-- entry. Set exactly one units and populate range.
| AnnualizedBaseAmount
-- ^ @ANNUALIZED_BASE_AMOUNT@
-- Filter by annualized base compensation amount and \`base compensation
-- entry\'s\` unit. Populate range and zero or more units.
| AnnualizedTotalAmount
-- ^ @ANNUALIZED_TOTAL_AMOUNT@
-- Filter by annualized total compensation amount and \`base compensation
-- entry\'s\` unit . Populate range and zero or more units.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompensationFilterType
instance FromHttpApiData CompensationFilterType where
parseQueryParam = \case
"FILTER_TYPE_UNSPECIFIED" -> Right FilterTypeUnspecified
"UNIT_ONLY" -> Right UnitOnly
"UNIT_AND_AMOUNT" -> Right UnitAndAmount
"ANNUALIZED_BASE_AMOUNT" -> Right AnnualizedBaseAmount
"ANNUALIZED_TOTAL_AMOUNT" -> Right AnnualizedTotalAmount
x -> Left ("Unable to parse CompensationFilterType from: " <> x)
instance ToHttpApiData CompensationFilterType where
toQueryParam = \case
FilterTypeUnspecified -> "FILTER_TYPE_UNSPECIFIED"
UnitOnly -> "UNIT_ONLY"
UnitAndAmount -> "UNIT_AND_AMOUNT"
AnnualizedBaseAmount -> "ANNUALIZED_BASE_AMOUNT"
AnnualizedTotalAmount -> "ANNUALIZED_TOTAL_AMOUNT"
instance FromJSON CompensationFilterType where
parseJSON = parseJSONText "CompensationFilterType"
instance ToJSON CompensationFilterType where
toJSON = toJSONText
-- | Required. The method of transportation to calculate the commute time
-- for.
data CommuteFilterCommuteMethod
= CommuteMethodUnspecified
-- ^ @COMMUTE_METHOD_UNSPECIFIED@
-- Commute method isn\'t specified.
| Driving
-- ^ @DRIVING@
-- Commute time is calculated based on driving time.
| Transit
-- ^ @TRANSIT@
-- Commute time is calculated based on public transit including bus, metro,
-- subway, and so on.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CommuteFilterCommuteMethod
instance FromHttpApiData CommuteFilterCommuteMethod where
parseQueryParam = \case
"COMMUTE_METHOD_UNSPECIFIED" -> Right CommuteMethodUnspecified
"DRIVING" -> Right Driving
"TRANSIT" -> Right Transit
x -> Left ("Unable to parse CommuteFilterCommuteMethod from: " <> x)
instance ToHttpApiData CommuteFilterCommuteMethod where
toQueryParam = \case
CommuteMethodUnspecified -> "COMMUTE_METHOD_UNSPECIFIED"
Driving -> "DRIVING"
Transit -> "TRANSIT"
instance FromJSON CommuteFilterCommuteMethod where
parseJSON = parseJSONText "CommuteFilterCommuteMethod"
instance ToJSON CommuteFilterCommuteMethod where
toJSON = toJSONText
-- | Controls whether highly similar jobs are returned next to each other in
-- the search results. Jobs are identified as highly similar based on their
-- titles, job categories, and locations. Highly similar results are
-- clustered so that only one representative job of the cluster is
-- displayed to the job seeker higher up in the results, with the other
-- jobs being displayed lower down in the results. Defaults to
-- DiversificationLevel.SIMPLE if no value is specified.
data SearchJobsRequestDiversificationLevel
= DiversificationLevelUnspecified
-- ^ @DIVERSIFICATION_LEVEL_UNSPECIFIED@
-- The diversification level isn\'t specified.
| Disabled
-- ^ @DISABLED@
-- Disables diversification. Jobs that would normally be pushed to the last
-- page would not have their positions altered. This may result in highly
-- similar jobs appearing in sequence in the search results.
| Simple
-- ^ @SIMPLE@
-- Default diversifying behavior. The result list is ordered so that highly
-- similar results are pushed to the end of the last page of search
-- results. If you are using pageToken to page through the result set,
-- latency might be lower but we can\'t guarantee that all results are
-- returned. If you are using page offset, latency might be higher but all
-- results are returned.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SearchJobsRequestDiversificationLevel
instance FromHttpApiData SearchJobsRequestDiversificationLevel where
parseQueryParam = \case
"DIVERSIFICATION_LEVEL_UNSPECIFIED" -> Right DiversificationLevelUnspecified
"DISABLED" -> Right Disabled
"SIMPLE" -> Right Simple
x -> Left ("Unable to parse SearchJobsRequestDiversificationLevel from: " <> x)
instance ToHttpApiData SearchJobsRequestDiversificationLevel where
toQueryParam = \case
DiversificationLevelUnspecified -> "DIVERSIFICATION_LEVEL_UNSPECIFIED"
Disabled -> "DISABLED"
Simple -> "SIMPLE"
instance FromJSON SearchJobsRequestDiversificationLevel where
parseJSON = parseJSONText "SearchJobsRequestDiversificationLevel"
instance ToJSON SearchJobsRequestDiversificationLevel where
toJSON = toJSONText
data JobDegreeTypesItem
= DegreeTypeUnspecified
-- ^ @DEGREE_TYPE_UNSPECIFIED@
-- Default value. Represents no degree, or early childhood education. Maps
-- to ISCED code 0. Ex) Kindergarten
| PrimaryEducation
-- ^ @PRIMARY_EDUCATION@
-- Primary education which is typically the first stage of compulsory
-- education. ISCED code 1. Ex) Elementary school
| LowerSecondaryEducation
-- ^ @LOWER_SECONDARY_EDUCATION@
-- Lower secondary education; First stage of secondary education building
-- on primary education, typically with a more subject-oriented curriculum.
-- ISCED code 2. Ex) Middle school
| UpperSecondaryEducation
-- ^ @UPPER_SECONDARY_EDUCATION@
-- Middle education; Second\/final stage of secondary education preparing
-- for tertiary education and\/or providing skills relevant to employment.
-- Usually with an increased range of subject options and streams. ISCED
-- code 3. Ex) High school
| AdultRemedialEducation
-- ^ @ADULT_REMEDIAL_EDUCATION@
-- Adult Remedial Education; Programmes providing learning experiences that
-- build on secondary education and prepare for labour market entry and\/or
-- tertiary education. The content is broader than secondary but not as
-- complex as tertiary education. ISCED code 4.
| AssociatesOrEquivalent
-- ^ @ASSOCIATES_OR_EQUIVALENT@
-- Associate\'s or equivalent; Short first tertiary programmes that are
-- typically practically-based, occupationally-specific and prepare for
-- labour market entry. These programmes may also provide a pathway to
-- other tertiary programmes. ISCED code 5.
| BachelorsOrEquivalent
-- ^ @BACHELORS_OR_EQUIVALENT@
-- Bachelor\'s or equivalent; Programmes designed to provide intermediate
-- academic and\/or professional knowledge, skills and competencies leading
-- to a first tertiary degree or equivalent qualification. ISCED code 6.
| MastersOrEquivalent
-- ^ @MASTERS_OR_EQUIVALENT@
-- Master\'s or equivalent; Programmes designed to provide advanced
-- academic and\/or professional knowledge, skills and competencies leading
-- to a second tertiary degree or equivalent qualification. ISCED code 7.
| DoctoralOrEquivalent
-- ^ @DOCTORAL_OR_EQUIVALENT@
-- Doctoral or equivalent; Programmes designed primarily to lead to an
-- advanced research qualification, usually concluding with the submission
-- and defense of a substantive dissertation of publishable quality based
-- on original research. ISCED code 8.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobDegreeTypesItem
instance FromHttpApiData JobDegreeTypesItem where
parseQueryParam = \case
"DEGREE_TYPE_UNSPECIFIED" -> Right DegreeTypeUnspecified
"PRIMARY_EDUCATION" -> Right PrimaryEducation
"LOWER_SECONDARY_EDUCATION" -> Right LowerSecondaryEducation
"UPPER_SECONDARY_EDUCATION" -> Right UpperSecondaryEducation
"ADULT_REMEDIAL_EDUCATION" -> Right AdultRemedialEducation
"ASSOCIATES_OR_EQUIVALENT" -> Right AssociatesOrEquivalent
"BACHELORS_OR_EQUIVALENT" -> Right BachelorsOrEquivalent
"MASTERS_OR_EQUIVALENT" -> Right MastersOrEquivalent
"DOCTORAL_OR_EQUIVALENT" -> Right DoctoralOrEquivalent
x -> Left ("Unable to parse JobDegreeTypesItem from: " <> x)
instance ToHttpApiData JobDegreeTypesItem where
toQueryParam = \case
DegreeTypeUnspecified -> "DEGREE_TYPE_UNSPECIFIED"
PrimaryEducation -> "PRIMARY_EDUCATION"
LowerSecondaryEducation -> "LOWER_SECONDARY_EDUCATION"
UpperSecondaryEducation -> "UPPER_SECONDARY_EDUCATION"
AdultRemedialEducation -> "ADULT_REMEDIAL_EDUCATION"
AssociatesOrEquivalent -> "ASSOCIATES_OR_EQUIVALENT"
BachelorsOrEquivalent -> "BACHELORS_OR_EQUIVALENT"
MastersOrEquivalent -> "MASTERS_OR_EQUIVALENT"
DoctoralOrEquivalent -> "DOCTORAL_OR_EQUIVALENT"
instance FromJSON JobDegreeTypesItem where
parseJSON = parseJSONText "JobDegreeTypesItem"
instance ToJSON JobDegreeTypesItem where
toJSON = toJSONText
-- | The desired job attributes returned for jobs in the search response.
-- Defaults to JobView.JOB_VIEW_FULL if no value is specified.
data ProjectsTenantsJobsListJobView
= JobViewUnspecified
-- ^ @JOB_VIEW_UNSPECIFIED@
-- Default value.
| JobViewIdOnly
-- ^ @JOB_VIEW_ID_ONLY@
-- A ID only view of job, with following attributes: Job.name,
-- Job.requisition_id, Job.language_code.
| JobViewMinimal
-- ^ @JOB_VIEW_MINIMAL@
-- A minimal view of the job, with the following attributes: Job.name,
-- Job.requisition_id, Job.title, Job.company, Job.DerivedInfo.locations,
-- Job.language_code.
| JobViewSmall
-- ^ @JOB_VIEW_SMALL@
-- A small view of the job, with the following attributes in the search
-- results: Job.name, Job.requisition_id, Job.title, Job.company,
-- Job.DerivedInfo.locations, Job.visibility, Job.language_code,
-- Job.description.
| JobViewFull
-- ^ @JOB_VIEW_FULL@
-- All available attributes are included in the search results.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsTenantsJobsListJobView
instance FromHttpApiData ProjectsTenantsJobsListJobView where
parseQueryParam = \case
"JOB_VIEW_UNSPECIFIED" -> Right JobViewUnspecified
"JOB_VIEW_ID_ONLY" -> Right JobViewIdOnly
"JOB_VIEW_MINIMAL" -> Right JobViewMinimal
"JOB_VIEW_SMALL" -> Right JobViewSmall
"JOB_VIEW_FULL" -> Right JobViewFull
x -> Left ("Unable to parse ProjectsTenantsJobsListJobView from: " <> x)
instance ToHttpApiData ProjectsTenantsJobsListJobView where
toQueryParam = \case
JobViewUnspecified -> "JOB_VIEW_UNSPECIFIED"
JobViewIdOnly -> "JOB_VIEW_ID_ONLY"
JobViewMinimal -> "JOB_VIEW_MINIMAL"
JobViewSmall -> "JOB_VIEW_SMALL"
JobViewFull -> "JOB_VIEW_FULL"
instance FromJSON ProjectsTenantsJobsListJobView where
parseJSON = parseJSONText "ProjectsTenantsJobsListJobView"
instance ToJSON ProjectsTenantsJobsListJobView where
toJSON = toJSONText
data JobDerivedInfoJobCategoriesItem
= JobCategoryUnspecified
-- ^ @JOB_CATEGORY_UNSPECIFIED@
-- The default value if the category isn\'t specified.
| AccountingAndFinance
-- ^ @ACCOUNTING_AND_FINANCE@
-- An accounting and finance job, such as an Accountant.
| AdministrativeAndOffice
-- ^ @ADMINISTRATIVE_AND_OFFICE@
-- An administrative and office job, such as an Administrative Assistant.
| AdvertisingAndMarketing
-- ^ @ADVERTISING_AND_MARKETING@
-- An advertising and marketing job, such as Marketing Manager.
| AnimalCare
-- ^ @ANIMAL_CARE@
-- An animal care job, such as Veterinarian.
| ArtFashionAndDesign
-- ^ @ART_FASHION_AND_DESIGN@
-- An art, fashion, or design job, such as Designer.
| BusinessOperations
-- ^ @BUSINESS_OPERATIONS@
-- A business operations job, such as Business Operations Manager.
| CleaningAndFacilities
-- ^ @CLEANING_AND_FACILITIES@
-- A cleaning and facilities job, such as Custodial Staff.
| ComputerAndIt
-- ^ @COMPUTER_AND_IT@
-- A computer and IT job, such as Systems Administrator.
| Construction
-- ^ @CONSTRUCTION@
-- A construction job, such as General Laborer.
| CustomerService
-- ^ @CUSTOMER_SERVICE@
-- A customer service job, such s Cashier.
| Education
-- ^ @EDUCATION@
-- An education job, such as School Teacher.
| EntertainmentAndTravel
-- ^ @ENTERTAINMENT_AND_TRAVEL@
-- An entertainment and travel job, such as Flight Attendant.
| FarmingAndOutdoors
-- ^ @FARMING_AND_OUTDOORS@
-- A farming or outdoor job, such as Park Ranger.
| Healthcare
-- ^ @HEALTHCARE@
-- A healthcare job, such as Registered Nurse.
| HumanResources
-- ^ @HUMAN_RESOURCES@
-- A human resources job, such as Human Resources Director.
| InstallationMaintenanceAndRepair
-- ^ @INSTALLATION_MAINTENANCE_AND_REPAIR@
-- An installation, maintenance, or repair job, such as Electrician.
| Legal
-- ^ @LEGAL@
-- A legal job, such as Law Clerk.
| Management
-- ^ @MANAGEMENT@
-- A management job, often used in conjunction with another category, such
-- as Store Manager.
| ManufacturingAndWarehouse
-- ^ @MANUFACTURING_AND_WAREHOUSE@
-- A manufacturing or warehouse job, such as Assembly Technician.
| MediaCommunicationsAndWriting
-- ^ @MEDIA_COMMUNICATIONS_AND_WRITING@
-- A media, communications, or writing job, such as Media Relations.
| OilGasAndMining
-- ^ @OIL_GAS_AND_MINING@
-- An oil, gas or mining job, such as Offshore Driller.
| PersonalCareAndServices
-- ^ @PERSONAL_CARE_AND_SERVICES@
-- A personal care and services job, such as Hair Stylist.
| ProtectiveServices
-- ^ @PROTECTIVE_SERVICES@
-- A protective services job, such as Security Guard.
| RealEState
-- ^ @REAL_ESTATE@
-- A real estate job, such as Buyer\'s Agent.
| RestaurantAndHospitality
-- ^ @RESTAURANT_AND_HOSPITALITY@
-- A restaurant and hospitality job, such as Restaurant Server.
| SalesAndRetail
-- ^ @SALES_AND_RETAIL@
-- A sales and\/or retail job, such Sales Associate.
| ScienceAndEngineering
-- ^ @SCIENCE_AND_ENGINEERING@
-- A science and engineering job, such as Lab Technician.
| SocialServicesAndNonProfit
-- ^ @SOCIAL_SERVICES_AND_NON_PROFIT@
-- A social services or non-profit job, such as Case Worker.
| SportsFitnessAndRecreation
-- ^ @SPORTS_FITNESS_AND_RECREATION@
-- A sports, fitness, or recreation job, such as Personal Trainer.
| TransportationAndLogistics
-- ^ @TRANSPORTATION_AND_LOGISTICS@
-- A transportation or logistics job, such as Truck Driver.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobDerivedInfoJobCategoriesItem
instance FromHttpApiData JobDerivedInfoJobCategoriesItem where
parseQueryParam = \case
"JOB_CATEGORY_UNSPECIFIED" -> Right JobCategoryUnspecified
"ACCOUNTING_AND_FINANCE" -> Right AccountingAndFinance
"ADMINISTRATIVE_AND_OFFICE" -> Right AdministrativeAndOffice
"ADVERTISING_AND_MARKETING" -> Right AdvertisingAndMarketing
"ANIMAL_CARE" -> Right AnimalCare
"ART_FASHION_AND_DESIGN" -> Right ArtFashionAndDesign
"BUSINESS_OPERATIONS" -> Right BusinessOperations
"CLEANING_AND_FACILITIES" -> Right CleaningAndFacilities
"COMPUTER_AND_IT" -> Right ComputerAndIt
"CONSTRUCTION" -> Right Construction
"CUSTOMER_SERVICE" -> Right CustomerService
"EDUCATION" -> Right Education
"ENTERTAINMENT_AND_TRAVEL" -> Right EntertainmentAndTravel
"FARMING_AND_OUTDOORS" -> Right FarmingAndOutdoors
"HEALTHCARE" -> Right Healthcare
"HUMAN_RESOURCES" -> Right HumanResources
"INSTALLATION_MAINTENANCE_AND_REPAIR" -> Right InstallationMaintenanceAndRepair
"LEGAL" -> Right Legal
"MANAGEMENT" -> Right Management
"MANUFACTURING_AND_WAREHOUSE" -> Right ManufacturingAndWarehouse
"MEDIA_COMMUNICATIONS_AND_WRITING" -> Right MediaCommunicationsAndWriting
"OIL_GAS_AND_MINING" -> Right OilGasAndMining
"PERSONAL_CARE_AND_SERVICES" -> Right PersonalCareAndServices
"PROTECTIVE_SERVICES" -> Right ProtectiveServices
"REAL_ESTATE" -> Right RealEState
"RESTAURANT_AND_HOSPITALITY" -> Right RestaurantAndHospitality
"SALES_AND_RETAIL" -> Right SalesAndRetail
"SCIENCE_AND_ENGINEERING" -> Right ScienceAndEngineering
"SOCIAL_SERVICES_AND_NON_PROFIT" -> Right SocialServicesAndNonProfit
"SPORTS_FITNESS_AND_RECREATION" -> Right SportsFitnessAndRecreation
"TRANSPORTATION_AND_LOGISTICS" -> Right TransportationAndLogistics
x -> Left ("Unable to parse JobDerivedInfoJobCategoriesItem from: " <> x)
instance ToHttpApiData JobDerivedInfoJobCategoriesItem where
toQueryParam = \case
JobCategoryUnspecified -> "JOB_CATEGORY_UNSPECIFIED"
AccountingAndFinance -> "ACCOUNTING_AND_FINANCE"
AdministrativeAndOffice -> "ADMINISTRATIVE_AND_OFFICE"
AdvertisingAndMarketing -> "ADVERTISING_AND_MARKETING"
AnimalCare -> "ANIMAL_CARE"
ArtFashionAndDesign -> "ART_FASHION_AND_DESIGN"
BusinessOperations -> "BUSINESS_OPERATIONS"
CleaningAndFacilities -> "CLEANING_AND_FACILITIES"
ComputerAndIt -> "COMPUTER_AND_IT"
Construction -> "CONSTRUCTION"
CustomerService -> "CUSTOMER_SERVICE"
Education -> "EDUCATION"
EntertainmentAndTravel -> "ENTERTAINMENT_AND_TRAVEL"
FarmingAndOutdoors -> "FARMING_AND_OUTDOORS"
Healthcare -> "HEALTHCARE"
HumanResources -> "HUMAN_RESOURCES"
InstallationMaintenanceAndRepair -> "INSTALLATION_MAINTENANCE_AND_REPAIR"
Legal -> "LEGAL"
Management -> "MANAGEMENT"
ManufacturingAndWarehouse -> "MANUFACTURING_AND_WAREHOUSE"
MediaCommunicationsAndWriting -> "MEDIA_COMMUNICATIONS_AND_WRITING"
OilGasAndMining -> "OIL_GAS_AND_MINING"
PersonalCareAndServices -> "PERSONAL_CARE_AND_SERVICES"
ProtectiveServices -> "PROTECTIVE_SERVICES"
RealEState -> "REAL_ESTATE"
RestaurantAndHospitality -> "RESTAURANT_AND_HOSPITALITY"
SalesAndRetail -> "SALES_AND_RETAIL"
ScienceAndEngineering -> "SCIENCE_AND_ENGINEERING"
SocialServicesAndNonProfit -> "SOCIAL_SERVICES_AND_NON_PROFIT"
SportsFitnessAndRecreation -> "SPORTS_FITNESS_AND_RECREATION"
TransportationAndLogistics -> "TRANSPORTATION_AND_LOGISTICS"
instance FromJSON JobDerivedInfoJobCategoriesItem where
parseJSON = parseJSONText "JobDerivedInfoJobCategoriesItem"
instance ToJSON JobDerivedInfoJobCategoriesItem where
toJSON = toJSONText
-- | Compensation type. Default is
-- CompensationType.COMPENSATION_TYPE_UNSPECIFIED.
data CompensationEntryType
= CompensationTypeUnspecified
-- ^ @COMPENSATION_TYPE_UNSPECIFIED@
-- Default value.
| Base
-- ^ @BASE@
-- Base compensation: Refers to the fixed amount of money paid to an
-- employee by an employer in return for work performed. Base compensation
-- does not include benefits, bonuses or any other potential compensation
-- from an employer.
| Bonus
-- ^ @BONUS@
-- Bonus.
| SigningBonus
-- ^ @SIGNING_BONUS@
-- Signing bonus.
| Equity
-- ^ @EQUITY@
-- Equity.
| ProfitSharing
-- ^ @PROFIT_SHARING@
-- Profit sharing.
| Commissions
-- ^ @COMMISSIONS@
-- Commission.
| Tips
-- ^ @TIPS@
-- Tips.
| OtherCompensationType
-- ^ @OTHER_COMPENSATION_TYPE@
-- Other compensation type.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompensationEntryType
instance FromHttpApiData CompensationEntryType where
parseQueryParam = \case
"COMPENSATION_TYPE_UNSPECIFIED" -> Right CompensationTypeUnspecified
"BASE" -> Right Base
"BONUS" -> Right Bonus
"SIGNING_BONUS" -> Right SigningBonus
"EQUITY" -> Right Equity
"PROFIT_SHARING" -> Right ProfitSharing
"COMMISSIONS" -> Right Commissions
"TIPS" -> Right Tips
"OTHER_COMPENSATION_TYPE" -> Right OtherCompensationType
x -> Left ("Unable to parse CompensationEntryType from: " <> x)
instance ToHttpApiData CompensationEntryType where
toQueryParam = \case
CompensationTypeUnspecified -> "COMPENSATION_TYPE_UNSPECIFIED"
Base -> "BASE"
Bonus -> "BONUS"
SigningBonus -> "SIGNING_BONUS"
Equity -> "EQUITY"
ProfitSharing -> "PROFIT_SHARING"
Commissions -> "COMMISSIONS"
Tips -> "TIPS"
OtherCompensationType -> "OTHER_COMPENSATION_TYPE"
instance FromJSON CompensationEntryType where
parseJSON = parseJSONText "CompensationEntryType"
instance ToJSON CompensationEntryType where
toJSON = toJSONText
data JobQueryEmploymentTypesItem
= EmploymentTypeUnspecified
-- ^ @EMPLOYMENT_TYPE_UNSPECIFIED@
-- The default value if the employment type isn\'t specified.
| FullTime
-- ^ @FULL_TIME@
-- The job requires working a number of hours that constitute full time
-- employment, typically 40 or more hours per week.
| PartTime
-- ^ @PART_TIME@
-- The job entails working fewer hours than a full time job, typically less
-- than 40 hours a week.
| Contractor
-- ^ @CONTRACTOR@
-- The job is offered as a contracted, as opposed to a salaried employee,
-- position.
| ContractToHire
-- ^ @CONTRACT_TO_HIRE@
-- The job is offered as a contracted position with the understanding that
-- it\'s converted into a full-time position at the end of the contract.
-- Jobs of this type are also returned by a search for
-- EmploymentType.CONTRACTOR jobs.
| Temporary
-- ^ @TEMPORARY@
-- The job is offered as a temporary employment opportunity, usually a
-- short-term engagement.
| Intern
-- ^ @INTERN@
-- The job is a fixed-term opportunity for students or entry-level job
-- seekers to obtain on-the-job training, typically offered as a summer
-- position.
| Volunteer
-- ^ @VOLUNTEER@
-- The is an opportunity for an individual to volunteer, where there\'s no
-- expectation of compensation for the provided services.
| PerDiem
-- ^ @PER_DIEM@
-- The job requires an employee to work on an as-needed basis with a
-- flexible schedule.
| FlyInFlyOut
-- ^ @FLY_IN_FLY_OUT@
-- The job involves employing people in remote areas and flying them
-- temporarily to the work site instead of relocating employees and their
-- families permanently.
| OtherEmploymentType
-- ^ @OTHER_EMPLOYMENT_TYPE@
-- The job does not fit any of the other listed types.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobQueryEmploymentTypesItem
instance FromHttpApiData JobQueryEmploymentTypesItem where
parseQueryParam = \case
"EMPLOYMENT_TYPE_UNSPECIFIED" -> Right EmploymentTypeUnspecified
"FULL_TIME" -> Right FullTime
"PART_TIME" -> Right PartTime
"CONTRACTOR" -> Right Contractor
"CONTRACT_TO_HIRE" -> Right ContractToHire
"TEMPORARY" -> Right Temporary
"INTERN" -> Right Intern
"VOLUNTEER" -> Right Volunteer
"PER_DIEM" -> Right PerDiem
"FLY_IN_FLY_OUT" -> Right FlyInFlyOut
"OTHER_EMPLOYMENT_TYPE" -> Right OtherEmploymentType
x -> Left ("Unable to parse JobQueryEmploymentTypesItem from: " <> x)
instance ToHttpApiData JobQueryEmploymentTypesItem where
toQueryParam = \case
EmploymentTypeUnspecified -> "EMPLOYMENT_TYPE_UNSPECIFIED"
FullTime -> "FULL_TIME"
PartTime -> "PART_TIME"
Contractor -> "CONTRACTOR"
ContractToHire -> "CONTRACT_TO_HIRE"
Temporary -> "TEMPORARY"
Intern -> "INTERN"
Volunteer -> "VOLUNTEER"
PerDiem -> "PER_DIEM"
FlyInFlyOut -> "FLY_IN_FLY_OUT"
OtherEmploymentType -> "OTHER_EMPLOYMENT_TYPE"
instance FromJSON JobQueryEmploymentTypesItem where
parseJSON = parseJSONText "JobQueryEmploymentTypesItem"
instance ToJSON JobQueryEmploymentTypesItem where
toJSON = toJSONText
-- | Type of the device.
data DeviceInfoDeviceType
= DeviceTypeUnspecified
-- ^ @DEVICE_TYPE_UNSPECIFIED@
-- The device type isn\'t specified.
| Web
-- ^ @WEB@
-- A desktop web browser, such as, Chrome, Firefox, Safari, or Internet
-- Explorer)
| MobileWeb
-- ^ @MOBILE_WEB@
-- A mobile device web browser, such as a phone or tablet with a Chrome
-- browser.
| Android
-- ^ @ANDROID@
-- An Android device native application.
| Ios
-- ^ @IOS@
-- An iOS device native application.
| Bot
-- ^ @BOT@
-- A bot, as opposed to a device operated by human beings, such as a web
-- crawler.
| Other
-- ^ @OTHER@
-- Other devices types.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable DeviceInfoDeviceType
instance FromHttpApiData DeviceInfoDeviceType where
parseQueryParam = \case
"DEVICE_TYPE_UNSPECIFIED" -> Right DeviceTypeUnspecified
"WEB" -> Right Web
"MOBILE_WEB" -> Right MobileWeb
"ANDROID" -> Right Android
"IOS" -> Right Ios
"BOT" -> Right Bot
"OTHER" -> Right Other
x -> Left ("Unable to parse DeviceInfoDeviceType from: " <> x)
instance ToHttpApiData DeviceInfoDeviceType where
toQueryParam = \case
DeviceTypeUnspecified -> "DEVICE_TYPE_UNSPECIFIED"
Web -> "WEB"
MobileWeb -> "MOBILE_WEB"
Android -> "ANDROID"
Ios -> "IOS"
Bot -> "BOT"
Other -> "OTHER"
instance FromJSON DeviceInfoDeviceType where
parseJSON = parseJSONText "DeviceInfoDeviceType"
instance ToJSON DeviceInfoDeviceType where
toJSON = toJSONText
-- | Frequency of the specified amount. Default is
-- CompensationUnit.COMPENSATION_UNIT_UNSPECIFIED.
data CompensationEntryUnit
= CompensationUnitUnspecified
-- ^ @COMPENSATION_UNIT_UNSPECIFIED@
-- Default value.
| Hourly
-- ^ @HOURLY@
-- Hourly.
| Daily
-- ^ @DAILY@
-- Daily.
| Weekly
-- ^ @WEEKLY@
-- Weekly
| Monthly
-- ^ @MONTHLY@
-- Monthly.
| Yearly
-- ^ @YEARLY@
-- Yearly.
| OneTime
-- ^ @ONE_TIME@
-- One time.
| OtherCompensationUnit
-- ^ @OTHER_COMPENSATION_UNIT@
-- Other compensation units.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompensationEntryUnit
instance FromHttpApiData CompensationEntryUnit where
parseQueryParam = \case
"COMPENSATION_UNIT_UNSPECIFIED" -> Right CompensationUnitUnspecified
"HOURLY" -> Right Hourly
"DAILY" -> Right Daily
"WEEKLY" -> Right Weekly
"MONTHLY" -> Right Monthly
"YEARLY" -> Right Yearly
"ONE_TIME" -> Right OneTime
"OTHER_COMPENSATION_UNIT" -> Right OtherCompensationUnit
x -> Left ("Unable to parse CompensationEntryUnit from: " <> x)
instance ToHttpApiData CompensationEntryUnit where
toQueryParam = \case
CompensationUnitUnspecified -> "COMPENSATION_UNIT_UNSPECIFIED"
Hourly -> "HOURLY"
Daily -> "DAILY"
Weekly -> "WEEKLY"
Monthly -> "MONTHLY"
Yearly -> "YEARLY"
OneTime -> "ONE_TIME"
OtherCompensationUnit -> "OTHER_COMPENSATION_UNIT"
instance FromJSON CompensationEntryUnit where
parseJSON = parseJSONText "CompensationEntryUnit"
instance ToJSON CompensationEntryUnit where
toJSON = toJSONText
-- | The experience level associated with the job, such as \"Entry Level\".
data JobJobLevel
= JobLevelUnspecified
-- ^ @JOB_LEVEL_UNSPECIFIED@
-- The default value if the level isn\'t specified.
| EntryLevel
-- ^ @ENTRY_LEVEL@
-- Entry-level individual contributors, typically with less than 2 years of
-- experience in a similar role. Includes interns.
| Experienced
-- ^ @EXPERIENCED@
-- Experienced individual contributors, typically with 2+ years of
-- experience in a similar role.
| Manager
-- ^ @MANAGER@
-- Entry- to mid-level managers responsible for managing a team of people.
| Director
-- ^ @DIRECTOR@
-- Senior-level managers responsible for managing teams of managers.
| Executive
-- ^ @EXECUTIVE@
-- Executive-level managers and above, including C-level positions.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobJobLevel
instance FromHttpApiData JobJobLevel where
parseQueryParam = \case
"JOB_LEVEL_UNSPECIFIED" -> Right JobLevelUnspecified
"ENTRY_LEVEL" -> Right EntryLevel
"EXPERIENCED" -> Right Experienced
"MANAGER" -> Right Manager
"DIRECTOR" -> Right Director
"EXECUTIVE" -> Right Executive
x -> Left ("Unable to parse JobJobLevel from: " <> x)
instance ToHttpApiData JobJobLevel where
toQueryParam = \case
JobLevelUnspecified -> "JOB_LEVEL_UNSPECIFIED"
EntryLevel -> "ENTRY_LEVEL"
Experienced -> "EXPERIENCED"
Manager -> "MANAGER"
Director -> "DIRECTOR"
Executive -> "EXECUTIVE"
instance FromJSON JobJobLevel where
parseJSON = parseJSONText "JobJobLevel"
instance ToJSON JobJobLevel where
toJSON = toJSONText
-- | Deprecated. The job is only visible to the owner. The visibility of the
-- job. Defaults to Visibility.ACCOUNT_ONLY if not specified.
data JobVisibility
= VisibilityUnspecified
-- ^ @VISIBILITY_UNSPECIFIED@
-- Default value.
| AccountOnly
-- ^ @ACCOUNT_ONLY@
-- The resource is only visible to the GCP account who owns it.
| SharedWithGoogle
-- ^ @SHARED_WITH_GOOGLE@
-- The resource is visible to the owner and may be visible to other
-- applications and processes at Google.
| SharedWithPublic
-- ^ @SHARED_WITH_PUBLIC@
-- The resource is visible to the owner and may be visible to all other API
-- clients.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobVisibility
instance FromHttpApiData JobVisibility where
parseQueryParam = \case
"VISIBILITY_UNSPECIFIED" -> Right VisibilityUnspecified
"ACCOUNT_ONLY" -> Right AccountOnly
"SHARED_WITH_GOOGLE" -> Right SharedWithGoogle
"SHARED_WITH_PUBLIC" -> Right SharedWithPublic
x -> Left ("Unable to parse JobVisibility from: " <> x)
instance ToHttpApiData JobVisibility where
toQueryParam = \case
VisibilityUnspecified -> "VISIBILITY_UNSPECIFIED"
AccountOnly -> "ACCOUNT_ONLY"
SharedWithGoogle -> "SHARED_WITH_GOOGLE"
SharedWithPublic -> "SHARED_WITH_PUBLIC"
instance FromJSON JobVisibility where
parseJSON = parseJSONText "JobVisibility"
instance ToJSON JobVisibility where
toJSON = toJSONText
data JobEmploymentTypesItem
= JETIEmploymentTypeUnspecified
-- ^ @EMPLOYMENT_TYPE_UNSPECIFIED@
-- The default value if the employment type isn\'t specified.
| JETIFullTime
-- ^ @FULL_TIME@
-- The job requires working a number of hours that constitute full time
-- employment, typically 40 or more hours per week.
| JETIPartTime
-- ^ @PART_TIME@
-- The job entails working fewer hours than a full time job, typically less
-- than 40 hours a week.
| JETIContractor
-- ^ @CONTRACTOR@
-- The job is offered as a contracted, as opposed to a salaried employee,
-- position.
| JETIContractToHire
-- ^ @CONTRACT_TO_HIRE@
-- The job is offered as a contracted position with the understanding that
-- it\'s converted into a full-time position at the end of the contract.
-- Jobs of this type are also returned by a search for
-- EmploymentType.CONTRACTOR jobs.
| JETITemporary
-- ^ @TEMPORARY@
-- The job is offered as a temporary employment opportunity, usually a
-- short-term engagement.
| JETIIntern
-- ^ @INTERN@
-- The job is a fixed-term opportunity for students or entry-level job
-- seekers to obtain on-the-job training, typically offered as a summer
-- position.
| JETIVolunteer
-- ^ @VOLUNTEER@
-- The is an opportunity for an individual to volunteer, where there\'s no
-- expectation of compensation for the provided services.
| JETIPerDiem
-- ^ @PER_DIEM@
-- The job requires an employee to work on an as-needed basis with a
-- flexible schedule.
| JETIFlyInFlyOut
-- ^ @FLY_IN_FLY_OUT@
-- The job involves employing people in remote areas and flying them
-- temporarily to the work site instead of relocating employees and their
-- families permanently.
| JETIOtherEmploymentType
-- ^ @OTHER_EMPLOYMENT_TYPE@
-- The job does not fit any of the other listed types.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobEmploymentTypesItem
instance FromHttpApiData JobEmploymentTypesItem where
parseQueryParam = \case
"EMPLOYMENT_TYPE_UNSPECIFIED" -> Right JETIEmploymentTypeUnspecified
"FULL_TIME" -> Right JETIFullTime
"PART_TIME" -> Right JETIPartTime
"CONTRACTOR" -> Right JETIContractor
"CONTRACT_TO_HIRE" -> Right JETIContractToHire
"TEMPORARY" -> Right JETITemporary
"INTERN" -> Right JETIIntern
"VOLUNTEER" -> Right JETIVolunteer
"PER_DIEM" -> Right JETIPerDiem
"FLY_IN_FLY_OUT" -> Right JETIFlyInFlyOut
"OTHER_EMPLOYMENT_TYPE" -> Right JETIOtherEmploymentType
x -> Left ("Unable to parse JobEmploymentTypesItem from: " <> x)
instance ToHttpApiData JobEmploymentTypesItem where
toQueryParam = \case
JETIEmploymentTypeUnspecified -> "EMPLOYMENT_TYPE_UNSPECIFIED"
JETIFullTime -> "FULL_TIME"
JETIPartTime -> "PART_TIME"
JETIContractor -> "CONTRACTOR"
JETIContractToHire -> "CONTRACT_TO_HIRE"
JETITemporary -> "TEMPORARY"
JETIIntern -> "INTERN"
JETIVolunteer -> "VOLUNTEER"
JETIPerDiem -> "PER_DIEM"
JETIFlyInFlyOut -> "FLY_IN_FLY_OUT"
JETIOtherEmploymentType -> "OTHER_EMPLOYMENT_TYPE"
instance FromJSON JobEmploymentTypesItem where
parseJSON = parseJSONText "JobEmploymentTypesItem"
instance ToJSON JobEmploymentTypesItem where
toJSON = toJSONText
-- | Required. Controls over how important the score of
-- CustomRankingInfo.ranking_expression gets applied to job\'s final
-- ranking position. An error is thrown if not specified.
data CustomRankingInfoImportanceLevel
= ImportanceLevelUnspecified
-- ^ @IMPORTANCE_LEVEL_UNSPECIFIED@
-- Default value if the importance level isn\'t specified.
| None
-- ^ @NONE@
-- The given ranking expression is of None importance, existing relevance
-- score (determined by API algorithm) dominates job\'s final ranking
-- position.
| Low
-- ^ @LOW@
-- The given ranking expression is of Low importance in terms of job\'s
-- final ranking position compared to existing relevance score (determined
-- by API algorithm).
| Mild
-- ^ @MILD@
-- The given ranking expression is of Mild importance in terms of job\'s
-- final ranking position compared to existing relevance score (determined
-- by API algorithm).
| Medium
-- ^ @MEDIUM@
-- The given ranking expression is of Medium importance in terms of job\'s
-- final ranking position compared to existing relevance score (determined
-- by API algorithm).
| High
-- ^ @HIGH@
-- The given ranking expression is of High importance in terms of job\'s
-- final ranking position compared to existing relevance score (determined
-- by API algorithm).
| Extreme
-- ^ @EXTREME@
-- The given ranking expression is of Extreme importance, and dominates
-- job\'s final ranking position with existing relevance score (determined
-- by API algorithm) ignored.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CustomRankingInfoImportanceLevel
instance FromHttpApiData CustomRankingInfoImportanceLevel where
parseQueryParam = \case
"IMPORTANCE_LEVEL_UNSPECIFIED" -> Right ImportanceLevelUnspecified
"NONE" -> Right None
"LOW" -> Right Low
"MILD" -> Right Mild
"MEDIUM" -> Right Medium
"HIGH" -> Right High
"EXTREME" -> Right Extreme
x -> Left ("Unable to parse CustomRankingInfoImportanceLevel from: " <> x)
instance ToHttpApiData CustomRankingInfoImportanceLevel where
toQueryParam = \case
ImportanceLevelUnspecified -> "IMPORTANCE_LEVEL_UNSPECIFIED"
None -> "NONE"
Low -> "LOW"
Mild -> "MILD"
Medium -> "MEDIUM"
High -> "HIGH"
Extreme -> "EXTREME"
instance FromJSON CustomRankingInfoImportanceLevel where
parseJSON = parseJSONText "CustomRankingInfoImportanceLevel"
instance ToJSON CustomRankingInfoImportanceLevel where
toJSON = toJSONText
data CompensationFilterUnitsItem
= CFUICompensationUnitUnspecified
-- ^ @COMPENSATION_UNIT_UNSPECIFIED@
-- Default value.
| CFUIHourly
-- ^ @HOURLY@
-- Hourly.
| CFUIDaily
-- ^ @DAILY@
-- Daily.
| CFUIWeekly
-- ^ @WEEKLY@
-- Weekly
| CFUIMonthly
-- ^ @MONTHLY@
-- Monthly.
| CFUIYearly
-- ^ @YEARLY@
-- Yearly.
| CFUIOneTime
-- ^ @ONE_TIME@
-- One time.
| CFUIOtherCompensationUnit
-- ^ @OTHER_COMPENSATION_UNIT@
-- Other compensation units.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompensationFilterUnitsItem
instance FromHttpApiData CompensationFilterUnitsItem where
parseQueryParam = \case
"COMPENSATION_UNIT_UNSPECIFIED" -> Right CFUICompensationUnitUnspecified
"HOURLY" -> Right CFUIHourly
"DAILY" -> Right CFUIDaily
"WEEKLY" -> Right CFUIWeekly
"MONTHLY" -> Right CFUIMonthly
"YEARLY" -> Right CFUIYearly
"ONE_TIME" -> Right CFUIOneTime
"OTHER_COMPENSATION_UNIT" -> Right CFUIOtherCompensationUnit
x -> Left ("Unable to parse CompensationFilterUnitsItem from: " <> x)
instance ToHttpApiData CompensationFilterUnitsItem where
toQueryParam = \case
CFUICompensationUnitUnspecified -> "COMPENSATION_UNIT_UNSPECIFIED"
CFUIHourly -> "HOURLY"
CFUIDaily -> "DAILY"
CFUIWeekly -> "WEEKLY"
CFUIMonthly -> "MONTHLY"
CFUIYearly -> "YEARLY"
CFUIOneTime -> "ONE_TIME"
CFUIOtherCompensationUnit -> "OTHER_COMPENSATION_UNIT"
instance FromJSON CompensationFilterUnitsItem where
parseJSON = parseJSONText "CompensationFilterUnitsItem"
instance ToJSON CompensationFilterUnitsItem where
toJSON = toJSONText
-- | The job PostingRegion (for example, state, country) throughout which the
-- job is available. If this field is set, a LocationFilter in a search
-- query within the job region finds this job posting if an exact location
-- match isn\'t specified. If this field is set to PostingRegion.NATION or
-- PostingRegion.ADMINISTRATIVE_AREA, setting job Job.addresses to the same
-- location level as this field is strongly recommended.
data JobPostingRegion
= PostingRegionUnspecified
-- ^ @POSTING_REGION_UNSPECIFIED@
-- If the region is unspecified, the job is only returned if it matches the
-- LocationFilter.
| AdministrativeArea
-- ^ @ADMINISTRATIVE_AREA@
-- In addition to exact location matching, job posting is returned when the
-- LocationFilter in the search query is in the same administrative area as
-- the returned job posting. For example, if a \`ADMINISTRATIVE_AREA\` job
-- is posted in \"CA, USA\", it\'s returned if LocationFilter has
-- \"Mountain View\". Administrative area refers to top-level
-- administrative subdivision of this country. For example, US state, IT
-- region, UK constituent nation and JP prefecture.
| NATion
-- ^ @NATION@
-- In addition to exact location matching, job is returned when
-- LocationFilter in search query is in the same country as this job. For
-- example, if a \`NATION_WIDE\` job is posted in \"USA\", it\'s returned
-- if LocationFilter has \'Mountain View\'.
| Telecommute
-- ^ @TELECOMMUTE@
-- Job allows employees to work remotely (telecommute). If locations are
-- provided with this value, the job is considered as having a location,
-- but telecommuting is allowed.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobPostingRegion
instance FromHttpApiData JobPostingRegion where
parseQueryParam = \case
"POSTING_REGION_UNSPECIFIED" -> Right PostingRegionUnspecified
"ADMINISTRATIVE_AREA" -> Right AdministrativeArea
"NATION" -> Right NATion
"TELECOMMUTE" -> Right Telecommute
x -> Left ("Unable to parse JobPostingRegion from: " <> x)
instance ToHttpApiData JobPostingRegion where
toQueryParam = \case
PostingRegionUnspecified -> "POSTING_REGION_UNSPECIFIED"
AdministrativeArea -> "ADMINISTRATIVE_AREA"
NATion -> "NATION"
Telecommute -> "TELECOMMUTE"
instance FromJSON JobPostingRegion where
parseJSON = parseJSONText "JobPostingRegion"
instance ToJSON JobPostingRegion where
toJSON = toJSONText
-- | The employer\'s company size.
data CompanySize
= CSCompanySizeUnspecified
-- ^ @COMPANY_SIZE_UNSPECIFIED@
-- Default value if the size isn\'t specified.
| CSMini
-- ^ @MINI@
-- The company has less than 50 employees.
| CSSmall
-- ^ @SMALL@
-- The company has between 50 and 99 employees.
| CSSmedium
-- ^ @SMEDIUM@
-- The company has between 100 and 499 employees.
| CSMedium
-- ^ @MEDIUM@
-- The company has between 500 and 999 employees.
| CSBig
-- ^ @BIG@
-- The company has between 1,000 and 4,999 employees.
| CSBigger
-- ^ @BIGGER@
-- The company has between 5,000 and 9,999 employees.
| CSGiant
-- ^ @GIANT@
-- The company has 10,000 or more employees.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompanySize
instance FromHttpApiData CompanySize where
parseQueryParam = \case
"COMPANY_SIZE_UNSPECIFIED" -> Right CSCompanySizeUnspecified
"MINI" -> Right CSMini
"SMALL" -> Right CSSmall
"SMEDIUM" -> Right CSSmedium
"MEDIUM" -> Right CSMedium
"BIG" -> Right CSBig
"BIGGER" -> Right CSBigger
"GIANT" -> Right CSGiant
x -> Left ("Unable to parse CompanySize from: " <> x)
instance ToHttpApiData CompanySize where
toQueryParam = \case
CSCompanySizeUnspecified -> "COMPANY_SIZE_UNSPECIFIED"
CSMini -> "MINI"
CSSmall -> "SMALL"
CSSmedium -> "SMEDIUM"
CSMedium -> "MEDIUM"
CSBig -> "BIG"
CSBigger -> "BIGGER"
CSGiant -> "GIANT"
instance FromJSON CompanySize where
parseJSON = parseJSONText "CompanySize"
instance ToJSON CompanySize where
toJSON = toJSONText
-- | The completion topic. The default is CompletionType.COMBINED.
data ProjectsTenantsCompleteQueryType
= CompletionTypeUnspecified
-- ^ @COMPLETION_TYPE_UNSPECIFIED@
-- Default value.
| JobTitle
-- ^ @JOB_TITLE@
-- Suggest job titles for jobs autocomplete. For CompletionType.JOB_TITLE
-- type, only open jobs with the same language_codes are returned.
| CompanyName
-- ^ @COMPANY_NAME@
-- Suggest company names for jobs autocomplete. For
-- CompletionType.COMPANY_NAME type, only companies having open jobs with
-- the same language_codes are returned.
| Combined
-- ^ @COMBINED@
-- Suggest both job titles and company names for jobs autocomplete. For
-- CompletionType.COMBINED type, only open jobs with the same
-- language_codes or companies having open jobs with the same
-- language_codes are returned.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsTenantsCompleteQueryType
instance FromHttpApiData ProjectsTenantsCompleteQueryType where
parseQueryParam = \case
"COMPLETION_TYPE_UNSPECIFIED" -> Right CompletionTypeUnspecified
"JOB_TITLE" -> Right JobTitle
"COMPANY_NAME" -> Right CompanyName
"COMBINED" -> Right Combined
x -> Left ("Unable to parse ProjectsTenantsCompleteQueryType from: " <> x)
instance ToHttpApiData ProjectsTenantsCompleteQueryType where
toQueryParam = \case
CompletionTypeUnspecified -> "COMPLETION_TYPE_UNSPECIFIED"
JobTitle -> "JOB_TITLE"
CompanyName -> "COMPANY_NAME"
Combined -> "COMBINED"
instance FromJSON ProjectsTenantsCompleteQueryType where
parseJSON = parseJSONText "ProjectsTenantsCompleteQueryType"
instance ToJSON ProjectsTenantsCompleteQueryType where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | Specifies the traffic density to use when calculating commute time.
data CommuteFilterRoadTraffic
= RoadTrafficUnspecified
-- ^ @ROAD_TRAFFIC_UNSPECIFIED@
-- Road traffic situation isn\'t specified.
| TrafficFree
-- ^ @TRAFFIC_FREE@
-- Optimal commute time without considering any traffic impact.
| BusyHour
-- ^ @BUSY_HOUR@
-- Commute time calculation takes in account the peak traffic impact.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CommuteFilterRoadTraffic
instance FromHttpApiData CommuteFilterRoadTraffic where
parseQueryParam = \case
"ROAD_TRAFFIC_UNSPECIFIED" -> Right RoadTrafficUnspecified
"TRAFFIC_FREE" -> Right TrafficFree
"BUSY_HOUR" -> Right BusyHour
x -> Left ("Unable to parse CommuteFilterRoadTraffic from: " <> x)
instance ToHttpApiData CommuteFilterRoadTraffic where
toQueryParam = \case
RoadTrafficUnspecified -> "ROAD_TRAFFIC_UNSPECIFIED"
TrafficFree -> "TRAFFIC_FREE"
BusyHour -> "BUSY_HOUR"
instance FromJSON CommuteFilterRoadTraffic where
parseJSON = parseJSONText "CommuteFilterRoadTraffic"
instance ToJSON CommuteFilterRoadTraffic where
toJSON = toJSONText
-- | The completion topic.
data CompletionResultType
= CRTCompletionTypeUnspecified
-- ^ @COMPLETION_TYPE_UNSPECIFIED@
-- Default value.
| CRTJobTitle
-- ^ @JOB_TITLE@
-- Suggest job titles for jobs autocomplete. For CompletionType.JOB_TITLE
-- type, only open jobs with the same language_codes are returned.
| CRTCompanyName
-- ^ @COMPANY_NAME@
-- Suggest company names for jobs autocomplete. For
-- CompletionType.COMPANY_NAME type, only companies having open jobs with
-- the same language_codes are returned.
| CRTCombined
-- ^ @COMBINED@
-- Suggest both job titles and company names for jobs autocomplete. For
-- CompletionType.COMBINED type, only open jobs with the same
-- language_codes or companies having open jobs with the same
-- language_codes are returned.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompletionResultType
instance FromHttpApiData CompletionResultType where
parseQueryParam = \case
"COMPLETION_TYPE_UNSPECIFIED" -> Right CRTCompletionTypeUnspecified
"JOB_TITLE" -> Right CRTJobTitle
"COMPANY_NAME" -> Right CRTCompanyName
"COMBINED" -> Right CRTCombined
x -> Left ("Unable to parse CompletionResultType from: " <> x)
instance ToHttpApiData CompletionResultType where
toQueryParam = \case
CRTCompletionTypeUnspecified -> "COMPLETION_TYPE_UNSPECIFIED"
CRTJobTitle -> "JOB_TITLE"
CRTCompanyName -> "COMPANY_NAME"
CRTCombined -> "COMBINED"
instance FromJSON CompletionResultType where
parseJSON = parseJSONText "CompletionResultType"
instance ToJSON CompletionResultType where
toJSON = toJSONText
-- | The scope of the completion. The defaults is CompletionScope.PUBLIC.
data ProjectsTenantsCompleteQueryScope
= PTCQSCompletionScopeUnspecified
-- ^ @COMPLETION_SCOPE_UNSPECIFIED@
-- Default value.
| PTCQSTenant
-- ^ @TENANT@
-- Suggestions are based only on the data provided by the client.
| PTCQSPublic
-- ^ @PUBLIC@
-- Suggestions are based on all jobs data in the system that\'s visible to
-- the client
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsTenantsCompleteQueryScope
instance FromHttpApiData ProjectsTenantsCompleteQueryScope where
parseQueryParam = \case
"COMPLETION_SCOPE_UNSPECIFIED" -> Right PTCQSCompletionScopeUnspecified
"TENANT" -> Right PTCQSTenant
"PUBLIC" -> Right PTCQSPublic
x -> Left ("Unable to parse ProjectsTenantsCompleteQueryScope from: " <> x)
instance ToHttpApiData ProjectsTenantsCompleteQueryScope where
toQueryParam = \case
PTCQSCompletionScopeUnspecified -> "COMPLETION_SCOPE_UNSPECIFIED"
PTCQSTenant -> "TENANT"
PTCQSPublic -> "PUBLIC"
instance FromJSON ProjectsTenantsCompleteQueryScope where
parseJSON = parseJSONText "ProjectsTenantsCompleteQueryScope"
instance ToJSON ProjectsTenantsCompleteQueryScope where
toJSON = toJSONText
-- | The type of a location, which corresponds to the address lines field of
-- google.type.PostalAddress. For example, \"Downtown, Atlanta, GA, USA\"
-- has a type of LocationType.NEIGHBORHOOD, and \"Kansas City, KS, USA\"
-- has a type of LocationType.LOCALITY.
data LocationLocationType
= LLTLocationTypeUnspecified
-- ^ @LOCATION_TYPE_UNSPECIFIED@
-- Default value if the type isn\'t specified.
| LLTCountry
-- ^ @COUNTRY@
-- A country level location.
| LLTAdministrativeArea
-- ^ @ADMINISTRATIVE_AREA@
-- A state or equivalent level location.
| LLTSubAdministrativeArea
-- ^ @SUB_ADMINISTRATIVE_AREA@
-- A county or equivalent level location.
| LLTLocality
-- ^ @LOCALITY@
-- A city or equivalent level location.
| LLTPostalCode
-- ^ @POSTAL_CODE@
-- A postal code level location.
| LLTSubLocality
-- ^ @SUB_LOCALITY@
-- A sublocality is a subdivision of a locality, for example a city
-- borough, ward, or arrondissement. Sublocalities are usually recognized
-- by a local political authority. For example, Manhattan and Brooklyn are
-- recognized as boroughs by the City of New York, and are therefore
-- modeled as sublocalities.
| LLTSubLocality1
-- ^ @SUB_LOCALITY_1@
-- A district or equivalent level location.
| LLTSubLocality2
-- ^ @SUB_LOCALITY_2@
-- A smaller district or equivalent level display.
| LLTNeighborhood
-- ^ @NEIGHBORHOOD@
-- A neighborhood level location.
| LLTStreetAddress
-- ^ @STREET_ADDRESS@
-- A street address level location.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LocationLocationType
instance FromHttpApiData LocationLocationType where
parseQueryParam = \case
"LOCATION_TYPE_UNSPECIFIED" -> Right LLTLocationTypeUnspecified
"COUNTRY" -> Right LLTCountry
"ADMINISTRATIVE_AREA" -> Right LLTAdministrativeArea
"SUB_ADMINISTRATIVE_AREA" -> Right LLTSubAdministrativeArea
"LOCALITY" -> Right LLTLocality
"POSTAL_CODE" -> Right LLTPostalCode
"SUB_LOCALITY" -> Right LLTSubLocality
"SUB_LOCALITY_1" -> Right LLTSubLocality1
"SUB_LOCALITY_2" -> Right LLTSubLocality2
"NEIGHBORHOOD" -> Right LLTNeighborhood
"STREET_ADDRESS" -> Right LLTStreetAddress
x -> Left ("Unable to parse LocationLocationType from: " <> x)
instance ToHttpApiData LocationLocationType where
toQueryParam = \case
LLTLocationTypeUnspecified -> "LOCATION_TYPE_UNSPECIFIED"
LLTCountry -> "COUNTRY"
LLTAdministrativeArea -> "ADMINISTRATIVE_AREA"
LLTSubAdministrativeArea -> "SUB_ADMINISTRATIVE_AREA"
LLTLocality -> "LOCALITY"
LLTPostalCode -> "POSTAL_CODE"
LLTSubLocality -> "SUB_LOCALITY"
LLTSubLocality1 -> "SUB_LOCALITY_1"
LLTSubLocality2 -> "SUB_LOCALITY_2"
LLTNeighborhood -> "NEIGHBORHOOD"
LLTStreetAddress -> "STREET_ADDRESS"
instance FromJSON LocationLocationType where
parseJSON = parseJSONText "LocationLocationType"
instance ToJSON LocationLocationType where
toJSON = toJSONText
-- | Required. The type of the event (see JobEventType).
data JobEventType
= JobEventTypeUnspecified
-- ^ @JOB_EVENT_TYPE_UNSPECIFIED@
-- The event is unspecified by other provided values.
| Impression
-- ^ @IMPRESSION@
-- The job seeker or other entity interacting with the service has had a
-- job rendered in their view, such as in a list of search results in a
-- compressed or clipped format. This event is typically associated with
-- the viewing of a jobs list on a single page by a job seeker.
| View
-- ^ @VIEW@
-- The job seeker, or other entity interacting with the service, has viewed
-- the details of a job, including the full description. This event
-- doesn\'t apply to the viewing a snippet of a job appearing as a part of
-- the job search results. Viewing a snippet is associated with an
-- impression).
| ViewRedirect
-- ^ @VIEW_REDIRECT@
-- The job seeker or other entity interacting with the service performed an
-- action to view a job and was redirected to a different website for job.
| ApplicationStart
-- ^ @APPLICATION_START@
-- The job seeker or other entity interacting with the service began the
-- process or demonstrated the intention of applying for a job.
| ApplicationFinish
-- ^ @APPLICATION_FINISH@
-- The job seeker or other entity interacting with the service submitted an
-- application for a job.
| ApplicationQuickSubmission
-- ^ @APPLICATION_QUICK_SUBMISSION@
-- The job seeker or other entity interacting with the service submitted an
-- application for a job with a single click without entering information.
-- If a job seeker performs this action, send only this event to the
-- service. Do not also send JobEventType.APPLICATION_START or
-- JobEventType.APPLICATION_FINISH events.
| ApplicationRedirect
-- ^ @APPLICATION_REDIRECT@
-- The job seeker or other entity interacting with the service performed an
-- action to apply to a job and was redirected to a different website to
-- complete the application.
| ApplicationStartFromSearch
-- ^ @APPLICATION_START_FROM_SEARCH@
-- The job seeker or other entity interacting with the service began the
-- process or demonstrated the intention of applying for a job from the
-- search results page without viewing the details of the job posting. If
-- sending this event, JobEventType.VIEW event shouldn\'t be sent.
| ApplicationRedirectFromSearch
-- ^ @APPLICATION_REDIRECT_FROM_SEARCH@
-- The job seeker, or other entity interacting with the service, performs
-- an action with a single click from the search results page to apply to a
-- job (without viewing the details of the job posting), and is redirected
-- to a different website to complete the application. If a candidate
-- performs this action, send only this event to the service. Do not also
-- send JobEventType.APPLICATION_START, JobEventType.APPLICATION_FINISH or
-- JobEventType.VIEW events.
| ApplicationCompanySubmit
-- ^ @APPLICATION_COMPANY_SUBMIT@
-- This event should be used when a company submits an application on
-- behalf of a job seeker. This event is intended for use by staffing
-- agencies attempting to place candidates.
| Bookmark
-- ^ @BOOKMARK@
-- The job seeker or other entity interacting with the service demonstrated
-- an interest in a job by bookmarking or saving it.
| Notification
-- ^ @NOTIFICATION@
-- The job seeker or other entity interacting with the service was sent a
-- notification, such as an email alert or device notification, containing
-- one or more jobs listings generated by the service.
| Hired
-- ^ @HIRED@
-- The job seeker or other entity interacting with the service was employed
-- by the hiring entity (employer). Send this event only if the job seeker
-- was hired through an application that was initiated by a search
-- conducted through the Cloud Talent Solution service.
| SentCv
-- ^ @SENT_CV@
-- A recruiter or staffing agency submitted an application on behalf of the
-- candidate after interacting with the service to identify a suitable job
-- posting.
| InterviewGranted
-- ^ @INTERVIEW_GRANTED@
-- The entity interacting with the service (for example, the job seeker),
-- was granted an initial interview by the hiring entity (employer). This
-- event should only be sent if the job seeker was granted an interview as
-- part of an application that was initiated by a search conducted through
-- \/ recommendation provided by the Cloud Talent Solution service.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobEventType
instance FromHttpApiData JobEventType where
parseQueryParam = \case
"JOB_EVENT_TYPE_UNSPECIFIED" -> Right JobEventTypeUnspecified
"IMPRESSION" -> Right Impression
"VIEW" -> Right View
"VIEW_REDIRECT" -> Right ViewRedirect
"APPLICATION_START" -> Right ApplicationStart
"APPLICATION_FINISH" -> Right ApplicationFinish
"APPLICATION_QUICK_SUBMISSION" -> Right ApplicationQuickSubmission
"APPLICATION_REDIRECT" -> Right ApplicationRedirect
"APPLICATION_START_FROM_SEARCH" -> Right ApplicationStartFromSearch
"APPLICATION_REDIRECT_FROM_SEARCH" -> Right ApplicationRedirectFromSearch
"APPLICATION_COMPANY_SUBMIT" -> Right ApplicationCompanySubmit
"BOOKMARK" -> Right Bookmark
"NOTIFICATION" -> Right Notification
"HIRED" -> Right Hired
"SENT_CV" -> Right SentCv
"INTERVIEW_GRANTED" -> Right InterviewGranted
x -> Left ("Unable to parse JobEventType from: " <> x)
instance ToHttpApiData JobEventType where
toQueryParam = \case
JobEventTypeUnspecified -> "JOB_EVENT_TYPE_UNSPECIFIED"
Impression -> "IMPRESSION"
View -> "VIEW"
ViewRedirect -> "VIEW_REDIRECT"
ApplicationStart -> "APPLICATION_START"
ApplicationFinish -> "APPLICATION_FINISH"
ApplicationQuickSubmission -> "APPLICATION_QUICK_SUBMISSION"
ApplicationRedirect -> "APPLICATION_REDIRECT"
ApplicationStartFromSearch -> "APPLICATION_START_FROM_SEARCH"
ApplicationRedirectFromSearch -> "APPLICATION_REDIRECT_FROM_SEARCH"
ApplicationCompanySubmit -> "APPLICATION_COMPANY_SUBMIT"
Bookmark -> "BOOKMARK"
Notification -> "NOTIFICATION"
Hired -> "HIRED"
SentCv -> "SENT_CV"
InterviewGranted -> "INTERVIEW_GRANTED"
instance FromJSON JobEventType where
parseJSON = parseJSONText "JobEventType"
instance ToJSON JobEventType where
toJSON = toJSONText
-- | The state of a long running operation.
data BatchOperationMetadataState
= StateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Default value.
| Initializing
-- ^ @INITIALIZING@
-- The batch operation is being prepared for processing.
| Processing
-- ^ @PROCESSING@
-- The batch operation is actively being processed.
| Succeeded
-- ^ @SUCCEEDED@
-- The batch operation is processed, and at least one item has been
-- successfully processed.
| Failed
-- ^ @FAILED@
-- The batch operation is done and no item has been successfully processed.
| Cancelling
-- ^ @CANCELLING@
-- The batch operation is in the process of cancelling after
-- google.longrunning.Operations.CancelOperation is called.
| Cancelled
-- ^ @CANCELLED@
-- The batch operation is done after
-- google.longrunning.Operations.CancelOperation is called. Any items
-- processed before cancelling are returned in the response.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BatchOperationMetadataState
instance FromHttpApiData BatchOperationMetadataState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right StateUnspecified
"INITIALIZING" -> Right Initializing
"PROCESSING" -> Right Processing
"SUCCEEDED" -> Right Succeeded
"FAILED" -> Right Failed
"CANCELLING" -> Right Cancelling
"CANCELLED" -> Right Cancelled
x -> Left ("Unable to parse BatchOperationMetadataState from: " <> x)
instance ToHttpApiData BatchOperationMetadataState where
toQueryParam = \case
StateUnspecified -> "STATE_UNSPECIFIED"
Initializing -> "INITIALIZING"
Processing -> "PROCESSING"
Succeeded -> "SUCCEEDED"
Failed -> "FAILED"
Cancelling -> "CANCELLING"
Cancelled -> "CANCELLED"
instance FromJSON BatchOperationMetadataState where
parseJSON = parseJSONText "BatchOperationMetadataState"
instance ToJSON BatchOperationMetadataState where
toJSON = toJSONText
-- | Mode of a search. Defaults to SearchMode.JOB_SEARCH.
data SearchJobsRequestSearchMode
= SearchModeUnspecified
-- ^ @SEARCH_MODE_UNSPECIFIED@
-- The mode of the search method isn\'t specified. The default search
-- behavior is identical to JOB_SEARCH search behavior.
| JobSearch
-- ^ @JOB_SEARCH@
-- The job search matches against all jobs, and featured jobs (jobs with
-- promotionValue > 0) are not specially handled.
| FeaturedJobSearch
-- ^ @FEATURED_JOB_SEARCH@
-- The job search matches only against featured jobs (jobs with a
-- promotionValue > 0). This method doesn\'t return any jobs having a
-- promotionValue \<= 0. The search results order is determined by the
-- promotionValue (jobs with a higher promotionValue are returned higher up
-- in the search results), with relevance being used as a tiebreaker.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SearchJobsRequestSearchMode
instance FromHttpApiData SearchJobsRequestSearchMode where
parseQueryParam = \case
"SEARCH_MODE_UNSPECIFIED" -> Right SearchModeUnspecified
"JOB_SEARCH" -> Right JobSearch
"FEATURED_JOB_SEARCH" -> Right FeaturedJobSearch
x -> Left ("Unable to parse SearchJobsRequestSearchMode from: " <> x)
instance ToHttpApiData SearchJobsRequestSearchMode where
toQueryParam = \case
SearchModeUnspecified -> "SEARCH_MODE_UNSPECIFIED"
JobSearch -> "JOB_SEARCH"
FeaturedJobSearch -> "FEATURED_JOB_SEARCH"
instance FromJSON SearchJobsRequestSearchMode where
parseJSON = parseJSONText "SearchJobsRequestSearchMode"
instance ToJSON SearchJobsRequestSearchMode where
toJSON = toJSONText
-- | Allows the client to return jobs without a set location, specifically,
-- telecommuting jobs (telecommuting is considered by the service as a
-- special location. Job.posting_region indicates if a job permits
-- telecommuting. If this field is set to
-- TelecommutePreference.TELECOMMUTE_ALLOWED, telecommuting jobs are
-- searched, and address and lat_lng are ignored. If not set or set to
-- TelecommutePreference.TELECOMMUTE_EXCLUDED, telecommute job are not
-- searched. This filter can be used by itself to search exclusively for
-- telecommuting jobs, or it can be combined with another location filter
-- to search for a combination of job locations, such as \"Mountain View\"
-- or \"telecommuting\" jobs. However, when used in combination with other
-- location filters, telecommuting jobs can be treated as less relevant
-- than other jobs in the search response. This field is only used for job
-- search requests.
data LocationFilterTelecommutePreference
= TelecommutePreferenceUnspecified
-- ^ @TELECOMMUTE_PREFERENCE_UNSPECIFIED@
-- Default value if the telecommute preference isn\'t specified.
| TelecommuteExcluded
-- ^ @TELECOMMUTE_EXCLUDED@
-- Exclude telecommute jobs.
| TelecommuteAllowed
-- ^ @TELECOMMUTE_ALLOWED@
-- Allow telecommute jobs.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LocationFilterTelecommutePreference
instance FromHttpApiData LocationFilterTelecommutePreference where
parseQueryParam = \case
"TELECOMMUTE_PREFERENCE_UNSPECIFIED" -> Right TelecommutePreferenceUnspecified
"TELECOMMUTE_EXCLUDED" -> Right TelecommuteExcluded
"TELECOMMUTE_ALLOWED" -> Right TelecommuteAllowed
x -> Left ("Unable to parse LocationFilterTelecommutePreference from: " <> x)
instance ToHttpApiData LocationFilterTelecommutePreference where
toQueryParam = \case
TelecommutePreferenceUnspecified -> "TELECOMMUTE_PREFERENCE_UNSPECIFIED"
TelecommuteExcluded -> "TELECOMMUTE_EXCLUDED"
TelecommuteAllowed -> "TELECOMMUTE_ALLOWED"
instance FromJSON LocationFilterTelecommutePreference where
parseJSON = parseJSONText "LocationFilterTelecommutePreference"
instance ToJSON LocationFilterTelecommutePreference where
toJSON = toJSONText
-- | Option for job HTML content sanitization. Applied fields are: *
-- description * applicationInfo.instruction * incentives * qualifications
-- * responsibilities HTML tags in these fields may be stripped if
-- sanitiazation isn\'t disabled. Defaults to
-- HtmlSanitization.SIMPLE_FORMATTING_ONLY.
data ProcessingOptionsHTMLSanitization
= HTMLSanitizationUnspecified
-- ^ @HTML_SANITIZATION_UNSPECIFIED@
-- Default value.
| HTMLSanitizationDisabled
-- ^ @HTML_SANITIZATION_DISABLED@
-- Disables sanitization on HTML input.
| SimpleFormattingOnly
-- ^ @SIMPLE_FORMATTING_ONLY@
-- Sanitizes HTML input, only accepts bold, italic, ordered list, and
-- unordered list markup tags.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProcessingOptionsHTMLSanitization
instance FromHttpApiData ProcessingOptionsHTMLSanitization where
parseQueryParam = \case
"HTML_SANITIZATION_UNSPECIFIED" -> Right HTMLSanitizationUnspecified
"HTML_SANITIZATION_DISABLED" -> Right HTMLSanitizationDisabled
"SIMPLE_FORMATTING_ONLY" -> Right SimpleFormattingOnly
x -> Left ("Unable to parse ProcessingOptionsHTMLSanitization from: " <> x)
instance ToHttpApiData ProcessingOptionsHTMLSanitization where
toQueryParam = \case
HTMLSanitizationUnspecified -> "HTML_SANITIZATION_UNSPECIFIED"
HTMLSanitizationDisabled -> "HTML_SANITIZATION_DISABLED"
SimpleFormattingOnly -> "SIMPLE_FORMATTING_ONLY"
instance FromJSON ProcessingOptionsHTMLSanitization where
parseJSON = parseJSONText "ProcessingOptionsHTMLSanitization"
instance ToJSON ProcessingOptionsHTMLSanitization where
toJSON = toJSONText
data JobQueryJobCategoriesItem
= JQJCIJobCategoryUnspecified
-- ^ @JOB_CATEGORY_UNSPECIFIED@
-- The default value if the category isn\'t specified.
| JQJCIAccountingAndFinance
-- ^ @ACCOUNTING_AND_FINANCE@
-- An accounting and finance job, such as an Accountant.
| JQJCIAdministrativeAndOffice
-- ^ @ADMINISTRATIVE_AND_OFFICE@
-- An administrative and office job, such as an Administrative Assistant.
| JQJCIAdvertisingAndMarketing
-- ^ @ADVERTISING_AND_MARKETING@
-- An advertising and marketing job, such as Marketing Manager.
| JQJCIAnimalCare
-- ^ @ANIMAL_CARE@
-- An animal care job, such as Veterinarian.
| JQJCIArtFashionAndDesign
-- ^ @ART_FASHION_AND_DESIGN@
-- An art, fashion, or design job, such as Designer.
| JQJCIBusinessOperations
-- ^ @BUSINESS_OPERATIONS@
-- A business operations job, such as Business Operations Manager.
| JQJCICleaningAndFacilities
-- ^ @CLEANING_AND_FACILITIES@
-- A cleaning and facilities job, such as Custodial Staff.
| JQJCIComputerAndIt
-- ^ @COMPUTER_AND_IT@
-- A computer and IT job, such as Systems Administrator.
| JQJCIConstruction
-- ^ @CONSTRUCTION@
-- A construction job, such as General Laborer.
| JQJCICustomerService
-- ^ @CUSTOMER_SERVICE@
-- A customer service job, such s Cashier.
| JQJCIEducation
-- ^ @EDUCATION@
-- An education job, such as School Teacher.
| JQJCIEntertainmentAndTravel
-- ^ @ENTERTAINMENT_AND_TRAVEL@
-- An entertainment and travel job, such as Flight Attendant.
| JQJCIFarmingAndOutdoors
-- ^ @FARMING_AND_OUTDOORS@
-- A farming or outdoor job, such as Park Ranger.
| JQJCIHealthcare
-- ^ @HEALTHCARE@
-- A healthcare job, such as Registered Nurse.
| JQJCIHumanResources
-- ^ @HUMAN_RESOURCES@
-- A human resources job, such as Human Resources Director.
| JQJCIInstallationMaintenanceAndRepair
-- ^ @INSTALLATION_MAINTENANCE_AND_REPAIR@
-- An installation, maintenance, or repair job, such as Electrician.
| JQJCILegal
-- ^ @LEGAL@
-- A legal job, such as Law Clerk.
| JQJCIManagement
-- ^ @MANAGEMENT@
-- A management job, often used in conjunction with another category, such
-- as Store Manager.
| JQJCIManufacturingAndWarehouse
-- ^ @MANUFACTURING_AND_WAREHOUSE@
-- A manufacturing or warehouse job, such as Assembly Technician.
| JQJCIMediaCommunicationsAndWriting
-- ^ @MEDIA_COMMUNICATIONS_AND_WRITING@
-- A media, communications, or writing job, such as Media Relations.
| JQJCIOilGasAndMining
-- ^ @OIL_GAS_AND_MINING@
-- An oil, gas or mining job, such as Offshore Driller.
| JQJCIPersonalCareAndServices
-- ^ @PERSONAL_CARE_AND_SERVICES@
-- A personal care and services job, such as Hair Stylist.
| JQJCIProtectiveServices
-- ^ @PROTECTIVE_SERVICES@
-- A protective services job, such as Security Guard.
| JQJCIRealEState
-- ^ @REAL_ESTATE@
-- A real estate job, such as Buyer\'s Agent.
| JQJCIRestaurantAndHospitality
-- ^ @RESTAURANT_AND_HOSPITALITY@
-- A restaurant and hospitality job, such as Restaurant Server.
| JQJCISalesAndRetail
-- ^ @SALES_AND_RETAIL@
-- A sales and\/or retail job, such Sales Associate.
| JQJCIScienceAndEngineering
-- ^ @SCIENCE_AND_ENGINEERING@
-- A science and engineering job, such as Lab Technician.
| JQJCISocialServicesAndNonProfit
-- ^ @SOCIAL_SERVICES_AND_NON_PROFIT@
-- A social services or non-profit job, such as Case Worker.
| JQJCISportsFitnessAndRecreation
-- ^ @SPORTS_FITNESS_AND_RECREATION@
-- A sports, fitness, or recreation job, such as Personal Trainer.
| JQJCITransportationAndLogistics
-- ^ @TRANSPORTATION_AND_LOGISTICS@
-- A transportation or logistics job, such as Truck Driver.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobQueryJobCategoriesItem
instance FromHttpApiData JobQueryJobCategoriesItem where
parseQueryParam = \case
"JOB_CATEGORY_UNSPECIFIED" -> Right JQJCIJobCategoryUnspecified
"ACCOUNTING_AND_FINANCE" -> Right JQJCIAccountingAndFinance
"ADMINISTRATIVE_AND_OFFICE" -> Right JQJCIAdministrativeAndOffice
"ADVERTISING_AND_MARKETING" -> Right JQJCIAdvertisingAndMarketing
"ANIMAL_CARE" -> Right JQJCIAnimalCare
"ART_FASHION_AND_DESIGN" -> Right JQJCIArtFashionAndDesign
"BUSINESS_OPERATIONS" -> Right JQJCIBusinessOperations
"CLEANING_AND_FACILITIES" -> Right JQJCICleaningAndFacilities
"COMPUTER_AND_IT" -> Right JQJCIComputerAndIt
"CONSTRUCTION" -> Right JQJCIConstruction
"CUSTOMER_SERVICE" -> Right JQJCICustomerService
"EDUCATION" -> Right JQJCIEducation
"ENTERTAINMENT_AND_TRAVEL" -> Right JQJCIEntertainmentAndTravel
"FARMING_AND_OUTDOORS" -> Right JQJCIFarmingAndOutdoors
"HEALTHCARE" -> Right JQJCIHealthcare
"HUMAN_RESOURCES" -> Right JQJCIHumanResources
"INSTALLATION_MAINTENANCE_AND_REPAIR" -> Right JQJCIInstallationMaintenanceAndRepair
"LEGAL" -> Right JQJCILegal
"MANAGEMENT" -> Right JQJCIManagement
"MANUFACTURING_AND_WAREHOUSE" -> Right JQJCIManufacturingAndWarehouse
"MEDIA_COMMUNICATIONS_AND_WRITING" -> Right JQJCIMediaCommunicationsAndWriting
"OIL_GAS_AND_MINING" -> Right JQJCIOilGasAndMining
"PERSONAL_CARE_AND_SERVICES" -> Right JQJCIPersonalCareAndServices
"PROTECTIVE_SERVICES" -> Right JQJCIProtectiveServices
"REAL_ESTATE" -> Right JQJCIRealEState
"RESTAURANT_AND_HOSPITALITY" -> Right JQJCIRestaurantAndHospitality
"SALES_AND_RETAIL" -> Right JQJCISalesAndRetail
"SCIENCE_AND_ENGINEERING" -> Right JQJCIScienceAndEngineering
"SOCIAL_SERVICES_AND_NON_PROFIT" -> Right JQJCISocialServicesAndNonProfit
"SPORTS_FITNESS_AND_RECREATION" -> Right JQJCISportsFitnessAndRecreation
"TRANSPORTATION_AND_LOGISTICS" -> Right JQJCITransportationAndLogistics
x -> Left ("Unable to parse JobQueryJobCategoriesItem from: " <> x)
instance ToHttpApiData JobQueryJobCategoriesItem where
toQueryParam = \case
JQJCIJobCategoryUnspecified -> "JOB_CATEGORY_UNSPECIFIED"
JQJCIAccountingAndFinance -> "ACCOUNTING_AND_FINANCE"
JQJCIAdministrativeAndOffice -> "ADMINISTRATIVE_AND_OFFICE"
JQJCIAdvertisingAndMarketing -> "ADVERTISING_AND_MARKETING"
JQJCIAnimalCare -> "ANIMAL_CARE"
JQJCIArtFashionAndDesign -> "ART_FASHION_AND_DESIGN"
JQJCIBusinessOperations -> "BUSINESS_OPERATIONS"
JQJCICleaningAndFacilities -> "CLEANING_AND_FACILITIES"
JQJCIComputerAndIt -> "COMPUTER_AND_IT"
JQJCIConstruction -> "CONSTRUCTION"
JQJCICustomerService -> "CUSTOMER_SERVICE"
JQJCIEducation -> "EDUCATION"
JQJCIEntertainmentAndTravel -> "ENTERTAINMENT_AND_TRAVEL"
JQJCIFarmingAndOutdoors -> "FARMING_AND_OUTDOORS"
JQJCIHealthcare -> "HEALTHCARE"
JQJCIHumanResources -> "HUMAN_RESOURCES"
JQJCIInstallationMaintenanceAndRepair -> "INSTALLATION_MAINTENANCE_AND_REPAIR"
JQJCILegal -> "LEGAL"
JQJCIManagement -> "MANAGEMENT"
JQJCIManufacturingAndWarehouse -> "MANUFACTURING_AND_WAREHOUSE"
JQJCIMediaCommunicationsAndWriting -> "MEDIA_COMMUNICATIONS_AND_WRITING"
JQJCIOilGasAndMining -> "OIL_GAS_AND_MINING"
JQJCIPersonalCareAndServices -> "PERSONAL_CARE_AND_SERVICES"
JQJCIProtectiveServices -> "PROTECTIVE_SERVICES"
JQJCIRealEState -> "REAL_ESTATE"
JQJCIRestaurantAndHospitality -> "RESTAURANT_AND_HOSPITALITY"
JQJCISalesAndRetail -> "SALES_AND_RETAIL"
JQJCIScienceAndEngineering -> "SCIENCE_AND_ENGINEERING"
JQJCISocialServicesAndNonProfit -> "SOCIAL_SERVICES_AND_NON_PROFIT"
JQJCISportsFitnessAndRecreation -> "SPORTS_FITNESS_AND_RECREATION"
JQJCITransportationAndLogistics -> "TRANSPORTATION_AND_LOGISTICS"
instance FromJSON JobQueryJobCategoriesItem where
parseJSON = parseJSONText "JobQueryJobCategoriesItem"
instance ToJSON JobQueryJobCategoriesItem where
toJSON = toJSONText
data JobJobBenefitsItem
= JobBenefitUnspecified
-- ^ @JOB_BENEFIT_UNSPECIFIED@
-- Default value if the type isn\'t specified.
| ChildCare
-- ^ @CHILD_CARE@
-- The job includes access to programs that support child care, such as
-- daycare.
| Dental
-- ^ @DENTAL@
-- The job includes dental services covered by a dental insurance plan.
| DomesticPartner
-- ^ @DOMESTIC_PARTNER@
-- The job offers specific benefits to domestic partners.
| FlexibleHours
-- ^ @FLEXIBLE_HOURS@
-- The job allows for a flexible work schedule.
| Medical
-- ^ @MEDICAL@
-- The job includes health services covered by a medical insurance plan.
| LifeInsurance
-- ^ @LIFE_INSURANCE@
-- The job includes a life insurance plan provided by the employer or
-- available for purchase by the employee.
| ParentalLeave
-- ^ @PARENTAL_LEAVE@
-- The job allows for a leave of absence to a parent to care for a newborn
-- child.
| RetirementPlan
-- ^ @RETIREMENT_PLAN@
-- The job includes a workplace retirement plan provided by the employer or
-- available for purchase by the employee.
| SickDays
-- ^ @SICK_DAYS@
-- The job allows for paid time off due to illness.
| Vacation
-- ^ @VACATION@
-- The job includes paid time off for vacation.
| Vision
-- ^ @VISION@
-- The job includes vision services covered by a vision insurance plan.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobJobBenefitsItem
instance FromHttpApiData JobJobBenefitsItem where
parseQueryParam = \case
"JOB_BENEFIT_UNSPECIFIED" -> Right JobBenefitUnspecified
"CHILD_CARE" -> Right ChildCare
"DENTAL" -> Right Dental
"DOMESTIC_PARTNER" -> Right DomesticPartner
"FLEXIBLE_HOURS" -> Right FlexibleHours
"MEDICAL" -> Right Medical
"LIFE_INSURANCE" -> Right LifeInsurance
"PARENTAL_LEAVE" -> Right ParentalLeave
"RETIREMENT_PLAN" -> Right RetirementPlan
"SICK_DAYS" -> Right SickDays
"VACATION" -> Right Vacation
"VISION" -> Right Vision
x -> Left ("Unable to parse JobJobBenefitsItem from: " <> x)
instance ToHttpApiData JobJobBenefitsItem where
toQueryParam = \case
JobBenefitUnspecified -> "JOB_BENEFIT_UNSPECIFIED"
ChildCare -> "CHILD_CARE"
Dental -> "DENTAL"
DomesticPartner -> "DOMESTIC_PARTNER"
FlexibleHours -> "FLEXIBLE_HOURS"
Medical -> "MEDICAL"
LifeInsurance -> "LIFE_INSURANCE"
ParentalLeave -> "PARENTAL_LEAVE"
RetirementPlan -> "RETIREMENT_PLAN"
SickDays -> "SICK_DAYS"
Vacation -> "VACATION"
Vision -> "VISION"
instance FromJSON JobJobBenefitsItem where
parseJSON = parseJSONText "JobJobBenefitsItem"
instance ToJSON JobJobBenefitsItem where
toJSON = toJSONText
-- | The desired job attributes returned for jobs in the search response.
-- Defaults to JobView.JOB_VIEW_SMALL if no value is specified.
data SearchJobsRequestJobView
= SJRJVJobViewUnspecified
-- ^ @JOB_VIEW_UNSPECIFIED@
-- Default value.
| SJRJVJobViewIdOnly
-- ^ @JOB_VIEW_ID_ONLY@
-- A ID only view of job, with following attributes: Job.name,
-- Job.requisition_id, Job.language_code.
| SJRJVJobViewMinimal
-- ^ @JOB_VIEW_MINIMAL@
-- A minimal view of the job, with the following attributes: Job.name,
-- Job.requisition_id, Job.title, Job.company, Job.DerivedInfo.locations,
-- Job.language_code.
| SJRJVJobViewSmall
-- ^ @JOB_VIEW_SMALL@
-- A small view of the job, with the following attributes in the search
-- results: Job.name, Job.requisition_id, Job.title, Job.company,
-- Job.DerivedInfo.locations, Job.visibility, Job.language_code,
-- Job.description.
| SJRJVJobViewFull
-- ^ @JOB_VIEW_FULL@
-- All available attributes are included in the search results.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SearchJobsRequestJobView
instance FromHttpApiData SearchJobsRequestJobView where
parseQueryParam = \case
"JOB_VIEW_UNSPECIFIED" -> Right SJRJVJobViewUnspecified
"JOB_VIEW_ID_ONLY" -> Right SJRJVJobViewIdOnly
"JOB_VIEW_MINIMAL" -> Right SJRJVJobViewMinimal
"JOB_VIEW_SMALL" -> Right SJRJVJobViewSmall
"JOB_VIEW_FULL" -> Right SJRJVJobViewFull
x -> Left ("Unable to parse SearchJobsRequestJobView from: " <> x)
instance ToHttpApiData SearchJobsRequestJobView where
toQueryParam = \case
SJRJVJobViewUnspecified -> "JOB_VIEW_UNSPECIFIED"
SJRJVJobViewIdOnly -> "JOB_VIEW_ID_ONLY"
SJRJVJobViewMinimal -> "JOB_VIEW_MINIMAL"
SJRJVJobViewSmall -> "JOB_VIEW_SMALL"
SJRJVJobViewFull -> "JOB_VIEW_FULL"
instance FromJSON SearchJobsRequestJobView where
parseJSON = parseJSONText "SearchJobsRequestJobView"
instance ToJSON SearchJobsRequestJobView where
toJSON = toJSONText
|
brendanhay/gogol
|
gogol-jobs/gen/Network/Google/Jobs/Types/Sum.hs
|
mpl-2.0
| 84,641 | 0 | 11 | 19,256 | 9,076 | 4,904 | 4,172 | 1,118 | 0 |
module Test.Compiler (iotests) where
import Test.HUnit hiding (test)
import System.Directory
import Control.Monad
import System.IO
import CPP.CompileTools
import FFI.TypeParser (importHni)
windowsLineMode = NewlineMode { inputNL = CRLF, outputNL = CRLF }
readFileCRLF name = do
h <- openFile name ReadMode
hSetNewlineMode h windowsLineMode
hGetContents h
comp2 f g x y = f $ g x y
test testName = liftM2 (comp2 (testName ~:) (~=?))
(readFileCRLF $ "hn_tests/" ++ testName ++ ".cpp")
(importHni "lib/lib.hni" >>= compileFile ("hn_tests/" ++ testName ++ ".hn"))
iotests =
(map fst . filter (\x -> snd x == ".hn") . map (break (== '.'))) <$> getDirectoryContents "hn_tests"
>>= mapM test
|
ingvar-lynn/HNC
|
Test/Compiler.hs
|
lgpl-3.0
| 701 | 10 | 14 | 118 | 270 | 142 | 128 | 19 | 1 |
{-
Created : 2013 Sep 27 (Sat) 09:01:51 by carr.
Last Modified : 2014 Mar 05 (Wed) 12:53:51 by Harold Carr.
-}
module FP00Lists where
{-# ANN sum' "HLint: ignore Use sum" #-}
sum' :: [Int] -> Int
sum' = foldr (+) 0
{-
sum' [] = 0
sum' (x:xs) = x + sum' xs
-}
max' :: [Int] -> Int
max' [] = error "NoSuchElement"
max' (x:xs) = foldr (\el acc -> if el > acc then el else acc) x xs
{-
where max'' x [] = x
max'' x (x':xs) = max'' (if x > x' then x else x') xs
-}
-- End of file.
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/course/2013-11-coursera-fp-odersky-but-in-haskell/FP00Lists.hs
|
unlicense
| 513 | 0 | 9 | 146 | 102 | 59 | 43 | 7 | 2 |
import Data.Map (singleton, findMin, deleteMin, insert)
a239870 n = a239870_list !! (n-1)
a239870_list = f 9 (3, 2) (singleton 4 (2, 2)) where
f zz (bz, ez) m
| xx < zz = if ex `mod` 3 > 0
then xx : f zz (bz, ez+1) (insert (bx*xx) (bx, ex+1) $ deleteMin m)
else f zz (bz, ez+1) (insert (bx*xx) (bx, ex+1) $ deleteMin m)
| xx > zz = if ez `mod` 3 > 0
then zz : f (zz+2*bz+1) (bz+1, 2) (insert (bz*zz) (bz, 3) m)
else f (zz+2*bz+1) (bz+1, 2) (insert (bz*zz) (bz, 3) m)
| otherwise = f (zz+2*bz+1) (bz+1, 2) m
where (xx, (bx, ex)) = findMin m
|
peterokagey/haskellOEIS
|
src/Sandbox/OEIS/A239870.hs
|
apache-2.0
| 592 | 0 | 15 | 165 | 430 | 233 | 197 | 12 | 3 |
-- Copyright 2019-2021 Google LLC
--
-- 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.
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoStarIsType #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Provides a class of types isomorphic to some statically-known @'Fin' n@.
--
-- This comes with Generics-based generated instances, and can be used to
-- generate instances of 'Enum' and 'Bounded' (for which the stock deriving
-- only supports sum types with no fields).
--
-- Since this is all still represented by 'Int' internally, things will start
-- raising 'error's if your type has more values than can fit in positive
-- 'Int's. It's not recommended to use this on large types, and there's not
-- much reason to want to anyway, as its main uses are to derive 'Enum' (which
-- is also based on 'Int') and to make the type compatible with
-- 'Data.Finite.Table.Table' (which would be impractically large for a key type
-- with too many values to represent as 'Int').
--
-- The most common way to get a 'Finite' instance for a type is to tack on a
-- @deriving Finite via 'Wrapped' 'Generic' MyType@ clause, which results in an
-- automatically-generated instance based on the type's ADT structure.
--
-- This also provides instances @'Enum' (Wrapped Finite a)@ and
-- @'Bounded' (Wrapped Finite a)@, so some types that would otherwise not be
-- compatible with derived 'Enum' instances can get them by adding a
-- @deriving (Enum, Bounded) via Wrapped Finite MyType@ clause.
module Data.Finite
( -- * Finite Enumerations
Finite(..), cardinality, enumerate, asFin
-- * Implementation Details
, SC, GFinite(..), GCardinality
) where
import Data.Functor.Identity (Identity)
import Data.Int (Int8, Int16)
import Data.Proxy (Proxy(..))
import Data.Semigroup (WrappedMonoid, Min, Max, First, Last)
import Data.Void (Void)
import Data.Word (Word8, Word16)
import GHC.Generics
( Generic(..), V1, U1(..), M1(..), K1(..), (:+:)(..), (:*:)(..)
)
import GHC.TypeNats (type (+), type (*), type (<=), KnownNat, Nat, natVal)
import Control.Lens (Iso', iso)
import Data.SInt (SInt, sintVal, addSInt, mulSInt, staticSIntVal, reifySInt)
import Data.Fin.Int.Explicit
( enumFin, concatFin, splitFin, crossFin, divModFin, minFin, maxFin
, fin
)
import Data.Fin.Int (Fin, finToInt, unsafeFin)
import qualified Data.Vec.Short as V
import Data.Wrapped (Wrapped(..))
-- | A typeclass of finite enumerable types.
--
-- These allow constructing 'Data.Functor.Rep.Representable' Functors using a
-- simple 'Data.Vec.Short.Vec' as the underlying storage, with constant-time
-- lookup and efficient traversals.
--
-- Note that since 'Fin' is (currently) represented by 'Int', any type with
-- more values than 'Int' can't have an instance. This means we can't have
-- instances for 32- and 64-bit arithmetic types, since 'Int' is only required
-- to have 30 bits of precision.
--
-- Annoyingly, we also can't have an instance for 'Int' and 'Word', because
-- 'Fin' wastes one bit of the 'Int' by forbidding negative values. The
-- cardinality of 'Int' and 'Word' would need to be twice as large as we can
-- actually represent in a 'Fin'. Another obstacle is that their cardinality
-- varies between implementations and architectures; it's possible to work
-- around this by making their Cardinality an irreducible type family
-- application, and using 'Data.SInt.SI#' to plug in a value at runtime, but
-- this makes the 'Fin's related to 'Int' and 'Word' annoying to work with,
-- since their bound is only known at runtime.
--
-- Fortunately, those instances are unlikely to be important, since a table of
-- 2^32 elements is moderately impractical (32GiB of pointers alone), and a
-- table of 2^64 elements is unrepresentable in current computer architectures.
--
-- 'toFin' and 'fromFin' shall be total functions and shall be the two sides of
-- an isomorphism.
class Finite a where
type Cardinality a :: Nat
-- | A witness that the cardinality is known at runtime.
--
-- This isn't part of the class context because we can only perform
-- arithmetic on 'KnownNat' instances in expression context; that is, we
-- can't convince GHC that an instance with
-- @type Cardinality (Maybe a) = Cardinality a + 1@ is valid if the
-- 'KnownNat' is in the class context. Instead, we use 'SInt' to allow
-- computing the cardinality at runtime.
cardinality' :: SC a (Cardinality a)
toFin :: a -> Fin (Cardinality a)
fromFin :: Fin (Cardinality a) -> a
-- | A wrapper type around @'Cardinality' a@ to support DerivingVia on GHC 8.6.
--
-- Instance methods that don't mention the instance head outside of type
-- families / aliases don't work with DerivingVia on GHC 8.6 because it uses
-- type signatures rather than TypeApplications to choose the instance to call
-- into.
newtype SC a n = SC { getSC :: SInt n }
-- | A witness that the cardinality of @a@ is known at runtime.
cardinality :: forall a. Finite a => SInt (Cardinality a)
cardinality = getSC (cardinality' @a)
-- | Generate a list containing every value of @a@.
enumerate :: forall a. Finite a => [a]
enumerate = fromFin <$> enumFin (cardinality @a)
-- | Implement 'toFin' by 'fromEnum'.
--
-- This should only be used for types with 'fromEnum' range @0..Cardinality a@;
-- this is notably not the case for signed integer types, which have negative
-- 'fromEnum' values.
toFinEnum :: Enum a => SInt (Cardinality a) -> a -> Fin (Cardinality a)
toFinEnum sn = fin sn . fromEnum
-- | Implement 'fromFin' by 'toEnum'.
--
-- The same restrictions apply as for 'toFinEnum'.
fromFinEnum :: Enum a => Fin (Cardinality a) -> a
fromFinEnum = toEnum . finToInt
instance Finite Char where
type Cardinality Char = 1114112 -- According to 'minBound' and 'maxBound'
cardinality' = SC staticSIntVal
toFin = toFinEnum staticSIntVal
fromFin = fromFinEnum
toFinExcessK
:: forall n a. (KnownNat n, Integral a) => a -> Fin (Cardinality a)
toFinExcessK =
unsafeFin . (+ (fromIntegral (natVal @n Proxy) :: Int)) . fromIntegral
fromFinExcessK
:: forall n a. (KnownNat n, Integral a) => Fin (Cardinality a) -> a
fromFinExcessK =
subtract (fromIntegral (natVal @n Proxy)) . fromIntegral . finToInt
instance Finite Int8 where
type Cardinality Int8 = 256
cardinality' = SC staticSIntVal
toFin = toFinExcessK @128
fromFin = fromFinExcessK @128
instance Finite Int16 where
type Cardinality Int16 = 65536
cardinality' = SC staticSIntVal
toFin = toFinExcessK @32768
fromFin = fromFinExcessK @32768
instance Finite Word8 where
type Cardinality Word8 = 256
cardinality' = SC staticSIntVal
toFin = unsafeFin . id @Int . fromIntegral
fromFin = fromIntegral . finToInt
instance Finite Word16 where
type Cardinality Word16 = 65536
cardinality' = SC staticSIntVal
toFin = unsafeFin . id @Int . fromIntegral
fromFin = fromIntegral . finToInt
instance KnownNat n => Finite (Fin n) where
type Cardinality (Fin n) = n
cardinality' = SC sintVal
toFin = id
fromFin = id
-- Aesthetics: make more derived instances fit on one line.
type G = Wrapped Generic
deriving via G () instance Finite ()
deriving via G Bool instance Finite Bool
deriving via G Ordering instance Finite Ordering
deriving via G Void instance Finite Void
deriving via G (Identity a) instance Finite a => Finite (Identity a)
deriving via G (WrappedMonoid a) instance Finite a => Finite (WrappedMonoid a)
deriving via G (Last a) instance Finite a => Finite (Last a)
deriving via G (First a) instance Finite a => Finite (First a)
deriving via G (Max a) instance Finite a => Finite (Max a)
deriving via G (Min a) instance Finite a => Finite (Min a)
deriving via G (Maybe a) instance Finite a => Finite (Maybe a)
deriving via G (Either a b) instance (Finite a, Finite b) => Finite (Either a b)
deriving via G (a, b) instance (Finite a, Finite b) => Finite (a, b)
deriving via G (a, b, c)
instance (Finite a, Finite b, Finite c) => Finite (a, b, c)
deriving via G (a, b, c, d)
instance (Finite a, Finite b, Finite c, Finite d) => Finite (a, b, c, d)
deriving via G (a, b, c, d, e)
instance (Finite a, Finite b, Finite c, Finite d, Finite e)
=> Finite (a, b, c, d, e)
instance (Generic a, GFinite (Rep a)) => Finite (Wrapped Generic a) where
type Cardinality (Wrapped Generic a) = GCardinality (Rep a)
cardinality' = SC $ gcardinality @(Rep a)
toFin = gtoFin . from . unWrapped
fromFin = Wrapped . to . gfromFin
-- | The derived cardinality of a generic representation type.
type family GCardinality a where
GCardinality V1 = 0
GCardinality U1 = 1
GCardinality (K1 i a) = Cardinality a
GCardinality (M1 i c f) = GCardinality f
GCardinality (f :+: g) = GCardinality f + GCardinality g
GCardinality (f :*: g) = GCardinality f * GCardinality g
-- | The derived 'Finite' implementation of a generic representation type.
class GFinite a where
gcardinality :: SInt (GCardinality a)
gtoFin :: a p -> Fin (GCardinality a)
gfromFin :: Fin (GCardinality a) -> a p
instance GFinite V1 where
gcardinality = staticSIntVal
gtoFin x = case x of {}
gfromFin x = V.nil V.! x
instance GFinite U1 where
gcardinality = staticSIntVal
gtoFin U1 = minFin
gfromFin !_ = U1
instance Finite a => GFinite (K1 i a) where
gcardinality = cardinality @a
gtoFin = toFin . unK1
gfromFin = K1 . fromFin
instance GFinite f => GFinite (M1 i c f) where
gcardinality = gcardinality @f
gtoFin = gtoFin . unM1
gfromFin = M1 . gfromFin
instance (GFinite f, GFinite g) => GFinite (f :+: g) where
gcardinality = gcardinality @f `addSInt` gcardinality @g
gtoFin x = concatFin (gcardinality @f) $ case x of
L1 f -> Left $ gtoFin f
R1 g -> Right $ gtoFin g
gfromFin =
either (L1 . gfromFin) (R1 . gfromFin) . splitFin (gcardinality @f)
{-# INLINE gtoFin #-}
{-# INLINE gfromFin #-}
instance (GFinite f, GFinite g) => GFinite (f :*: g) where
gcardinality = gcardinality @f `mulSInt` gcardinality @g
gtoFin (f :*: g) = crossFin (gcardinality @g) (gtoFin f) (gtoFin g)
gfromFin x =
let (f, g) = divModFin (gcardinality @g) x
in gfromFin f :*: gfromFin g
{-# INLINE gtoFin #-}
{-# INLINE gfromFin #-}
-- | An 'Control.Lens.Iso' between @a@ and the corresponding 'Fin' type.
asFin :: Finite a => Iso' a (Fin (Cardinality a))
asFin = iso toFin fromFin
instance Finite a => Enum (Wrapped Finite a) where
toEnum = Wrapped . fromFin . fin (cardinality @a)
fromEnum = finToInt . toFin . unWrapped
enumFrom = reifySInt (cardinality @a) $
fmap (Wrapped . fromFin) . enumFrom . toFin . unWrapped
enumFromThen (Wrapped x) = reifySInt (cardinality @a) $
fmap (Wrapped . fromFin) . enumFromThen (toFin x) . toFin . unWrapped
enumFromTo (Wrapped x) = reifySInt (cardinality @a) $
fmap (Wrapped . fromFin) . enumFromTo (toFin x) . toFin . unWrapped
enumFromThenTo (Wrapped x) (Wrapped y) = reifySInt (cardinality @a) $
fmap (Wrapped . fromFin) . enumFromThenTo (toFin x) (toFin y) .
toFin . unWrapped
instance (Finite a, 1 <= Cardinality a) => Bounded (Wrapped Finite a) where
minBound = Wrapped $ fromFin minFin
maxBound = Wrapped $ fromFin (maxFin (cardinality @a))
|
google/hs-fin-vec
|
finite-table/src/Data/Finite.hs
|
apache-2.0
| 12,344 | 2 | 13 | 2,368 | 2,892 | 1,576 | 1,316 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Snap-agnostic low-level CRUD operations. No model definitions are used
on this level. Instead, objects must be
This module may be used for batch uploading of database data.
-}
module Snap.Snaplet.Redson.Snapless.CRUD
( -- * CRUD operations
create
, read
, update
, delete
-- * Redis helpers
, InstanceId
, instanceKey
, modelIndex
, modelTimeline
, collate
, onlyFields
)
where
import Prelude hiding (id, read)
import Control.Monad.State
import Data.Functor
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import qualified Data.Map as M
import Database.Redis
import Snap.Snaplet.Redson.Snapless.Metamodel
type InstanceId = B.ByteString
------------------------------------------------------------------------------
-- | Build Redis key given model name and instance id.
instanceKey :: ModelName -> InstanceId -> B.ByteString
instanceKey model id = B.concat [model, ":", id]
------------------------------------------------------------------------------
-- | Get Redis key which stores id counter for model.
modelIdKey :: ModelName -> B.ByteString
modelIdKey model = B.concat ["global:", model, ":id"]
------------------------------------------------------------------------------
-- | Get Redis key which stores timeline for model.
modelTimeline :: ModelName -> B.ByteString
modelTimeline model = B.concat ["global:", model, ":timeline"]
------------------------------------------------------------------------------
-- | Build Redis key for field index of model.
modelIndex :: ModelName
-> B.ByteString -- ^ Field name
-> B.ByteString -- ^ Field value
-> B.ByteString
modelIndex model field value = B.concat [model, ":", field, ":", value]
------------------------------------------------------------------------------
-- | Strip value of punctuation, spaces, convert all to lowercase.
collate :: FieldValue -> FieldValue
collate = E.encodeUtf8 . T.toLower .
(T.filter (\c -> (not (isSpace c || isPunctuation c)))) .
E.decodeUtf8
------------------------------------------------------------------------------
-- | Perform provided action for every indexed field in commit.
--
-- Action is called with index field name and its value in commit.
forIndices :: Commit
-> [FieldIndex]
-> (FieldName -> FieldValue -> Redis ())
-> Redis ()
forIndices commit findices action =
mapM_ (\i -> case (M.lookup i commit) of
Just v -> action i v
Nothing -> return ())
(fst <$> findices)
------------------------------------------------------------------------------
-- | Create reverse indices for new commit.
createIndices :: ModelName
-> InstanceId
-> Commit
-> [FieldIndex]
-> Redis ()
createIndices mname id commit findices =
forIndices commit findices $
\i rawVal ->
let
v = collate rawVal
in
when (v /= "") $
sadd (modelIndex mname i v) [id] >> return ()
------------------------------------------------------------------------------
-- | Remove indices previously created by commit (should contain all
-- indexed fields only).
deleteIndices :: ModelName
-> InstanceId -- ^ Instance id.
-> [(FieldName, FieldValue)] -- ^ Commit with old
-- indexed values (zipped
-- from HMGET).
-> Redis ()
deleteIndices mname id commit =
mapM_ (\(i, v) -> srem (modelIndex mname i v) [id])
commit
------------------------------------------------------------------------------
-- | Get old values of index fields stored under key.
getOldIndices :: B.ByteString -> [FieldName] -> Redis [Maybe B.ByteString]
getOldIndices key findices = do
reply <- hmget key findices
return $ case reply of
Left _ -> []
Right l -> l
------------------------------------------------------------------------------
-- | Extract values of named fields from commit.
onlyFields :: Commit -> [FieldName] -> [Maybe FieldValue]
onlyFields commit names = map (flip M.lookup commit) names
------------------------------------------------------------------------------
-- | Create new instance in Redis and indices for it.
--
-- Bump model id counter and update timeline, return new instance id.
--
-- TODO: Support pubsub from here
create :: ModelName -- ^ Model name
-> Commit -- ^ Key-values of instance data
-> [FieldIndex]
-> Redis (Either Reply InstanceId)
create mname commit findices = do
-- Take id from global:model:id
Right n <- incr $ modelIdKey mname
newId <- return $ (B.pack . show) n
-- Save new instance
_ <- hmset (instanceKey mname newId) (M.toList commit)
_ <- lpush (modelTimeline mname) [newId]
createIndices mname newId commit findices
return (Right newId)
------------------------------------------------------------------------------
-- | Read existing instance from Redis.
read :: ModelName
-> InstanceId
-> Redis (Either Reply Commit)
read mname id = (fmap M.fromList) <$> hgetall key
where
key = instanceKey mname id
------------------------------------------------------------------------------
-- | Modify existing instance in Redis, updating indices.
--
-- TODO: Handle non-existing instance as error here?
update :: ModelName
-> InstanceId
-> Commit
-> [FieldIndex]
-> Redis (Either Reply ())
update mname id commit findices =
let
key = instanceKey mname id
unpacked = M.toList commit
newFields = map fst unpacked
indnames = fst <$> findices
in do
old <- getOldIndices key indnames
hmset key unpacked
deleteIndices mname id $
zip (filter (flip elem newFields) indnames)
(catMaybes old)
createIndices mname id commit findices
return (Right ())
------------------------------------------------------------------------------
-- | Remove existing instance in Redis, cleaning up old indices.
--
-- Does not check if instance exists.
delete :: ModelName
-> InstanceId
-> [FieldIndex]
-> Redis (Either Reply ())
delete mname id findices =
let
key = instanceKey mname id
indnames = fst <$> findices
in do
old <- getOldIndices key indnames
lrem (modelTimeline mname) 1 id >> del [key]
deleteIndices mname id (zip indnames (catMaybes old))
return (Right ())
|
dzhus/snaplet-redson
|
src/Snap/Snaplet/Redson/Snapless/CRUD.hs
|
bsd-3-clause
| 6,854 | 0 | 15 | 1,690 | 1,388 | 739 | 649 | 124 | 2 |
-- |
-- This module contians the main nobs to control the game play.
--
-- All length data is relative to the screen width.
module Lseed.Constants where
groundLevel :: Double
groundLevel = 0.03
budSize :: Double
budSize = 0.01
stipeLength :: Double
stipeLength = 0.05
blossomSize :: Double
blossomSize = 0.03
stipeWidth :: Double
stipeWidth = 0.005
-- | Light and growths interpolation frequency
ticksPerDay :: Integer
ticksPerDay = 9
-- | Plant length growth per Day and Light
--
-- 1 means: Can grow one stipeLength during one day, when catching the sunlight
-- with one branch of (projected) length screenwidth
growthPerDayAndLight :: Double
growthPerDayAndLight = 40.0
-- | Plants up to this size get an boost in growths
smallPlantBoostSize :: Double
smallPlantBoostSize = 0.5
-- | Minimum growths for plants of size less then smallPlantBoostSize
smallPlantBoostLength :: Double
smallPlantBoostLength = 0.2
-- | Cost (in light units) per (sum for all branches (length * distance), to limit the growth of the plants
costPerLength :: Double
costPerLength = 0.0015
-- | Cost (in length growths equivalent) per seed to be grown
seedGrowthCost :: Double
seedGrowthCost = 1.0
-- | Branch translucency. Proportion of light that is let through by a plant
lightFalloff :: Double
lightFalloff = 0.7
-- | Length of one day, in seconds
dayLength :: Double
dayLength = 15
-- | ε
eps = 1e-9
-- | Minimum radial angular distance between two branches
minAngle :: Double
minAngle = pi/20
-- | Derived constants
tickLength = dayLength / fromIntegral ticksPerDay
|
nomeata/L-seed
|
src/Lseed/Constants.hs
|
bsd-3-clause
| 1,567 | 0 | 6 | 272 | 185 | 117 | 68 | 31 | 1 |
module Kata.Monad where
import Data.Rope
data QEnv = QEnv
data DiagnosticState = DiagnosticState
{ stateDiagnosticMapping :: Map ByteString Severity
, warningsAsErrors :: Bool,
, errorsAsFatal :: Bool,
, ignoreAllWarnings :: Bool
, stateErrorHasOccurred :: Bool
, stateFatalErrorHasOccurred :: Bool
, stateWarningsAsErrors :: Bool
, stateErrorsAsFatal :: Bool
, stateSuppressAllDiagnostics :: Bool
}
data QState = QState
{ diagnosticState :: DiagnosticState }
getDiagnosticState :: Q DiagnosticState
getDiagnosticState = gets diagnosticState
putDiagnosticState :: DiagnosticState -> Q ()
putDiagnosticState ds = modify $ \s -> s { diagnosticState = ds }
data Severity
= Ignored
| Warning
| WarningNoError
| Error
| ErrorNoFatal
| Fatal
deriving (Show,Read,Eq,Ord)
data DiagnosticGroup
= InternalGroup
| PreprocessingGroup
| MacroGroup
| ParsingGroup
| TypeCheckingGroup
deriving (Show,Read,Eq,Ord)
failDiagnosticKind :: DiagnosticKind
failDiagnosticKind = DiagnosticKind (pack "monad-fail") Fatal
type DiagnosticTags = [ByteString]
newtype DiagnosticKind = DiagnosticKind DiagnosticTags Severity
-- -Werror -- make all warnings into errors
-- -Werror=switch -- make all warnings tagged 'switch' into errors
-- -Wno-error=switch -- make all warnings tagged 'switch' into non-errors
kindSeverity :: DiagnosticKind -> DiagnosticState -> Severity
kindSeverity (DiagnosticKind tags dflt) state =
ext state (go tags dflt (stateDiagnosticMapping state))
where
go :: DiagnosticTags -> Severity -> Map ByteString Severity -> Severity
go [] dflt _ = dflt
go (t:ts) dflt map = case lookup t map of
Just severity -> severity
Nothing -> go ts dflt map
ext :: DiagnosticState -> Severity -> Severity
ext _ Ignored = Ignored
ext s Warning
| ignoreAllWarnings s = Ignored
| warningsAsErrors s = Error
| otherwise = Warning
ext s WarningNoError
| ignoreAllWarnings s = Ignored
| otherwise = Warning
ext s Error
| errorsAsFatal s = Fatal
| otherwise = Error
ext _ ErrorNoFatal = Error
ext _ Fatal = Fatal
data Note = Note
{ noteTags :: DiagnosticTags
, noteLocation :: Location
, noteMessage :: Rope
}
data Diagnostic = Diagnostic
{ diagnosticKind :: DiagnosticKind
, diagnosticLocation :: Location
, diagnosticMessage :: Rope
, diagnosticNotes :: [(DiagnosticTags,Location, Rope)]
}
setWarningsAsErrors :: Bool -> Q ()
setWarningsAsErrors =
modify (\s -> s { warningsAsErrors ::
addNote :: Tags -> Rope -> Diagnostic -> Diagnostic
addNote ::
data Diagnostics = Diagnostics { getDiagnostics :: Seq Diagnostic }
deriving (Monoid)
data QError = QError Source Int
newtype Q a = Q { runQ :: RWST QEnv Diagnostics QState (ErrorT Diagnostic IO) a }
deriving
( Functor
, Applicative
, Alternative
, Monad, MonadPlus
, MonadReader QEnv
, MonadState QState
, MonadWriter QLog
, MonadError QError
)
note :: Diagnostic -> Q ()
note = tell
warn :: Diagnostic -> Q ()
warn = tell
error :: Diagnostic -> Q a
error = throw
fatal :: Diagnostic -> Q a
fatal = throw
|
ekmett/kata
|
Kata/Monad.hs
|
bsd-3-clause
| 3,413 | 20 | 11 | 927 | 880 | 475 | 405 | -1 | -1 |
module Language.RTL.Code
( verilog
) where
import Data.List
import Text.Printf
import Language.RTL.Core
verilog :: Name -> Module -> IO ()
verilog name m = writeFile (name ++ ".v") $ unlines
[ "module " ++ name
, "( input reset"
, ", input clock"
, unlines [ printf ", input %-5s %s" (widthDecl w) name | (name, w) <- inputs m ] ++ unlines [ printf ", output %-5s %s" (widthDecl w) name | (name, a) <- outputs m, let w = width a ] ++ ");"
, ""
, unlines [ printf "reg %-5s %s;" (widthDecl w) (pathName path) | (path, w) <- regs m ]
, unlines [ printf "wire %-5s %s;" (widthDecl w) (pathName path) | (path, w) <- wires m ]
-- XXX
, unlines [ printf "assign %s %s;" name (bv a) | (name, a) <- outputs m ]
, "endmodule"
]
pathName :: Path -> String
pathName p = "\\" ++ intercalate "." p
widthDecl :: Int -> String
widthDecl w = if w == 1 then "" else "[" ++ show (w - 1) ++ ":0]"
bv :: BV -> String
bv a = case a of
Input name _ -> name
Reg path _ -> pathName path
Wire path _ -> pathName path
Const w a -> printf "%d'd%d" w a
Concat a b
| width a == 0 -> bv b
| width b == 0 -> bv a
| otherwise -> "{" ++ bv a ++ ", " ++ bv b ++ "}"
Select a msb lsb
| msb == lsb -> msb - lsb + 1
Add a _ -> width a
Sub a _ -> width a
Mul a _ -> width a
Not a -> width a
And a _ -> width a
Or a _ -> width a
Xor a _ -> width a
Eq _ _ -> 1
Lt _ _ -> 1
Gt _ _ -> 1
Le _ _ -> 1
Ge _ _ -> 1
Mux _ a _ -> width a
|
tomahawkins/rtl
|
Language/RTL/Code.hs
|
bsd-3-clause
| 1,531 | 0 | 16 | 480 | 744 | 361 | 383 | 45 | 19 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
module ExampleDataSource (
-- * initialise the state
initGlobalState,
-- * requests for this data source
Id(..), ExampleReq(..),
countAardvarks,
listWombats,
) where
import Haxl.Prelude
import Prelude ()
import Haxl.Core
import Data.Typeable
import Data.Hashable
import Control.Concurrent
import System.IO
-- Here is an example minimal data source. Our data source will have
-- two requests:
--
-- countAardvarks :: String -> Haxl Int
-- listWombats :: Id -> Haxl [Id]
--
-- First, the data source defines a request type, with one constructor
-- for each request:
newtype Id = Id Int
deriving (Eq, Ord, Enum, Num, Integral, Real, Hashable, Typeable)
instance Show Id where
show (Id i) = show i
data ExampleReq a where
CountAardvarks :: String -> ExampleReq Int
ListWombats :: Id -> ExampleReq [Id]
deriving Typeable -- requests must be Typeable
-- The request type (ExampleReq) is parameterized by the result type of
-- each request. Each request might have a different result, so we use a
-- GADT - a data type in which each constructor may have different type
-- parameters. Here CountAardvarks is a request that takes a String
-- argument and its result is Int, whereas ListWombats takes an Id
-- argument and returns a [Id].
-- The request type needs instances for 'Eq1' and 'Hashable1'. These
-- are like 'Eq' and 'Hashable', but for types with one parameter
-- where the parameter is irrelevant for hashing and equality.
-- These two instances are used to support caching of requests.
-- We need Eq, but we have to derive it with a standalone declaration
-- like this, because plain deriving doesn't work with GADTs.
deriving instance Eq (ExampleReq a)
deriving instance Show (ExampleReq a)
instance Show1 ExampleReq where show1 = show
instance Hashable (ExampleReq a) where
hashWithSalt s (CountAardvarks a) = hashWithSalt s (0::Int,a)
hashWithSalt s (ListWombats a) = hashWithSalt s (1::Int,a)
instance StateKey ExampleReq where
data State ExampleReq = ExampleState {
-- in here you can put any state that the
-- data source needs to maintain throughout the
-- run.
}
-- Next we need to define an instance of DataSourceName:
instance DataSourceName ExampleReq where
dataSourceName _ = "ExampleDataSource"
-- Next we need to define an instance of DataSource:
instance DataSource u ExampleReq where
-- I'll define exampleFetch below
fetch = exampleFetch
-- Every data source should define a function 'initGlobalState' that
-- initialises the state for that data source. The arguments to this
-- function might vary depending on the data source - we might need to
-- pass in resources from the environment, or parameters to set up the
-- data source.
initGlobalState :: IO (State ExampleReq)
initGlobalState = do
-- initialize the state here.
return ExampleState { }
-- The most important bit: fetching the data. The fetching function
-- takes a list of BlockedFetch, which is defined as
--
-- data BlockedFetch r
-- = forall a . BlockedFetch (r a) (ResultVar a)
--
-- That is, each BlockedFetch is a pair of
--
-- - the request to fetch (with result type a)
-- - a ResultVar to store either the result or an error
--
-- The job of fetch is to fetch the data and fill in all the ResultVars.
--
exampleFetch :: State ExampleReq -- current state
-> Flags -- tracing verbosity, etc.
-> u -- user environment
-> [BlockedFetch ExampleReq] -- requests to fetch
-> PerformFetch -- tells the framework how to fetch
exampleFetch _state _flags _user bfs = SyncFetch $ mapM_ fetch1 bfs
-- There are two ways a data source can fetch data: synchronously or
-- asynchronously. See the type 'PerformFetch' in "Haxl.Core.Types" for
-- details.
fetch1 :: BlockedFetch ExampleReq -> IO ()
fetch1 (BlockedFetch (CountAardvarks "BANG") _) =
error "BANG" -- data sources should not throw exceptions, but in
-- the event that one does, the framework will
-- propagate the exception to the call site of
-- dataFetch.
fetch1 (BlockedFetch (CountAardvarks "BANG2") m) = do
putSuccess m 1
error "BANG2" -- the exception is propagated even if we have already
-- put the result with putSuccess
fetch1 (BlockedFetch (CountAardvarks "BANG3") _) = do
hPutStr stderr "BANG3"
killThread =<< myThreadId -- an asynchronous exception
fetch1 (BlockedFetch (CountAardvarks str) m) =
putSuccess m (length (filter (== 'a') str))
fetch1 (BlockedFetch (ListWombats a) r) =
if a > 999999
then putFailure r $ FetchError "too large"
else putSuccess r $ take (fromIntegral a) [1..]
-- Normally a data source will provide some convenient wrappers for
-- its requests:
countAardvarks :: String -> GenHaxl () Int
countAardvarks str = dataFetch (CountAardvarks str)
listWombats :: Id -> GenHaxl () [Id]
listWombats id = dataFetch (ListWombats id)
|
xich/Haxl-1
|
tests/ExampleDataSource.hs
|
bsd-3-clause
| 5,357 | 1 | 10 | 1,180 | 784 | 441 | 343 | 68 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Rel.Github where
import Data.ByteString.Lazy (ByteString)
import qualified Data.Text as Text
import Data.Aeson (FromJSON(parseJSON), eitherDecode, withObject, withText, (.:))
import qualified Rel.Git as Git
import Monad.Result
-- Github monad
data Github a = Github { runGithub :: Config -> IO (Result a) }
data Config = Config {}
instance Functor Github where
fmap f ma = Github $ \c -> fmap f `fmap` runGithub ma c
instance Applicative Github where
pure x = Github $ \_ -> return $ pure x
f <*> g = Github $ \c -> runGithub f c `mapAp` runGithub g c
instance Monad Github where
ma >>= f = Github $ \c -> runGithub ma c >>= flatten . fmap (flip runGithub c . f)
return x = Github $ \_ -> return $ pure x
instance ResultantMonad Github where
point x = Github $ \_ -> x
mapResult f ma = Github $ \c -> f `fmap` runGithub ma c
-- Webhook data types
data PushEvent = PushEvent
{ ref :: Git.Ref
, before :: String
, after :: String
, repository :: Repository
}
data Repository = Repository
{ name :: String
, fullName :: String
, url :: String
, cloneUrl :: String
, gitUrl :: String
, sshUrl :: String
}
instance FromJSON PushEvent where
parseJSON = withObject "PushEvent" $ \x ->
PushEvent <$> x .: "ref"
<*> x .: "before"
<*> x .: "after"
<*> x .: "repository"
instance FromJSON Repository where
parseJSON = withObject "Repository" $ \x ->
Repository <$> x .: "name"
<*> x .: "full_name"
<*> x .: "url"
<*> x .: "clone_url"
<*> x .: "git_url"
<*> x .: "ssh_url"
instance FromJSON Git.Ref where
parseJSON = withText "ref" (return . Git.parseRef . Text.unpack)
defaultConfig :: Config
defaultConfig = Config {}
decodeRequest :: ResultR Github m => ByteString -> m PushEvent
decodeRequest = fromEither . eitherDecode
|
shmookey/pure
|
src/Rel/Github.hs
|
bsd-3-clause
| 2,120 | 58 | 19 | 553 | 647 | 359 | 288 | 56 | 1 |
module Lets.StoreLens (
Store(..)
, setS
, getS
, mapS
, duplicateS
, extendS
, extractS
, Lens(..)
, getsetLaw
, setgetLaw
, setsetLaw
, get
, set
, modify
, (%~)
, fmodify
, (|=)
, fstL
, sndL
, mapL
, setL
, compose
, (|.)
, identity
, product
, (***)
, choice
, (|||)
, cityL
, countryL
, streetL
, suburbL
, localityL
, ageL
, nameL
, addressL
, getSuburb
, setStreet
, getAgeAndCountry
, setCityAndLocality
, getSuburbOrCity
, setStreetOrState
, modifyCityUppercase
) where
import Control.Applicative(Applicative((<*>)))
import Data.Char(toUpper)
import Data.Functor((<$>))
import Data.Map(Map)
import qualified Data.Map as Map(insert, delete, lookup)
import Data.Set(Set)
import qualified Data.Set as Set(insert, delete, member)
import Lets.Data(Store(Store), Person(Person), Locality(Locality), Address(Address), bool)
import Prelude hiding (product)
-- $setup
-- >>> import qualified Data.Map as Map(fromList)
-- >>> import qualified Data.Set as Set(fromList)
-- >>> import Data.Char(ord)
-- >>> import Lets.Data
setS ::
Store s a
-> s
-> a
setS (Store s _) =
s
getS ::
Store s a
-> s
getS (Store _ g) =
g
mapS ::
(a -> b)
-> Store s a
-> Store s b
mapS =
error "todo: mapS"
duplicateS ::
Store s a
-> Store s (Store s a)
duplicateS =
error "todo: duplicateS"
extendS ::
(Store s a -> b)
-> Store s a
-> Store s b
extendS =
error "todo: extendS"
extractS ::
Store s a
-> a
extractS =
error "todo: extractS"
----
data Lens a b =
Lens
(a -> Store b a)
-- |
--
-- >>> get fstL (0 :: Int, "abc")
-- 0
--
-- >>> get sndL ("abc", 0 :: Int)
-- 0
--
-- prop> let types = (x :: Int, y :: String) in get fstL (x, y) == x
--
-- prop> let types = (x :: Int, y :: String) in get sndL (x, y) == y
get ::
Lens a b
-> a
-> b
get (Lens r) =
getS . r
-- |
--
-- >>> set fstL (0 :: Int, "abc") 1
-- (1,"abc")
--
-- >>> set sndL ("abc", 0 :: Int) 1
-- ("abc",1)
--
-- prop> let types = (x :: Int, y :: String) in set fstL (x, y) z == (z, y)
--
-- prop> let types = (x :: Int, y :: String) in set sndL (x, y) z == (x, z)
set ::
Lens a b
-> a
-> b
-> a
set (Lens r) =
setS . r
-- | The get/set law of lenses. This function should always return @True@.
getsetLaw ::
Eq a =>
Lens a b
-> a
-> Bool
getsetLaw l =
\a -> set l a (get l a) == a
-- | The set/get law of lenses. This function should always return @True@.
setgetLaw ::
Eq b =>
Lens a b
-> a
-> b
-> Bool
setgetLaw l a b =
get l (set l a b) == b
-- | The set/set law of lenses. This function should always return @True@.
setsetLaw ::
Eq a =>
Lens a b
-> a
-> b
-> b
-> Bool
setsetLaw l a b1 b2 =
set l (set l a b1) b2 == set l a b2
----
-- |
--
-- >>> modify fstL (+1) (0 :: Int, "abc")
-- (1,"abc")
--
-- >>> modify sndL (+1) ("abc", 0 :: Int)
-- ("abc",1)
--
-- prop> let types = (x :: Int, y :: String) in modify fstL id (x, y) == (x, y)
--
-- prop> let types = (x :: Int, y :: String) in modify sndL id (x, y) == (x, y)
modify ::
Lens a b
-> (b -> b)
-> a
-> a
modify =
error "todo: modify"
-- | An alias for @modify@.
(%~) ::
Lens a b
-> (b -> b)
-> a
-> a
(%~) =
modify
infixr 4 %~
-- |
--
-- >>> fstL .~ 1 $ (0 :: Int, "abc")
-- (1,"abc")
--
-- >>> sndL .~ 1 $ ("abc", 0 :: Int)
-- ("abc",1)
--
-- prop> let types = (x :: Int, y :: String) in set fstL (x, y) z == (fstL .~ z $ (x, y))
--
-- prop> let types = (x :: Int, y :: String) in set sndL (x, y) z == (sndL .~ z $ (x, y))
(.~) ::
Lens a b
-> b
-> a
-> a
(.~) =
error "todo: (.~)"
infixl 5 .~
-- |
--
-- >>> fmodify fstL (+) (5 :: Int, "abc") 8
-- (13,"abc")
--
-- >>> fmodify fstL (\n -> bool Nothing (Just (n * 2)) (even n)) (10, "abc")
-- Just (20,"abc")
--
-- >>> fmodify fstL (\n -> bool Nothing (Just (n * 2)) (even n)) (11, "abc")
-- Nothing
fmodify ::
Functor f =>
Lens a b
-> (b -> f b)
-> a
-> f a
fmodify =
error "todo: fmodify"
-- |
--
-- >>> fstL |= Just 3 $ (7, "abc")
-- Just (3,"abc")
--
-- >>> (fstL |= (+1) $ (3, "abc")) 17
-- (18,"abc")
(|=) ::
Functor f =>
Lens a b
-> f b
-> a
-> f a
(|=) =
error "todo: (|=)"
infixl 5 |=
-- |
--
-- >>> modify fstL (*10) (3, "abc")
-- (30,"abc")
--
-- prop> let types = (x :: Int, y :: String) in getsetLaw fstL (x, y)
--
-- prop> let types = (x :: Int, y :: String) in setgetLaw fstL (x, y) z
--
-- prop> let types = (x :: Int, y :: String) in setsetLaw fstL (x, y) z
fstL ::
Lens (x, y) x
fstL =
error "todo: fstL"
-- |
--
-- >>> modify sndL (++ "def") (13, "abc")
-- (13,"abcdef")
--
-- prop> let types = (x :: Int, y :: String) in getsetLaw sndL (x, y)
--
-- prop> let types = (x :: Int, y :: String) in setgetLaw sndL (x, y) z
--
-- prop> let types = (x :: Int, y :: String) in setsetLaw sndL (x, y) z
sndL ::
Lens (x, y) y
sndL =
error "todo: sndL"
-- |
--
-- >>> get (mapL 3) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d']))
-- Just 'c'
--
-- >>> get (mapL 33) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d']))
-- Nothing
--
-- >>> set (mapL 3) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) (Just 'X')
-- fromList [(1,'a'),(2,'b'),(3,'X'),(4,'d')]
--
-- >>> set (mapL 33) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) (Just 'X')
-- fromList [(1,'a'),(2,'b'),(3,'c'),(4,'d'),(33,'X')]
--
-- >>> set (mapL 3) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) Nothing
-- fromList [(1,'a'),(2,'b'),(4,'d')]
--
-- >>> set (mapL 33) (Map.fromList (map (\c -> (ord c - 96, c)) ['a'..'d'])) Nothing
-- fromList [(1,'a'),(2,'b'),(3,'c'),(4,'d')]
mapL ::
Ord k =>
k
-> Lens (Map k v) (Maybe v)
mapL =
error "todo: mapL"
-- |
--
-- >>> get (setL 3) (Set.fromList [1..5])
-- True
--
-- >>> get (setL 33) (Set.fromList [1..5])
-- False
--
-- >>> set (setL 3) (Set.fromList [1..5]) True
-- fromList [1,2,3,4,5]
--
-- >>> set (setL 3) (Set.fromList [1..5]) False
-- fromList [1,2,4,5]
--
-- >>> set (setL 33) (Set.fromList [1..5]) True
-- fromList [1,2,3,4,5,33]
--
-- >>> set (setL 33) (Set.fromList [1..5]) False
-- fromList [1,2,3,4,5]
setL ::
Ord k =>
k
-> Lens (Set k) Bool
setL =
error "todo: setL"
-- |
--
-- >>> get (compose fstL sndL) ("abc", (7, "def"))
-- 7
--
-- >>> set (compose fstL sndL) ("abc", (7, "def")) 8
-- ("abc",(8,"def"))
compose ::
Lens b c
-> Lens a b
-> Lens a c
compose =
error "todo: compose"
-- | An alias for @compose@.
(|.) ::
Lens b c
-> Lens a b
-> Lens a c
(|.) =
compose
infixr 9 |.
-- |
--
-- >>> get identity 3
-- 3
--
-- >>> set identity 3 4
-- 4
identity ::
Lens a a
identity =
error "todo: identity"
-- |
--
-- >>> get (product fstL sndL) (("abc", 3), (4, "def"))
-- ("abc","def")
--
-- >>> set (product fstL sndL) (("abc", 3), (4, "def")) ("ghi", "jkl")
-- (("ghi",3),(4,"jkl"))
product ::
Lens a b
-> Lens c d
-> Lens (a, c) (b, d)
product =
error "todo: product"
-- | An alias for @product@.
(***) ::
Lens a b
-> Lens c d
-> Lens (a, c) (b, d)
(***) =
product
infixr 3 ***
-- |
--
-- >>> get (choice fstL sndL) (Left ("abc", 7))
-- "abc"
--
-- >>> get (choice fstL sndL) (Right ("abc", 7))
-- 7
--
-- >>> set (choice fstL sndL) (Left ("abc", 7)) "def"
-- Left ("def",7)
--
-- >>> set (choice fstL sndL) (Right ("abc", 7)) 8
-- Right ("abc",8)
choice ::
Lens a x
-> Lens b x
-> Lens (Either a b) x
choice =
error "todo: choice"
-- | An alias for @choice@.
(|||) ::
Lens a x
-> Lens b x
-> Lens (Either a b) x
(|||) =
choice
infixr 2 |||
----
cityL ::
Lens Locality String
cityL =
Lens
(\(Locality c t y) ->
Store (\c' -> Locality c' t y) c)
stateL ::
Lens Locality String
stateL =
Lens
(\(Locality c t y) ->
Store (\t' -> Locality c t' y) t)
countryL ::
Lens Locality String
countryL =
Lens
(\(Locality c t y) ->
Store (\y' -> Locality c t y') y)
streetL ::
Lens Address String
streetL =
Lens
(\(Address t s l) ->
Store (\t' -> Address t' s l) t)
suburbL ::
Lens Address String
suburbL =
Lens
(\(Address t s l) ->
Store (\s' -> Address t s' l) s)
localityL ::
Lens Address Locality
localityL =
Lens
(\(Address t s l) ->
Store (\l' -> Address t s l') l)
ageL ::
Lens Person Int
ageL =
Lens
(\(Person a n d) ->
Store (\a' -> Person a' n d) a)
nameL ::
Lens Person String
nameL =
Lens
(\(Person a n d) ->
Store (\n' -> Person a n' d) n)
addressL ::
Lens Person Address
addressL =
Lens
(\(Person a n d) ->
Store (\d' -> Person a n d') d)
-- |
--
-- >>> get (suburbL |. addressL) fred
-- "Fredville"
--
-- >>> get (suburbL |. addressL) mary
-- "Maryland"
getSuburb ::
Person
-> String
getSuburb =
error "todo: getSuburb"
-- |
--
-- >>> setStreet fred "Some Other St"
-- Person 24 "Fred" (Address "Some Other St" "Fredville" (Locality "Fredmania" "New South Fred" "Fredalia"))
--
-- >>> setStreet mary "Some Other St"
-- Person 28 "Mary" (Address "Some Other St" "Maryland" (Locality "Mary Mary" "Western Mary" "Maristan"))
setStreet ::
Person
-> String
-> Person
setStreet =
error "todo: setStreet"
-- |
--
-- >>> getAgeAndCountry (fred, maryLocality)
-- (24,"Maristan")
--
-- >>> getAgeAndCountry (mary, fredLocality)
-- (28,"Fredalia")
getAgeAndCountry ::
(Person, Locality)
-> (Int, String)
getAgeAndCountry =
error "todo: getAgeAndCountry"
-- |
--
-- >>> setCityAndLocality (fred, maryAddress) ("Some Other City", fredLocality)
-- (Person 24 "Fred" (Address "15 Fred St" "Fredville" (Locality "Some Other City" "New South Fred" "Fredalia")),Address "83 Mary Ln" "Maryland" (Locality "Fredmania" "New South Fred" "Fredalia"))
--
-- >>> setCityAndLocality (mary, fredAddress) ("Some Other City", maryLocality)
-- (Person 28 "Mary" (Address "83 Mary Ln" "Maryland" (Locality "Some Other City" "Western Mary" "Maristan")),Address "15 Fred St" "Fredville" (Locality "Mary Mary" "Western Mary" "Maristan"))
setCityAndLocality ::
(Person, Address) -> (String, Locality) -> (Person, Address)
setCityAndLocality =
error "todo: setCityAndLocality"
-- |
--
-- >>> getSuburbOrCity (Left maryAddress)
-- "Maryland"
--
-- >>> getSuburbOrCity (Right fredLocality)
-- "Fredmania"
getSuburbOrCity ::
Either Address Locality
-> String
getSuburbOrCity =
error "todo: getSuburbOrCity"
-- |
--
-- >>> setStreetOrState (Right maryLocality) "Some Other State"
-- Right (Locality "Mary Mary" "Some Other State" "Maristan")
--
-- >>> setStreetOrState (Left fred) "Some Other St"
-- Left (Person 24 "Fred" (Address "Some Other St" "Fredville" (Locality "Fredmania" "New South Fred" "Fredalia")))
setStreetOrState ::
Either Person Locality
-> String
-> Either Person Locality
setStreetOrState =
error "todo: setStreetOrState"
-- |
--
-- >>> modifyCityUppercase fred
-- Person 24 "Fred" (Address "15 Fred St" "Fredville" (Locality "FREDMANIA" "New South Fred" "Fredalia"))
--
-- >>> modifyCityUppercase mary
-- Person 28 "Mary" (Address "83 Mary Ln" "Maryland" (Locality "MARY MARY" "Western Mary" "Maristan"))
modifyCityUppercase ::
Person
-> Person
modifyCityUppercase =
error "todo: modifyCityUppercase"
|
newmana/lets-lens
|
src/Lets/StoreLens.hs
|
bsd-3-clause
| 11,080 | 0 | 11 | 2,548 | 2,327 | 1,353 | 974 | 319 | 1 |
module Surreals
( Surreal(Surreal) ) where
data Surreal = Surreal [Surreal] [Surreal] deriving Show
leftSet (Surreal ls _) = ls
rightSet (Surreal _ rs) = rs
-- x >= y iff no Xᴿ <= y and x <= no yᴸ
x `gte` y = not $ or $ (map (\xr -> xr `lte` y) (rightSet x)) ++ (map (\yl -> x `lte` yl) (leftSet y))
x `lte` y = y `gte` x
instance Eq Surreal where
x == y = (x `gte` y) && (x `lte` y)
instance Ord Surreal where
(<=) = lte
instance Num Surreal where
x + y = Surreal left right
where
left = map (+y) (leftSet x) ++ map (+x) (leftSet y)
right = map (+y) (rightSet x) ++ map (+x) (rightSet y)
x * y = Surreal (left1++left2) (right1++right2)
where
left1 = [ xl*y + x*yl - xl*yl | xl <- leftSet x, yl <- leftSet y ]
left2 = [ xr*y + x*yr - xr*yr | xr <- rightSet x, yr <- rightSet y ]
right1 = [ xl*y + x*yr - xl*yr | xl <- leftSet x, yr <- rightSet y ]
right2 = [ xr*y + x*yl - xr*yl | xr <- rightSet x, yl <- leftSet y ]
negate (Surreal ls rs) = Surreal (map negate rs) (map negate ls)
abs x = x * signum x
signum x
| x == zero = zero
| x > zero = Surreal [zero] []
| otherwise = Surreal [] [zero]
where zero = Surreal [] []
fromInteger n
| n == 0 = Surreal [] []
| n > 0 = Surreal [fromInteger (n-1)] []
| otherwise = Surreal [] [fromInteger (n+1)]
|
fonse/surreal-numbers
|
src/Surreals.hs
|
bsd-3-clause
| 1,365 | 0 | 13 | 396 | 775 | 399 | 376 | 33 | 1 |
{-# LANGUAGE DataKinds #-}
module LDrive.Calibration where
import Ivory.Language
import Ivory.Stdlib
import Ivory.Tower
import Ivory.BSP.STM32.ClockConfig
import LDrive.Platforms (currentMeasPeriod, currentMeasHz)
import LDrive.Types
import LDrive.Calibration.Inductance
import LDrive.Calibration.Encoder
import LDrive.Calibration.Resistance
import LDrive.Calibration.Lock
import LDrive.Ivory.Types.Calibration
import LDrive.Ivory.Types.CalI
import LDrive.Ivory.Types.CalEnc
import LDrive.Ivory.Types.CalR
import LDrive.Ivory.Types.AdcEncSample
calibrationTower :: ClockConfig
-> PWMInput
-> Tower e (
ChanInput ('Struct "adc_enc_sample")
, ChanOutput ('Struct "calibration"))
calibrationTower cc timingsIn = do
adcEncChan <- channel
calResult <- channel
(calIn, calOut) <- channel
let measPeriod = currentMeasPeriod cc
let measHz = currentMeasHz cc
(phaseRIn, phaseRDone) <- phaseResistanceTower measPeriod calOut timingsIn
(phaseIIn, phaseIDone) <- phaseInductanceTower measPeriod calOut timingsIn
(lockIn, lockDone) <- phaseLockTower measHz calOut timingsIn
(encOffIn, encOffDone) <- encoderOffsetTower measHz calOut timingsIn
monitor "calibration_controller" $ do
calib <- state "calibState"
calibPhaseResistance <- stateInit "calibPhaseResistance" $ ival false
calibPhaseInductance <- stateInit "calibPhaseInductance" $ ival false
calibPhaseLock <- stateInit "calibPhaseLock" $ ival false
calibEncoder <- stateInit "calibEncoder" $ ival false
adcEnc <- state "adcEnc"
handler systemInit "init" $ do
calUpdate <- emitter calIn 1
callback $ const $ do
store (calib ~> testCurrent) 10.0
store (calib ~> calR ~> maxVoltage) 1.0
store (calib ~> calR ~> integrator) 10.0
store (calib ~> calR ~> seconds) 3.0
store (calib ~> calI ~> testVoltageLow) (-1.0)
store (calib ~> calI ~> testVoltageHigh) 1.0
store (calib ~> calI ~> cycles) 5000
store (calib ~> calEnc ~> steps) 1024
store (calib ~> calEnc ~> scanRange) (4 * pi)
emit calUpdate $ constRef calib
store calibPhaseResistance true
handler phaseRDone "phaseRDone" $ do
calUpdate <- emitter calIn 1
callback $ \x -> do
refCopy calib x
store calibPhaseResistance false
store calibPhaseInductance true
tc <- calib ~>* testCurrent
r <- calib ~> calR ~>* resistance
store (calib ~> voltageMag) $ tc * r
emit calUpdate $ constRef calib
handler phaseIDone "phaseIDone" $ do
calUpdate <- emitter calIn 1
callback $ \x -> do
refCopy calib x
emit calUpdate $ constRef calib
store calibPhaseInductance false
store calibPhaseLock true
handler lockDone "phaseLockDone" $ do
calUpdate <- emitter calIn 1
callback $ \x -> do
refCopy calib x
emit calUpdate $ constRef calib
store calibPhaseLock false
store calibEncoder true
handler encOffDone "encOffDone" $ do
calUpdate <- emitter calIn 1
calDone <- emitter (fst calResult) 1
callback $ \x -> do
refCopy calib x
emit calUpdate $ constRef calib
store calibEncoder false
emit calDone $ constRef calib
handler (snd adcEncChan) "adc_chan" $ do
phaseR <- emitter phaseRIn 1
phaseI <- emitter phaseIIn 1
lock <- emitter lockIn 1
encOff <- emitter encOffIn 1
callback $ \ae -> do
refCopy adcEnc ae
isPhaseR <- deref calibPhaseResistance
when isPhaseR $ do
emit phaseR $ constRef (adcEnc ~> adc_sample)
isPhaseI <- deref calibPhaseInductance
when isPhaseI $ do
emit phaseI $ constRef (adcEnc ~> adc_sample)
isPhaseLock <- deref calibPhaseLock
when isPhaseLock $ do
emit lock $ constRef (adcEnc ~> adc_sample)
isCalibEncoder <- deref calibEncoder
when isCalibEncoder $ do
emit encOff $ ae
return (fst adcEncChan, snd calResult)
|
sorki/odrive
|
src/LDrive/Calibration.hs
|
bsd-3-clause
| 4,134 | 0 | 23 | 1,101 | 1,242 | 571 | 671 | 105 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.UK.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Ordinal.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = UK}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (OrdinalData 1)
[ "перший"
, "перша"
, "перше"
, "1а"
, "1-а"
, "1ий"
, "1-ий"
, "1е"
, "1-е"
]
, examples (OrdinalData 4)
[ "четвертий"
, "четверта"
, "четверте"
, "4ий"
, "4а"
, "4е"
, "4-ий"
, "4-а"
, "4-е"
]
, examples (OrdinalData 15)
[ "п‘ятнадцятий"
, "15й"
, "15-й"
]
, examples (OrdinalData 21)
[ "21й"
, "21-й"
, "двадцять перший"
]
, examples (OrdinalData 31)
[ "31ий"
, "31-ий"
, "тридцять перший"
]
, examples (OrdinalData 48)
[ "48е"
, "48-е"
, "сорок восьме"
]
, examples (OrdinalData 99)
[ "99ий"
, "99-й"
, "дев‘яносто дев‘ятий"
]
]
|
rfranek/duckling
|
Duckling/Ordinal/UK/Corpus.hs
|
bsd-3-clause
| 1,885 | 0 | 9 | 742 | 287 | 174 | 113 | 53 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Volume.FR.Rules
( rules ) where
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Types
import Duckling.Volume.Helpers
import qualified Duckling.Volume.Types as TVolume
ruleLatentVolMl :: Rule
ruleLatentVolMl = Rule
{ name = "<latent vol> ml"
, pattern =
[ dimension Volume
, regex "m(l|illilitres?)"
]
, prod = \tokens -> case tokens of
(Token Volume vd:_) ->
Just . Token Volume $ withUnit TVolume.Millilitre vd
_ -> Nothing
}
ruleVolHectoliters :: Rule
ruleVolHectoliters = Rule
{ name = "<vol> hectoliters"
, pattern =
[ dimension Volume
, regex "hectolitres?"
]
, prod = \tokens -> case tokens of
(Token Volume vd:_) ->
Just . Token Volume $ withUnit TVolume.Hectolitre vd
_ -> Nothing
}
ruleVolLiters :: Rule
ruleVolLiters = Rule
{ name = "<vol> liters"
, pattern =
[ dimension Volume
, regex "l(itres?)?"
]
, prod = \tokens -> case tokens of
(Token Volume vd:_) ->
Just . Token Volume $ withUnit TVolume.Litre vd
_ -> Nothing
}
ruleHalfLiter :: Rule
ruleHalfLiter = Rule
{ name = "half liter"
, pattern =
[ regex "demi( |-)?litre"
]
, prod = \_ -> Just . Token Volume . withUnit TVolume.Litre $ volume 0.5
}
ruleLatentVolGallon :: Rule
ruleLatentVolGallon = Rule
{ name = "<latent vol> gallon"
, pattern =
[ dimension Volume
, regex "gal(l?ons?)?"
]
, prod = \tokens -> case tokens of
(Token Volume vd:_) ->
Just . Token Volume $ withUnit TVolume.Gallon vd
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleHalfLiter
, ruleLatentVolGallon
, ruleLatentVolMl
, ruleVolHectoliters
, ruleVolLiters
]
|
rfranek/duckling
|
Duckling/Volume/FR/Rules.hs
|
bsd-3-clause
| 2,107 | 0 | 13 | 516 | 519 | 293 | 226 | 63 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Trans.List
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- The ListT monad transformer, adding backtracking to a given monad,
-- which must be commutative.
-----------------------------------------------------------------------------
module Control.Monad.Trans.List (
-- * The ListT monad transformer
ListT(..),
mapListT,
-- * Lifting other operations
liftCallCC,
liftCatch,
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Applicative
import Control.Monad
-- | Parameterizable list monad, with an inner monad.
--
-- /Note:/ this does not yield a monad unless the argument monad is commutative.
newtype ListT m a = ListT { runListT :: m [a] }
-- | Map between 'ListT' computations.
--
-- * @'runListT' ('mapListT' f m) = f ('runListT' m@)
mapListT :: (m [a] -> n [b]) -> ListT m a -> ListT n b
mapListT f m = ListT $ f (runListT m)
instance (Functor m) => Functor (ListT m) where
fmap f = mapListT $ fmap $ map f
instance (Applicative m) => Applicative (ListT m) where
pure a = ListT $ pure [a]
f <*> v = ListT $ (<*>) <$> runListT f <*> runListT v
instance (Applicative m) => Alternative (ListT m) where
empty = ListT $ pure []
m <|> n = ListT $ (++) <$> runListT m <*> runListT n
instance (Monad m) => Monad (ListT m) where
return a = ListT $ return [a]
m >>= k = ListT $ do
a <- runListT m
b <- mapM (runListT . k) a
return (concat b)
fail _ = ListT $ return []
instance (Monad m) => MonadPlus (ListT m) where
mzero = ListT $ return []
m `mplus` n = ListT $ do
a <- runListT m
b <- runListT n
return (a ++ b)
instance MonadTrans ListT where
lift m = ListT $ do
a <- m
return [a]
instance (MonadIO m) => MonadIO (ListT m) where
liftIO = lift . liftIO
-- | Lift a @callCC@ operation to the new monad.
liftCallCC :: ((([a] -> m [b]) -> m [a]) -> m [a]) ->
((a -> ListT m b) -> ListT m a) -> ListT m a
liftCallCC callCC f = ListT $
callCC $ \c ->
runListT (f (\a -> ListT $ c [a]))
-- | Lift a @catchError@ operation to the new monad.
liftCatch :: (m [a] -> (e -> m [a]) -> m [a]) ->
ListT m a -> (e -> ListT m a) -> ListT m a
liftCatch catchError m h = ListT $ runListT m
`catchError` \e -> runListT (h e)
|
ekmett/transformers
|
Control/Monad/Trans/List.hs
|
bsd-3-clause
| 2,666 | 0 | 14 | 666 | 860 | 454 | 406 | 48 | 1 |
module Main where
import Funpaala
main :: IO ()
main = funpaala
|
YoshikuniJujo/funpaala
|
app/Main.hs
|
bsd-3-clause
| 66 | 0 | 6 | 14 | 22 | 13 | 9 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Language.Hakaru.Util.Visual where
import System.IO
import Control.Monad
import Data.Aeson
import Data.List
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Char8 as BS
plot :: Show a => [a] -> String -> IO ()
plot samples filename = do
h <- openFile filename WriteMode
hPrint h samples
hClose h
batchPrint :: Show a => Int -> [a] -> IO ()
batchPrint n l = do
let batch = take n l
print batch
when (length batch == n) $ batchPrint n (drop n l)
viz :: ToJSON a => Int -> [String] -> [[a]] -> IO ()
viz n name samples = viz' n 50 0 name samples
viz' :: ToJSON a => Int -> Int -> Int -> [String] -> [[a]] -> IO ()
viz' n c cur name samples = do
putStrLn batch
when (c+cur < n) $
viz' n c (cur+c) name (drop c samples)
where
total = "total_samples" .= n
current_sample = "current_sample" .= cur
chunk = object (zipWith (\ name s -> T.pack name .= s)
name
(transpose $ take c samples))
batch = B.unpack $ encode
(object ["rvars" .= chunk,
total,
current_sample])
|
zaxtax/hakaru-old
|
Language/Hakaru/Util/Visual.hs
|
bsd-3-clause
| 1,222 | 0 | 14 | 353 | 489 | 253 | 236 | 35 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
module Data.Foscam.File.ImageId(
ImageId(..)
, AsImageId(..)
, imageId
) where
import Control.Applicative(Applicative((<*>)), (<$>))
import Control.Category(id)
import Control.Lens(Cons(_Cons), Optic', Choice, prism', lens, (^?), ( # ))
import Control.Monad(Monad)
import Data.Digit(Digit, digitC)
import Data.Eq(Eq)
import Data.Foscam.File.Internal(digitCharacter)
import Data.Functor(Functor)
import Data.Maybe(Maybe(Nothing, Just))
import Data.Ord(Ord)
import Data.String(String)
import Data.Traversable(traverse)
import Text.Parser.Char(CharParsing)
import Text.Parser.Combinators((<?>), try, many)
import Prelude(Show)
-- $setup
-- >>> import Text.Parsec
data ImageId =
ImageId
Digit
[Digit]
deriving (Eq, Ord, Show)
class AsImageId p f s where
_ImageId ::
Optic' p f s ImageId
instance AsImageId p f ImageId where
_ImageId =
id
instance (Choice p, Applicative f) => AsImageId p f String where
_ImageId =
prism'
(\(ImageId h t) -> (digitC #) <$> (h:t))
(\s -> case s of
[] ->
Nothing
h:t ->
let ch = (^? digitC)
in ImageId <$> ch h <*> traverse ch t)
instance Cons ImageId ImageId Digit Digit where
_Cons =
prism'
(\(h, ImageId h' t) -> ImageId h (h':t))
(\(ImageId h t) -> case t of
[] ->
Nothing
u:v ->
Just (h, ImageId u v))
class AsImageIdHead p f s where
_ImageIdHead ::
Optic' p f s Digit
instance AsImageIdHead p f Digit where
_ImageIdHead =
id
instance (p ~ (->), Functor f) => AsImageIdHead p f ImageId where
_ImageIdHead =
lens
(\(ImageId h _) -> h)
(\(ImageId _ t) h -> ImageId h t)
class AsImageIdTail p f s where
_ImageIdTail ::
Optic' p f s [Digit]
instance AsImageIdTail p f [Digit] where
_ImageIdTail =
id
instance (p ~ (->), Functor f) => AsImageIdTail p f ImageId where
_ImageIdTail =
lens
(\(ImageId _ t) -> t)
(\(ImageId h _) t -> ImageId h t)
-- |
--
-- >>> parse imageId "test" "2062"
-- Right (ImageId 2 [0,6,2])
--
-- >>> parse imageId "test" "2"
-- Right (ImageId 2 [])
--
-- >>> parse imageId "test" "a"
-- Left "test" (line 1, column 2):
-- expecting image ID
-- not a digit: a
--
-- >>> parse imageId "test" ""
-- Left "test" (line 1, column 1):
-- unexpected end of input
-- expecting image ID
imageId ::
(Monad f, CharParsing f) =>
f ImageId
imageId =
let i = try digitCharacter
in ImageId <$> i <*> many i <?> "image ID"
|
tonymorris/foscam-filename
|
src/Data/Foscam/File/ImageId.hs
|
bsd-3-clause
| 2,723 | 0 | 16 | 719 | 878 | 500 | 378 | 81 | 1 |
module Chp4 where
-- | pattern matching for functions
-- | very similar as you define function with values as input, instead of type variables
-- | the output type should be consistent. Type inference will check for it
pm 3 4 = "7"
pm 1 2 = "3"
pm x y = "Other then else"
-- | for triplet tuple, we can wild card first 2 values, and return only 3rd.
third (_, _, z) = z
-- | you can also pattern match in list comprehensions.
xs = [(1,3), (4,3), (2,4), (5,3), (5,6), (3,1)]
v = [a+b | (a,b) <- xs]
-- | [4,7,6,8,11,4]
-- | A pattern like x:xs will bind the head of the list to x and the rest of it to xs, even if there's only one element so xs ends up being an empty list.
dehead (y:_) = y
-- | length' :: (Num b) => [a] -> b
-- | [] is empty list, [1,2,3] === 1 : 2 : 3 : []
length' [] = 0
length' (_:xs) = 1 + length' xs
-- | as patterns => @, so we can use variable z@y to as whole y structure
capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]
{--
Guards are indicated by pipes that follow a function's name and its parameters. Usually, they're indented a bit to the right and lined up. A guard is basically a boolean expression. If it evaluates to True, then the corresponding function body is used. If it evaluates to False, checking drops through to the next guard and so on.
--}
-- | instead of matching a concrete value, we use a condional check to match a response
bmiTell bmi
| bmi <= 18.5 = "You're underweight, you emo, you!"
| bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
-- | Many times, the last guard is otherwise. otherwise is defined simply as otherwise = True and catches everything.
max' a b | a > b = a | otherwise = b
{--
We put the keyword where after the guards (usually it's best to indent it as much as the pipes are indented) and then we define several names or functions. These names are visible across the guards and give us the advantage of not having to repeat ourselves.
--}
-- | bmiTell :: (RealFloat a) => a -> a -> String
bmiTell2 weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
skinny = 18.5
normal = 25.0
fat = 30.0
-- | You can also use where bindings to pattern match
-- | where bindings aren't shared across function bodies of different patterns. If you want several patterns of one function to access some shared name, you have to define it globally.
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
-- | Just like we've defined constants in where blocks, you can also define functions(bmi weight height = weight / height ^ 2).
calcBmis xs = [bmi w h | (w, h) <- xs]
where bmi weight height = weight / height ^ 2
res = calcBmis [(180, 50)]
-- | let bindings, you can bind local variables/functions and use it in next in expression
-- | form: let <bindings> in <expression>
letBindings1 = 4 * (let a = 9 in a + 1) + 2
-- | we can also introduce function in bindings
letBindings2 = [let square x = x * x in (square 5, square 3, square 2)]
-- | We include a let inside a list comprehension much like we would a predicate, only it doesn't filter the list, it only binds to names.
calcBmis2 xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2]
{--
The names defined in a let inside a list comprehension are visible to the output function (the part before the |) and all predicates and sections that come after of the binding.
We can't use the bmi name in the (w, h) <- xs part because it's defined prior to the let binding.
--}
-- | since let bindings are expressions and are fairly local in their scope, they can't be used across guards. Some people prefer where bindings because the names come after the function they're being used in. That way, the function body is closer to its name and type declaration and to some that's more readable.
-- | case expressions are, well, expressions, much like if else expressions and let bindings.
head' [] = error "No head for empty lists!"
head' (x:_) = x
-- | above equivalent
head1' xs = case xs of [] -> error "No head for empty lists!"
(x:_) -> x
-- | Whereas pattern matching on function parameters can only be done when defining functions, case expressions can be used pretty much anywhere.
describeList xs = "The list is " ++ case xs of [] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list."
{--
They are useful for pattern matching against something in the middle of an expression. Because pattern matching in function definitions is syntactic sugar for case expressions, we could have also defined this like so:
--}
describeList2 xs = "The list is " ++ what xs
where what [] = "empty."
what [x] = "a singleton list."
what xs = "a longer list."
|
jamesyang124/haskell-playground
|
src/Chp4.hs
|
bsd-3-clause
| 5,219 | 0 | 11 | 1,240 | 801 | 433 | 368 | 46 | 3 |
{-# LANGUAGE CPP #-}
module Main where
import qualified Ros.Test_srvs.AddTwoIntsRequest as Req
import qualified Ros.Test_srvs.AddTwoIntsResponse as Res
import Ros.Test_srvs.EmptyRequest
import Ros.Test_srvs.EmptyResponse
import Ros.Service (callService)
import Ros.Service.ServiceTypes
import Test.Tasty
import Test.Tasty.HUnit
import GHC.Int
import qualified Data.Int as Int
import Ros.Internal.Msg.SrvInfo
import Ros.Internal.RosBinary
import Control.Applicative ((<$>))
import Control.Exception
-- To run:
-- 1. start ros: run "roscore"
-- 2. in another terminal start the add_two_ints server:
-- python roshask/Tests/ServiceClientTests/add_two_ints_server.py
-- 3. in a new terminal make sure $ROS_MASTER_URI is correct and run
-- cabal test servicetest --show-details=always
type Response a = IO (Either ServiceResponseExcept a)
main :: IO ()
main = defaultMain $ testGroup "Service Tests" [
addIntsTest 4 7
, notOkTest 100 100
, requestResponseDontMatchTest
, noProviderTest
, connectionHeaderBadMD5Test
, emptyServiceTest]
addIntsTest :: GHC.Int.Int64 -> GHC.Int.Int64 -> TestTree
addIntsTest x y = testCase ("add_two_ints, add " ++ show x ++ " + " ++ show y) $
do res <- callService "/add_two_ints" Req.AddTwoIntsRequest{Req.a=x, Req.b=y} :: Response Res.AddTwoIntsResponse
Right (Res.AddTwoIntsResponse (x + y)) @=? res
-- add_two_ints_server returns None (triggering the NotOkError) if both a and b are 100
notOkTest :: GHC.Int.Int64 -> GHC.Int.Int64 -> TestTree
notOkTest x y = testCase ("NotOKError, add_two_ints, add " ++ show x ++ " + " ++ show y) $
do res <- callService "/add_two_ints" Req.AddTwoIntsRequest{Req.a=x, Req.b=y} :: Response Res.AddTwoIntsResponse
Left (NotOkExcept "service cannot process request: service handler returned None") @=? res
-- tests that an error is returned if the server is not registered with the master
noProviderTest :: TestTree
noProviderTest = testCase ("service not registered error") $
do res <- callService "/not_add_two_ints" Req.AddTwoIntsRequest{Req.a=x, Req.b=y} :: Response Res.AddTwoIntsResponse
Left (MasterExcept "lookupService failed, code: -1, statusMessage: no provider") @=? res
where
x = 10
y = 10
-- From the deprecated @testpack@ package by John Goerzen
assertRaises :: (Show a, Control.Exception.Exception e, Show e, Eq e)
=> String -> e -> IO a -> IO ()
assertRaises msg selector action =
let thetest e = if e == selector then return ()
else assertFailure $
msg ++ "\nReceived unexpected exception: "
++ show e
++ "\ninstead of exception: " ++ show selector
in do
r <- Control.Exception.try action
case r of
Left e -> thetest e
Right _ -> assertFailure $
msg ++ "\nReceived no exception, "
++ "but was expecting exception: "
++ show selector
requestResponseDontMatchTest :: TestTree
requestResponseDontMatchTest =
testGroup "check request and response" [testMd5, testName]
where
testMd5 = testCase ("check md5") $ do
assertRaises "Failed to detect mismatch"
(ErrorCall "Request and response type do not match")
--(callService "/add_two_ints" (Req.AddTwoIntsRequest 1 1) :: IO (Either ServiceResponseExcept BadMD5))
(callService "/add_two_ints" (Req.AddTwoIntsRequest 1 1) :: Response BadMD5)
testName = testCase ("check name") $ do
assertRaises "Failed to detect mismatch"
(ErrorCall "Request and response type do not match")
(callService "/add_two_ints" (Req.AddTwoIntsRequest 1 1) :: IO (Either ServiceResponseExcept BadName))
connectionHeaderBadMD5Test :: TestTree
connectionHeaderBadMD5Test = testCase "connection header wrong MD5 error" $
do res <- callService "/add_two_ints" $ BadMD5 10 :: Response BadMD5
Left (ConHeadExcept "Connection header from server has error, connection header is: [(\"error\",\"request from [roshask]: md5sums do not match: [6a2e34150c00229791cc89ff309fff22] vs. [6a2e34150c00229791cc89ff309fff21]\")]") @=? res
emptyServiceTest :: TestTree
emptyServiceTest =
testCase "emptyService" $
do res <- callService "/empty_srv" $ EmptyRequest :: Response EmptyResponse
Right (EmptyResponse) @=? res
data BadMD5 = BadMD5 {a :: Int.Int64} deriving (Show, Eq)
instance SrvInfo BadMD5 where
srvMD5 _ = "6a2e34150c00229791cc89ff309fff22"
srvTypeName _ = "test_srvs/AddTwoInts"
instance RosBinary BadMD5 where
put obj' = put (a obj')
get = BadMD5 <$> get
data BadName = BadName Int.Int64 deriving (Show, Eq)
instance SrvInfo BadName where
srvMD5 _ = "6a2e34150c00229791cc89ff309fff21"
srvTypeName _ = "test_srvs/AddTwoIntu"
instance RosBinary BadName where
put (BadName x) = put x
get = BadName <$> get
#if MIN_VERSION_base(4,7,0)
#else
instance Eq ErrorCall where
x == y = (show x) == (show y)
#endif
|
akru/roshask
|
Tests/ServiceClientTests/ServiceClientTest.hs
|
bsd-3-clause
| 5,054 | 0 | 15 | 1,079 | 1,108 | 583 | 525 | 91 | 3 |
{-# LANGUAGE TypeFamilies, TemplateHaskell, MultiParamTypeClasses, OverloadedLists,RecordWildCards #-}
-- | Anything that isn't a standard class like Eq, Show, or Ord goes in this module.
module Network.AuthorizeNet.Instances where
import Network.AuthorizeNet.Request
import Network.AuthorizeNet.Response
import Network.AuthorizeNet.TH
import Network.AuthorizeNet.Types
import Language.Haskell.TH.Lift
import GHC.Exts
import Text.XML.HaXml
import Text.XML.HaXml.Schema.Schema as Schema
import qualified Text.XML.HaXml.Schema.PrimitiveTypes as XML
import qualified Data.Text as T
import qualified Text.Parse as Parse
instance SchemaType T.Text where
parseSchemaType s = do
e <- Schema.element [s]
case e of
Elem _ _ [] -> return $ T.pack ""
_ -> commit $ interior e $ parseSimpleType
schemaTypeToXML s text = toXMLElement s [] [toXMLText (simpleTypeText text)]
instance SimpleType T.Text where
acceptingParser = fmap T.pack (Parse.many Parse.next)
simpleTypeText text = T.unpack text
instance SchemaType a => SchemaType (ArrayOf a) where
parseSchemaType s = return ArrayOf `apply` many (parseSchemaType s)
schemaTypeToXML s (ArrayOf xs) = concatMap (schemaTypeToXML s) xs
instance IsList (ArrayOf a) where
type Item (ArrayOf a) = a
fromList xs = ArrayOf xs
toList (ArrayOf xs) = xs
-- XML instances for general types
$(deriveXml ''SubscriptionIdList)
$(deriveXml ''ArrayOfString)
$(deriveXml ''ArrayOfNumericString)
$(deriveXml ''NumericString)
$(deriveXml ''MerchantAuthentication)
$(deriveXml ''CustomerType)
$(deriveXml ''NameAndAddress)
$(deriveXml ''CardArt)
$(deriveXml ''CreditCard)
$(deriveXml ''CreditCardMasked)
$(deriveXml ''Decimal)
$(deriveXml ''CustomerAddress)
$(deriveXml ''DriversLicense)
$(deriveXml ''BankAccountType)
$(deriveXml ''EcheckType)
$(deriveXml ''TransactionType)
$(deriveXml ''BankAccount)
$(deriveXml ''BankAccountMasked)
$(deriveXml ''CreditCardTrack)
$(deriveXml ''EncryptedTrackData)
$(deriveXml ''PayPal)
$(deriveXml ''OpaqueData)
$(deriveXml ''PaymentEmv)
$(deriveXml ''Payment)
$(deriveXml ''TokenMasked)
$(deriveXml ''PaymentMasked)
$(deriveXml ''PaymentProfile)
$(deriveXml ''CustomerPaymentProfile)
$(deriveXml ''CustomerPaymentProfileEx)
$(deriveXml ''CustomerPaymentProfileMasked)
$(deriveXml ''CustomerPaymentProfileSearchType)
$(deriveXml ''CustomerPaymentProfileOrderFieldEnum)
$(deriveXml ''CustomerPaymentProfileSorting)
$(deriveXml ''Paging)
$(deriveXml ''CustomerPaymentProfileListItem)
$(deriveXml ''ArrayOfCustomerPaymentProfileListItem)
$(deriveXml ''CustomerProfileBase)
$(deriveXml ''CustomerProfile)
$(deriveXml ''CustomerProfileEx)
$(deriveXml ''CustomerAddressEx)
$(deriveXml ''CustomerProfileMasked)
$(deriveXml ''ValidationMode)
$(deriveXml ''CustomerProfilePayment)
$(deriveXml ''Solution)
$(deriveXml ''Order)
$(deriveXml ''LineItem)
$(deriveXml ''LineItems)
$(deriveXml ''ExtendedAmount)
$(deriveXml ''CustomerData)
$(deriveXml ''CcAuthentication)
$(deriveXml ''TransRetailInfo)
$(deriveXml ''SettingName)
$(deriveXml ''Setting)
$(deriveXml ''ArrayOfSetting)
$(deriveXml ''UserField)
$(deriveXml ''ArrayOfUserField)
$(deriveXml ''SecureAcceptance)
$(deriveXml ''EmvResponse)
$(deriveXml ''TransactionRequest)
$(deriveXml ''MessageType)
$(deriveXml ''Message)
$(deriveXml ''Messages)
$(deriveXml ''PrePaidCard)
$(deriveXml ''TransactionResponse_message)
$(deriveXml ''ArrayOfTransactionResponseMessage)
$(deriveXml ''TransactionResponse_error)
$(deriveXml ''ArrayOfTransactionResponseError)
$(deriveXml ''TransactionResponse_splitTenderPayment)
$(deriveXml ''ArrayOfTransactionResponseSplitTenderPayment)
$(deriveXmlFull ''ANetApiResponse)
-- Instances for requests
$(deriveXml ''AuthenticateTestRequest)
$(deriveXml ''CreateCustomerProfileRequest)
$(deriveXml ''GetCustomerProfileRequest)
$(deriveXml ''GetCustomerProfileIdsRequest)
$(deriveXml ''UpdateCustomerProfileRequest)
$(deriveXml ''DeleteCustomerProfileRequest)
$(deriveXml ''CreateCustomerPaymentProfileRequest)
$(deriveXml ''GetCustomerPaymentProfileRequest)
$(deriveXml ''GetCustomerPaymentProfileListRequest)
$(deriveXml ''ValidateCustomerPaymentProfileRequest)
$(deriveXml ''UpdateCustomerPaymentProfileRequest)
$(deriveXml ''DeleteCustomerPaymentProfileRequest)
$(deriveXml ''CreateCustomerProfileFromTransactionRequest)
$(deriveXml ''GetHostedProfilePageRequest)
$(deriveXml ''CreateTransactionRequest)
instance ApiRequest AuthenticateTestRequest where
type ResponseType AuthenticateTestRequest = AuthenticateTestResponse
instance ApiRequest CreateCustomerProfileRequest where
type ResponseType CreateCustomerProfileRequest = CreateCustomerProfileResponse
instance ApiRequest GetCustomerProfileRequest where
type ResponseType GetCustomerProfileRequest = GetCustomerProfileResponse
instance ApiRequest GetCustomerProfileIdsRequest where
type ResponseType GetCustomerProfileIdsRequest = GetCustomerProfileIdsResponse
instance ApiRequest UpdateCustomerProfileRequest where
type ResponseType UpdateCustomerProfileRequest = UpdateCustomerProfileResponse
instance ApiRequest DeleteCustomerProfileRequest where
type ResponseType DeleteCustomerProfileRequest = DeleteCustomerProfileResponse
instance ApiRequest CreateCustomerPaymentProfileRequest where
type ResponseType CreateCustomerPaymentProfileRequest = CreateCustomerPaymentProfileResponse
instance ApiRequest GetCustomerPaymentProfileRequest where
type ResponseType GetCustomerPaymentProfileRequest = GetCustomerPaymentProfileResponse
instance ApiRequest GetCustomerPaymentProfileListRequest where
type ResponseType GetCustomerPaymentProfileListRequest = GetCustomerPaymentProfileListResponse
instance ApiRequest ValidateCustomerPaymentProfileRequest where
type ResponseType ValidateCustomerPaymentProfileRequest = ValidateCustomerPaymentProfileResponse
instance ApiRequest UpdateCustomerPaymentProfileRequest where
type ResponseType UpdateCustomerPaymentProfileRequest = UpdateCustomerPaymentProfileResponse
instance ApiRequest DeleteCustomerPaymentProfileRequest where
type ResponseType DeleteCustomerPaymentProfileRequest = DeleteCustomerPaymentProfileResponse
instance ApiRequest CreateCustomerProfileFromTransactionRequest where
type ResponseType CreateCustomerProfileFromTransactionRequest = CreateCustomerProfileResponse
instance ApiRequest GetHostedProfilePageRequest where
type ResponseType GetHostedProfilePageRequest = GetHostedProfilePageResponse
instance ApiRequest CreateTransactionRequest where
type ResponseType CreateTransactionRequest = CreateTransactionResponse
-- Instances for response types
$(deriveXmlFull ''AuthenticateTestResponse)
$(deriveXml ''CreateCustomerProfileResponse)
$(deriveXmlFull ''GetCustomerProfileResponse)
$(deriveXml ''GetCustomerProfileIdsResponse)
$(deriveXml ''UpdateCustomerProfileResponse)
$(deriveXml ''DeleteCustomerProfileResponse)
$(deriveXml ''CreateCustomerPaymentProfileResponse)
$(deriveXmlFull ''GetCustomerPaymentProfileResponse)
$(deriveXmlFull ''GetCustomerPaymentProfileListResponse)
$(deriveXml ''ValidateCustomerPaymentProfileResponse)
$(deriveXml ''UpdateCustomerPaymentProfileResponse)
$(deriveXml ''DeleteCustomerPaymentProfileResponse)
$(deriveXml ''GetHostedProfilePageResponse)
$(deriveXml ''CreateProfileResponse)
$(deriveXml ''TransactionResponse)
$(deriveXml ''CreateTransactionResponse)
instance ApiResponse AuthenticateTestResponse where
aNetApiResponse (AuthenticateTestResponse{..}) = ANetApiResponse authenticateTestResponse_refId authenticateTestResponse_messages authenticateTestResponse_sessionToken
instance ApiResponse CreateCustomerProfileResponse where
aNetApiResponse (CreateCustomerProfileResponse{..}) = ANetApiResponse createCustomerProfileResponse_refId createCustomerProfileResponse_messages createCustomerProfileResponse_sessionToken
instance ApiResponse GetCustomerProfileResponse where
aNetApiResponse (GetCustomerProfileResponse{..}) = ANetApiResponse getCustomerProfileResponse_refId getCustomerProfileResponse_messages getCustomerProfileResponse_sessionToken
instance ApiResponse GetCustomerProfileIdsResponse where
aNetApiResponse (GetCustomerProfileIdsResponse{..}) = ANetApiResponse getCustomerProfileIdsResponse_refId getCustomerProfileIdsResponse_messages getCustomerProfileIdsResponse_sessionToken
instance ApiResponse UpdateCustomerProfileResponse where
aNetApiResponse (UpdateCustomerProfileResponse{..}) = ANetApiResponse updateCustomerProfileResponse_refId updateCustomerProfileResponse_messages updateCustomerProfileResponse_sessionToken
instance ApiResponse DeleteCustomerProfileResponse where
aNetApiResponse (DeleteCustomerProfileResponse{..}) = ANetApiResponse deleteCustomerProfileResponse_refId deleteCustomerProfileResponse_messages deleteCustomerProfileResponse_sessionToken
instance ApiResponse CreateCustomerPaymentProfileResponse where
aNetApiResponse (CreateCustomerPaymentProfileResponse{..}) = ANetApiResponse createCustomerPaymentProfileResponse_refId createCustomerPaymentProfileResponse_messages createCustomerPaymentProfileResponse_sessionToken
instance ApiResponse GetCustomerPaymentProfileResponse where
aNetApiResponse (GetCustomerPaymentProfileResponse{..}) = ANetApiResponse getCustomerPaymentProfileResponse_refId getCustomerPaymentProfileResponse_messages getCustomerPaymentProfileResponse_sessionToken
instance ApiResponse GetCustomerPaymentProfileListResponse where
aNetApiResponse (GetCustomerPaymentProfileListResponse{..}) = ANetApiResponse getCustomerPaymentProfileListResponse_refId getCustomerPaymentProfileListResponse_messages getCustomerPaymentProfileListResponse_sessionToken
instance ApiResponse ValidateCustomerPaymentProfileResponse where
aNetApiResponse (ValidateCustomerPaymentProfileResponse{..}) = ANetApiResponse validateCustomerPaymentProfileResponse_refId validateCustomerPaymentProfileResponse_messages validateCustomerPaymentProfileResponse_sessionToken
instance ApiResponse UpdateCustomerPaymentProfileResponse where
aNetApiResponse (UpdateCustomerPaymentProfileResponse{..}) = ANetApiResponse updateCustomerPaymentProfileResponse_refId updateCustomerPaymentProfileResponse_messages updateCustomerPaymentProfileResponse_sessionToken
instance ApiResponse DeleteCustomerPaymentProfileResponse where
aNetApiResponse (DeleteCustomerPaymentProfileResponse{..}) = ANetApiResponse deleteCustomerPaymentProfileResponse_refId deleteCustomerPaymentProfileResponse_messages deleteCustomerPaymentProfileResponse_sessionToken
instance ApiResponse GetHostedProfilePageResponse where
aNetApiResponse (GetHostedProfilePageResponse{..}) = ANetApiResponse getHostedProfilePageResponse_refId getHostedProfilePageResponse_messages getHostedProfilePageResponse_sessionToken
instance ApiResponse CreateTransactionResponse where
aNetApiResponse (CreateTransactionResponse{..}) = ANetApiResponse createTransactionResponse_refId createTransactionResponse_messages createTransactionResponse_sessionToken
|
MichaelBurge/haskell-authorize-net
|
src/Network/AuthorizeNet/Instances.hs
|
bsd-3-clause
| 10,998 | 0 | 13 | 856 | 2,291 | 1,069 | 1,222 | 189 | 0 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts #-}
module Opaleye.Binary where
import Opaleye.QueryArr (Query)
import qualified Opaleye.Internal.Binary as B
import qualified Opaleye.Internal.PrimQuery as PQ
import Data.Profunctor.Product.Default (Default, def)
-- | Example type specialization:
--
-- @
-- unionAll :: Query (Column a, Column b)
-- -> Query (Column a, Column b)
-- -> Query (Column a, Column b)
-- @
--
-- Assuming the @makeAdaptorAndInstance@ splice has been run for the product type @Foo@:
--
-- @
-- unionAll :: Query (Foo (Column a) (Column b) (Column c))
-- -> Query (Foo (Column a) (Column b) (Column c))
-- -> Query (Foo (Column a) (Column b) (Column c))
-- @
unionAll :: Default B.Binaryspec columns columns =>
Query columns -> Query columns -> Query columns
unionAll = unionAllExplicit def
unionAllExplicit :: B.Binaryspec columns columns'
-> Query columns -> Query columns -> Query columns'
unionAllExplicit = B.sameTypeBinOpHelper PQ.UnionAll
-- | The same as unionAll, except that it additionally removes any
-- duplicate rows.
union :: Default B.Binaryspec columns columns =>
Query columns -> Query columns -> Query columns
union = unionExplicit def
unionExplicit :: B.Binaryspec columns columns'
-> Query columns -> Query columns -> Query columns'
unionExplicit = B.sameTypeBinOpHelper PQ.Union
intersectAll :: Default B.Binaryspec columns columns =>
Query columns -> Query columns -> Query columns
intersectAll = intersectAllExplicit def
intersectAllExplicit :: B.Binaryspec columns columns'
-> Query columns -> Query columns -> Query columns'
intersectAllExplicit = B.sameTypeBinOpHelper PQ.IntersectAll
-- | The same as intersectAll, except that it additionally removes any
-- duplicate rows.
intersect :: Default B.Binaryspec columns columns =>
Query columns -> Query columns -> Query columns
intersect = intersectExplicit def
intersectExplicit :: B.Binaryspec columns columns'
-> Query columns -> Query columns -> Query columns'
intersectExplicit = B.sameTypeBinOpHelper PQ.Intersect
exceptAll :: Default B.Binaryspec columns columns =>
Query columns -> Query columns -> Query columns
exceptAll = exceptAllExplicit def
exceptAllExplicit :: B.Binaryspec columns columns'
-> Query columns -> Query columns -> Query columns'
exceptAllExplicit = B.sameTypeBinOpHelper PQ.ExceptAll
-- | The same as exceptAll, except that it additionally removes any
-- duplicate rows.
except :: Default B.Binaryspec columns columns =>
Query columns -> Query columns -> Query columns
except = exceptExplicit def
exceptExplicit :: B.Binaryspec columns columns'
-> Query columns -> Query columns -> Query columns'
exceptExplicit = B.sameTypeBinOpHelper PQ.Except
|
silkapp/haskell-opaleye
|
src/Opaleye/Binary.hs
|
bsd-3-clause
| 2,923 | 0 | 8 | 617 | 599 | 302 | 297 | 42 | 1 |
-- | See <https://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFPropertyListRef/Reference/reference.html>
module CoreFoundation.Types.PropertyList(
-- * Basic interface
Plist,
CFPropertyList,
PlistClass,
toPlist,
fromPlist,
PlistView(..),
viewPlist,
-- * "Data.PropertyList" compat
toPropertyList,
fromPropertyList,
) where
import Prelude hiding(String)
import qualified Prelude
import CoreFoundation.Types.Base
import CoreFoundation.Types.String
import CoreFoundation.Types.Number
import CoreFoundation.Types.Boolean
import CoreFoundation.Types.Date
import CoreFoundation.Types.Data
import CoreFoundation.Types.Array
import CoreFoundation.Types.Dictionary
import Control.Arrow((***))
import Control.Applicative
import Data.Typeable
import Control.DeepSeq
import qualified Data.Vector as V
import Data.Functor.Identity
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.PropertyList as PL
import Data.PropertyList.Algebra hiding(toPlist, fromPlist)
import qualified Data.PropertyList.Algebra as PL
import Foreign hiding(fromBool)
-- | The CoreFoundation @CFPropertyList@ type
data CFPropertyList
{- |
Wraps the @CFPropertyListRef@ type. This is understood to be a
superclass of all of:
* 'String'
* 'Number'
* 'Boolean'
* 'Date'
* 'Data'
* 'Array Plist'
* 'Dictionary String Plist'
These can be converted to 'Plist's using 'toPlist', and can be
extracted using either 'fromPlist' or 'viewPlist'.
-}
newtype Plist = Plist { unPlist :: Ref CFPropertyList }
deriving(Typeable)
instance CF Plist where
type Repr Plist = CFPropertyList
wrap = Plist
unwrap = unPlist
-- | Private class: don't add more instances!
class CFConcrete a => PlistClass a
instance PlistClass String
instance PlistClass Number
instance PlistClass Boolean
instance PlistClass Date
instance PlistClass Data
instance PlistClass (Array Plist)
instance PlistClass (Dictionary String Plist)
-- | Cast to 'Plist'
toPlist :: PlistClass a => a -> Plist
toPlist = unsafeCastCF
-- | Try coercing the 'Plist'
fromPlist :: PlistClass a => Plist -> Maybe a
fromPlist = dynamicCast . toObject
-- | Query the type of the 'Plist'
viewPlist :: Plist -> PlistView
viewPlist (fromPlist -> Just v) = String v
viewPlist (fromPlist -> Just v) = Number v
viewPlist (fromPlist -> Just v) = Boolean v
viewPlist (fromPlist -> Just v) = Date v
viewPlist (fromPlist -> Just v) = Data v
viewPlist (fromPlist -> Just v) = Array v
viewPlist (fromPlist -> Just v) = Dictionary v
viewPlist _ = error "CoreFoundation.PropertyList.viewPlist: Unexpected type in Plist"
-- | View of the \"outer level\" of a 'Plist'.
data PlistView
= String !String
| Number !Number
| Boolean !Boolean
| Date !Date
| Data !Data
| Array !(Array Plist)
| Dictionary !(Dictionary String Plist)
deriving(Show, Eq, Ord, Typeable)
instance NFData PlistView
instance Show Plist where
show = show . viewPlist
instance Eq Plist where
a == b = viewPlist a == viewPlist b
instance Ord Plist where
compare a b = compare (viewPlist a) (viewPlist b)
instance NFData Plist
------------ support for Data.PropertyList
instance PListAlgebra Identity Plist where
plistAlgebra (Identity v) = case v of
PLArray w -> mk $ V.fromList w
PLData w -> mk w
PLDate w -> mk w
PLDict w -> mk $ cvtMap w
PLReal w -> mk $ D w
PLInt w -> mk $ I $ fromIntegral w
PLString w -> mk $ T.pack w
PLBool w -> mk w
where
mk :: PlistClass a => Hs a -> Plist
mk = toPlist . fromHs
cvtMap :: CF a => M.Map Prelude.String a -> (V.Vector String, V.Vector a)
cvtMap = (V.map fromString *** id) . V.unzip . V.fromList . M.toList
uncvtMap :: CF a => (V.Vector String, V.Vector a) -> M.Map Prelude.String a
uncvtMap = M.fromList . V.toList . uncurry V.zip . (V.map toString *** id)
plNumber (D d) = PLReal d
plNumber (I i) = PLInt (fromIntegral i)
instance Applicative f => PListCoalgebra f Plist where
{-# SPECIALISE instance PListCoalgebra Identity Plist #-}
plistCoalgebra v = case v of
(fromPlist -> Just v) -> mk (PLArray . V.toList) v
(fromPlist -> Just v) -> mk PLData v
(fromPlist -> Just v) -> mk PLDate v
(fromPlist -> Just v) -> mk (PLDict . uncvtMap) v
(fromPlist -> Just v) -> mk plNumber v
(fromPlist -> Just v) -> mk (PLString . T.unpack) v
(fromPlist -> Just v) -> mk PLBool v
where
mk :: forall a. PlistClass a => (Hs a -> PropertyListS Plist) -> a -> f (PropertyListS Plist)
mk ctor v = pure . ctor . toHs $ v
-- | Convert to 'PL.PropertyList'
toPropertyList :: Plist -> PL.PropertyList
toPropertyList = PL.toPlist
-- | Convert from 'PL.PropertyList'
fromPropertyList :: PL.PropertyList -> Plist
fromPropertyList = PL.toPlistWith idId
where
idId :: Identity a -> Identity a
idId = id
|
reinerp/CoreFoundation
|
CoreFoundation/Types/PropertyList.hs
|
bsd-3-clause
| 4,823 | 0 | 14 | 900 | 1,444 | 750 | 694 | -1 | -1 |
{-# LANGUAGE TypeFamilies, FlexibleContexts, UndecidableInstances #-}
module Data.Graph.Interface (
Vertex,
Edge(..),
Graph(..),
Adj,
Context(..),
InspectableGraph(..),
DecomposableGraph(..),
IncidenceGraph(..),
BidirectionalGraph(..),
AdjacencyGraph(..),
BidirectionalAdjacencyGraph(..),
AdjacencyMatrix(..),
VertexListGraph(..),
EdgeListGraph(..),
MutableGraph(..),
MarksVertices(..),
-- * Generic mutator
(&),
-- * Graph traversals
ufold,
gmap,
nmap,
emap,
-- * Context inspection
suc',
pre',
out',
inn',
outdeg',
indeg',
neighbors'
) where
import Control.Monad.ST
import qualified Data.Foldable as F
import Data.Hashable
import Data.Maybe ( fromMaybe, isJust )
import qualified Data.Set as S
type Vertex = Int
data Edge gr = Edge { edgeSource :: Vertex
, edgeTarget :: Vertex
, edgeLabel :: EdgeLabel gr
}
instance Show (EdgeLabel gr) => Show (Edge gr) where
show (Edge s d lbl) = "Edge " ++ show s ++ " " ++ show d ++ " " ++ show lbl
instance (Eq (EdgeLabel gr)) => Eq (Edge gr) where
(Edge s1 d1 l1) == (Edge s2 d2 l2) = s1 == s2 && d1 == d2 && l1 == l2
instance (Ord (EdgeLabel gr)) => Ord (Edge gr) where
compare (Edge s1 d1 l1) (Edge s2 d2 l2) =
compare (s1, d1, l1) (s2, d2, l2)
instance (Hashable (EdgeLabel gr)) => Hashable (Edge gr) where
hashWithSalt s (Edge s1 d1 l1) =
s `hashWithSalt` s1 `hashWithSalt` d1 `hashWithSalt` l1
type Adj gr = [(Vertex, EdgeLabel gr)]
data Context gr = Context { lpre' :: Adj gr
, vertex' :: Vertex
, lab' :: VertexLabel gr
, lsuc' :: Adj gr
}
instance (Eq (VertexLabel gr), Eq (EdgeLabel gr), Ord (VertexLabel gr), Ord (EdgeLabel gr)) => Eq (Context gr) where
(Context ps1 n1 l1 ss1) == (Context ps2 n2 l2 ss2) =
n1 == n2 && l1 == l2 && S.fromList ps1 == S.fromList ps2 &&
S.fromList ss1 == S.fromList ss2
class MarksVertices (k :: * -> *) where
newMarker :: (VertexListGraph gr) => gr -> ST s (k s)
markVertex :: k s -> Vertex -> ST s ()
isVertexMarked :: k s -> Vertex -> ST s Bool
class MarksVertices (VertexMarker gr) => Graph gr where
type EdgeLabel gr
type VertexLabel gr
type VertexMarker gr :: * -> *
isEmpty :: gr -> Bool
empty :: gr
mkGraph :: [(Vertex, VertexLabel gr)] -> [Edge gr] -> gr
maxVertex :: gr -> Vertex
class (Graph gr) => InspectableGraph gr where
context :: gr -> Vertex -> Maybe (Context gr)
-- | Test if a node is in the grap. The default implementation can
-- be overridden if desired
gelem :: Vertex -> gr -> Bool
gelem n g = isJust (context g n)
lab :: gr -> Vertex -> Maybe (VertexLabel gr)
lab g n = do
c <- context g n
return (lab' c)
-- | An interface for graphs that can *efficiently* be decomposed into
-- a context and the remaining graph. FIXME: Define what should happen
-- to self loops in the matched context. Should they be included or
-- excluded? Including them has the advantage that match and & are
-- dual operations.
class (InspectableGraph gr) => DecomposableGraph gr where
match :: Vertex -> gr -> Maybe (Context gr, gr)
-- | Graphs with efficient access to the outgoing edges for a given
-- node. Minimum required implementation: 'out'
class (Graph gr) => IncidenceGraph gr where
out :: gr -> Vertex -> [Edge gr]
outDeg :: gr -> Vertex -> Int
outDeg g = length . out g
-- | Graphs with efficient access to incoming edges. Minimum required
-- implementation: 'inn'
class (IncidenceGraph gr) => BidirectionalGraph gr where
inn :: gr -> Vertex -> [Edge gr]
inDeg :: gr -> Vertex -> Int
inDeg g = length . inn g
degree :: gr -> Vertex -> Int
degree g n = outDeg g n + inDeg g n
-- FIXME: For suc/pre, return a proxy object that is an instance of
-- Foldable and Traversable. This should be a small wrapper with just
-- enough information. Then an in-place fold is simple, and getting
-- a list would just be F.toList
-- | Graphs with efficient access to successor nodes. Minimum
-- required implementation: InspectableGraph
class (InspectableGraph gr) => AdjacencyGraph gr where
foldSuc :: (Vertex -> EdgeLabel gr -> a -> a) -> a -> gr -> Vertex -> a
suc :: gr -> Vertex -> [Vertex]
suc g = map fst . lsuc g
-- | Suggested complexity: log(N)
lsuc :: gr -> Vertex -> [(Vertex, EdgeLabel gr)]
lsuc g = maybe [] lsuc' . context g
-- | Graphs with efficient access to predecessor nodes. Minimum required
-- implementation: 'lpre' or 'pre'.
class (AdjacencyGraph gr) => BidirectionalAdjacencyGraph gr where
foldPre :: (Vertex -> EdgeLabel gr -> a -> a) -> a -> gr -> Vertex -> a
pre :: gr -> Vertex -> [Vertex]
pre g = map fst . lpre g
lpre :: gr -> Vertex -> [(Vertex, EdgeLabel gr)]
lpre g = maybe [] lpre' . context g
neighbors :: gr -> Vertex -> [Vertex]
neighbors g n = pre g n ++ suc g n
-- | Graphs with efficient access to all of the nodes in the graph.
-- Minimum required implementation: @labNodes@.
class (Graph gr) => VertexListGraph gr where
-- | Suggested complexity: log(N)
labeledVertices :: gr -> [(Vertex, VertexLabel gr)]
vertices :: gr -> [Vertex]
vertices = map fst . labeledVertices
numVertices :: gr -> Int
numVertices = length . vertices
-- | Graphs with efficient access to all of the edges in the graph.
-- Minimum required implementation: @edges@.
class (Graph gr) => EdgeListGraph gr where
edges :: gr -> [Edge gr]
numEdges :: gr -> Int
numEdges = length . edges
-- | Graphs with efficient implementations of adjacency tests.
class (Graph gr) => AdjacencyMatrix gr where
edgesBetween :: gr -> Vertex -> Vertex -> [EdgeLabel gr]
edgeExists :: gr -> Vertex -> Vertex -> Bool
edgeExists g v1 v2 = null (edgesBetween g v1 v2)
-- | The singular variants have default implementations. They are
-- class members so that they can be overridden with more efficient
-- implementations if desired.
class (Graph gr) => MutableGraph gr where
-- | Insert an edge into the graph. Edges will be inserted only if
-- both of the endpoints are in the graph. For graphs that do not
-- allow multi-edges, inserting an edge that already exists will
-- overwrite the edge label. For multigraphs, a duplicate edge will
-- be inserted.
insertEdge :: Vertex -> Vertex -> EdgeLabel gr -> gr -> Maybe gr
-- | Add a vertex to the graph. If the vertex already exists
-- in the graph, its label is overwritten.
insertVertex :: Vertex -> VertexLabel gr -> gr -> gr
-- | Delete a node from the graph.
removeVertex :: Vertex -> gr -> gr
-- | Remove all of the incoming and outgoing edges from a node (but
-- leave the node itself in the graph).
clearVertex :: Vertex -> gr -> gr
-- | Remove the edge referenced by the given descriptor (obtained
-- from insertEdge)
removeEdge :: (Eq (EdgeLabel gr)) => Edge gr -> gr -> gr
-- | Remove all edges with the given endpoints (regardless of label)
removeEdges :: Vertex -> Vertex -> gr -> gr
-- FIXME Make this a package-private function. It is kind of ugly.
-- | This function is the merge operator from FGL. It has some
-- important invariants that /must/ be obeyed. The vertex whose
-- context is being inserted must /not/ be in the graph.
-- Additionally, the other vertices referred to in the context /must/
-- exist in the graph.
(&) :: (MutableGraph gr) => Context gr -> gr -> gr
Context ps n l ss & g0 =
let g1 = insertVertex n l g0
addSucEdge (d, el) g = fromMaybe g (insertEdge n d el g)
addPreEdge (s, el) g = fromMaybe g (insertEdge s n el g)
g2 = foldr addSucEdge g1 ss
in foldr addPreEdge g2 ps
-- | Fold a function over all of the contexts of the graph
ufold :: (VertexListGraph gr, InspectableGraph gr)
=> (Context gr -> c -> c) -- ^ Fold function
-> c -- ^ Seed value
-> gr -- ^ Graph
-> c
ufold f seed g = foldr f seed ctxts
where
errMsg = "ufold: context lookup failure"
errLookup = fromMaybe (error errMsg)
ctxts = map (errLookup . context g) (vertices g)
-- | Map a function over a graph. The function can perform arbitrary
-- modifications to each context (which are combined to form a new
-- graph).
gmap :: (MutableGraph gr2, InspectableGraph gr1, VertexListGraph gr1)
=> (Context gr1 -> Context gr2)
-> gr1
-> gr2
gmap f = ufold (\c -> (f c&)) empty
-- | Map a function over the node labels of a graph
nmap :: (EdgeLabel gr1 ~ EdgeLabel gr2,
MutableGraph gr2, InspectableGraph gr1, VertexListGraph gr1)
=> (VertexLabel gr1 -> VertexLabel gr2)
-> gr1
-> gr2
nmap f = gmap (\(Context p v l s) -> Context p v (f l) s)
-- | Map a function over the edge labels of a graph
emap :: (VertexLabel gr1 ~ VertexLabel gr2,
MutableGraph gr2, InspectableGraph gr1, VertexListGraph gr1)
=> (EdgeLabel gr1 -> EdgeLabel gr2)
-> gr1
-> gr2
emap f = gmap (\(Context p v l s) -> Context (adjMap f p) v l (adjMap f s))
where
adjMap g = map (\(v, l) -> (v, g l))
-- Context inspection
suc' :: (Graph gr) => Context gr -> [Vertex]
suc' = F.toList . fmap fst . lsuc'
pre' :: (BidirectionalGraph gr) => Context gr -> [Vertex]
pre' = map fst . lpre'
out' :: (Graph gr) => Context gr -> [Edge gr]
out' (Context _ src _ s) = map (toEdge src) s
where
toEdge source (dst, lbl) = Edge source dst lbl
inn' :: (BidirectionalGraph gr) => Context gr -> [Edge gr]
inn' (Context p dst _ _) = map (toEdge dst) p
where
toEdge dest (src, lbl) = Edge src dest lbl
outdeg' :: (Graph gr) => Context gr -> Int
outdeg' (Context _ _ _ s) = length s
indeg' :: (BidirectionalGraph gr) => Context gr -> Int
indeg' (Context p _ _ _) = length p
-- | All nodes linked to or from in the context. This function *may*
-- return duplicates if some node is both a predecessor and a
-- successor.
neighbors' :: (BidirectionalGraph gr) => Context gr -> [Vertex]
neighbors' (Context p _ _ s) = map fst (p ++ s)
|
travitch/hbgl-experimental
|
src/Data/Graph/Interface.hs
|
bsd-3-clause
| 10,092 | 0 | 12 | 2,436 | 2,988 | 1,598 | 1,390 | 175 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.AmountOfMoney.TR.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.AmountOfMoney.TR.Corpus
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "TR Tests"
[ makeCorpusTest [Seal AmountOfMoney] corpus
]
|
facebookincubator/duckling
|
tests/Duckling/AmountOfMoney/TR/Tests.hs
|
bsd-3-clause
| 522 | 0 | 9 | 78 | 79 | 50 | 29 | 11 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Types.Check where
import qualified Data.HashMap.Strict as HM
import Data.Map.Strict (Map, keys, singleton, empty)
import Data.Maybe
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Yaml hiding (array)
import Data.Yaml.Builder
import Prelude hiding (lookup, putStr)
import Types.Dynamic (Complex, Dyn)
import Types.Shared (Check (..), Prefix)
import Check.Snmp.Snmp (Rules(..))
type Route = Map Text (Check -> IO Complex)
type RouteCheck = Map Text (Check -> Either String Check)
{--
describeCheck :: Monad m => Check -> CheckT m YamlBuilder
describeCheck (Check _ _ t _) = do
routes <- get
case lookup t routes of
Nothing -> return $ string ""
Just (AC (_, x)) -> return $ example [x]
--}
--
type Description = Text
type Name = Text
type Required = Bool
type CheckValue = Dyn -> Either String Dyn
class Checkable a where
route :: Rules -> a -> Route
describe :: a -> [(Prefix, Required, CheckValue, Description)]
routeCheck :: Rules -> a -> RouteCheck
example :: [a] -> YamlBuilder
example xs = mapping [("checks", array $ map example' xs)]
type Problem = String
routeCheck' :: Checkable a => a -> Text -> RouteCheck
routeCheck' x checkT = singleton checkT $! fun (describe x)
where
fun :: [(Prefix, Required, CheckValue, Description)] -> Check -> Either String Check
fun desc check =
let Object params = cparams check
checking = map tryCheck desc
eitherToMaybeProblem (Left y) = Just y
eitherToMaybeProblem (Right _) = Nothing
tryCheck :: (Prefix, Required, CheckValue, Description) -> Maybe Problem
tryCheck (field, isMustBe, cv, _) =
case (HM.member field params, isMustBe) of
(True, True) -> eitherToMaybeProblem $ cv (params HM.! field )
(True, False) -> eitherToMaybeProblem $ cv (params HM.! field)
(False, True) -> Just $ "field not found " <> show field
(False, False) -> Nothing
result :: [Maybe Problem] -> Either String Check
result r = case catMaybes r of
[] -> Right check
xs -> Left $ foldr1 (\z y -> z ++ " " ++ y) xs
in result checking
example' :: Checkable a => a -> YamlBuilder
example' a = let m = describe a
def = [("name", string "must be"), ("period", string "must be, in cron format")]
ty = [("type", string $ head $ keys $ route (Rules empty) a)]
nds = def <> ty <> map fun m
fun (t, b, _, d) = if b
then (t, string $ "must be: " <> d)
else (t, string $ "can be: " <> d)
in mapping nds
|
chemist/fixmon
|
src/Types/Check.hs
|
bsd-3-clause
| 3,049 | 0 | 19 | 1,041 | 889 | 492 | 397 | 57 | 6 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
-----------------------------------------------------------------------------
--
-- Machine-dependent assembly language
--
-- (c) The University of Glasgow 1993-2004
--
-----------------------------------------------------------------------------
#include "HsVersions.h"
module PPC.Instr (
archWordFormat,
RI(..),
Instr(..),
stackFrameHeaderSize,
maxSpillSlots,
allocMoreStack,
makeFarBranches
)
where
import GhcPrelude
import PPC.Regs
import PPC.Cond
import Instruction
import Format
import TargetReg
import RegClass
import Reg
import GHC.Platform.Regs
import GHC.Cmm.BlockId
import GHC.Cmm.Dataflow.Collections
import GHC.Cmm.Dataflow.Label
import DynFlags
import GHC.Cmm
import GHC.Cmm.Info
import FastString
import GHC.Cmm.CLabel
import Outputable
import GHC.Platform
import UniqFM (listToUFM, lookupUFM)
import UniqSupply
import Control.Monad (replicateM)
import Data.Maybe (fromMaybe)
--------------------------------------------------------------------------------
-- Format of a PPC memory address.
--
archWordFormat :: Bool -> Format
archWordFormat is32Bit
| is32Bit = II32
| otherwise = II64
-- | Instruction instance for powerpc
instance Instruction Instr where
regUsageOfInstr = ppc_regUsageOfInstr
patchRegsOfInstr = ppc_patchRegsOfInstr
isJumpishInstr = ppc_isJumpishInstr
jumpDestsOfInstr = ppc_jumpDestsOfInstr
patchJumpInstr = ppc_patchJumpInstr
mkSpillInstr = ppc_mkSpillInstr
mkLoadInstr = ppc_mkLoadInstr
takeDeltaInstr = ppc_takeDeltaInstr
isMetaInstr = ppc_isMetaInstr
mkRegRegMoveInstr _ = ppc_mkRegRegMoveInstr
takeRegRegMoveInstr = ppc_takeRegRegMoveInstr
mkJumpInstr = ppc_mkJumpInstr
mkStackAllocInstr = ppc_mkStackAllocInstr
mkStackDeallocInstr = ppc_mkStackDeallocInstr
ppc_mkStackAllocInstr :: Platform -> Int -> [Instr]
ppc_mkStackAllocInstr platform amount
= ppc_mkStackAllocInstr' platform (-amount)
ppc_mkStackDeallocInstr :: Platform -> Int -> [Instr]
ppc_mkStackDeallocInstr platform amount
= ppc_mkStackAllocInstr' platform amount
ppc_mkStackAllocInstr' :: Platform -> Int -> [Instr]
ppc_mkStackAllocInstr' platform amount
| fits16Bits amount
= [ LD fmt r0 (AddrRegImm sp zero)
, STU fmt r0 (AddrRegImm sp immAmount)
]
| otherwise
= [ LD fmt r0 (AddrRegImm sp zero)
, ADDIS tmp sp (HA immAmount)
, ADD tmp tmp (RIImm (LO immAmount))
, STU fmt r0 (AddrRegReg sp tmp)
]
where
fmt = intFormat $ widthFromBytes (platformWordSizeInBytes platform)
zero = ImmInt 0
tmp = tmpReg platform
immAmount = ImmInt amount
--
-- See note [extra spill slots] in X86/Instr.hs
--
allocMoreStack
:: Platform
-> Int
-> NatCmmDecl statics PPC.Instr.Instr
-> UniqSM (NatCmmDecl statics PPC.Instr.Instr, [(BlockId,BlockId)])
allocMoreStack _ _ top@(CmmData _ _) = return (top,[])
allocMoreStack platform slots (CmmProc info lbl live (ListGraph code)) = do
let
infos = mapKeys info
entries = case code of
[] -> infos
BasicBlock entry _ : _ -- first block is the entry point
| entry `elem` infos -> infos
| otherwise -> entry : infos
uniqs <- replicateM (length entries) getUniqueM
let
delta = ((x + stackAlign - 1) `quot` stackAlign) * stackAlign -- round up
where x = slots * spillSlotSize -- sp delta
alloc = mkStackAllocInstr platform delta
dealloc = mkStackDeallocInstr platform delta
retargetList = (zip entries (map mkBlockId uniqs))
new_blockmap :: LabelMap BlockId
new_blockmap = mapFromList retargetList
insert_stack_insns (BasicBlock id insns)
| Just new_blockid <- mapLookup id new_blockmap
= [ BasicBlock id $ alloc ++ [BCC ALWAYS new_blockid Nothing]
, BasicBlock new_blockid block'
]
| otherwise
= [ BasicBlock id block' ]
where
block' = foldr insert_dealloc [] insns
insert_dealloc insn r
-- BCTR might or might not be a non-local jump. For
-- "labeled-goto" we use JMP, and for "computed-goto" we
-- use MTCTR followed by BCTR. See 'PPC.CodeGen.genJump'.
= case insn of
JMP _ _ -> dealloc ++ (insn : r)
BCTR [] Nothing _ -> dealloc ++ (insn : r)
BCTR ids label rs -> BCTR (map (fmap retarget) ids) label rs : r
BCCFAR cond b p -> BCCFAR cond (retarget b) p : r
BCC cond b p -> BCC cond (retarget b) p : r
_ -> insn : r
-- BL and BCTRL are call-like instructions rather than
-- jumps, and are used only for C calls.
retarget :: BlockId -> BlockId
retarget b
= fromMaybe b (mapLookup b new_blockmap)
new_code
= concatMap insert_stack_insns code
-- in
return (CmmProc info lbl live (ListGraph new_code),retargetList)
-- -----------------------------------------------------------------------------
-- Machine's assembly language
-- We have a few common "instructions" (nearly all the pseudo-ops) but
-- mostly all of 'Instr' is machine-specific.
-- Register or immediate
data RI
= RIReg Reg
| RIImm Imm
data Instr
-- comment pseudo-op
= COMMENT FastString
-- some static data spat out during code
-- generation. Will be extracted before
-- pretty-printing.
| LDATA Section RawCmmStatics
-- start a new basic block. Useful during
-- codegen, removed later. Preceding
-- instruction should be a jump, as per the
-- invariants for a BasicBlock (see Cmm).
| NEWBLOCK BlockId
-- specify current stack offset for
-- benefit of subsequent passes
| DELTA Int
-- Loads and stores.
| LD Format Reg AddrMode -- Load format, dst, src
| LDFAR Format Reg AddrMode -- Load format, dst, src 32 bit offset
| LDR Format Reg AddrMode -- Load and reserve format, dst, src
| LA Format Reg AddrMode -- Load arithmetic format, dst, src
| ST Format Reg AddrMode -- Store format, src, dst
| STFAR Format Reg AddrMode -- Store format, src, dst 32 bit offset
| STU Format Reg AddrMode -- Store with Update format, src, dst
| STC Format Reg AddrMode -- Store conditional format, src, dst
| LIS Reg Imm -- Load Immediate Shifted dst, src
| LI Reg Imm -- Load Immediate dst, src
| MR Reg Reg -- Move Register dst, src -- also for fmr
| CMP Format Reg RI -- format, src1, src2
| CMPL Format Reg RI -- format, src1, src2
| BCC Cond BlockId (Maybe Bool) -- cond, block, hint
| BCCFAR Cond BlockId (Maybe Bool) -- cond, block, hint
-- hint:
-- Just True: branch likely taken
-- Just False: branch likely not taken
-- Nothing: no hint
| JMP CLabel [Reg] -- same as branch,
-- but with CLabel instead of block ID
-- and live global registers
| MTCTR Reg
| BCTR [Maybe BlockId] (Maybe CLabel) [Reg]
-- with list of local destinations, and
-- jump table location if necessary
| BL CLabel [Reg] -- with list of argument regs
| BCTRL [Reg]
| ADD Reg Reg RI -- dst, src1, src2
| ADDO Reg Reg Reg -- add and set overflow
| ADDC Reg Reg Reg -- (carrying) dst, src1, src2
| ADDE Reg Reg Reg -- (extended) dst, src1, src2
| ADDZE Reg Reg -- (to zero extended) dst, src
| ADDIS Reg Reg Imm -- Add Immediate Shifted dst, src1, src2
| SUBF Reg Reg Reg -- dst, src1, src2 ; dst = src2 - src1
| SUBFO Reg Reg Reg -- subtract from and set overflow
| SUBFC Reg Reg RI -- (carrying) dst, src1, src2 ;
-- dst = src2 - src1
| SUBFE Reg Reg Reg -- (extended) dst, src1, src2 ;
-- dst = src2 - src1
| MULL Format Reg Reg RI
| MULLO Format Reg Reg Reg -- multiply and set overflow
| MFOV Format Reg -- move overflow bit (1|33) to register
-- pseudo-instruction; pretty printed as
-- mfxer dst
-- extr[w|d]i dst, dst, 1, [1|33]
| MULHU Format Reg Reg Reg
| DIV Format Bool Reg Reg Reg
| AND Reg Reg RI -- dst, src1, src2
| ANDC Reg Reg Reg -- AND with complement, dst = src1 & ~ src2
| NAND Reg Reg Reg -- dst, src1, src2
| OR Reg Reg RI -- dst, src1, src2
| ORIS Reg Reg Imm -- OR Immediate Shifted dst, src1, src2
| XOR Reg Reg RI -- dst, src1, src2
| XORIS Reg Reg Imm -- XOR Immediate Shifted dst, src1, src2
| EXTS Format Reg Reg
| CNTLZ Format Reg Reg
| NEG Reg Reg
| NOT Reg Reg
| SL Format Reg Reg RI -- shift left
| SR Format Reg Reg RI -- shift right
| SRA Format Reg Reg RI -- shift right arithmetic
| RLWINM Reg Reg Int Int Int -- Rotate Left Word Immediate then AND with Mask
| CLRLI Format Reg Reg Int -- clear left immediate (extended mnemonic)
| CLRRI Format Reg Reg Int -- clear right immediate (extended mnemonic)
| FADD Format Reg Reg Reg
| FSUB Format Reg Reg Reg
| FMUL Format Reg Reg Reg
| FDIV Format Reg Reg Reg
| FABS Reg Reg -- abs is the same for single and double
| FNEG Reg Reg -- negate is the same for single and double prec.
| FCMP Reg Reg
| FCTIWZ Reg Reg -- convert to integer word
| FCTIDZ Reg Reg -- convert to integer double word
| FCFID Reg Reg -- convert from integer double word
| FRSP Reg Reg -- reduce to single precision
-- (but destination is a FP register)
| CRNOR Int Int Int -- condition register nor
| MFCR Reg -- move from condition register
| MFLR Reg -- move from link register
| FETCHPC Reg -- pseudo-instruction:
-- bcl to next insn, mflr reg
| HWSYNC -- heavy weight sync
| ISYNC -- instruction synchronize
| LWSYNC -- memory barrier
| NOP -- no operation, PowerPC 64 bit
-- needs this as place holder to
-- reload TOC pointer
-- | Get the registers that are being used by this instruction.
-- regUsage doesn't need to do any trickery for jumps and such.
-- Just state precisely the regs read and written by that insn.
-- The consequences of control flow transfers, as far as register
-- allocation goes, are taken care of by the register allocator.
--
ppc_regUsageOfInstr :: Platform -> Instr -> RegUsage
ppc_regUsageOfInstr platform instr
= case instr of
LD _ reg addr -> usage (regAddr addr, [reg])
LDFAR _ reg addr -> usage (regAddr addr, [reg])
LDR _ reg addr -> usage (regAddr addr, [reg])
LA _ reg addr -> usage (regAddr addr, [reg])
ST _ reg addr -> usage (reg : regAddr addr, [])
STFAR _ reg addr -> usage (reg : regAddr addr, [])
STU _ reg addr -> usage (reg : regAddr addr, [])
STC _ reg addr -> usage (reg : regAddr addr, [])
LIS reg _ -> usage ([], [reg])
LI reg _ -> usage ([], [reg])
MR reg1 reg2 -> usage ([reg2], [reg1])
CMP _ reg ri -> usage (reg : regRI ri,[])
CMPL _ reg ri -> usage (reg : regRI ri,[])
BCC _ _ _ -> noUsage
BCCFAR _ _ _ -> noUsage
JMP _ regs -> usage (regs, [])
MTCTR reg -> usage ([reg],[])
BCTR _ _ regs -> usage (regs, [])
BL _ params -> usage (params, callClobberedRegs platform)
BCTRL params -> usage (params, callClobberedRegs platform)
ADD reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
ADDO reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
ADDC reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
ADDE reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
ADDZE reg1 reg2 -> usage ([reg2], [reg1])
ADDIS reg1 reg2 _ -> usage ([reg2], [reg1])
SUBF reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
SUBFO reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
SUBFC reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
SUBFE reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
MULL _ reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
MULLO _ reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
MFOV _ reg -> usage ([], [reg])
MULHU _ reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
DIV _ _ reg1 reg2 reg3
-> usage ([reg2,reg3], [reg1])
AND reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
ANDC reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
NAND reg1 reg2 reg3 -> usage ([reg2,reg3], [reg1])
OR reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
ORIS reg1 reg2 _ -> usage ([reg2], [reg1])
XOR reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
XORIS reg1 reg2 _ -> usage ([reg2], [reg1])
EXTS _ reg1 reg2 -> usage ([reg2], [reg1])
CNTLZ _ reg1 reg2 -> usage ([reg2], [reg1])
NEG reg1 reg2 -> usage ([reg2], [reg1])
NOT reg1 reg2 -> usage ([reg2], [reg1])
SL _ reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
SR _ reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
SRA _ reg1 reg2 ri -> usage (reg2 : regRI ri, [reg1])
RLWINM reg1 reg2 _ _ _ -> usage ([reg2], [reg1])
CLRLI _ reg1 reg2 _ -> usage ([reg2], [reg1])
CLRRI _ reg1 reg2 _ -> usage ([reg2], [reg1])
FADD _ r1 r2 r3 -> usage ([r2,r3], [r1])
FSUB _ r1 r2 r3 -> usage ([r2,r3], [r1])
FMUL _ r1 r2 r3 -> usage ([r2,r3], [r1])
FDIV _ r1 r2 r3 -> usage ([r2,r3], [r1])
FABS r1 r2 -> usage ([r2], [r1])
FNEG r1 r2 -> usage ([r2], [r1])
FCMP r1 r2 -> usage ([r1,r2], [])
FCTIWZ r1 r2 -> usage ([r2], [r1])
FCTIDZ r1 r2 -> usage ([r2], [r1])
FCFID r1 r2 -> usage ([r2], [r1])
FRSP r1 r2 -> usage ([r2], [r1])
MFCR reg -> usage ([], [reg])
MFLR reg -> usage ([], [reg])
FETCHPC reg -> usage ([], [reg])
_ -> noUsage
where
usage (src, dst) = RU (filter (interesting platform) src)
(filter (interesting platform) dst)
regAddr (AddrRegReg r1 r2) = [r1, r2]
regAddr (AddrRegImm r1 _) = [r1]
regRI (RIReg r) = [r]
regRI _ = []
interesting :: Platform -> Reg -> Bool
interesting _ (RegVirtual _) = True
interesting platform (RegReal (RealRegSingle i)) = freeReg platform i
interesting _ (RegReal (RealRegPair{}))
= panic "PPC.Instr.interesting: no reg pairs on this arch"
-- | Apply a given mapping to all the register references in this
-- instruction.
ppc_patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr
ppc_patchRegsOfInstr instr env
= case instr of
LD fmt reg addr -> LD fmt (env reg) (fixAddr addr)
LDFAR fmt reg addr -> LDFAR fmt (env reg) (fixAddr addr)
LDR fmt reg addr -> LDR fmt (env reg) (fixAddr addr)
LA fmt reg addr -> LA fmt (env reg) (fixAddr addr)
ST fmt reg addr -> ST fmt (env reg) (fixAddr addr)
STFAR fmt reg addr -> STFAR fmt (env reg) (fixAddr addr)
STU fmt reg addr -> STU fmt (env reg) (fixAddr addr)
STC fmt reg addr -> STC fmt (env reg) (fixAddr addr)
LIS reg imm -> LIS (env reg) imm
LI reg imm -> LI (env reg) imm
MR reg1 reg2 -> MR (env reg1) (env reg2)
CMP fmt reg ri -> CMP fmt (env reg) (fixRI ri)
CMPL fmt reg ri -> CMPL fmt (env reg) (fixRI ri)
BCC cond lbl p -> BCC cond lbl p
BCCFAR cond lbl p -> BCCFAR cond lbl p
JMP l regs -> JMP l regs -- global regs will not be remapped
MTCTR reg -> MTCTR (env reg)
BCTR targets lbl rs -> BCTR targets lbl rs
BL imm argRegs -> BL imm argRegs -- argument regs
BCTRL argRegs -> BCTRL argRegs -- cannot be remapped
ADD reg1 reg2 ri -> ADD (env reg1) (env reg2) (fixRI ri)
ADDO reg1 reg2 reg3 -> ADDO (env reg1) (env reg2) (env reg3)
ADDC reg1 reg2 reg3 -> ADDC (env reg1) (env reg2) (env reg3)
ADDE reg1 reg2 reg3 -> ADDE (env reg1) (env reg2) (env reg3)
ADDZE reg1 reg2 -> ADDZE (env reg1) (env reg2)
ADDIS reg1 reg2 imm -> ADDIS (env reg1) (env reg2) imm
SUBF reg1 reg2 reg3 -> SUBF (env reg1) (env reg2) (env reg3)
SUBFO reg1 reg2 reg3 -> SUBFO (env reg1) (env reg2) (env reg3)
SUBFC reg1 reg2 ri -> SUBFC (env reg1) (env reg2) (fixRI ri)
SUBFE reg1 reg2 reg3 -> SUBFE (env reg1) (env reg2) (env reg3)
MULL fmt reg1 reg2 ri
-> MULL fmt (env reg1) (env reg2) (fixRI ri)
MULLO fmt reg1 reg2 reg3
-> MULLO fmt (env reg1) (env reg2) (env reg3)
MFOV fmt reg -> MFOV fmt (env reg)
MULHU fmt reg1 reg2 reg3
-> MULHU fmt (env reg1) (env reg2) (env reg3)
DIV fmt sgn reg1 reg2 reg3
-> DIV fmt sgn (env reg1) (env reg2) (env reg3)
AND reg1 reg2 ri -> AND (env reg1) (env reg2) (fixRI ri)
ANDC reg1 reg2 reg3 -> ANDC (env reg1) (env reg2) (env reg3)
NAND reg1 reg2 reg3 -> NAND (env reg1) (env reg2) (env reg3)
OR reg1 reg2 ri -> OR (env reg1) (env reg2) (fixRI ri)
ORIS reg1 reg2 imm -> ORIS (env reg1) (env reg2) imm
XOR reg1 reg2 ri -> XOR (env reg1) (env reg2) (fixRI ri)
XORIS reg1 reg2 imm -> XORIS (env reg1) (env reg2) imm
EXTS fmt reg1 reg2 -> EXTS fmt (env reg1) (env reg2)
CNTLZ fmt reg1 reg2 -> CNTLZ fmt (env reg1) (env reg2)
NEG reg1 reg2 -> NEG (env reg1) (env reg2)
NOT reg1 reg2 -> NOT (env reg1) (env reg2)
SL fmt reg1 reg2 ri
-> SL fmt (env reg1) (env reg2) (fixRI ri)
SR fmt reg1 reg2 ri
-> SR fmt (env reg1) (env reg2) (fixRI ri)
SRA fmt reg1 reg2 ri
-> SRA fmt (env reg1) (env reg2) (fixRI ri)
RLWINM reg1 reg2 sh mb me
-> RLWINM (env reg1) (env reg2) sh mb me
CLRLI fmt reg1 reg2 n -> CLRLI fmt (env reg1) (env reg2) n
CLRRI fmt reg1 reg2 n -> CLRRI fmt (env reg1) (env reg2) n
FADD fmt r1 r2 r3 -> FADD fmt (env r1) (env r2) (env r3)
FSUB fmt r1 r2 r3 -> FSUB fmt (env r1) (env r2) (env r3)
FMUL fmt r1 r2 r3 -> FMUL fmt (env r1) (env r2) (env r3)
FDIV fmt r1 r2 r3 -> FDIV fmt (env r1) (env r2) (env r3)
FABS r1 r2 -> FABS (env r1) (env r2)
FNEG r1 r2 -> FNEG (env r1) (env r2)
FCMP r1 r2 -> FCMP (env r1) (env r2)
FCTIWZ r1 r2 -> FCTIWZ (env r1) (env r2)
FCTIDZ r1 r2 -> FCTIDZ (env r1) (env r2)
FCFID r1 r2 -> FCFID (env r1) (env r2)
FRSP r1 r2 -> FRSP (env r1) (env r2)
MFCR reg -> MFCR (env reg)
MFLR reg -> MFLR (env reg)
FETCHPC reg -> FETCHPC (env reg)
_ -> instr
where
fixAddr (AddrRegReg r1 r2) = AddrRegReg (env r1) (env r2)
fixAddr (AddrRegImm r1 i) = AddrRegImm (env r1) i
fixRI (RIReg r) = RIReg (env r)
fixRI other = other
--------------------------------------------------------------------------------
-- | Checks whether this instruction is a jump/branch instruction.
-- One that can change the flow of control in a way that the
-- register allocator needs to worry about.
ppc_isJumpishInstr :: Instr -> Bool
ppc_isJumpishInstr instr
= case instr of
BCC{} -> True
BCCFAR{} -> True
BCTR{} -> True
BCTRL{} -> True
BL{} -> True
JMP{} -> True
_ -> False
-- | Checks whether this instruction is a jump/branch instruction.
-- One that can change the flow of control in a way that the
-- register allocator needs to worry about.
ppc_jumpDestsOfInstr :: Instr -> [BlockId]
ppc_jumpDestsOfInstr insn
= case insn of
BCC _ id _ -> [id]
BCCFAR _ id _ -> [id]
BCTR targets _ _ -> [id | Just id <- targets]
_ -> []
-- | Change the destination of this jump instruction.
-- Used in the linear allocator when adding fixup blocks for join
-- points.
ppc_patchJumpInstr :: Instr -> (BlockId -> BlockId) -> Instr
ppc_patchJumpInstr insn patchF
= case insn of
BCC cc id p -> BCC cc (patchF id) p
BCCFAR cc id p -> BCCFAR cc (patchF id) p
BCTR ids lbl rs -> BCTR (map (fmap patchF) ids) lbl rs
_ -> insn
-- -----------------------------------------------------------------------------
-- | An instruction to spill a register into a spill slot.
ppc_mkSpillInstr
:: DynFlags
-> Reg -- register to spill
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
ppc_mkSpillInstr dflags reg delta slot
= let platform = targetPlatform dflags
off = spillSlotToOffset dflags slot
arch = platformArch platform
in
let fmt = case targetClassOfReg platform reg of
RcInteger -> case arch of
ArchPPC -> II32
_ -> II64
RcDouble -> FF64
_ -> panic "PPC.Instr.mkSpillInstr: no match"
instr = case makeImmediate W32 True (off-delta) of
Just _ -> ST
Nothing -> STFAR -- pseudo instruction: 32 bit offsets
in instr fmt reg (AddrRegImm sp (ImmInt (off-delta)))
ppc_mkLoadInstr
:: DynFlags
-> Reg -- register to load
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
ppc_mkLoadInstr dflags reg delta slot
= let platform = targetPlatform dflags
off = spillSlotToOffset dflags slot
arch = platformArch platform
in
let fmt = case targetClassOfReg platform reg of
RcInteger -> case arch of
ArchPPC -> II32
_ -> II64
RcDouble -> FF64
_ -> panic "PPC.Instr.mkLoadInstr: no match"
instr = case makeImmediate W32 True (off-delta) of
Just _ -> LD
Nothing -> LDFAR -- pseudo instruction: 32 bit offsets
in instr fmt reg (AddrRegImm sp (ImmInt (off-delta)))
-- | The size of a minimal stackframe header including minimal
-- parameter save area.
stackFrameHeaderSize :: DynFlags -> Int
stackFrameHeaderSize dflags
= case platformOS platform of
OSAIX -> 24 + 8 * 4
_ -> case platformArch platform of
-- header + parameter save area
ArchPPC -> 64 -- TODO: check ABI spec
ArchPPC_64 ELF_V1 -> 48 + 8 * 8
ArchPPC_64 ELF_V2 -> 32 + 8 * 8
_ -> panic "PPC.stackFrameHeaderSize: not defined for this OS"
where platform = targetPlatform dflags
-- | The maximum number of bytes required to spill a register. PPC32
-- has 32-bit GPRs and 64-bit FPRs, while PPC64 has 64-bit GPRs and
-- 64-bit FPRs. So the maximum is 8 regardless of platforms unlike
-- x86. Note that AltiVec's vector registers are 128-bit wide so we
-- must not use this to spill them.
spillSlotSize :: Int
spillSlotSize = 8
-- | The number of spill slots available without allocating more.
maxSpillSlots :: DynFlags -> Int
maxSpillSlots dflags
= ((rESERVED_C_STACK_BYTES dflags - stackFrameHeaderSize dflags)
`div` spillSlotSize) - 1
-- = 0 -- useful for testing allocMoreStack
-- | The number of bytes that the stack pointer should be aligned
-- to. This is 16 both on PPC32 and PPC64 ELF (see ELF processor
-- specific supplements).
stackAlign :: Int
stackAlign = 16
-- | Convert a spill slot number to a *byte* offset, with no sign.
spillSlotToOffset :: DynFlags -> Int -> Int
spillSlotToOffset dflags slot
= stackFrameHeaderSize dflags + spillSlotSize * slot
--------------------------------------------------------------------------------
-- | See if this instruction is telling us the current C stack delta
ppc_takeDeltaInstr
:: Instr
-> Maybe Int
ppc_takeDeltaInstr instr
= case instr of
DELTA i -> Just i
_ -> Nothing
ppc_isMetaInstr
:: Instr
-> Bool
ppc_isMetaInstr instr
= case instr of
COMMENT{} -> True
LDATA{} -> True
NEWBLOCK{} -> True
DELTA{} -> True
_ -> False
-- | Copy the value in a register to another one.
-- Must work for all register classes.
ppc_mkRegRegMoveInstr
:: Reg
-> Reg
-> Instr
ppc_mkRegRegMoveInstr src dst
= MR dst src
-- | Make an unconditional jump instruction.
ppc_mkJumpInstr
:: BlockId
-> [Instr]
ppc_mkJumpInstr id
= [BCC ALWAYS id Nothing]
-- | Take the source and destination from this reg -> reg move instruction
-- or Nothing if it's not one
ppc_takeRegRegMoveInstr :: Instr -> Maybe (Reg,Reg)
ppc_takeRegRegMoveInstr (MR dst src) = Just (src,dst)
ppc_takeRegRegMoveInstr _ = Nothing
-- -----------------------------------------------------------------------------
-- Making far branches
-- Conditional branches on PowerPC are limited to +-32KB; if our Procs get too
-- big, we have to work around this limitation.
makeFarBranches
:: LabelMap RawCmmStatics
-> [NatBasicBlock Instr]
-> [NatBasicBlock Instr]
makeFarBranches info_env blocks
| last blockAddresses < nearLimit = blocks
| otherwise = zipWith handleBlock blockAddresses blocks
where
blockAddresses = scanl (+) 0 $ map blockLen blocks
blockLen (BasicBlock _ instrs) = length instrs
handleBlock addr (BasicBlock id instrs)
= BasicBlock id (zipWith makeFar [addr..] instrs)
makeFar _ (BCC ALWAYS tgt _) = BCC ALWAYS tgt Nothing
makeFar addr (BCC cond tgt p)
| abs (addr - targetAddr) >= nearLimit
= BCCFAR cond tgt p
| otherwise
= BCC cond tgt p
where Just targetAddr = lookupUFM blockAddressMap tgt
makeFar _ other = other
-- 8192 instructions are allowed; let's keep some distance, as
-- we have a few pseudo-insns that are pretty-printed as
-- multiple instructions, and it's just not worth the effort
-- to calculate things exactly
nearLimit = 7000 - mapSize info_env * maxRetInfoTableSizeW
blockAddressMap = listToUFM $ zip (map blockId blocks) blockAddresses
|
sdiehl/ghc
|
compiler/nativeGen/PPC/Instr.hs
|
bsd-3-clause
| 28,364 | 0 | 18 | 9,807 | 7,773 | 4,011 | 3,762 | 496 | 69 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Network.AIS.Vocabulary
(
-- * Identifiers
MMSI(..), MMSIType(..), mmsiType, MID(..), extractMID, toMid, EmergencyDeviceType(..), IMONumber(..), isValidImoNumber
-- * Maritime Information
-- ** Ship Types
, ShipType(..), TypeOfShipAndCargo(..), HazardOrPollutantCategory(..), decodeTypeOfShip, VesselDimensions(..), overallLength, overallBeam
-- ** Aid to Navigation Types
, AidToNavigation(..), isFloatingAtoN, isFixedAtoN
-- ** Navigational Information
, NavigationalStatus(..), SpecialManeuverIndicator(..)
-- *** Position
, Longitude, Latitude
-- *** Length
, LengthDecimeters, LengthNauticalMiles
-- *** Velocity
, Speed(..), VelocityKnots, VelocityTenthsOfKnot
-- *** Time
, TimeMinutes, CalendarTime(..)
-- *** Angles
, AngleDegrees, AngleTenthsOfDegree
-- *** Rate Of Turn
, RateOfTurn(..), PackedRateOfTurn, UnpackedRateOfTurn, unpackRateOfTurn, packRateOfTurn
-- *** Altitude
, Altitude(..)
-- ** Position Fixing Information
, PositionFixingDevice(..), PositionFixingStatus(..), AltitudeSensor(..)
-- * Protocol Information
-- ** Message Types
, MessageID(..)
-- ** Protocol State
, RepeatIndicator, SyncState(..), CommunicationsState(..), SOTDMASubmessage(..)
-- ** Station Metadata
, StationCapabilities(..), classACapabilities, StationClass(..), ClassBCoordinationType(..), StationType(..)
-- ** Transmission Metadata
, Channel(..), channelFrequency, TransmissionMode(..)
-- ** Addressing, Interrogation, and Message Control
, Addressee(..), Region(..), TargetDesignation(..), Interrogation(..), Acknowledgement(..)
, Assignment(..), AssignedReportingInterval(..), Reservation(..), isValidReservation
-- ** Application-Specific Messages
, ApplicationIdentifier(..)
)
where
import qualified Data.ExactPi.TypeLevel as E
import Data.Char (digitToInt)
import Data.Int
import Data.Word
import qualified Numeric.IEEE
import Numeric.Units.Dimensional.FixedPoint
import Numeric.Units.Dimensional.Quantities
import Numeric.Units.Dimensional.SIUnits
import Numeric.Units.Dimensional.Float
import qualified Numeric.Units.Dimensional as D
import Text.Printf
import Prelude hiding ((+), (/), sqrt, (**))
import qualified Prelude as P
-- | A <https://en.wikipedia.org/wiki/Maritime_Mobile_Service_Identity Maritime Mobile Service Identity>.
newtype MMSI = MMSI Word32
deriving (Eq, Ord)
instance Show MMSI where
showsPrec d (MMSI n) = showParen (d > app_prec) showStr
where
showStr = showString $ printf "MMSI %0.9d" n
app_prec = 10 -- precedence of application
-- | Maritime Identification Digits identifying a country or international
-- authority.
newtype MID = MID Word16
deriving (Eq, Ord, Show)
-- | Converts an integer to a 'MID' if it represents a valid 'MID', and to 'Nothing' otherwise.
toMid :: (Ord a, Integral a) => a -> Maybe MID
toMid n | 200 <= n && n <= 799 = Just . MID $ fromIntegral n
| otherwise = Nothing
-- | The type of an 'MMSI'.
--
-- MMSIs with certain leading digits are reserved for certain
-- classes of stations. For some of these classes, the MMSI also
-- includes 'MID' identifying the authority that issues the MMSI.
data MMSIType = MmsiInvalid -- ^ The MMSI is not valid.
| MmsiShipStation MID -- ^ The MMSI belongs to a ship station with the specified 'MID'.
| MmsiGroupShipStation MID -- ^ The MMSI belongs to a group of ship stations with the specified 'MID'.
| MmsiCoastStation MID -- ^ The MMSI belongs to a coast station with the specified 'MID'.
| MmsiSarAircraft MID -- ^ The MMSI belongs to a search-and-rescue aircraft with the specified 'MID'.
| MmsiHandheldStation -- ^ The MMSI belongs to a handheld station.
| MmsiEmergencyDevice EmergencyDeviceType -- ^ The MMSI belongs to an emergency device of the specified type.
| MmsiCraftAssociatedWithParentShip MID -- ^ The MMSI belongs to a craft associated with a parent ship with the specified 'MID'.
| MmsiNavigationalAid MID -- ^ The MMSI belongs to a navigational aid with the specified 'MID'.
deriving (Eq, Ord, Show)
-- | Certain 'MMSIType's include the issuing 'MID'. This function extracts that 'MID' when it exists.
extractMID :: MMSIType -> Maybe MID
extractMID (MmsiShipStation mid) = Just mid
extractMID (MmsiGroupShipStation mid) = Just mid
extractMID (MmsiCoastStation mid) = Just mid
extractMID (MmsiSarAircraft mid) = Just mid
extractMID (MmsiCraftAssociatedWithParentShip mid) = Just mid
extractMID (MmsiNavigationalAid mid) = Just mid
extractMID _ = Nothing
-- | The type of an emergency device.
data EmergencyDeviceType = SarTransponder -- ^ The device is a search-and-rescue transponder.
| MobDevice -- ^ The device is a man overboard device.
| Epirb -- ^ The device is an emergency position-indicating radiobeacon.
deriving (Eq, Ord, Show, Read)
-- | Determines the type of an 'MMSI' using the structure documented in ITU-R M.585-7.
mmsiType :: MMSI -> MMSIType
mmsiType (MMSI n) | n <= 999999999 = case digits n of
(0:0:ds) | Just m <- takeMid ds -> MmsiCoastStation m
(0:ds) | Just m <- takeMid ds -> MmsiGroupShipStation m
(1:1:1:ds) | Just m <- takeMid ds -> MmsiSarAircraft m
(8:_) -> MmsiHandheldStation
(9:7:0:_) -> MmsiEmergencyDevice SarTransponder
(9:7:2:_) -> MmsiEmergencyDevice MobDevice
(9:7:4:_) -> MmsiEmergencyDevice Epirb
(9:8:ds) | Just m <- takeMid ds -> MmsiCraftAssociatedWithParentShip m
(9:9:ds) | Just m <- takeMid ds -> MmsiNavigationalAid m
ds | Just m <- takeMid ds -> MmsiShipStation m
_ -> MmsiInvalid
| otherwise = MmsiInvalid
where
takeMid :: [Int] -> Maybe MID
takeMid (a:b:c:_) = toMid (100 P.* a P.+ 10 P.* b P.+ c)
takeMid _ = Nothing
digits :: Word32 -> [Int]
digits n = digitToInt <$> printf "%0.9d" n
newtype IMONumber = IMO Word32
deriving (Eq, Ord, Show)
isValidImoNumber :: IMONumber -> Bool
isValidImoNumber (IMO n) | n < 1000000 || 9999999 < n = False
| otherwise = n `mod` 10 == (fromIntegral . P.sum $ zipWith (P.*) (digits n) [7,6,5,4,3,2,0])
type RepeatIndicator = Word8
-- | A radio channel across which AIS messages may be conveyed.
data Channel = AisChannelA -- ^ AIS channel A, also known as VHF channel 87B.
| AisChannelB -- ^ AIS channel B, also known as VHF channel 88B.
| ItuRM1084Channel Word16 -- ^ A radio channel number of 25 kHz simplex, or simplex use of 25 kHz duplex,
-- in accordance with <https://www.itu.int/rec/R-REC-M.1084/en Recommendation ITU-R M.1084>.
deriving (Eq, Show, Read)
-- | Gets the radio frequency associated with a radio channel across which AIS messages may be conveyed.
channelFrequency :: Channel -> Maybe (Frequency Rational)
channelFrequency AisChannelA = Just $ 161.975 D.*~ mega hertz
channelFrequency AisChannelB = Just $ 162.025 D.*~ mega hertz
channelFrequency (ItuRM1084Channel n) | 6 == n = Just $ 156.3 D.*~ mega hertz
| 8 <= n && n <= 17 = fromBase 156.4 $ n P.- 8
| 67 <= n && n <= 77 = fromBase 156.375 $ n P.- 67
| 1006 == n = Nothing
| 1008 <= n && n <= 1017 = Nothing
| 1001 <= n && n <= 1028 = fromBase 156.050 $ n P.- 1001
| 1067 <= n && n <= 1077 = Nothing
| 1060 <= n && n <= 1088 = fromBase 156.025 $ n P.- 1060
| 2006 == n = Nothing
| 2008 <= n && n <= 2017 = Nothing
| 2001 <= n && n <= 2028 = fromBase 160.650 $ n P.- 2001
| 2067 <= n && n <= 2077 = Nothing
| 2060 <= n && n <= 2088 = fromBase 160.625 $ n P.- 2060
| otherwise = Nothing
where
fromBase b o = Just $ (b D.*~ mega hertz) D.+ (50 D.*~ kilo hertz) D.* (realToFrac o D.*~ one)
data MessageID = MNone
| MScheduledClassAPositionReport
| MAssignedScheduledClassAPositionReport
| MSpecialClassAPositionReport
| MBaseStationReport
| MStaticAndVoyageData
| MBinaryAddressedMessage
| MBinaryAcknowledgement
| MBinaryBroadcastMessage
| MStandardSarAircraftPositionReport
| MTimeInquiry
| MTimeResponse
| MAddressedSafetyRelatedMessage
| MSafetyRelatedAcknowledgement
| MSafetyRelatedBroadcastMessage
| MInterrogation
| MAssignmentModeCommand
| MDgnssBroadcastBinaryMessage
| MStandardClassBPositionReport
| MExtendedClassBPositionReport
| MDataLinkManagementMessage
| MAidToNavigationReport
| MChannelManagement
| MGroupAssignmentCommand
| MStaticDataReport
| MSingleSlotBinaryMessage
| MMultipleSlotBinaryMessage
| MLongRangePositionReport
deriving (Eq, Enum, Show, Read)
-- | The synchronization state of an AIS station.
data SyncState = SyncUtcDirect -- ^ The station is synchronized directly to UTC. See Section 3.1.1.1.
| SyncUtcIndirect -- ^ The station is synchronized indirectly to UTC, through . See section 3.1.1.2.
| SyncBaseStation -- ^ The station is synchronized to a base station. See section 3.1.1.3.
| SyncPeer -- ^ The station is synchronized to another station based on the highest number of received stations, or to another mobile station which is directly synchronized to a base station. See Sections 3.1.1.3 and 3.1.1.4.
deriving (Eq, Enum, Show, Read)
-- | The navigational status of a vessel
data NavigationalStatus = NavUnderWayEngine -- ^ The vessel is under way using an engine.
| NavAtAnchor -- ^ The vessel is at anchor.
| NavNotUnderCommand -- ^ The vessel is not under command.
| NavRestrictedManeuverability -- ^ The vessel is operating with restricted maneuverability.
| NavConstrainedByDraught -- ^ The vessel's maneuverability is constrained by its draught.
| NavMoored -- ^ The vessel is moored.
| NavAground -- ^ The vessel is aground.
| NavEngagedInFishing -- ^ The vessel is engaged in fishing.
| NavUnderWaySailing -- ^ The vessel is under way sailing.
| NavReservedIMOHazardC -- ^ This navigation status is reserved for future amendment pertaining to ships carrying dangerous goods, harmful substances, marine pollutants, or IMO hazard or pollutant category C.
| NavReservedIMOHazardA -- ^ This navigation status is reserved for future amendment pertaining to ships carrying dangerous goods, harmful substances, marine pollutants, or IMO hazard or pollutant category A.
| NavPowerDrivenVesselTowingAstern -- ^ The vessel is a power-driven vessel towing astern.
| NavPowerDrivenVesselPushingAheadOrTowingAlongside -- ^ The vessel is a power-driven vessel pushing ahead or towing alongside, or is in another navigational status defined by regional use.
| NavReserved
| NavAisSartMobEpirb -- ^ The reporting device is an active AIS SART, MOB device, or EPIRB.
| NavUndefined -- ^ The navigational status of the vessel is unspecified.
deriving (Eq, Enum, Show, Read)
-- | The state of a TDMA communications link.
data CommunicationsState = SOTDMA { syncState :: SyncState
, slotTimeout :: Word8
, submessage :: SOTDMASubmessage } -- ^ The state of an SOTDMA communications link, as specified in Section 3.3.7.2.2.
| ITDMA { syncState :: SyncState
, slotIncrement :: Word16
, numberOfSlots :: Word8
, keep :: Bool } -- ^ The state of an ITDMA communications link, as specified in Section 3.3.7.3.2.
deriving (Eq, Show, Read)
-- | An SOTDMA communications state submessage, as described in Section 3.3.7.2.3.
data SOTDMASubmessage = ReceivedStations Word16 -- ^ The number of other stations (not including the own station) which the station is currently receiving.
| SlotNumber Word16 -- ^ The slot number used for this transmission.
| UTCHourAndMinute Word8 Word8 -- ^ If the transmitting station has access to UTC, the hour and minute of the current UTC time.
| SlotOffset Word16 -- ^ The slot offset to the slot in which transmission from the transmitting station will occur in the next frame. If zero, the slot should be deallocated.
deriving (Eq, Show, Read)
-- | A device for determining the position of an object.
data PositionFixingDevice = PosFixUndefined -- ^ Position fix derived by unspecified means.
| PosFixGps -- ^ Positiion fix derived from the Global Positioning System or GPS.
| PosFixGlonass -- ^ Position fix derived from the Globalnaya Navigazionnaya Sputnikovaya Sistema or GLONASS.
| PosFixGpsGlonass -- ^ Position fix derived by combining both GPS and GLONASS.
| PosFixLoranC -- ^ Position fix derived from the LORAN-C radio navigation system.
| PosFixChayka -- ^ Position fix derived from the Chayka radio navigation system.
| PosFixIntegratedNavigationSystem -- ^ Position fix derived from an integrated navigation system.
| PosFixSurveyed -- ^ Position fix derived by surveying.
| PosFixGalileo -- ^ Position fix derived from the Galileo satellite navigation system.
| PosFixInternalGnss -- ^ Position fix derived from an internal GNSS receiver.
| PosFixReserved
deriving (Eq, Enum, Show, Read)
-- | The status of a position fixing device.
data PositionFixingStatus = PosStatusNormal -- ^ The position fixing device is operating normally.
| PosStatusManual -- ^ The position fixing device is operating in manual input mode.
| PosStatusEstimated -- ^ The position fixing device is operating in estimated or dead reckoning mode.
| PosStatusInoperative -- ^ The position fixing device is inoperative.
deriving (Eq, Enum, Show, Read)
-- | The nature of an aid to navigation.
data AidToNavigation = AidUnspecified -- ^ The type of aid to navigation is unspecified.
| AidReferencePoint -- ^ A reference point for use in navigation or communication.
| AidRacon -- ^ A radar beacon.
| AidFixedOffshoreStructure -- ^ A fixed structure off-shore, such as an oil platform or wind farm.
| AidEmergencyWreckMarkingBuoy -- ^ An emergency wreck marking buoy, generally used to mark the location of a recent and therefore uncharted wreck.
| AidLightWithoutSectors
| AidLightWithSectors
| AidLeadingLightFront
| AidLeadingLightRear
| AidBeaconCardinalN
| AidBeaconCardinalE
| AidBeaconCardinalS
| AidBeaconCardinalW
| AidBeaconPortHand
| AidBeaconStarboardHand
| AidBeaconPreferredChannelPortHand
| AidBeaconPreferredChannelStarboardHand
| AidBeaconIsolatedDanger
| AidBeaconSafeWater
| AidBeaconSpecialMark
| AidCardinalMarkN
| AidCardinalMarkE
| AidCardinalMarkS
| AidCardinalMarkW
| AidPortHandMark
| AidStarboardHandMark
| AidPreferredChannelPortHand
| AidPreferredChannelStarboardHand
| AidIsolatedDanger
| AidSafeWater
| AidSpecialMark
| AidLightVesselLanbyRig -- ^ A light vessel, Large Automated Navigation Buoy, or rig.
deriving (Eq, Enum, Show, Read)
-- | 'True' if an 'AidToNavigation' type denotes a fixed aid to navigation.
isFixedAtoN :: AidToNavigation -> Bool
isFixedAtoN aid = 5 <= x && x <= 19
where
x = fromEnum aid
-- | 'True' if an 'AidToNavigation' type denotes a floating aid to navigation.
isFloatingAtoN :: AidToNavigation -> Bool
isFloatingAtoN aid = 20 <= x
where
x = fromEnum aid
data Altitude = AltNotAvailable
| AltHigh
| AltSpecified (Length Word16)
deriving (Eq, Show)
-- | A means of sensing altitude.
data AltitudeSensor = AltGnss -- ^ Altitude measurement derived from GNSS position fix.
| AltBarometric -- ^ Altitude measurement derived from barometric altimetry.
deriving (Eq, Enum, Show, Read)
-- | An identifier denoting the application format of a binary AIS message.
data ApplicationIdentifier = ApplicationIdentifier { designatedAreaCode :: Word16 -- ^ A code identifying the authority that codified this application.
, functionIdentifier :: Word8 -- ^ An identifier assigned by the authority contolling the 'designatedAreaCode'.
}
deriving (Eq, Show)
-- | An acknowledgement of receipt of a previous AIS message.
data Acknowledgement = Acknowledgement { destinationID :: MMSI -- ^ The 'MMSI' of the station to whom the acknowledgement is addressed.
, acknowledgedSequenceNumber :: Word8 -- ^ The sequence number of the message whose receipt is acknowledged.
}
deriving (Eq, Show)
-- | A request for an AIS station to transmit a specified AIS message during a specified slot.
data Interrogation = Interrogation { interrogatedID :: MMSI -- ^ The 'MMSI' of the interrograted station.
, requestedMessageType :: MessageID -- ^ The type of message requested.
, requestedSlotOffset :: Word16 -- ^ The offset from the current slot at which a reply is requested.
}
deriving (Eq, Show)
-- | The station or stations to whom a message is addressed.
data Addressee = Broadcast -- ^ The message is addressed to all stations.
| Addressed MMSI -- ^ The message is addressed to the specified station or group of ship stations.
deriving (Eq, Show)
data Reservation = Reservation { reservedOffsetNumber :: Word16
, reservedNumberOfSlots :: Word8
, reservationTimeout :: TimeMinutes Word8
, reservationIncrement :: Word16
}
deriving (Eq, Show)
isValidReservation :: Reservation -> Bool
isValidReservation r = reservationTimeout r > _0 && reservedNumberOfSlots r > 0
-- | A classification of AIS stations.
data StationType = StationsAllMobile -- ^ All mobile stations.
| StationsClassAMobile -- ^ All mobile Class A stations.
| StationsClassBMobile -- ^ All mobile Class B stations.
| StationsSarAirborneMobile -- ^ All mobile airborne search and rescue stations.
| StationsClassBSelfOrganizingMobile -- ^ All mobile Class B stations with SOTDMA operating capability.
| StationsClassBCarrierSenseMobile -- ^ All mobile Class B stations limited to CSTDMA operating capability.
| StationsInlandWaterways -- ^ All AIS stations operating on inland waterways.
| StationsRegionalUseA
| StationsRegionalUseB
| StationsRegionalUseC
| StationsReserved
deriving (Eq, Enum, Read, Show)
data SpecialManeuverIndicator = SpecialManeuverNotAvailable
| NotEngagedInSpecialManeuver
| EngagedInSpecialManeuver
| SpecialManeuverReserved
deriving (Eq, Enum, Read, Show)
-- | A transmission mode controlling channel use by an AIS station.
data TransmissionMode = TransmitAB -- ^ Station transmits on both channel A and channel B.
| TransmitA -- ^ Station transmits on channel A only.
| TransmitB -- ^ Station transmits on channel B only.
| TransmitReserved
deriving (Eq, Enum, Read, Show)
data Assignment = Assignment { targetID :: MMSI
, assignedSlotOffset :: Word16
, assignedIncrement :: Word16
}
deriving (Eq, Show)
data TargetDesignation = GeographicTargetDesignation Region
| AddressedTargetDesignation [MMSI]
deriving (Eq, Show)
-- | A quadrangle in an ellipsoidal coordinate system.
data Region = Region { east :: Longitude -- ^ The longitude of the Eastern boundary.
, north :: Latitude -- ^ The latitude of the Northern boundary.
, west :: Longitude -- ^ The longitude of the Western boundary.
, south :: Latitude -- ^ The latitude of the Southern boundary.
}
deriving (Eq, Show)
-- | A reporting interval at which an AIS station is directed to report its position.
data AssignedReportingInterval = IntervalAsAutonomous -- ^ The station should report at the autonomously dervied reporting rate appropriate for its operating condition. See section 4.2.1.
| IntervalTenMinutes -- ^ The station should report at 10 minute intervals.
| Interval6Minutes -- ^ The station should report at 6 minute intervals.
| Interval3Minutes -- ^ The station should report at 3 minute intervals.
| Interval1Minute -- ^ The station should report at 1 minute intervals.
| Interval30Seconds -- ^ The station should report at 30 second intervals.
| Interval15Seconds -- ^ The station should report at 15 second intervals.
| Interval10Seconds -- ^ The station should report at 10 second intervals.
| Interval5Seconds -- ^ The station should report at 5 second intervals.
| IntervalNextShorter -- ^ The station should report at the next shorter reporting interval for its class than its operating conditions would dictate. See section 4.2.1.
| IntervalNextLonger -- ^ The station should report at the next longer reporting interval for its class than its operating conditions would dictate. See section 4.2.1.
| Interval2Seconds -- ^ The station should report at 2 second intervals.
| IntervalReserved
deriving (Eq, Enum, Show, Read)
type TenThousandthOfArcMinute = E.Pi E./ (E.ExactNatural 108000000)
type Longitude = SQuantity TenThousandthOfArcMinute DPlaneAngle Int32
type Latitude = SQuantity TenThousandthOfArcMinute DPlaneAngle Int32
data Speed s a = SpeedNotAvailable
| SpeedHigh
| SpeedSpecified (SQuantity s DVelocity a)
deriving (Eq, Show)
type VelocityTenthsOfKnot = Speed (E.ExactNatural 463 E./ E.ExactNatural 9000) Word16
type VelocityKnots = Speed (E.ExactNatural 463 E./ E.ExactNatural 900) Word16
-- | The rate at which a vessel is changing its heading.
--
-- The type parameter describes the format of measured turn rates.
data RateOfTurn a = RateNotAvailable -- ^ The rate of turn is not available.
| RateStarboardNoSensor -- ^ The vessel is turning to starboard at a rate exceeding 5 degrees per 30 seconds. A measured rate is not available.
| RatePortNoSensor -- ^ The vessel is turning to port at a rate exceeding 5 degrees per 30 seconds. A measured rate is not available.
| RateSpecified a -- ^ The vessel is turning at a specified rate. Negative values specify turns to port, positive values specify turns to starboard.
deriving (Eq)
-- | The rate at which a vessel is changing its heading, with measured rates represented in a compact
-- non-linear transmission format specified in Table 48.
type PackedRateOfTurn = RateOfTurn Word8
-- | The rate at which a vessel is changing its heading, with measured rates represented
-- in floating-point 'AngularVelocity' format.
type UnpackedRateOfTurn = RateOfTurn (AngularVelocity Double)
-- | Converts a 'RateOfTurn' from the compact 'PackedRateOfTurn' format used in AIS messages
-- to the linear and convenient 'UnpackedRateOfTurn' format.
unpackRateOfTurn :: PackedRateOfTurn -> UnpackedRateOfTurn
unpackRateOfTurn RateNotAvailable = RateNotAvailable
unpackRateOfTurn RateStarboardNoSensor = RateStarboardNoSensor
unpackRateOfTurn RatePortNoSensor = RatePortNoSensor
unpackRateOfTurn (RateSpecified r) = RateSpecified r''
where
s = (realToFrac $ signum r) D.*~ (degree / minute)
r' = (realToFrac r P./ 4.733) P.** 2 D.*~ (degree / minute)
r'' = copySign r' s
-- | Converts a 'RateOfTurn' from the linear and convenient 'UnpackedRateOfTurn' format
-- to the compact 'PackedRateOfTurn' format used in AIS messages.
packRateOfTurn :: UnpackedRateOfTurn -> PackedRateOfTurn
packRateOfTurn RateNotAvailable = RateNotAvailable
packRateOfTurn RateStarboardNoSensor = RateStarboardNoSensor
packRateOfTurn RatePortNoSensor = RatePortNoSensor
packRateOfTurn (RateSpecified r) = RateSpecified r''''
where
dpm = r D./~ (degree / minute)
s = signum dpm
r' = 4.733 P.* P.sqrt (P.abs dpm)
r'' = Numeric.IEEE.copySign r' s
r''' = round r'' :: Int
r'''' = fromIntegral $ max (-126) $ min 126 r'''
instance Show PackedRateOfTurn where
showsPrec _ RateNotAvailable = showString "RateNotAvailable"
showsPrec _ RateStarboardNoSensor = showString "RateStarboardNoSensor"
showsPrec _ RatePortNoSensor = showString "RatePortNoSensor"
showsPrec d r@(RateSpecified raw) = showParen (d > app_prec) showStr
where
showStr = showString "RateSpecified " . shows raw . showString " {- " . shows r' . showString " -}"
app_prec = 10 -- precedence of application
(RateSpecified r') = unpackRateOfTurn r
deriving instance Show UnpackedRateOfTurn
type Direction n a = SQuantity ((E.ExactNatural 2 E.* E.Pi) E./ E.ExactNatural n) DPlaneAngle a
type AngleTenthsOfDegree = Direction 3600 Word16
type AngleDegrees = Direction 360 Word16
type LengthNauticalMiles a = SQuantity (E.ExactNatural 1852) DLength a
type TimeMinutes a = SQuantity (E.ExactNatural 60) DTime a
-- | A time expressed as a month, day, hour, and minute where each item is optional.
data CalendarTime = CalendarTime { calMonth :: Maybe Word8
, calDay :: Maybe Word8
, calHour :: Maybe Word8
, calMinute :: Maybe Word8 }
deriving (Eq, Show)
type LengthDecimeters a = SQuantity (E.One E./ E.ExactNatural 10) DLength a
data VesselDimensions = VesselDimensions { forwardOfReferencePoint :: Length Word16
, aftOfReferencePoint :: Length Word16
, portOfReferencePoint :: Length Word8
, starboardOfReferencePoint :: Length Word8
}
deriving (Eq, Show)
-- | Gets the overall length of a vessel from its 'VesselDimensions'.
overallLength :: VesselDimensions -> Length Word16
overallLength dims = forwardOfReferencePoint dims + aftOfReferencePoint dims
-- | Gets the overall beam (width) of a vessel from its 'VesselDimensions'.
overallBeam :: VesselDimensions -> Length Word8
overallBeam dims = portOfReferencePoint dims + starboardOfReferencePoint dims
-- | The class of an AIS mobile station.
data StationClass = ClassA -- ^ A Class A station.
| ClassB (ClassBCoordinationType) -- ^ A Class B station of the specified 'CoordinationType'.
deriving (Eq, Ord, Show, Read)
-- | The coordination type of an AIS mobile station.
data ClassBCoordinationType = SelfOrganizing -- ^ The station is capable of participating in the SOTDMA access scheme.
| CarrierSensing -- ^ The station uses the CSTDMA access scheme.
deriving (Eq, Ord, Show, Read)
data StationCapabilities = StationCapabilities { stationClass :: StationClass
, equippedWithDisplay :: Bool
, equippedWithDigitalSelectiveCalling :: Bool
, capableOfOperatingOverEntireMarineBand :: Bool
, supportsChannelManagement :: Bool
}
deriving (Eq, Show, Read)
classACapabilities :: StationCapabilities
classACapabilities = StationCapabilities { stationClass = ClassA
, equippedWithDisplay = True
, equippedWithDigitalSelectiveCalling = True
, capableOfOperatingOverEntireMarineBand = True
, supportsChannelManagement = True
}
-- | A type of ship and cargo.
newtype TypeOfShipAndCargo = TypeOfShipAndCargo Word8
deriving (Eq, Ord)
instance Show TypeOfShipAndCargo where
show t@(TypeOfShipAndCargo n) = printf "TypeOfShipAndCargo %0.2d" n ++ showDecode (decodeTypeOfShip t)
where
showDecode (Nothing, _) = ""
showDecode (Just t', Nothing) = " {- " ++ show t' ++ " -}"
showDecode (Just t', Just h) = " {- " ++ show t' ++ " carrying " ++ show h ++ " -}"
-- | Decodes a 'TypeOfShipAndCargo' by splitting it into possibly a 'ShipType' and possibly
-- a 'HazardOrPollutantCategory'. Reserved codes are decoded to 'Nothing'.
decodeTypeOfShip :: TypeOfShipAndCargo -> (Maybe ShipType, Maybe HazardOrPollutantCategory)
decodeTypeOfShip (TypeOfShipAndCargo n) = decode n
where
decode 30 = simple FishingVessel
decode 31 = simple TowingVessel
decode 32 = simple TowingVessel
decode 33 = simple DredgingOrUnderwaterOperationsVessel
decode 34 = simple DivingVessel
decode 35 = simple MilitaryVessel
decode 36 = simple SailingVessel
decode 37 = simple PleasureCraft
decode 50 = simple PilotVessel
decode 51 = simple SearchAndRescueVessel
decode 52 = simple Tug
decode 53 = simple PortTender
decode 54 = simple AntiPollutionVessel
decode 55 = simple LawEnforcementVessel
decode 58 = simple MedicalTransport
decode 59 = simple NonPartyToArmedConflict
decode n' | 20 <= n' && n' <= 29 = category WingInGroundEffect
| 40 <= n' && n' <= 49 = category HighSpeedCraft
| 60 <= n' && n' <= 69 = category PassengerShip
| 70 <= n' && n' <= 79 = category CargoShip
| 80 <= n' && n' <= 89 = category Tanker
| otherwise = (Nothing, Nothing)
category t = (Just t, hazard)
simple t = (Just t, Nothing)
hazard = hazard' (n `mod` 10)
hazard' 1 = Just HazardX
hazard' 2 = Just HazardY
hazard' 3 = Just HazardZ
hazard' 4 = Just HazardOS
hazard' _ = Nothing
-- | An IMO Hazard or Pollutant Category.
data HazardOrPollutantCategory = HazardX -- ^ IMO Hazard or Pollutant Category X
| HazardY -- ^ IMO Hazard or Pollutant Category Y
| HazardZ -- ^ IMO Hazard or Pollutant Category Z
| HazardOS -- ^ IMO Hazard or Pollutant Category OS
deriving (Eq, Ord, Enum, Show, Read)
-- | A type of ship.
data ShipType = PilotVessel
| SearchAndRescueVessel
| Tug
| PortTender
| AntiPollutionVessel
| LawEnforcementVessel
| MedicalTransport
| NonPartyToArmedConflict
| FishingVessel
| TowingVessel
| DredgingOrUnderwaterOperationsVessel
| DivingVessel
| MilitaryVessel
| SailingVessel
| PleasureCraft
| WingInGroundEffect
| HighSpeedCraft
| PassengerShip
| CargoShip
| Tanker
deriving (Eq, Ord, Show, Read)
|
dmcclean/ais
|
src/Network/AIS/Vocabulary.hs
|
bsd-3-clause
| 34,249 | 1 | 13 | 10,761 | 5,132 | 2,893 | 2,239 | -1 | -1 |
data X = X { foo :: Int,
bar :: String,
} deriving (Eq, Show, Ord)
f x = x
|
itchyny/vim-haskell-indent
|
test/recordtype/after_deriving_parenthesis.in.hs
|
mit
| 75 | 1 | 8 | 20 | 47 | 26 | 21 | -1 | -1 |
module Fuml.Optimisation.SGD where
import Numeric.LinearAlgebra
import Data.Random
data SGDOpts = SGDOpts
{ learning_rate :: Double
, batch_size :: Int
, epochs :: Int
}
sgdBatch :: SGDOpts -> (Vector Double -> Vector Double) -> Vector Double -> Vector Double
sgdBatch opts grad p = p - scale (learning_rate opts) (grad p)
sgdEpoch :: SGDOpts -> ([a] -> Vector Double -> Vector Double) -> [a] -> Vector Double -> RVar (Vector Double)
sgdEpoch opts grad pts' p' = do
pts <- shuffle pts'
return $ go p' $ inGroupsOf (batch_size opts) pts
where go p [] = p
go p (batch:bs) = go (sgdBatch opts (grad batch) p) bs
inGroupsOf :: Int -> [a] -> [[a]]
inGroupsOf _ [] = []
inGroupsOf n xs = let (these,those) = splitAt n xs
in these : inGroupsOf n those
|
diffusionkinetics/open
|
fuml/lib/Fuml/Optimisation/SGD.hs
|
mit
| 794 | 0 | 11 | 185 | 348 | 177 | 171 | 19 | 2 |
{- |
Module : ./CASL/CompositionTable/ToXml.hs
Description : XML output for composition tables of qualitative calculi
Copyright : (c) Uni Bremen 2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (FlexibleInstances via xml package)
XML output for composition tables
-}
module CASL.CompositionTable.ToXml (tableXmlStr) where
{-
DTD see systemURI
-- hets -v2 -n RCC8CompositionTable -o comptable.xml Calculi/Space/RCC8.het
-- writes Calculi/Space/RCC8_RCC8CompositionTable.comptable.xml
eliminate ops on rhs, resulting in list of base relations
add equations for id
-}
import CASL.CompositionTable.CompositionTable
import Text.XML.Light
-- Using xml it is not very easy to just add a DOCTYPE node
-- Public identifier (suggestion)
publicId :: String
publicId = "-//CoFI//DTD CompositionTable 1.1//EN"
-- System URI
systemURI :: String
systemURI =
"http://www.informatik.uni-bremen.de/cofi/hets/CompositionTable.dtd"
tableProlog :: [String]
tableProlog =
[ "<?xml version='1.0absd' encoding='UTF-8' ?>"
, "<!DOCTYPE table PUBLIC " ++ shows publicId " "
++ shows systemURI ">" ]
-- this function renders a Table as xml string
tableXmlStr :: Table -> String
tableXmlStr t = unlines $ tableProlog ++ lines (ppElement $ table2Elem t)
table2Elem :: Table -> Element
table2Elem (Table as a b (Reflectiontable _) c) =
add_attrs (tabAttr2Attrs as)
$ unode "table" $ compTable2Elem a : conTable2Elems b ++ [models2Elem c]
toAttrFrStr :: String -> String -> Attr
toAttrFrStr = Attr . unqual
tabAttr2Attrs :: Table_Attrs -> [Attr]
tabAttr2Attrs v =
[ toAttrFrStr "name" $ tableName v
, toAttrFrStr "identity" $ baserelBaserel $ tableIdentity v ]
compTable2Elem :: Compositiontable -> Element
compTable2Elem (Compositiontable a) =
unode "compositiontable" $ map cmpEntry2Elem a
cmpEntry2Elem :: Cmptabentry -> Element
cmpEntry2Elem (Cmptabentry as a) =
add_attrs (cmpEntryAttrs2Attrs as)
$ unode "cmptabentry" $ map baserel2Elem a
cmpEntryAttrs2Attrs :: Cmptabentry_Attrs -> [Attr]
cmpEntryAttrs2Attrs (Cmptabentry_Attrs b1 b2) =
[ toAttrFrStr "argBaserel1" $ baserelBaserel b1
, toAttrFrStr "argBaserel2" $ baserelBaserel b2 ]
baserel2Elem :: Baserel -> Element
baserel2Elem = unode "baserel" . baserel2Attr
baserel2Attr :: Baserel -> Attr
baserel2Attr = toAttrFrStr "baserel" . baserelBaserel
conTable2Elems :: Conversetable -> [Element]
conTable2Elems ct = case ct of
Conversetable a ->
[unode "conversetable" $ concatMap (\ (Contabentry b cs)
-> map (\ c -> conEntry2Elem $ Contabentry b [c]) cs) a]
_ -> []
conEntry2Elem :: Contabentry -> Element
conEntry2Elem c@(Contabentry _ cs) =
add_attrs (conEntry2Attrs c) . unode "contabentry" $ case cs of
[_] -> []
_ -> map (unode "converseBaseRel" . baserelBaserel) cs
conEntry2Attrs :: Contabentry -> [Attr]
conEntry2Attrs (Contabentry a cs) =
toAttrFrStr "argBaseRel" (baserelBaserel a)
: case cs of
[c] -> [ toAttrFrStr "converseBaseRel" $ baserelBaserel c ]
_ -> []
models2Elem :: Models -> Element
models2Elem (Models a) = unode "models" $ map model2Elem a
model2Elem :: Model -> Element
model2Elem = unode "model" . model2Attrs
model2Attrs :: Model -> [Attr]
model2Attrs (Model s1 s2) =
[ toAttrFrStr "string1" s1
, toAttrFrStr "string2" s2 ]
|
spechub/Hets
|
CASL/CompositionTable/ToXml.hs
|
gpl-2.0
| 3,401 | 0 | 18 | 585 | 813 | 419 | 394 | 65 | 2 |
{-#LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
module Carnap.Languages.ModalFirstOrder.Logic.Hardegree
(hardegreeMPLCalc,parseHardegreeMPL)
where
import Text.Parsec
import qualified Data.Map as M
import Carnap.Core.Data.Types (Form)
import Carnap.Languages.PurePropositional.Syntax
import Carnap.Languages.ModalFirstOrder.Syntax
import Carnap.Languages.ModalFirstOrder.Parser
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Parser
import Carnap.Calculi.NaturalDeduction.Checker (hoProcessLineHardegreeMemo, hoProcessLineHardegree)
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.Util.LanguageClasses
import Carnap.Languages.Util.GenericConstructors
import Carnap.Languages.PureFirstOrder.Logic.Rules
import Carnap.Languages.ModalFirstOrder.Logic.Rules
import Carnap.Languages.ModalPropositional.Logic.Hardegree
data HardegreeMPLOver a = ModalProp a | UI | UE | EI | EE
| QN1 | QN2 | QN3 | QN4
| NUO | NEO
deriving Eq
instance Show a => Show (HardegreeMPLOver a) where
show (ModalProp x) = show x
show UI = "UD"
show UE = "∀O"
show EI = "∃I"
show EE = "∃O"
show QN1 = "QN"
show QN2 = "QN"
show QN3 = "QN"
show QN4 = "QN"
show NUO = "~∀O"
show NEO = "~∃O"
type HardegreeMPL = HardegreeMPLOver HardegreeK
instance Inference HardegreeMPL IndexedModalFirstOrderLex (Form Bool) where
ruleOf UI = liftAbsRule $ universalGeneralization
ruleOf UE = liftAbsRule $ universalInstantiation
ruleOf EI = liftAbsRule $ existentialGeneralization
ruleOf EE = liftAbsRule $ existentialInstantiation
ruleOf QN1 = liftAbsRule $ quantifierNegation !! 0
ruleOf QN2 = liftAbsRule $ quantifierNegation !! 1
ruleOf QN3 = liftAbsRule $ quantifierNegation !! 2
ruleOf QN4 = liftAbsRule $ quantifierNegation !! 3
ruleOf NUO = liftAbsRule $ negatedUniversalInstantiation
ruleOf NEO = liftAbsRule $ negatedExistentialInstantiation
premisesOf (ModalProp x) = map liftSequent (premisesOf x)
premisesOf r = upperSequents (ruleOf r)
conclusionOf (ModalProp x) = liftSequent (conclusionOf x)
conclusionOf r = lowerSequent (ruleOf r)
indirectInference (ModalProp x) = indirectInference x
indirectInference UI = Just (TypedProof (ProofType 0 1))
indirectInference _ = Nothing
globalRestriction (Left ded) n UE = Just (globalOldConstraint [tau] (Left ded) n )
globalRestriction (Left ded) n EE = Just (globalNewConstraint [tau] (Left ded) n )
globalRestriction (Left ded) n NEO = Just (globalOldConstraint [tau] (Left ded) n )
globalRestriction (Left ded) n NUO = Just (globalNewConstraint [tau] (Left ded) n )
--XXX: Would be nice to avoid this boilerplate, via some way of
--lifting global constraints
globalRestriction (Left ded) n (ModalProp (RelK DiaD1)) = Just (globalNewIdxConstraint [someWorld `indexcons` someOtherWorld] (Left ded) n )
globalRestriction (Left ded) n (ModalProp (RelK DiaD2)) = Just (globalNewIdxConstraint [someWorld `indexcons` someOtherWorld] (Left ded) n )
globalRestriction (Left ded) n (ModalProp (RelK DiaOut)) = Just (globalNewIdxConstraint [someWorld `indexcons` someOtherWorld] (Left ded) n )
globalRestriction (Left ded) n (ModalProp (RelK ND)) = Just (globalNewIdxConstraint [someWorld `indexcons` someOtherWorld] (Left ded) n )
globalRestriction (Left ded) n (ModalProp (RelK DiaIn)) = Just (globalOldIdxConstraint [someWorld `indexcons` someOtherWorld] (Left ded) n )
globalRestriction (Left ded) n (ModalProp (RelK BoxOut)) = Just (globalOldIdxConstraint [someWorld `indexcons` someOtherWorld] (Left ded) n )
globalRestriction (Left ded) n (ModalProp (RelK (MoPL FalO))) = Just (globalOldIdxConstraint [someOtherWorld,someWorld] (Left ded) n )
globalRestriction (Left ded) n (ModalProp (RelK (MoPL FalI))) = Just (globalOldIdxConstraint [someOtherWorld,someWorld] (Left ded) n )
globalRestriction (Left ded) n x = case indirectInference x of
Nothing -> Just (globalOldIdxConstraint [someWorld] (Left ded) n)
_ -> Nothing
globalRestriction _ _ _ = Nothing
isAssumption (ModalProp x) = isAssumption x
isAssumption _ = False
parseHardegreeMPL ders = try liftK <|> quantRule
where liftK = do r <- parseHardegreeK
return (map ModalProp r)
quantRule = do r <- choice (map (try . string) ["∀I", "AI","UD", "∀O", "AO", "∃I", "EI"
, "∃O", "EO", "~∃O","-∃O" ,"-EO"
, "~EO","~∀O","~AO","-∀O","-AO" ])
case r of
r | r `elem` ["∀I","AI","UD"] -> return [UI]
| r `elem` ["∀O","AO"] -> return [UE]
| r `elem` ["∃I","EI"] -> return [EI]
| r `elem` ["∃O","EO"] -> return [EE]
| r `elem` ["~∃O","-∃O" ,"-EO", "~EO"] -> return [NEO]
| r `elem` ["~∀O","~AO","-∀O","-AO"] -> return [NUO]
parseHardegreeMPLProof :: RuntimeNaturalDeductionConfig IndexedModalFirstOrderLex (Form Bool) -> String
-> [DeductionLine HardegreeMPL IndexedModalFirstOrderLex (Form Bool)]
parseHardegreeMPLProof ders = toDeductionHardegree (parseHardegreeMPL ders) (hardegreeMPLFormulaParser)
hardegreeMPLCalc = mkNDCalc
{ ndRenderer = MontagueStyle
, ndParseProof = parseHardegreeMPLProof
, ndProcessLine = hoProcessLineHardegree
, ndProcessLineMemo = Just hoProcessLineHardegreeMemo
, ndParseSeq = indexedModalFOSeqParser
}
|
opentower/carnap
|
Carnap/src/Carnap/Languages/ModalFirstOrder/Logic/Hardegree.hs
|
gpl-3.0
| 6,233 | 0 | 16 | 1,749 | 1,735 | 929 | 806 | 93 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
-- Module : Khan.Model.Ansible
-- Copyright : (c) 2013 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Khan.Model.Ansible
(
-- * Idempotence predicate
Changed
-- * Capturing ansible output
, capture
-- * JSON output formatters
, ImageInput (..)
, Inv (..)
, Host (..)
-- * Inventory
, inventoryPath
-- * CLI arguments
, (+$+)
, overrides
) where
import Control.Monad.Except
import qualified Data.Aeson.Encode.Pretty as Aeson
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.List (intercalate)
import qualified Data.Text as Text
import Data.Text.Format
import Data.Text.Format.Params
import qualified Filesystem.Path.CurrentOS as Path
import Khan.Internal.AWS
import Khan.Internal.Options
import Khan.Internal.Types
import Khan.Model.Ansible.Serialisation
import Khan.Prelude
import Network.AWS
import System.Exit
class Changed a where
changed :: a -> Bool
instance Changed Bool where
changed = id
instance Changed (Modified a) where
changed (Changed _) = True
changed (Unchanged _) = False
capture :: (Params ps, Changed a)
=> Bool
-> Common
-> Format
-> ps
-> AWS a
-> AWS ()
capture ansible c f ps aws = contextAWS c (aws >>= success . changed)
>>= either failure return
>>= exit
where
success True = changed' (f <> " changed.") ps
success False = unchanged (f <> " unchanged.") ps
failure (Err s) = failed "{}" $ Only s
failure (Ex ex) = failure . toError $ show ex
failure (Ers es) = failure . toError . intercalate ", " $ map show es
exit o = liftIO $ do
when ansible $ LBS.putStrLn (Aeson.encodePretty o)
case o of
Fail _ -> exitFailure
NoChange _ | not ansible -> exitWith (ExitFailure 69)
_ -> exitSuccess
changed' g = return . Change . format g
unchanged g = return . NoChange . format g
failed g = return . Fail . format g
inventoryPath :: CacheDir -> Env -> AWS FilePath
inventoryPath (CacheDir dir) env = do
r <- Text.pack . show <$> getRegion
return $ dir </> Path.fromText (Text.concat [r, "_", _env env])
overrides :: Naming a => a -> [String] -> [String]
overrides (names -> n) = (+$+ [("--extra-vars", Text.unpack quoted)])
where
quoted = "'" <> Text.intercalate " " vars <> "'"
vars = map (\(k, v) -> k <> "=" <> v) (extraVars n)
(+$+) :: [String] -> [(String, String)] -> [String]
(+$+) args extras = args ++ foldr' add [] extras
where
add (k, v) xs =
if k `elem` args
then xs
else k : v : xs
|
zinfra/khan
|
khan/src/Khan/Model/Ansible.hs
|
mpl-2.0
| 3,487 | 0 | 16 | 1,093 | 904 | 496 | 408 | 76 | 6 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="el-GR">
<title>Forced Browse Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Ευρετήριο</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Αναζήτηση</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/bruteforce/src/main/javahelp/org/zaproxy/zap/extension/bruteforce/resources/help_el_GR/helpset_el_GR.hs
|
apache-2.0
| 991 | 79 | 67 | 158 | 449 | 226 | 223 | -1 | -1 |
{- |
Module : Data.DRS.Input
Copyright : (c) Harm Brouwer and Noortje Venhuizen
License : Apache-2.0
Maintainer : [email protected], [email protected]
Stability : provisional
Portability : portable
DRS input
-}
module Data.DRS.Input
(
module Input
) where
import Data.DRS.Input.Boxer as Input
import Data.DRS.Input.String as Input
|
hbrouwer/pdrt-sandbox
|
src/Data/DRS/Input.hs
|
apache-2.0
| 357 | 0 | 4 | 70 | 32 | 24 | 8 | 5 | 0 |
module BrowseSpec where
import Control.Applicative
import Language.Haskell.GhcMod
import Test.Hspec
import TestUtils
import Dir
spec :: Spec
spec = do
describe "browse Data.Map" $ do
it "contains at least `differenceWithKey'" $ do
syms <- runD $ lines <$> browse "Data.Map"
syms `shouldContain` ["differenceWithKey"]
describe "browse -d Data.Either" $ do
it "contains functions (e.g. `either') including their type signature" $ do
syms <- run defaultOptions { detailed = True }
$ lines <$> browse "Data.Either"
syms `shouldContain` ["either :: (a -> c) -> (b -> c) -> Either a b -> c"]
it "contains type constructors (e.g. `Left') including their type signature" $ do
syms <- run defaultOptions { detailed = True}
$ lines <$> browse "Data.Either"
syms `shouldContain` ["Left :: a -> Either a b"]
describe "`browse' in a project directory" $ do
it "lists symbols defined in a a local module (e.g. `Baz.baz)" $ do
withDirectory_ "test/data" $ do
syms <- runID $ lines <$> browse "Baz"
syms `shouldContain` ["baz"]
|
cabrera/ghc-mod
|
test/BrowseSpec.hs
|
bsd-3-clause
| 1,218 | 0 | 18 | 366 | 258 | 127 | 131 | 26 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Reflex.Plan.Pure where
import Reflex
import Reflex.Pure
import Reflex.TestPlan
import Control.Applicative
import Control.Monad.Fix
import Control.Monad.State
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.Bifunctor
import Data.Maybe
import Data.Monoid
import Prelude
mapToPureEvent :: IntMap a -> Event (Pure Int) a
mapToPureEvent m = Event $ flip IntMap.lookup m
type TimeM = (->) Int
newtype PurePlan a = PurePlan { unPlan :: StateT IntSet TimeM a } deriving (Functor, Applicative, Monad, MonadFix)
liftPlan :: TimeM a -> PurePlan a
liftPlan = PurePlan . lift
instance MonadHold (Pure Int) PurePlan where
hold initial = liftPlan . hold initial
holdDyn initial = liftPlan . holdDyn initial
holdIncremental initial = liftPlan . holdIncremental initial
buildDynamic getInitial = liftPlan . buildDynamic getInitial
headE = liftPlan . headE
now = liftPlan now
instance MonadSample (Pure Int) PurePlan where
sample = liftPlan . sample
instance TestPlan (Pure Int) PurePlan where
plan occs = do
PurePlan . modify $ IntSet.union (IntMap.keysSet m)
return $ mapToPureEvent m
where m = IntMap.fromList (first fromIntegral <$> occs)
runPure :: PurePlan a -> (a, IntSet)
runPure (PurePlan p) = runStateT p mempty $ 0
relevantTimes :: IntSet -> IntSet
relevantTimes occs = IntSet.fromList [0..l + 1]
where l = fromMaybe 0 (fst <$> IntSet.maxView occs)
testBehavior :: (Behavior (Pure Int) a, IntSet) -> IntMap a
testBehavior (b, occs) = IntMap.fromSet (sample b) (relevantTimes occs)
testEvent :: (Event (Pure Int) a, IntSet) -> IntMap (Maybe a)
testEvent (Event readEvent, occs) = IntMap.fromSet readEvent (relevantTimes occs)
|
ryantrinkle/reflex
|
test/Reflex/Plan/Pure.hs
|
bsd-3-clause
| 2,018 | 0 | 12 | 333 | 637 | 338 | 299 | 51 | 1 |
module IHaskell.Publish (publishResult) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import IHaskell.Display
import IHaskell.Types
import IHaskell.CSS (ihaskellCSS)
-- | Publish evaluation results, ignore any CommMsgs. This function can be used to create a function
-- of type (EvaluationResult -> IO ()), which can be used to publish results to the frontend. The
-- resultant function shares some state between different calls by storing it inside the MVars
-- passed while creating it using this function. Pager output is accumulated in the MVar passed for
-- this purpose if a pager is being used (indicated by an argument), and sent to the frontend
-- otherwise.
publishResult :: (Message -> IO ()) -- ^ A function to send messages
-> MessageHeader -- ^ Message header to use for reply
-> MVar [Display] -- ^ A MVar to use for displays
-> MVar Bool -- ^ A mutable boolean to decide whether the output need to be cleared and
-- redrawn
-> MVar [DisplayData] -- ^ A MVar to use for storing pager output
-> Bool -- ^ Whether to use the pager
-> EvaluationResult -- ^ The evaluation result
-> IO ()
publishResult send replyHeader displayed updateNeeded pagerOutput usePager result = do
let final =
case result of
IntermediateResult{} -> False
FinalResult{} -> True
outs = outputs result
-- If necessary, clear all previous output and redraw.
clear <- readMVar updateNeeded
when clear $ do
clearOutput
disps <- readMVar displayed
mapM_ sendOutput $ reverse disps
-- Draw this message.
sendOutput outs
-- If this is the final message, add it to the list of completed messages. If it isn't, make sure we
-- clear it later by marking update needed as true.
modifyMVar_ updateNeeded (const $ return $ not final)
when final $ do
modifyMVar_ displayed (return . (outs :))
-- If this has some pager output, store it for later.
let pager = pagerOut result
unless (null pager) $
if usePager
then modifyMVar_ pagerOutput (return . (++ pager))
else sendOutput $ Display pager
where
clearOutput = do
header <- dupHeader replyHeader ClearOutputMessage
send $ ClearOutput header True
sendOutput (ManyDisplay manyOuts) = mapM_ sendOutput manyOuts
sendOutput (Display outs) = do
header <- dupHeader replyHeader DisplayDataMessage
send $ PublishDisplayData header "haskell" $ map (convertSvgToHtml . prependCss) outs
convertSvgToHtml (DisplayData MimeSvg svg) = html $ makeSvgImg $ base64 $ E.encodeUtf8 svg
convertSvgToHtml x = x
makeSvgImg :: Base64 -> String
makeSvgImg base64data = T.unpack $ "<img src=\"data:image/svg+xml;base64," <>
base64data <>
"\"/>"
prependCss (DisplayData MimeHtml html) =
DisplayData MimeHtml $ mconcat ["<style>", T.pack ihaskellCSS, "</style>", html]
prependCss x = x
|
thomasjm/IHaskell
|
src/IHaskell/Publish.hs
|
mit
| 3,217 | 0 | 15 | 909 | 585 | 298 | 287 | 51 | 6 |
{-|
Module : Idris.Info
Description : Get information about Idris.
Copyright : 2016 The Idris Community
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.Info
( getIdrisDataDir
, getIdrisCRTSDir
, getIdrisJSRTSDir
, getIdrisLibDir
, getIdrisDocDir
, getIdrisFlagsLib
, getIdrisFlagsInc
, getIdrisFlagsEnv
, getIdrisCC
, getIdrisVersion
, getIdrisVersionNoGit
, getIdrisUserDataDir
, getIdrisInitScript
, getIdrisHistoryFile
, getIdrisInstalledPackages
, getIdrisLoggingCategories
, getIdrisDataFileByName
) where
import Idris.Imports (installedPackages)
import Idris.Options (loggingCatsStr)
import qualified IRTS.System as S
import Paths_idris
import Version_idris (gitHash)
import Data.Version
import System.Directory
import System.FilePath
getIdrisDataDir :: IO String
getIdrisDataDir = S.getIdrisDataDir
getIdrisCRTSDir :: IO String
getIdrisCRTSDir = S.getIdrisCRTSDir
getIdrisJSRTSDir :: IO String
getIdrisJSRTSDir = S.getIdrisJSRTSDir
getIdrisDocDir :: IO String
getIdrisDocDir = S.getIdrisDocDir
getIdrisLibDir :: IO String
getIdrisLibDir = S.getIdrisLibDir
getIdrisFlagsLib :: IO [String]
getIdrisFlagsLib = S.getLibFlags
getIdrisFlagsInc :: IO [String]
getIdrisFlagsInc = S.getIncFlags
getIdrisFlagsEnv :: IO [String]
getIdrisFlagsEnv = S.getEnvFlags
getIdrisCC :: IO String
getIdrisCC = S.getCC
getIdrisVersion = showVersion S.version ++ suffix
where
suffix = if gitHash =="" then "" else "-" ++ gitHash
getIdrisVersionNoGit = S.version
-- | Get the platform-specific, user-specific Idris dir
getIdrisUserDataDir :: IO FilePath
getIdrisUserDataDir = getAppUserDataDirectory "idris"
-- | Locate the platform-specific location for the init script
getIdrisInitScript :: IO FilePath
getIdrisInitScript = do
idrisDir <- getIdrisUserDataDir
return $ idrisDir </> "repl" </> "init"
getIdrisHistoryFile :: IO FilePath
getIdrisHistoryFile = do
udir <- getIdrisUserDataDir
return (udir </> "repl" </> "history")
getIdrisInstalledPackages :: IO [String]
getIdrisInstalledPackages = installedPackages
getIdrisLoggingCategories :: IO [String]
getIdrisLoggingCategories = return $ words loggingCatsStr
getIdrisDataFileByName :: String -> IO FilePath
getIdrisDataFileByName = S.getIdrisDataFileByName
|
Heather/Idris-dev
|
src/Idris/Info.hs
|
bsd-3-clause
| 2,294 | 0 | 10 | 337 | 450 | 252 | 198 | 63 | 2 |
module Turbinado.Utility.General where
import Data.List
import Data.Maybe
--
-- * Utility.General
--
-- | Replaces all instances of a value in a list by another value.
replace :: Eq a =>
a -- ^ Value to look for
-> a -- ^ Value to replace it with
-> [a] -- ^ Input list
-> [a] -- ^ Output list
replace x y = map (\z -> if z == x then y else z)
maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . reads
-- | Same as 'lookup' specialized to strings, but
-- returns the empty string if lookup fails.
lookupOrNil :: String -> [(String,String)] -> String
lookupOrNil n = fromMaybe "" . lookup n
each :: [a] -> (a -> b) -> [b]
each l f = map f l
|
abuiles/turbinado-blog
|
Turbinado/Utility/General.hs
|
bsd-3-clause
| 714 | 0 | 9 | 187 | 206 | 115 | 91 | 15 | 2 |
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, MultiParamTypeClasses, OverloadedStrings #-}
module YesodCoreTest.Redirect
( specs
, Widget
, resourcesY
) where
import YesodCoreTest.YesodTest
import Yesod.Core.Handler (redirectWith, setEtag, setWeakEtag)
import qualified Network.HTTP.Types as H
data Y = Y
mkYesod "Y" [parseRoutes|
/ RootR GET POST
/r301 R301 GET
/r303 R303 GET
/r307 R307 GET
/rregular RRegular GET
/etag EtagR GET
/weak-etag WeakEtagR GET
|]
instance Yesod Y where approot = ApprootStatic "http://test"
app :: Session () -> IO ()
app = yesod Y
getRootR :: Handler ()
getRootR = return ()
postRootR :: Handler ()
postRootR = return ()
getR301, getR303, getR307, getRRegular, getEtagR, getWeakEtagR :: Handler ()
getR301 = redirectWith H.status301 RootR
getR303 = redirectWith H.status303 RootR
getR307 = redirectWith H.status307 RootR
getRRegular = redirect RootR
getEtagR = setEtag "hello world"
getWeakEtagR = setWeakEtag "hello world"
specs :: Spec
specs = describe "Redirect" $ do
it "no redirect" $ app $ do
res <- request defaultRequest { pathInfo = [], requestMethod = "POST" }
assertStatus 200 res
assertBodyContains "" res
it "301 redirect" $ app $ do
res <- request defaultRequest { pathInfo = ["r301"] }
assertStatus 301 res
assertBodyContains "" res
it "303 redirect" $ app $ do
res <- request defaultRequest { pathInfo = ["r303"] }
assertStatus 303 res
assertBodyContains "" res
it "307 redirect" $ app $ do
res <- request defaultRequest { pathInfo = ["r307"] }
assertStatus 307 res
assertBodyContains "" res
it "303 redirect for regular, HTTP 1.1" $ app $ do
res <- request defaultRequest {
pathInfo = ["rregular"],
httpVersion = H.http11
}
assertStatus 303 res
assertBodyContains "" res
it "302 redirect for regular, HTTP 1.0" $ app $ do
res <- request defaultRequest {
pathInfo = ["rregular"]
, httpVersion = H.http10
}
assertStatus 302 res
assertBodyContains "" res
describe "etag" $ do
it "no if-none-match" $ app $ do
res <- request defaultRequest { pathInfo = ["etag"] }
assertStatus 200 res
assertHeader "etag" "\"hello world\"" res
-- Note: this violates the RFC around ETag format, but is being left as is
-- out of concerns that it might break existing users with misbehaving clients.
it "single, unquoted if-none-match" $ app $ do
res <- request defaultRequest
{ pathInfo = ["etag"]
, requestHeaders = [("if-none-match", "hello world")]
}
assertStatus 304 res
it "different if-none-match" $ app $ do
res <- request defaultRequest
{ pathInfo = ["etag"]
, requestHeaders = [("if-none-match", "hello world!")]
}
assertStatus 200 res
assertHeader "etag" "\"hello world\"" res
it "single, quoted if-none-match" $ app $ do
res <- request defaultRequest
{ pathInfo = ["etag"]
, requestHeaders = [("if-none-match", "\"hello world\"")]
}
assertStatus 304 res
it "multiple quoted if-none-match" $ app $ do
res <- request defaultRequest
{ pathInfo = ["etag"]
, requestHeaders = [("if-none-match", "\"foo\", \"hello world\"")]
}
assertStatus 304 res
it "ignore weak when provided normal etag" $ app $ do
res <- request defaultRequest
{ pathInfo = ["etag"]
, requestHeaders = [("if-none-match", "\"foo\", W/\"hello world\"")]
}
assertStatus 200 res
it "weak etag" $ app $ do
res <- request defaultRequest
{ pathInfo = ["weak-etag"]
, requestHeaders = [("if-none-match", "\"foo\", W/\"hello world\"")]
}
assertStatus 304 res
it "different if-none-match for weak etag" $ app $ do
res <- request defaultRequest
{ pathInfo = ["weak-etag"]
, requestHeaders = [("if-none-match", "W/\"foo\"")]
}
assertStatus 200 res
it "ignore strong when expecting weak" $ app $ do
res <- request defaultRequest
{ pathInfo = ["weak-etag"]
, requestHeaders = [("if-none-match", "\"hello world\", W/\"foo\"")]
}
assertStatus 200 res
|
psibi/yesod
|
yesod-core/test/YesodCoreTest/Redirect.hs
|
mit
| 4,468 | 0 | 19 | 1,288 | 1,114 | 564 | 550 | 100 | 1 |
module Stackage.Types
( module X
, module Stackage.Types
) where
import Data.Map as X (Map)
import Data.Map (unionWith)
import Data.Monoid (Monoid (..))
import Data.Set as X (Set)
import Data.Version as X (Version)
import Distribution.Package as X (PackageIdentifier (..),
PackageName (..))
import Distribution.PackageDescription (GenericPackageDescription)
import Distribution.Version as X (VersionRange (..))
import Distribution.Version (intersectVersionRanges)
newtype PackageDB = PackageDB (Map PackageName PackageInfo)
deriving (Show, Eq)
instance Monoid PackageDB where
mempty = PackageDB mempty
PackageDB x `mappend` PackageDB y =
PackageDB $ unionWith newest x y
where
newest pi1 pi2
| piVersion pi1 > piVersion pi2 = pi1
| otherwise = pi2
data PackageInfo = PackageInfo
{ piVersion :: Version
, piDeps :: Map PackageName VersionRange
, piHasTests :: Bool
, piBuildToolsExe :: Set Executable -- ^ required just for building executable/lib
, piBuildToolsAll :: Set Executable -- ^ required for all stanzas
, piGPD :: Maybe GenericPackageDescription
, piExecs :: Set Executable
, piGithubUser :: [String]
}
deriving (Show, Eq)
newtype Executable = Executable String
deriving (Show, Eq, Ord)
-- | Information on a package we're going to build.
data BuildInfo = BuildInfo
{ biVersion :: Version
, biUsers :: [PackageName]
, biMaintainer :: Maintainer
, biDeps :: Map PackageName VersionRange
, biGithubUser :: [String]
, biHasTests :: Bool
}
data HaskellPlatform = HaskellPlatform
{ hpcore :: Set PackageIdentifier
, hplibs :: Set PackageIdentifier
}
deriving (Show, Eq, Ord)
instance Monoid HaskellPlatform where
mempty = HaskellPlatform mempty mempty
HaskellPlatform a x `mappend` HaskellPlatform b y = HaskellPlatform (mappend a b) (mappend x y)
data InstallInfo = InstallInfo
{ iiCore :: Map PackageName (Maybe Version)
, iiPackages :: Map PackageName SelectedPackageInfo
, iiOptionalCore :: Map PackageName Version
-- ^ This is intended to hold onto packages which might be automatically
-- provided in the global package database. In practice, this would be
-- Haskell Platform packages provided by distributions.
, iiPackageDB :: PackageDB
}
data SelectedPackageInfo = SelectedPackageInfo
{ spiVersion :: Version
, spiMaintainer :: Maintainer
, spiGithubUser :: [String]
, spiHasTests :: Bool
}
deriving (Show, Read)
data BuildPlan = BuildPlan
{ bpTools :: [String]
, bpPackages :: Map PackageName SelectedPackageInfo
, bpCore :: Map PackageName (Maybe Version)
, bpOptionalCore :: Map PackageName Version
-- ^ See 'iiOptionalCore'
, bpSkippedTests :: Set PackageName
, bpExpectedFailures :: Set PackageName
-- ^ Expected test failures. Unlike SkippedTests, we should still try to
-- build them.
}
-- | Email address of a Stackage maintainer.
newtype Maintainer = Maintainer { unMaintainer :: String }
deriving (Show, Eq, Ord, Read)
data SelectSettings = SelectSettings
{ haskellPlatformDir :: FilePath
, flags :: Map PackageName Version -> Set String
-- ^ Compile flags which should be turned on. Takes a Map providing the
-- core packages so that flags can be set appropriately.
, disabledFlags :: Set String
-- ^ Compile flags which should always be disabled.
, extraCore :: Set PackageName
, ignoreUpgradeableCore :: Bool
-- ^ Do not pin down the versions of upgradeable core packages.
, requireHaskellPlatform :: Bool
, allowedPackage :: GenericPackageDescription -> Either String ()
-- ^ Checks if a package is allowed into the distribution. By default, we
-- allow all packages in, though this could be used to filter out certain
-- untrusted packages, or packages with an unacceptable license.
--
-- Returns a reason for stripping in Left, or Right if the package is
-- allowed.
, expectedFailures :: Set PackageName
, excludedPackages :: Set PackageName
-- ^ Packages which should be dropped from the list of stable packages,
-- even if present via the Haskell Platform or @stablePackages@. If these
-- packages are dependencies of others, they will still be included.
, stablePackages :: Bool -- ^ require Haskell Platform?
-> Map PackageName (VersionRange, Maintainer)
, useGlobalDatabase :: Bool
-- ^ Instead of checking the Haskell Platform file for core packages, query
-- the global database. For this to be reliable, you should only have
-- default packages in your global database. Default is @False@.
, skippedTests :: Set PackageName
-- ^ Do not build or run test suites, usually in order to avoid a
-- dependency.
, selectGhcVersion :: GhcMajorVersion
, selectTarballDir :: FilePath
-- ^ Directory containing replacement tarballs.
, selectUnderlayPackageDirs :: [FilePath]
-- ^ Additional package directories to reference
}
data BuildStage = BSTools | BSBuild | BSTest
data BuildSettings = BuildSettings
{ sandboxRoot :: FilePath
, extraArgs :: BuildStage -> [String]
, testWorkerThreads :: Int
-- ^ How many threads to spawn for running test suites.
, buildDocs :: Bool
-- ^ Build docs as part of the test procedure.
, tarballDir :: FilePath
-- ^ Directory containing replacement tarballs.
, cabalFileDir :: Maybe FilePath
-- ^ Directory to place cabal files in
, underlayPackageDirs :: [FilePath]
-- ^ Additional package directories to reference
}
-- | A wrapper around a @Map@ providing a better @Monoid@ instance.
newtype PackageMap = PackageMap { unPackageMap :: Map PackageName (VersionRange, Maintainer) }
instance Monoid PackageMap where
mempty = PackageMap mempty
PackageMap x `mappend` PackageMap y =
PackageMap $ unionWith go x y
where
go (r1, m1) (r2, _) = (intersectVersionRanges r1 r2, m1)
-- | GHC major version. For example, for GHC 7.4.2, this would be 7 4.
data GhcMajorVersion = GhcMajorVersion Int Int
deriving (Show, Ord, Eq)
|
feuerbach/stackage
|
Stackage/Types.hs
|
mit
| 6,754 | 0 | 12 | 1,945 | 1,127 | 662 | 465 | 102 | 0 |
module MonadIn1 where
f :: Monad m => m Int
f = do
let x@(y:ys) = [1,2]
case x of
(z:zs) -> return z
|
kmate/HaRe
|
old/testing/simplifyExpr/MonadIn1.hs
|
bsd-3-clause
| 126 | 0 | 12 | 49 | 73 | 38 | 35 | 6 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
-----------------------------------------------------------------------------
{- |
Module : Numeric.GSL.Minimization
Copyright : (c) Alberto Ruiz 2006-9
License : GPL-style
Maintainer : Alberto Ruiz (aruiz at um dot es)
Stability : provisional
Portability : uses ffi
Minimization of a multidimensional function using some of the algorithms described in:
<http://www.gnu.org/software/gsl/manual/html_node/Multidimensional-Minimization.html>
The example in the GSL manual:
@
f [x,y] = 10*(x-1)^2 + 20*(y-2)^2 + 30
main = do
let (s,p) = minimize NMSimplex2 1E-2 30 [1,1] f [5,7]
print s
print p
\> main
[0.9920430849306288,1.9969168063253182]
0.000 512.500 1.130 6.500 5.000
1.000 290.625 1.409 5.250 4.000
2.000 290.625 1.409 5.250 4.000
3.000 252.500 1.409 5.500 1.000
...
22.000 30.001 0.013 0.992 1.997
23.000 30.001 0.008 0.992 1.997
@
The path to the solution can be graphically shown by means of:
@'Graphics.Plot.mplot' $ drop 3 ('toColumns' p)@
Taken from the GSL manual:
The vector Broyden-Fletcher-Goldfarb-Shanno (BFGS) algorithm is a quasi-Newton method which builds up an approximation to the second derivatives of the function f using the difference between successive gradient vectors. By combining the first and second derivatives the algorithm is able to take Newton-type steps towards the function minimum, assuming quadratic behavior in that region.
The bfgs2 version of this minimizer is the most efficient version available, and is a faithful implementation of the line minimization scheme described in Fletcher's Practical Methods of Optimization, Algorithms 2.6.2 and 2.6.4. It supercedes the original bfgs routine and requires substantially fewer function and gradient evaluations. The user-supplied tolerance tol corresponds to the parameter \sigma used by Fletcher. A value of 0.1 is recommended for typical use (larger values correspond to less accurate line searches).
The nmsimplex2 version is a new O(N) implementation of the earlier O(N^2) nmsimplex minimiser. It calculates the size of simplex as the rms distance of each vertex from the center rather than the mean distance, which has the advantage of allowing a linear update.
-}
-----------------------------------------------------------------------------
module Numeric.GSL.Minimization (
minimize, minimizeV, MinimizeMethod(..),
minimizeD, minimizeVD, MinimizeMethodD(..),
minimizeNMSimplex,
minimizeConjugateGradient,
minimizeVectorBFGS2
) where
import Data.Packed.Internal
import Data.Packed.Matrix
import Numeric.GSL.Internal
import Foreign.Ptr(Ptr, FunPtr, freeHaskellFunPtr)
import Foreign.C.Types
import System.IO.Unsafe(unsafePerformIO)
------------------------------------------------------------------------
{-# DEPRECATED minimizeNMSimplex "use minimize NMSimplex2 eps maxit sizes f xi" #-}
minimizeNMSimplex f xi szs eps maxit = minimize NMSimplex eps maxit szs f xi
{-# DEPRECATED minimizeConjugateGradient "use minimizeD ConjugateFR eps maxit step tol f g xi" #-}
minimizeConjugateGradient step tol eps maxit f g xi = minimizeD ConjugateFR eps maxit step tol f g xi
{-# DEPRECATED minimizeVectorBFGS2 "use minimizeD VectorBFGS2 eps maxit step tol f g xi" #-}
minimizeVectorBFGS2 step tol eps maxit f g xi = minimizeD VectorBFGS2 eps maxit step tol f g xi
-------------------------------------------------------------------------
data MinimizeMethod = NMSimplex
| NMSimplex2
deriving (Enum,Eq,Show,Bounded)
-- | Minimization without derivatives
minimize :: MinimizeMethod
-> Double -- ^ desired precision of the solution (size test)
-> Int -- ^ maximum number of iterations allowed
-> [Double] -- ^ sizes of the initial search box
-> ([Double] -> Double) -- ^ function to minimize
-> [Double] -- ^ starting point
-> ([Double], Matrix Double) -- ^ solution vector and optimization path
-- | Minimization without derivatives (vector version)
minimizeV :: MinimizeMethod
-> Double -- ^ desired precision of the solution (size test)
-> Int -- ^ maximum number of iterations allowed
-> Vector Double -- ^ sizes of the initial search box
-> (Vector Double -> Double) -- ^ function to minimize
-> Vector Double -- ^ starting point
-> (Vector Double, Matrix Double) -- ^ solution vector and optimization path
minimize method eps maxit sz f xi = v2l $ minimizeV method eps maxit (fromList sz) (f.toList) (fromList xi)
where v2l (v,m) = (toList v, m)
ww2 w1 o1 w2 o2 f = w1 o1 $ \a1 -> w2 o2 $ \a2 -> f a1 a2
minimizeV method eps maxit szv f xiv = unsafePerformIO $ do
let n = dim xiv
fp <- mkVecfun (iv f)
rawpath <- ww2 vec xiv vec szv $ \xiv' szv' ->
createMIO maxit (n+3)
(c_minimize (fi (fromEnum method)) fp eps (fi maxit) // xiv' // szv')
"minimize"
let it = round (rawpath @@> (maxit-1,0))
path = takeRows it rawpath
sol = cdat $ dropColumns 3 $ dropRows (it-1) path
freeHaskellFunPtr fp
return (sol, path)
foreign import ccall safe "gsl-aux.h minimize"
c_minimize:: CInt -> FunPtr (CInt -> Ptr Double -> Double) -> Double -> CInt -> TVVM
----------------------------------------------------------------------------------
data MinimizeMethodD = ConjugateFR
| ConjugatePR
| VectorBFGS
| VectorBFGS2
| SteepestDescent
deriving (Enum,Eq,Show,Bounded)
-- | Minimization with derivatives.
minimizeD :: MinimizeMethodD
-> Double -- ^ desired precision of the solution (gradient test)
-> Int -- ^ maximum number of iterations allowed
-> Double -- ^ size of the first trial step
-> Double -- ^ tol (precise meaning depends on method)
-> ([Double] -> Double) -- ^ function to minimize
-> ([Double] -> [Double]) -- ^ gradient
-> [Double] -- ^ starting point
-> ([Double], Matrix Double) -- ^ solution vector and optimization path
-- | Minimization with derivatives (vector version)
minimizeVD :: MinimizeMethodD
-> Double -- ^ desired precision of the solution (gradient test)
-> Int -- ^ maximum number of iterations allowed
-> Double -- ^ size of the first trial step
-> Double -- ^ tol (precise meaning depends on method)
-> (Vector Double -> Double) -- ^ function to minimize
-> (Vector Double -> Vector Double) -- ^ gradient
-> Vector Double -- ^ starting point
-> (Vector Double, Matrix Double) -- ^ solution vector and optimization path
minimizeD method eps maxit istep tol f df xi = v2l $ minimizeVD
method eps maxit istep tol (f.toList) (fromList.df.toList) (fromList xi)
where v2l (v,m) = (toList v, m)
minimizeVD method eps maxit istep tol f df xiv = unsafePerformIO $ do
let n = dim xiv
f' = f
df' = (checkdim1 n . df)
fp <- mkVecfun (iv f')
dfp <- mkVecVecfun (aux_vTov df')
rawpath <- vec xiv $ \xiv' ->
createMIO maxit (n+2)
(c_minimizeD (fi (fromEnum method)) fp dfp istep tol eps (fi maxit) // xiv')
"minimizeD"
let it = round (rawpath @@> (maxit-1,0))
path = takeRows it rawpath
sol = cdat $ dropColumns 2 $ dropRows (it-1) path
freeHaskellFunPtr fp
freeHaskellFunPtr dfp
return (sol,path)
foreign import ccall safe "gsl-aux.h minimizeD"
c_minimizeD :: CInt
-> FunPtr (CInt -> Ptr Double -> Double)
-> FunPtr TVV
-> Double -> Double -> Double -> CInt
-> TVM
---------------------------------------------------------------------
checkdim1 n v
| dim v == n = v
| otherwise = error $ "Error: "++ show n
++ " components expected in the result of the gradient supplied to minimizeD"
|
mightymoose/liquidhaskell
|
benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/Minimization.hs
|
bsd-3-clause
| 8,297 | 0 | 19 | 2,158 | 1,408 | 745 | 663 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances, MultiParamTypeClasses, PatternGuards #-}
----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.BorderResize
-- Copyright : (c) Jan Vornberger 2009
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : not portable
--
-- This layout modifier will allow to resize windows by dragging their
-- borders with the mouse. However, it only works in layouts or modified
-- layouts that react to the 'SetGeometry' message.
-- "XMonad.Layout.WindowArranger" can be used to create such a setup,
-- but it is probably must useful in a floating layout such as
-- "XMonad.Layout.PositionStoreFloat" with which it has been mainly tested.
-- See the documentation of PositionStoreFloat for a typical usage example.
--
-----------------------------------------------------------------------------
module XMonad.Layout.BorderResize
( -- * Usage
-- $usage
borderResize
, BorderResize (..)
, RectWithBorders, BorderInfo,
) where
import XMonad
import XMonad.Layout.Decoration
import XMonad.Layout.WindowArranger
import XMonad.Util.XUtils
import Control.Monad(when)
import qualified Data.Map as M
-- $usage
-- You can use this module with the following in your
-- @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.BorderResize
-- > myLayout = borderResize (... layout setup that reacts to SetGeometry ...)
-- > main = xmonad def { layoutHook = myLayout }
--
type BorderBlueprint = (Rectangle, Glyph, BorderType)
data BorderType = RightSideBorder
| LeftSideBorder
| TopSideBorder
| BottomSideBorder
deriving (Show, Read, Eq)
data BorderInfo = BI { bWin :: Window,
bRect :: Rectangle,
bType :: BorderType
} deriving (Show, Read)
type RectWithBorders = (Rectangle, [BorderInfo])
data BorderResize a = BR (M.Map Window RectWithBorders) deriving (Show, Read)
brBorderSize :: Dimension
brBorderSize = 2
borderResize :: l a -> ModifiedLayout BorderResize l a
borderResize = ModifiedLayout (BR M.empty)
instance LayoutModifier BorderResize Window where
redoLayout _ _ Nothing wrs = return (wrs, Nothing)
redoLayout (BR wrsLastTime) _ _ wrs = do
let correctOrder = map fst wrs
wrsCurrent = M.fromList wrs
wrsGone = M.difference wrsLastTime wrsCurrent
wrsAppeared = M.difference wrsCurrent wrsLastTime
wrsStillThere = M.intersectionWith testIfUnchanged wrsLastTime wrsCurrent
handleGone wrsGone
wrsCreated <- handleAppeared wrsAppeared
let wrsChanged = handleStillThere wrsStillThere
wrsThisTime = M.union wrsChanged wrsCreated
return (compileWrs wrsThisTime correctOrder, Just $ BR wrsThisTime)
-- What we return is the original wrs with the new border
-- windows inserted at the correct positions - this way, the core
-- will restack the borders correctly.
-- We also return information about our borders, so that we
-- can handle events that they receive and destroy them when
-- they are no longer needed.
where
testIfUnchanged entry@(rLastTime, _) rCurrent =
if rLastTime == rCurrent
then (Nothing, entry)
else (Just rCurrent, entry)
handleMess (BR wrsLastTime) m
| Just e <- fromMessage m :: Maybe Event =
handleResize (createBorderLookupTable wrsLastTime) e >> return Nothing
| Just _ <- fromMessage m :: Maybe LayoutMessages =
handleGone wrsLastTime >> return (Just $ BR M.empty)
handleMess _ _ = return Nothing
compileWrs :: M.Map Window RectWithBorders -> [Window] -> [(Window, Rectangle)]
compileWrs wrsThisTime correctOrder = let wrs = reorder (M.toList wrsThisTime) correctOrder
in concat $ map compileWr wrs
compileWr :: (Window, RectWithBorders) -> [(Window, Rectangle)]
compileWr (w, (r, borderInfos)) =
let borderWrs = for borderInfos $ \bi -> (bWin bi, bRect bi)
in borderWrs ++ [(w, r)]
handleGone :: M.Map Window RectWithBorders -> X ()
handleGone wrsGone = mapM_ deleteWindow borderWins
where
borderWins = map bWin . concat . map snd . M.elems $ wrsGone
handleAppeared :: M.Map Window Rectangle -> X (M.Map Window RectWithBorders)
handleAppeared wrsAppeared = do
let wrs = M.toList wrsAppeared
wrsCreated <- mapM handleSingleAppeared wrs
return $ M.fromList wrsCreated
handleSingleAppeared :: (Window, Rectangle) -> X (Window, RectWithBorders)
handleSingleAppeared (w, r) = do
let borderBlueprints = prepareBorders r
borderInfos <- mapM createBorder borderBlueprints
return (w, (r, borderInfos))
handleStillThere :: M.Map Window (Maybe Rectangle, RectWithBorders) -> M.Map Window RectWithBorders
handleStillThere wrsStillThere = M.map handleSingleStillThere wrsStillThere
handleSingleStillThere :: (Maybe Rectangle, RectWithBorders) -> RectWithBorders
handleSingleStillThere (Nothing, entry) = entry
handleSingleStillThere (Just rCurrent, (_, borderInfos)) = (rCurrent, updatedBorderInfos)
where
changedBorderBlueprints = prepareBorders rCurrent
updatedBorderInfos = map updateBorderInfo . zip borderInfos $ changedBorderBlueprints
-- assuming that the four borders are always in the same order
updateBorderInfo :: (BorderInfo, BorderBlueprint) -> BorderInfo
updateBorderInfo (borderInfo, (r, _, _)) = borderInfo { bRect = r }
createBorderLookupTable :: M.Map Window RectWithBorders -> [(Window, (BorderType, Window, Rectangle))]
createBorderLookupTable wrsLastTime = concat $ map processSingleEntry $ M.toList wrsLastTime
where
processSingleEntry :: (Window, RectWithBorders) -> [(Window, (BorderType, Window, Rectangle))]
processSingleEntry (w, (r, borderInfos)) = for borderInfos $ \bi -> (bWin bi, (bType bi, w, r))
prepareBorders :: Rectangle -> [BorderBlueprint]
prepareBorders (Rectangle x y wh ht) =
[((Rectangle (x + fi wh - fi brBorderSize) y brBorderSize ht), xC_right_side , RightSideBorder),
((Rectangle x y brBorderSize ht) , xC_left_side , LeftSideBorder),
((Rectangle x y wh brBorderSize) , xC_top_side , TopSideBorder),
((Rectangle x (y + fi ht - fi brBorderSize) wh brBorderSize), xC_bottom_side, BottomSideBorder)
]
handleResize :: [(Window, (BorderType, Window, Rectangle))] -> Event -> X ()
handleResize borders ButtonEvent { ev_window = ew, ev_event_type = et }
| et == buttonPress, Just edge <- lookup ew borders =
case edge of
(RightSideBorder, hostWin, (Rectangle hx hy _ hht)) ->
mouseDrag (\x _ -> do
let nwh = max 1 $ fi (x - hx)
rect = Rectangle hx hy nwh hht
focus hostWin
when (x - hx > 0) $ sendMessage (SetGeometry rect)) (focus hostWin)
(LeftSideBorder, hostWin, (Rectangle hx hy hwh hht)) ->
mouseDrag (\x _ -> do
let nx = max 0 $ min (hx + fi hwh) $ x
nwh = max 1 $ hwh + fi (hx - x)
rect = Rectangle nx hy nwh hht
focus hostWin
when (x < hx + fi hwh) $ sendMessage (SetGeometry rect)) (focus hostWin)
(TopSideBorder, hostWin, (Rectangle hx hy hwh hht)) ->
mouseDrag (\_ y -> do
let ny = max 0 $ min (hy + fi hht) $ y
nht = max 1 $ hht + fi (hy - y)
rect = Rectangle hx ny hwh nht
focus hostWin
when (y < hy + fi hht) $ sendMessage (SetGeometry rect)) (focus hostWin)
(BottomSideBorder, hostWin, (Rectangle hx hy hwh _)) ->
mouseDrag (\_ y -> do
let nht = max 1 $ fi (y - hy)
rect = Rectangle hx hy hwh nht
focus hostWin
when (y - hy > 0) $ sendMessage (SetGeometry rect)) (focus hostWin)
handleResize _ _ = return ()
createBorder :: BorderBlueprint -> X (BorderInfo)
createBorder (borderRect, borderCursor, borderType) = do
borderWin <- createInputWindow borderCursor borderRect
return BI { bWin = borderWin, bRect = borderRect, bType = borderType }
createInputWindow :: Glyph -> Rectangle -> X Window
createInputWindow cursorGlyph r = withDisplay $ \d -> do
win <- mkInputWindow d r
io $ selectInput d win (exposureMask .|. buttonPressMask)
cursor <- io $ createFontCursor d cursorGlyph
io $ defineCursor d win cursor
io $ freeCursor d cursor
showWindow win
return win
mkInputWindow :: Display -> Rectangle -> X Window
mkInputWindow d (Rectangle x y w h) = do
rw <- asks theRoot
let screen = defaultScreenOfDisplay d
visual = defaultVisualOfScreen screen
attrmask = cWOverrideRedirect
io $ allocaSetWindowAttributes $
\attributes -> do
set_override_redirect attributes True
createWindow d rw x y w h 0 0 inputOnly visual attrmask attributes
for :: [a] -> (a -> b) -> [b]
for = flip map
reorder :: (Eq a) => [(a, b)] -> [a] -> [(a, b)]
reorder wrs order =
let ordered = concat $ map (pickElem wrs) order
rest = filter (\(w, _) -> not (w `elem` order)) wrs
in ordered ++ rest
where
pickElem list e = case (lookup e list) of
Just result -> [(e, result)]
Nothing -> []
|
pjones/xmonad-test
|
vendor/xmonad-contrib/XMonad/Layout/BorderResize.hs
|
bsd-2-clause
| 9,955 | 2 | 22 | 2,827 | 2,686 | 1,410 | 1,276 | 154 | 4 |
-- !!! Test monomorphism + RULES
module ShouldCompile where
-- This example crashed GHC 4.08.1.
-- The reason was that foobar is monomorphic, so the RULE
-- should not generalise over it.
{-# NOINLINE [1] foo #-}
foo 1 = 2
bar 0 = 1
foobar = 2
{-# RULES
"foo/bar" foo bar = foobar
#-}
|
green-haskell/ghc
|
testsuite/tests/typecheck/should_compile/tc111.hs
|
bsd-3-clause
| 297 | 0 | 5 | 67 | 31 | 20 | 11 | 7 | 1 |
module Converter (rationalToGray, grayToSignIO, signToGray, Gray, startF, startC) where
import Stream
import Data.Ratio
import Control.Concurrent
import Control.Concurrent.MVar
import System.IO.Unsafe
type Gray = [Integer]
type State = (Integer, Integer)
-- Convert a rational number (in (-1,1)) to its Gray representation
rationalToGray :: Rational -> Gray
rationalToGray x
|x<0 = f (negate' (rationalToStream (-x))) (0,0)
|otherwise = f (rationalToStream x) (0,0)
-- Function to implement the two heads Turing machine that convert a
-- signed-digit stream to the corresponding Gray-code representation
f :: Stream -> State -> Stream
f (x:xs) (0,0)
|x==(-1) = 0:f xs (0,0)
|x==0 = c:1:ds
|x==1 = 1:f xs (1,0)
where c:ds = f xs (0,1)
f (x:xs) (0,1)
|x==(-1) = 0:f xs (1,0)
|x==0 = c:0:ds
|x==1 = 1:f xs (0,0)
where c:ds = f xs (0,1)
f (x:xs) (1,0)
|x==(-1) = 1:f xs (0,0)
|x==0 = c:1:ds
|x==1 = 0:f xs (1,0)
where c:ds = f xs (1,1)
f (x:xs) (1,1)
|x==(-1) = 1:f xs (1,0)
|x==0 = c:0:ds
|x==1 = 0:f xs (0,0)
where c:ds = f xs (1,1)
-- Anotherway to convert from a rational to Gray code representation
-- Behave exactly the same like above
rationalToGray' :: Rational -> Gray
rationalToGray' x
|x<0 = signToGray (negate' (rationalToStream (-x)))
|otherwise = signToGray (rationalToStream x)
-- Function to convert a signed-digit stream to Gray representation
-- Is much shorter than above
signToGray :: Stream -> Stream
signToGray (1:xs) = 1:f'(signToGray xs)
signToGray ((-1):xs) = 0:signToGray xs
signToGray (0:xs) = c:1:(f' ds)
where c:ds = signToGray xs
-- Convert a Gray-code stream to the corresponding signed-digit representation
-- Make use of threads
grayToSignIO :: Stream -> IO Stream
grayToSignIO (x1:x2:xs) = do
c <- threadTesting(x1:x2:xs)
if (c==1)
then (do co <- unsafeInterleaveIO (grayToSignIO (f'(x2:xs)))
return (1:co))
else if (c==2)
then (do co <- unsafeInterleaveIO (grayToSignIO (x2:xs))
return ((-1):co))
else (do co <- unsafeInterleaveIO (grayToSignIO (x1:f' xs))
return (0:co))
-- Flip the first bit of an infinite stream
f' (x:xs) = (f'' x):xs
where f'' 1 = 0
f'' 0 = 1
-- Launch two threads which run concurrently, test for the first digit of the stream (1, 0 or bottom)
-- As soon as one thread terminate, grab that result and proceed
threadTesting :: Stream -> IO Int
threadTesting xs = do m <- newEmptyMVar
c1 <- forkIO (f1 m xs)
c2 <- forkIO (f2 m xs)
c <- takeMVar m
killThread c1
killThread c2
return c
-- Test case 1, when the first bit is either 1 or 0.
-- In case of bottom, f1 will never terminate, then f2 will definitely terminate
f1 :: MVar Int -> Stream -> IO()
f1 m (0:xs) = putMVar m 2
f1 m (1:xs) = putMVar m 1
-- Test case 2, when the first bit is completely ignored, esp in case it was a bottom
-- If the second bit is 1, then we can output, don't care value of the first bit
-- If the second bit is 0, then loop forever, give chances to f1 to terminate
f2 :: MVar Int -> Stream -> IO()
f2 m (c1:c2:xs)
|c2==1 = putMVar m 3
|otherwise = yield
-- Testing
startC :: IO()
startC = do
c<- unsafeInterleaveIO (grayToSignIO (1:1:z0))
putStrLn (show (take 100 c))
startF = signToGray ((-1):1:z0)
z0 = 0:z0
loop' = loop'
z1' = (1:z1')
|
hferreiro/replay
|
testsuite/tests/concurrent/prog001/Converter.hs
|
bsd-3-clause
| 3,559 | 71 | 20 | 937 | 1,503 | 779 | 724 | 79 | 3 |
module Main (main) where
import Simpl021A
main :: IO ()
main = do print i
print j
|
urbanslug/ghc
|
testsuite/tests/simplCore/should_compile/Simpl021B.hs
|
bsd-3-clause
| 96 | 0 | 7 | 31 | 39 | 20 | 19 | 5 | 1 |
module TyMsgTest where
unboundE = \ x. f x
main = 1
|
pxqr/algorithm-wm
|
test/ty-error.hs
|
mit
| 54 | 3 | 4 | 14 | 21 | 13 | 8 | -1 | -1 |
{-|
Module : Test.Data.Instances.Common.Sign
Description : The Sign tests
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : [email protected]
Stability : experimental
Portability : Unknown
Contains the Test Tree Node for the Sign module, as well as associated
Generator functions
-}
module Test.Problem.Instances.Common.Sign (
tests -- :: TestTree
) where
import HSat.Problem.Instances.Common.Sign
import TestUtils
name :: String
name = "Sign"
tests :: TestTree
tests =
testGroup name [
testGroup "mkSign" [
mkSignTest1,
mkSignTest2
],
testGroup "pos" [
posTest1
],
testGroup "neg" [
negTest1
],
testGroup "mkSignFromInteger" [
mkSignFromIntegerTest1,
mkSignFromIntegerTest2,
mkSignFromIntegerTest3,
mkSignFromIntegerTest4
],
testGroup "signToInteger" [
signToIntegerTest1,
signToIntegerTest2,
signToIntegerTest3
],
testGroup "isPos" [
isPosTest1,
isPosTest2
],
testGroup "isNeg" [
isNegTest1,
isNegTest2
]
]
mkSignTest1 :: TestTree
mkSignTest1 =
testCase ("getBool . mkSign True " `equiv` " True") $
getBool (mkSign True) @=? True
mkSignTest2 :: TestTree
mkSignTest2 =
testCase ("getBool . mkSign False " `equiv` " False") $
False @=? getBool (mkSign False)
posTest1 :: TestTree
posTest1 =
testCase ("mkSign True " `equiv` " pos") $
pos @=? mkSign True
negTest1 :: TestTree
negTest1 =
testCase ("mkSign False " `equiv` " neg") $
neg @=? mkSign False
{-
positive integers should all create positive signs
-}
mkSignFromIntegerTest1 :: TestTree
mkSignFromIntegerTest1 =
testProperty ("mkSignFromInteger posInteger " `equiv` " pos") $
forAll
mkPosIntegerNonZero
(\int -> mkSignFromInteger int === pos)
--negative integers should create negative signs
mkSignFromIntegerTest2 :: TestTree
mkSignFromIntegerTest2 =
testProperty ("mkSignFromInteger negInteger " `equiv` " neg") $
forAll
mkNegIntegerNonZero
(\int -> mkSignFromInteger int === neg)
{-
Comparing the input and comparing something from and to a Sign should preserve
its comparison to zero
-}
mkSignFromIntegerTest3 :: TestTree
mkSignFromIntegerTest3 =
testProperty "signToInteger mkSignFromInteger has correct sign" $
forAll
mkIntegerNonZero
(\int ->
let exptd = compare 0 int
val = compare 0 (signToInteger $ mkSignFromInteger int)
in exptd === val
)
mkSignFromIntegerTest4 :: TestTree
mkSignFromIntegerTest4 =
testCase "mkSignFromInteger 0 throws Error" $
forceError $ mkSignFromInteger 0
signToIntegerTest1 :: TestTree
signToIntegerTest1 =
testCase ("signToInteger (mkSign True) " `equiv` " 1") $
1 @=? signToInteger (mkSign True)
signToIntegerTest2 :: TestTree
signToIntegerTest2 =
testCase ("signToInteger (mkSign False) " `equiv` " -1") $
(-1) @=? signToInteger (mkSign False)
signToIntegerTest3 :: TestTree
signToIntegerTest3 =
testProperty ("mkSignFromInteger . signToInteger " `equiv` " id") $ property
(\sign ->
let val = mkSignFromInteger $ signToInteger sign
in sign === val
)
isPosTest1 :: TestTree
isPosTest1 =
testCase ("isPos $ mkSign True " `equiv` " True") $
True @=? isPos (mkSign True)
isPosTest2 :: TestTree
isPosTest2 =
testCase ("isPos $ mkSign False " `equiv` " False") $
False @=? isPos (mkSign False)
isNegTest1 :: TestTree
isNegTest1 =
testCase ("isNeg $ mkSign True " `equiv` " False") $
False @=? isNeg (mkSign True)
isNegTest2 :: TestTree
isNegTest2 =
testCase ("isNeg $ mkSign False " `equiv` " True") $
True @=? isNeg (mkSign False)
{-
Generators and Arbitrary instances
-}
genSign :: Gen Sign
genSign = mkSign <$> arbitrary
instance Arbitrary Sign where
arbitrary = genSign
shrink sign =
map mkSign $ shrink . getBool $ sign
|
aburnett88/HSat
|
tests-src/Test/Problem/Instances/Common/Sign.hs
|
mit
| 3,842 | 0 | 16 | 810 | 838 | 458 | 380 | 108 | 1 |
import Data.List (maximum, tails, transpose)
input :: String
input = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08\n\
\49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00\n\
\81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65\n\
\52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91\n\
\22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80\n\
\24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50\n\
\32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70\n\
\67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21\n\
\24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72\n\
\21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95\n\
\78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92\n\
\16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57\n\
\86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58\n\
\19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40\n\
\04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66\n\
\88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69\n\
\04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36\n\
\20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16\n\
\20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54\n\
\01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48"
nums :: [[Int]]
nums = map (map read . words) $ lines input
-- | The last chunks in each row are smaller that 4, but it's totally fine
-- since their products will be smaller and be simply ignored later
horizontalChunks :: [[Int]] -> [[Int]]
horizontalChunks nums = concatMap (map (take 4) . tails) nums
diagonalChunks :: [[Int]] -> [[Int]]
diagonalChunks nums = concatMap (transpose . zipWith drop [0..]) $ map (take 4) (tails nums)
main = do
let
horizontal = horizontalChunks nums
vertical = horizontalChunks $ transpose nums
diagonal = diagonalChunks nums
revDiagonal = diagonalChunks $ map reverse nums
results = map product (horizontal ++ vertical ++ diagonal ++ revDiagonal)
print $ maximum results
|
mohsen3/crispy-goggles
|
ProjectEuler/problem11/A.hs
|
mit
| 2,261 | 0 | 14 | 735 | 269 | 142 | 127 | 17 | 1 |
module Main where
import Control.Applicative
ans :: Maybe Integer
ans = (+) <$> Just 4 <*> Just 6
main :: IO ()
main = print ans
|
calvinchengx/learnhaskell
|
applicatives/applicativefunctors.hs
|
mit
| 134 | 0 | 7 | 31 | 56 | 30 | 26 | 6 | 1 |
{-# LANGUAGE FlexibleContexts, Rank2Types #-}
module TestFramework where
import Rules
import Control.Monad.State
import Control.Monad.Except
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Generators
import Text.Show.Pretty
import Data.Maybe
import Data.Map (empty, insert)
import Data.Either (isLeft)
type UniversePropertyMonad = PropertyM (State (Either String Universe))
newtype ArbitraryUniverse = ArbitraryUniverse Universe
instance Arbitrary ArbitraryUniverse where
arbitrary = ArbitraryUniverse <$> generateUniverse defaultGeneratorProperties
shrink (ArbitraryUniverse u) = ArbitraryUniverse <$> shrinkUniverse u
instance Show ArbitraryUniverse where
show (ArbitraryUniverse u) = ppShow u
defaultGeneratorProperties :: GeneratorProperties
defaultGeneratorProperties = GeneratorProperties empty defaultInteractionProbabilities 1 5 5 5 defaultStepProbabilities
defaultInteractionProbabilities :: InteractionProbabilities
defaultInteractionProbabilities = InteractionProbabilities 1 1 1 1 1 1 1
defaultStepProbabilities :: StepProbabilities
defaultStepProbabilities = StepProbabilities 1 1 1 1 1
withWorkplaceProbability :: WorkplaceType -> Int -> GeneratorProperties -> GeneratorProperties
withWorkplaceProbability wpType probability props = props { workplaceProbabilities = insert wpType probability (workplaceProbabilities props) }
withFarmingProbability :: Int -> GeneratorProperties -> GeneratorProperties
withFarmingProbability probability props = props { interactionProbabilities = (interactionProbabilities props) { plantCropsProbability = probability}}
withArmingProbability :: Int -> GeneratorProperties -> GeneratorProperties
withArmingProbability probability props = props { interactionProbabilities = (interactionProbabilities props) { armWorkerProbability = probability}}
withAdventureProbability :: Int -> GeneratorProperties -> GeneratorProperties
withAdventureProbability probability props = props { interactionProbabilities = (interactionProbabilities props) { adventureProbability = probability}}
withNoResourceChangeSteps :: GeneratorProperties -> GeneratorProperties
withNoResourceChangeSteps props = props {stepProbabilities = (stepProbabilities props) {
addResourcesProbability = 0,
collectResourcesStepProbability = 0,
payResourcesProbability = 0,
addDogProbability = 0}}
withOtherWorkersNotDoneProbability :: Int -> GeneratorProperties -> GeneratorProperties
withOtherWorkersNotDoneProbability probability props = props { otherWorkersNotDoneProbability = probability }
generalUniverseProperty :: Testable a => UniversePropertyMonad a -> Property
generalUniverseProperty = propertyWithProperties defaultGeneratorProperties
movingWorkerProperty :: Testable a => UniversePropertyMonad a -> Property
movingWorkerProperty = propertyWithProperties defaultGeneratorProperties {movingWorkerProbability = 50}
newtype PrettyPrintedUniverse = PrettyUniverse { unPretty :: Universe}
instance Show PrettyPrintedUniverse where
show (PrettyUniverse u) = ppShow u
propertyWithProperties :: Testable a => GeneratorProperties -> UniversePropertyMonad a -> Property
propertyWithProperties properties action = monadic extractProperty action
where extractProperty act = forAllShrink (PrettyUniverse <$> generateUniverse properties) ((fmap PrettyUniverse) . shrinkUniverse . unPretty) (execOnUniverse act)
execOnUniverse act (PrettyUniverse universe) = checkResult $ runState act (Right universe)
checkResult (prop, Right resultUniverse) =
counterexample ("Resulting universe: " ++ ppShow resultUniverse) $
prop
checkResult (prop, Left msg) =
counterexample ("Unexpected error: " ++ msg) $
prop
getUniverse :: UniversePropertyMonad Universe
getUniverse = do
universeOrError <- run get
case universeOrError of
Right universe -> return universe
Left msg -> stop $ counterexample ("Tried to access universe, but was already failed: " ++ msg) False
getsUniverse :: (Universe -> a) -> UniversePropertyMonad a
getsUniverse x = x <$> getUniverse
applyToUniverse :: (forall m. MonadError String m => Universe -> m Universe) -> UniversePropertyMonad ()
applyToUniverse action = do
currentState <- run get
let nextState = action =<< currentState
when (isLeft nextState) $ monitor $ counterexample ("Last valid universe: " ++ ppShow currentState)
run $ put nextState
shouldHaveFailed :: UniversePropertyMonad ()
shouldHaveFailed = do
universeOrError <- run get
case universeOrError of
Right universe -> stop $ counterexample ("Was expecting failure, but was successful: " ++ ppShow universe) False
Left _ -> return ()
preMaybe :: Monad m => Maybe b -> PropertyM m b
preMaybe value = pre (isJust value) >> return (fromJust value)
|
martin-kolinek/some-board-game-rules
|
test/TestFramework.hs
|
mit
| 4,947 | 0 | 14 | 823 | 1,131 | 583 | 548 | 80 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
module Main where
import Yesod
import Data.Text as T hiding (zip)
import Control.Applicative
import Control.Monad (forM)
import Yesod.Form
import Data.String
main :: IO ()
main = warp 3000 CarApp
data CarApp = CarApp
instance Yesod CarApp
instance RenderMessage CarApp FormMessage where
renderMessage _ _ = defaultFormMessage
mkYesod "CarApp" [parseRoutes|
/ HomeR GET
|]
-- /car/#Int CarR
--data Car = Car { carModel :: Text
-- , carYear :: Int
-- , carColor :: Maybe Text
-- }
-- deriving Show
--carAForm :: Int -> AForm Handler Car
--carAForm x = Car
-- <$> areq textField "Model" (Just (T.pack (show x)))
-- <*> areq intField "Year" (Just 1996)
-- <*> aopt textField "Color" Nothing
-- -- <*> areq hiddenField "This is a question!" (Just (T.pack "This is a question!")) -- pure doesnt show anything
-- -- <*> areq checkBoxField "Some answer" (Just True)
--
--intAForm :: AForm Handler Int
--intAForm = areq intField "Bitte geben sie eine positive Zahl ein!" Nothing
--
--carForm :: Html -> MForm Handler (FormResult Car, Widget)
--carForm = renderBootstrap $ carAForm 1
--
--nCarAForm :: Int -> AForm Handler [Car]
--nCarAForm 1 = (\x -> [x]) <$> carAForm 1
--nCarAForm n = (:) <$> carAForm n <*> nCarAForm (n-1)
t1, t2, t3, t4 :: (String,Bool)
t1 = ("t1 - false1", False)
t2 = ("t2 - false2", False)
t3 = ("t3 - true3", True)
t4 = ("t4 - false4", False)
listEditMForm :: [(String,Bool)]-> MForm Handler (FormResult [(FormResult Bool, FormResult Text)], Widget)
listEditMForm xs = do
ifields <- forM xs (\(s,i) -> mreq intField (fromString s) (Just i))
tfields <- forM xs (\(s,i) -> mreq textField (fromString s) (Just $ pack s))
let (iresults,iviews) = unzip ifields
let (tresults,tviews) = unzip tfields
let results = zip iresults tresults
let views = zip iviews tviews
let widget = [whamlet|
<h1>Multi Field Form
$forall (iv,tv) <- views
Field #
#{fvLabel iv}: #
^{fvInput tv} #
^{fvInput iv}
<input type=submit value="Testing mForms">
|]
return ((FormSuccess results), widget)
--linkWidget :: Int -> Widget
--linkWidget count = toWidget [hamlet| <a href=@{CarR count}> Klick mich!|]
getHomeR :: Handler Html
getHomeR = do
((res, widget), enctype) <- runFormGet $ listEditMForm [t1, t2, t3, t4]
defaultLayout [whamlet|
<p>Result = #{show res}
<form enctype=#{enctype}>
^{widget}
|]
--((result, widget), enctype) <- runFormGet $ renderBootstrap intAForm
--case result of
-- FormSuccess int -> if int > 0 then defaultLayout [whamlet|<p> Hallo!
-- ^{linkWidget int}
-- |]
-- else defaultLayout [whamlet|<form method=get action=@{HomeR} enctype=#{enctype}>
-- ^{widget}
-- <button>Submit
-- |]
-- FormMissing -> defaultLayout [whamlet|<form method=get action=@{HomeR} enctype=#{enctype}>
-- ^{widget}
-- <button>Submit
-- |]
-- _ -> defaultLayout [whamlet|<form method=get action=@{HomeR} enctype=#{enctype}>
-- ^{widget}
-- <button>Submit
-- |]
--handleCarR :: Int -> Handler Html
--handleCarR count = do
-- ((result,widget), enctype) <- runFormPost $ renderBootstrap $ nCarAForm count
-- case result of
-- FormMissing -> defaultLayout $ do
-- setTitle "Form Demo"
-- [whamlet|
-- <h2>Form Demo
-- <form method=post action=@{CarR count} enctype=#{enctype}>
-- ^{widget}
-- <button>Submit
-- |]
--
-- FormSuccess car -> defaultLayout $ do
-- setTitle "Form Auswerten"
-- [whamlet|
-- <h2>Car received:
-- <p>#{show car}
-- <p>
-- <a href=@{HomeR}>Zurück
-- |]
-- _ -> defaultLayout
-- [whamlet|
-- <h2>Fehler!
-- <p>Bitte nochmal eingeben:
-- <form method=post action=@{CarR count} enctype=#{enctype}>
-- ^{widget}
-- <button>Abschicken
-- |]
|
cirquit/quizlearner
|
resources/form/n_app_forms.hs
|
mit
| 5,130 | 0 | 14 | 1,945 | 556 | 341 | 215 | 39 | 1 |
module Logic.Validation where
import Logic.Types
import Control.Lens
import Data.Maybe
import qualified Data.Map as Map
validateCommand :: GameState -> Command -> Bool
validateCommand gs (MoveCommand us target) =
all id [allUnitsExist, targetOk target]
where
allUnitsExist = all id . map doesExist $ us
doesExist u = isJust $ Map.lookup u (gs ^. units)
targetOk (PositionTarget p) = True
targetOk (UnitTarget u) = doesExist u
|
HarvestGame/logic-prototype
|
src/Logic/Validation.hs
|
mit
| 470 | 0 | 10 | 107 | 152 | 80 | 72 | 12 | 2 |
{-------------------------------------------------
Exercise: implement the "nim" game
1: * * * * *
2: * * * *
3: * * *
4: * *
5: *
players take turn removing one or more stars from the end of a row
the winner is the player who removes the last star or stars from the board
--------------------------------------------------}
import Data.Char
initialBoard :: [Int]
initialBoard = [5,4,3,2,1]
nim :: [Int] -> Int -> IO ()
nim board player =
do showBoard board
if finished board then
showWinner (nextPlayer player)
else
do showMove player
row <- getInt "Row: "
stars <- getInt "Stars: "
if valid board row stars then
nim (playBoard board row stars) (nextPlayer player)
else
do putStrLn "ERROR: Invalid move"
nim board player
nextPlayer :: Int -> Int
nextPlayer 1 = 2
nextPlayer 2 = 1
finished :: [Int] -> Bool
finished = all (==0)
valid :: [Int] -> Int -> Int -> Bool
valid board row stars = board !! (row - 1) >= stars
playBoard :: [Int] -> Int -> Int -> [Int]
playBoard xs row stars =
[ if r == row then x - stars else x | (r, x) <- zip [1..] xs ]
isNumeric :: String -> Bool
isNumeric str = all isDigit str
getInt :: String -> IO Int
getInt s = do putStr s
line <- getLine
if isNumeric line then
return (read line)
else
do putStrLn "ERROR: Invalid input"
getInt s
showMove :: Int -> IO ()
showMove player = do putStr "Player "
putStr (show player)
putStrLn " move:"
showWinner :: Int -> IO ()
showWinner player = do putStr "Player "
putStr (show player)
putStrLn " wins!"
showBoard :: [Int] -> IO ()
showBoard xs = showBoardH $ zip [1..] xs
where
showBoardH [] = return ()
showBoardH ((n, stars):xs) =
do putStr (show n)
putStr ": "
putStrLn (concat (replicate stars "* "))
showBoardH xs
main = nim initialBoard 1
|
feliposz/learning-stuff
|
haskell/c9lectures-ch9-nim.hs
|
mit
| 2,137 | 0 | 13 | 744 | 657 | 322 | 335 | 51 | 3 |
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Language.LSP.Types.CodeAction where
import Data.Aeson.TH
import Data.Aeson.Types
import Data.Default
import Data.String
import Data.Text ( Text )
import qualified Data.Text as T
import Language.LSP.Types.Command
import Language.LSP.Types.Diagnostic
import Language.LSP.Types.Common
import Language.LSP.Types.Location
import Language.LSP.Types.Progress
import Language.LSP.Types.TextDocument
import Language.LSP.Types.Utils
import Language.LSP.Types.WorkspaceEdit
data CodeActionKind
= -- | Empty kind.
CodeActionEmpty
| -- | Base kind for quickfix actions: @quickfix@.
CodeActionQuickFix
| -- | Base kind for refactoring actions: @refactor@.
CodeActionRefactor
| -- | Base kind for refactoring extraction actions: @refactor.extract@.
-- Example extract actions:
--
-- - Extract method
-- - Extract function
-- - Extract variable
-- - Extract interface from class
-- - ...
CodeActionRefactorExtract
| -- | Base kind for refactoring inline actions: @refactor.inline@.
--
-- Example inline actions:
--
-- - Inline function
-- - Inline variable
-- - Inline constant
-- - ...
CodeActionRefactorInline
| -- | Base kind for refactoring rewrite actions: @refactor.rewrite@.
--
-- Example rewrite actions:
--
-- - Convert JavaScript function to class
-- - Add or remove parameter
-- - Encapsulate field
-- - Make method static
-- - Move method to base class
-- - ...
CodeActionRefactorRewrite
| -- | Base kind for source actions: @source@.
--
-- Source code actions apply to the entire file.
CodeActionSource
| -- | Base kind for an organize imports source action: @source.organizeImports@.
CodeActionSourceOrganizeImports
| CodeActionUnknown Text
deriving (Read, Show, Eq)
fromHierarchicalString :: Text -> CodeActionKind
fromHierarchicalString t = case t of
"" -> CodeActionEmpty
"quickfix" -> CodeActionQuickFix
"refactor" -> CodeActionRefactor
"refactor.extract" -> CodeActionRefactorExtract
"refactor.inline" -> CodeActionRefactorInline
"refactor.rewrite" -> CodeActionRefactorRewrite
"source" -> CodeActionSource
"source.organizeImports" -> CodeActionSourceOrganizeImports
s -> CodeActionUnknown s
toHierarchicalString :: CodeActionKind -> Text
toHierarchicalString k = case k of
CodeActionEmpty -> ""
CodeActionQuickFix -> "quickfix"
CodeActionRefactor -> "refactor"
CodeActionRefactorExtract -> "refactor.extract"
CodeActionRefactorInline -> "refactor.inline"
CodeActionRefactorRewrite -> "refactor.rewrite"
CodeActionSource -> "source"
CodeActionSourceOrganizeImports -> "source.organizeImports"
(CodeActionUnknown s) -> s
instance IsString CodeActionKind where
fromString = fromHierarchicalString . T.pack
instance ToJSON CodeActionKind where
toJSON = String . toHierarchicalString
instance FromJSON CodeActionKind where
parseJSON (String s) = pure $ fromHierarchicalString s
parseJSON _ = fail "CodeActionKind"
-- | Does the first 'CodeActionKind' subsume the other one, hierarchically. Reflexive.
codeActionKindSubsumes :: CodeActionKind -> CodeActionKind -> Bool
-- Simple but ugly implementation: prefix on the string representation
codeActionKindSubsumes parent child = toHierarchicalString parent `T.isPrefixOf` toHierarchicalString child
-- | The 'CodeActionKind's listed in the LSP spec specifically.
specCodeActionKinds :: [CodeActionKind]
specCodeActionKinds = [
CodeActionQuickFix
, CodeActionRefactor
, CodeActionRefactorExtract
, CodeActionRefactorInline
, CodeActionRefactorRewrite
, CodeActionSource
, CodeActionSourceOrganizeImports
]
-- -------------------------------------
data CodeActionKindClientCapabilities =
CodeActionKindClientCapabilities
{ -- | The code action kind values the client supports. When this
-- property exists the client also guarantees that it will
-- handle values outside its set gracefully and falls back
-- to a default value when unknown.
_valueSet :: List CodeActionKind
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionKindClientCapabilities
instance Default CodeActionKindClientCapabilities where
def = CodeActionKindClientCapabilities (List specCodeActionKinds)
data CodeActionLiteralSupport =
CodeActionLiteralSupport
{ _codeActionKind :: CodeActionKindClientCapabilities -- ^ The code action kind is support with the following value set.
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionLiteralSupport
data CodeActionResolveClientCapabilities =
CodeActionResolveClientCapabilities
{ _properties :: List Text -- ^ The properties that a client can resolve lazily.
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionResolveClientCapabilities
data CodeActionClientCapabilities = CodeActionClientCapabilities
{ -- | Whether code action supports dynamic registration.
_dynamicRegistration :: Maybe Bool,
-- | The client support code action literals as a valid response
-- of the `textDocument/codeAction` request.
-- Since 3.8.0
_codeActionLiteralSupport :: Maybe CodeActionLiteralSupport,
-- | Whether code action supports the `isPreferred` property. Since LSP 3.15.0
_isPreferredSupport :: Maybe Bool,
-- | Whether code action supports the `disabled` property.
--
-- @since 3.16.0
_disabledSupport :: Maybe Bool,
-- | Whether code action supports the `data` property which is
-- preserved between a `textDocument/codeAction` and a
-- `codeAction/resolve` request.
--
-- @since 3.16.0
_dataSupport :: Maybe Bool,
-- | Whether the client supports resolving additional code action
-- properties via a separate `codeAction/resolve` request.
--
-- @since 3.16.0
_resolveSupport :: Maybe CodeActionResolveClientCapabilities,
-- | Whether the client honors the change annotations in
-- text edits and resource operations returned via the
-- `CodeAction#edit` property by for example presenting
-- the workspace edit in the user interface and asking
-- for confirmation.
--
-- @since 3.16.0
_honorsChangeAnnotations :: Maybe Bool
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionClientCapabilities
-- -------------------------------------
makeExtendingDatatype "CodeActionOptions" [''WorkDoneProgressOptions]
[("_codeActionKinds", [t| Maybe (List CodeActionKind) |]), ("_resolveProvider", [t| Maybe Bool |]) ]
deriveJSON lspOptions ''CodeActionOptions
makeExtendingDatatype "CodeActionRegistrationOptions"
[ ''TextDocumentRegistrationOptions
, ''CodeActionOptions
] []
deriveJSON lspOptions ''CodeActionRegistrationOptions
-- -------------------------------------
-- | Contains additional diagnostic information about the context in which a
-- code action is run.
data CodeActionContext = CodeActionContext
{ -- | An array of diagnostics known on the client side overlapping the range provided to the
-- @textDocument/codeAction@ request. They are provided so that the server knows which
-- errors are currently presented to the user for the given range. There is no guarantee
-- that these accurately reflect the error state of the resource. The primary parameter
-- to compute code actions is the provided range.
_diagnostics :: List Diagnostic
-- | Requested kind of actions to return.
--
-- Actions not of this kind are filtered out by the client before being shown. So servers
-- can omit computing them.
, _only :: Maybe (List CodeActionKind)
}
deriving (Read, Show, Eq)
deriveJSON lspOptions ''CodeActionContext
makeExtendingDatatype "CodeActionParams"
[ ''WorkDoneProgressParams
, ''PartialResultParams
]
[ ("_textDocument", [t|TextDocumentIdentifier|]),
("_range", [t|Range|]),
("_context", [t|CodeActionContext|])
]
deriveJSON lspOptions ''CodeActionParams
newtype Reason = Reason {_reason :: Text}
deriving (Read, Show, Eq)
deriveJSON lspOptions ''Reason
-- | A code action represents a change that can be performed in code, e.g. to fix a problem or
-- to refactor code.
--
-- A CodeAction must set either '_edit' and/or a '_command'. If both are supplied,
-- the '_edit' is applied first, then the '_command' is executed.
data CodeAction =
CodeAction
{ -- | A short, human-readable, title for this code action.
_title :: Text,
-- | The kind of the code action. Used to filter code actions.
_kind :: Maybe CodeActionKind,
-- | The diagnostics that this code action resolves.
_diagnostics :: Maybe (List Diagnostic),
-- | Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted
-- by keybindings.
--
-- A quick fix should be marked preferred if it properly addresses the underlying error.
-- A refactoring should be marked preferred if it is the most reasonable choice of actions to take.
--
-- Since LSP 3.15.0
_isPreferred :: Maybe Bool,
_disabled :: Maybe Reason, -- ^ Marks that the code action cannot currently be applied.
-- | The workspace edit this code action performs.
_edit :: Maybe WorkspaceEdit,
-- | A command this code action executes. If a code action
-- provides an edit and a command, first the edit is
-- executed and then the command.
_command :: Maybe Command,
-- | A data entry field that is preserved on a code action between
-- a `textDocument/codeAction` and a `codeAction/resolve` request.
--
-- @since 3.16.0
_xdata :: Maybe Value
}
deriving (Read, Show, Eq)
deriveJSON lspOptions ''CodeAction
|
wz1000/haskell-lsp
|
lsp-types/src/Language/LSP/Types/CodeAction.hs
|
mit
| 10,168 | 0 | 11 | 2,171 | 1,167 | 695 | 472 | 131 | 9 |
module Main where
import Data.Maybe
import Control.Applicative
import Options.Applicative as Opts
import Text.Blaze.Html.Renderer.String
import ParseMd
data Params = Params
{ inputPath :: String
, outputPath :: String
, headerPath :: Maybe String
, footerPath :: Maybe String
}
defaultHeaderPath :: String
defaultHeaderPath = "html/header.html"
defaultFooterPath :: String
defaultFooterPath = "html/footer.html"
inputParser :: Parser String
inputParser = strOption $
long "input"
<> short 'i'
<> metavar "FILE"
<> help "The input path."
outputParser :: Parser String
outputParser = strOption $
long "output"
<> short 'o'
<> metavar "TARGET"
<> help "The output path."
headerParser :: Parser (Maybe String)
headerParser = optional . strOption $
long "header"
<> short 'h'
<> metavar "FILE"
<> help "A custom header to insert before the output."
footerParser :: Parser (Maybe String)
footerParser = optional . strOption $
long "footer"
<> short 'f'
<> metavar "FILE"
<> help "A custom footer to insert after the output."
parser :: Parser Params
parser = Params
<$> inputParser
<*> outputParser
<*> headerParser
<*> footerParser
revealify :: Params -> IO ()
revealify params =
do file <- readFile $ inputPath params
headerFile <- readFile $ fromMaybe defaultHeaderPath (headerPath params)
footerFile <- readFile $ fromMaybe defaultFooterPath (footerPath params)
let html = markDownToslides file
writeFile (outputPath params) $ headerFile ++ renderHtml html ++ footerFile
main :: IO ()
main = execParser opts >>= revealify
where
opts = info (helper <*> parser)
(fullDesc
<> progDesc "Markdown to Reveal.js"
<> header "MarkdownToReveal" )
|
archaeron/MarkdownToReveal
|
src/Main.hs
|
mit
| 1,695 | 111 | 9 | 299 | 494 | 263 | 231 | 58 | 1 |
module Compiler.Syntax.Type.Token where
import Compiler.Serializable
import Compiler.Syntax.Type.Position
import Compiler.PreAST.Type.Symbol
data Tok = TokID String -- identifiers
| TokLParen -- (
| TokRParen -- )
| TokSemicolon -- ;
| TokColon -- :
| TokPeriod -- .
| TokComma -- ,
| TokTypeInt -- "integer"
| TokTypeReal -- "real"
| TokTypeVoid -- "void"
| TokInt String -- integer literal
| TokReal String -- real literal
| TokProgram -- "program"
| TokFunction -- "function"
| TokBegin -- "begin"
| TokReturn -- "return"
| TokEnd -- "end"
| TokVar -- "var"
| TokOf -- "of"
| TokIf -- "if"
| TokThen -- "then"
| TokElse -- "else"
| TokWhile -- "while"
| TokDo -- "do"
| TokAssign -- :=
| TokS -- <
| TokL -- >
| TokSE -- <=
| TokLE -- >=
| TokEq -- =
| TokNEq -- !=
| TokPlus -- +
| TokMinus -- -
| TokTimes -- *
| TokDiv -- /
| TokNot -- "not"
| TokTo -- ..
| TokError String -- anything else
| TokEOF -- EOF
-- | TokLSB -- [
-- | TokRSB -- ]
deriving (Eq, Show)
instance Serializable Tok where
serialize (TokID s) = s -- identifier
serialize TokLParen = "(" -- (
serialize TokRParen = ")" -- )
serialize TokSemicolon = ";" -- ;
serialize TokColon = ":" -- :
serialize TokPeriod = "." -- .
serialize TokComma = "," -- ,
serialize TokTypeInt = "integer" -- "integer"
serialize TokTypeReal = "real" -- "real"
serialize TokTypeVoid = "void" -- "void"
serialize (TokInt s) = s -- int numbers
serialize (TokReal s) = s -- real numbers
serialize TokProgram = "program" -- "program"
serialize TokFunction = "function" -- "function"
serialize TokBegin = "begin" -- "begin"
serialize TokReturn = "return" -- "return"
serialize TokEnd = "end" -- "end"
serialize TokVar = "var" -- "var"
serialize TokOf = "of" -- "of"
serialize TokIf = "if" -- "if"
serialize TokThen = "then" -- "then"
serialize TokElse = "else" -- "else"
serialize TokWhile = "while" -- "while"
serialize TokDo = "do" -- "do"
serialize TokAssign = ":=" -- :=
serialize TokS = "<" -- <
serialize TokL = ">" -- >
serialize TokSE = "<=" -- <=
serialize TokLE = ">=" -- >=
serialize TokEq = "=" -- =
serialize TokNEq = "!=" -- !=
serialize TokPlus = "+" -- +
serialize TokMinus = "-" -- -
serialize TokTimes = "*" -- *
serialize TokDiv = "/" -- /
serialize TokNot = "not" -- "not"
serialize TokTo = ".." -- ..
serialize (TokError s) = s
--------------------------------------------------------------------------------
-- Token
data TokenF a = Token a Position
deriving (Eq, Show)
instance Serializable a => Serializable (TokenF a) where
serialize (Token a pos) = green (serialize a) ++ " " ++ serialize pos
type Token = TokenF Tok
--------------------------------------------------------------------------------
getPosition :: TokenF a -> Position
getPosition (Token _ p) = p
toSym :: Token -> Symbol
toSym (Token (TokID i) p) = Symbol i p
toLiteral :: Token -> Value
toLiteral (Token (TokInt i) p) = IntLiteral (read i) p
toLiteral (Token (TokReal i) p) = RealLiteral (read i) p
|
banacorn/mini-pascal
|
src/Compiler/Syntax/Type/Token.hs
|
mit
| 4,522 | 0 | 10 | 2,100 | 812 | 472 | 340 | 95 | 1 |
{-# LANGUAGE GADTs, OverloadedStrings, ImplicitParams, FlexibleContexts #-}
module Tweets where
import Control.Lens
import Data.Aeson (FromJSON)
import Data.Conduit (ResumableSource)
import Web.Twitter.Conduit
import Web.Twitter.Conduit
import Web.Twitter.Types.Lens
import Control.Monad.Reader
import Control.Monad.Trans.Resource (MonadResource)
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Text as T
genTWInfo :: IO TWInfo
genTWInfo = do
putStrLn "screen_name?: "
sc <- getLine
xs <- BS8.lines <$> BS8.readFile ("token/" ++ sc)
return $ setCredential
(twitterOAuth
{ oauthConsumerKey = xs!!0
, oauthConsumerSecret = xs!!1 })
(Credential
[ ("oauth_token", xs!!2)
, ("oauth_token_secret", xs!!3) ])
def
data Config = Config
{ manager :: Manager
, twInfo :: TWInfo
}
type AuthM = ReaderT Config IO
runAuth :: AuthM a -> IO a
runAuth m = do
mgr <- newManager tlsManagerSettings
tw <- genTWInfo
runReaderT m $ Config mgr tw
forkAuth :: AuthM a -> AuthM (IO a)
forkAuth m = do
cfg <- ask
return $ runReaderT m cfg
callM :: (FromJSON res) => APIRequest api res -> AuthM res
callM api = ask >>= \config -> lift $ call (twInfo config) (manager config) api
streamM :: (FromJSON res, MonadResource m, MonadReader Config m) => APIRequest api res -> m (ResumableSource m res)
streamM api = ask >>= \config -> stream (twInfo config) (manager config) api
fetchTimeline :: Integer -> AuthM [Status]
fetchTimeline n = callM $ homeTimeline & count ?~ n
fetchStatus :: StatusId -> AuthM Status
fetchStatus = callM . showId
favo :: StatusId -> AuthM Status
favo st = callM $ favoritesCreate st
unfavo :: StatusId -> AuthM Status
unfavo st = callM $ favoritesDestroy st
tweet :: T.Text -> AuthM Status
tweet = callM . update
replyTo :: StatusId -> T.Text -> AuthM Status
replyTo st txt = callM $ update txt & inReplyToStatusId ?~ st
fetchThread :: Status -> AuthM [Status]
fetchThread = go where
go st = do
(st:) <$> case st^.statusInReplyToStatusId of
Just k -> go =<< fetchStatus k
Nothing -> return []
|
myuon/bwitterkuchen
|
src/Tweets.hs
|
mit
| 2,102 | 0 | 14 | 409 | 743 | 387 | 356 | 60 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
import IRC.Types
import System.Environment
main = do
[channel] <- getArgs
(_, send) <- connectToBot "127.0.0.1" 27315
send $ Join $ T.pack channel
|
UnNetHack/pinobot
|
commands/Join.hs
|
mit
| 222 | 0 | 9 | 39 | 69 | 37 | 32 | 8 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TupleSections #-}
-----------------------------------------------------------------------------
-- |
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Concurrent state monad, providing a State-like interface but allowing
-- for multiple threads to operate on the same value simultaneously.
--
-- This module performs state computations strictly. For a lazy version,
-- see "Control.Monad.State.Concurrent.Lazy".
-----------------------------------------------------------------------------
module Control.Monad.State.Concurrent.Strict (
module Control.Monad.State,
-- *** The StateC monad transformer
StateC,
-- *** Concurrent state operations
runStateC, evalStateC, execStateC,
-- *** Running concurrent operations on a single input
runStatesC, evalStatesC, execStatesC,
-- *** Lifting other operations
liftCallCC, liftCatch, liftListen, liftPass
) where
import Control.Applicative
import Control.Arrow (first)
import Control.Concurrent.Lifted.Fork
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.Exception (throwIO)
import Control.Monad
import Control.Monad.Catch
import Control.Monad.State
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706
import Prelude hiding (catch)
#endif
-- ---------------------------------------------------------------------------
-- | A concurrent state transformer monad parameterized by:
--
-- * @s@ - The state. This is contained in a 'TVar'.
--
-- * @m@ - The inner monad.
--
-- The 'return' function leaves the state unchanged, while @>>=@ performs
-- actions atomically on the held 'TVar'.
--
-- This is very similar to @transformers@' 'StateT', with the exception of
-- the 'MonadIO' constraint on every instance, which is necessary to
-- perform STM actions.
newtype StateC s m a = StateC { _runStateC :: TVar s -> m (a, TVar s) }
instance MonadTrans (StateC s) where
lift m = StateC $ \s -> do
a <- m
return (a, s)
instance (Functor m, MonadIO m) => Functor (StateC s m) where
fmap f m = StateC $ \s ->
fmap (first f) $ _runStateC m s
instance (Functor m, MonadIO m) => Applicative (StateC s m) where
pure = return
(<*>) = ap
instance (MonadIO m, Functor m, MonadPlus m) => Alternative (StateC s m) where
empty = mzero
(<|>) = mplus
instance (MonadPlus m, MonadIO m) => MonadPlus (StateC s m) where
mzero = StateC $ const mzero
m `mplus` n = StateC $ \s -> _runStateC m s `mplus` _runStateC n s
instance MonadIO m => Monad (StateC s m) where
return a = StateC $ \s -> return (a, s)
m >>= k = StateC $ \s -> do
(a, s') <- _runStateC m s
_runStateC (k a) s'
instance (Functor m, MonadIO m) => MonadState s (StateC s m) where
get = StateC $ \tv -> do
s <- liftIO $ readTVarIO tv
return (s, tv)
state f = StateC $ \tv -> do
newval <- liftIO . atomically $ do
old <- readTVar tv
let (a, s) = f old
_ <- swapTVar tv s
return a
return (newval, tv)
instance (MonadIO m, MonadFix m) => MonadFix (StateC s m) where
mfix f = StateC $ \s -> mfix $ \(a, _) -> _runStateC (f a) s
instance MonadIO m => MonadIO (StateC s m) where
liftIO i = StateC $ \s -> do
a <- liftIO i
return (a, s)
instance (MonadIO m, MonadCatch m) => MonadCatch (StateC s m) where
throwM = liftIO . throwIO
catch = liftCatch catch
mask a = StateC $ \tv -> mask $ \u -> _runStateC (a $ q u) tv where
q u (StateC f) = StateC (u . f)
uninterruptibleMask a =
StateC $ \tv -> uninterruptibleMask $ \u -> _runStateC (a $ q u) tv where
q u (StateC f) = StateC (u . f)
instance MonadFork m => MonadFork (StateC s m) where
fork = liftFork fork
forkOn i = liftFork (forkOn i)
forkOS = liftFork forkOS
liftFork :: Monad m => (m () -> m a) -> StateC t m () -> StateC t m a
liftFork f (StateC m) = StateC $ \tv -> do
tid <- f . voidM $ m tv
return (tid, tv)
where voidM = (>> return ())
-- | Unwrap a concurrent state monad computation as a function.
runStateC :: MonadIO m
=> StateC s m a -- ^ state-passing computation to execute
-> TVar s -- ^ initial state
-> m (a, s) -- ^ return value and final state
runStateC m s = do
(a, b) <- _runStateC m s
r <- liftIO $ readTVarIO b
return (a, r)
-- | Evaluate a concurrent state computation with the given initial state
-- and return the final value, discarding the final state.
--
-- * @'evalStateC' m s = 'liftM' 'fst' ('runStateC' m s)@
evalStateC :: MonadIO m
=> StateC s m a -- ^ state-passing computation to execute
-> TVar s -- ^ initial state
-> m a -- ^ return value
evalStateC m s = liftM fst $ runStateC m s
-- | Execute a concurrent state computation with the given initial state and return
-- the final state, discarding the final value.
--
-- * @'execStateC' m s = 'liftM' 'snd' ('runStateC' m s)@
execStateC :: MonadIO m
=> StateC s m a -- ^ state-passing computation to execute
-> TVar s -- ^ initial state
-> m s -- ^ final state
execStateC m s = liftM snd $ runStateC m s
-- | Uniform lifting of a @callCC@ operation to the new monad.
liftCallCC :: ((((a, TVar s) -> m (b, TVar s)) -> m (a, TVar s)) -> m (a, TVar s)) ->
((a -> StateC s m b) -> StateC s m a) -> StateC s m a
liftCallCC callCC f = StateC $ \tv ->
callCC $ \c ->
_runStateC (f (\a -> StateC $ \_ -> c (a, tv))) tv
-- | Lift a @catchError@ operation to the new monad.
liftCatch :: (m (a, TVar s) -> (e -> m (a, TVar s)) -> m (a, TVar s)) ->
StateC s m a -> (e -> StateC s m a) -> StateC s m a
liftCatch catchError m h =
StateC $ \s -> _runStateC m s `catchError` \e -> _runStateC (h e) s
-- | Lift a @listen@ operation to the new monad.
liftListen :: Monad m =>
(m (a, TVar s) -> m ((a, TVar s), w)) -> StateC s m a -> StateC s m (a,w)
liftListen listen m = StateC $ \tv -> do
((a, s'), w) <- listen (_runStateC m tv)
return ((a, w), s')
-- | Lift a @pass@ operation to the new monad.
liftPass :: Monad m =>
(m ((a, TVar s), b) -> m (a, TVar s)) -> StateC s m (a, b) -> StateC s m a
liftPass pass m = StateC $ \tv -> pass $ do
((a, f), s') <- _runStateC m tv
return ((a, s'), f)
-- | Run multiple state operations on the same value, returning the
-- resultant state and the value produced by each operation.
runStatesC :: MonadFork m
=> [StateC s m a] -- ^ state-passing computations to execute
-> s -- ^ initial state
-> m ([a], s) -- ^ return values and final state
runStatesC ms s = do
v <- liftIO $ newTVarIO s
mvs <- mapM (const (liftIO newEmptyMVar)) ms
forM_ (zip mvs ms) $ \(mv, operation) -> fork $ do
res <- evalStateC operation v
liftIO $ putMVar mv res
items <- forM mvs (liftIO . takeMVar)
end <- liftIO $ readTVarIO v
return (items, end)
-- | Run multiple state operations on the same value, returning all values
-- produced by each operation.
--
-- * @'evalStatesC' ms s = 'liftM' 'fst' ('runStatesC' ms s)@
evalStatesC :: MonadFork m
=> [StateC s m a] -- ^ state-passing computations to execute
-> s -- ^ initial state
-> m [a] -- ^ return values
evalStatesC ms s = liftM fst $ runStatesC ms s
-- | Run multiple state operations on the same value, returning the
-- resultant state.
--
-- * @'execStatesC' ms s = 'liftM' 'snd' ('runStatesC' ms s)@
execStatesC :: MonadFork m
=> [StateC s m a] -- ^ state-passing computations to execute
-> s -- ^ initial state
-> m s -- ^ final state
execStatesC ms s = liftM snd $ runStatesC ms s
|
pikajude/concurrent-state
|
src/Control/Monad/State/Concurrent/Strict.hs
|
mit
| 7,870 | 0 | 17 | 1,978 | 2,408 | 1,270 | 1,138 | 135 | 1 |
import Paths_report_comparator
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Builder
import Control.Monad (forM_)
import Main.Header
import Main.Body
import Main.EditAll
import Data.Types
-- Настройки, которые не удаётся сделать через glade
prepareGUI :: Builder -> IO ()
prepareGUI b = do
-- Цвет фона для вкладок
let c = 62000 -- 65535 — максимум
forM_ [ "photosVP", "notesVP", "matchedVP" ]
$ \ id -> do
vp <- builderGetObject b castToViewport id
-- TODO: В Windows фон по умолчанию ярче, поэтому цвет получается
-- похожим на дефолтный. Пытался считать дефолтный, чтобы увеличить
-- его на константу, но почему-то в Windows и Unix цвет считывается
-- одинаковый, хотя визуально они явно различаются.
--style <- get vp widgetStyle
--print =<< styleGetBackground style StateNormal
widgetModifyBg vp StateNormal (Color c c c)
-- Dirmode по умолчанию
photosDirMode <- builderGetObject b castToComboBox "photosDirMode"
comboBoxSetActive photosDirMode 0
setupHandlers :: Builder -> IO ()
setupHandlers b = do
-- Обновление меню страниц таблицы
notes <- builderGetObject b castToFileChooserButton "notes"
after notes currentFolderChanged (updateSheets b)
-- Обновление preview
photos <- builderGetObject b castToFileChooserButton "photos"
notesSheets <- builderGetObject b castToComboBox "notesSheets"
after photos currentFolderChanged (updatePhotosPreview b)
after notesSheets changed (updateNotesPreview b)
-- Клик по "editAll"
editAllPhotos <- builderGetObject b castToButton "editAllPhotos"
on editAllPhotos buttonActivated (editAll b Photo)
-- Клик по "Сравнить"
submit <- builderGetObject b castToButton "submit"
on submit buttonActivated (compareReports b) >> return ()
main :: IO ()
main = do
initGUI
b <- builderNew
getDataFileName "main.glade" >>= builderAddFromFile b
mainWindow <- builderGetObject b castToWindow "mainWindow"
windowMaximize mainWindow
onDestroy mainWindow mainQuit
prepareGUI b
setupHandlers b
widgetShow mainWindow
--editAll b Photo -- FIXME: временно для разработки
mainGUI
|
kahless/report-comparator
|
src/Main/Main.hs
|
mit
| 2,557 | 0 | 13 | 484 | 443 | 212 | 231 | 41 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
import Data.Foldable (for_)
import Data.String (fromString)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Pangram (isPangram)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "isPangram" $ for_ cases test
where
test Case{..} = it description $ isPangram (fromString input) `shouldBe` expected
data Case = Case { description :: String
, input :: String
, expected :: Bool
}
cases :: [Case]
cases = [ Case { description = "with empty sentence"
, input = ""
, expected = False
}
, Case { description = "with perfect lower case"
, input = "abcdefghijklmnopqrstuvwxyz"
, expected = True
}
, Case { description = "with only lower case"
, input = "the quick brown fox jumps over the lazy dog"
, expected = True
}
, Case { description = "with missing character 'x'"
, input = "a quick movement of the enemy will jeopardize five gunboats"
, expected = False
}
, Case { description = "with missing character 'h'"
, input = "five boxing wizards jump quickly at it"
, expected = False
}
, Case { description = "with underscores"
, input = "the_quick_brown_fox_jumps_over_the_lazy_dog"
, expected = True
}
, Case { description = "with numbers"
, input = "the 1 quick brown fox jumps over the 2 lazy dogs"
, expected = True
}
, Case { description = "with missing letters replaced by numbers"
, input = "7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog"
, expected = False
}
, Case { description = "with mixed case and punctuation"
, input = "\"Five quacking Zephyrs jolt my wax bed.\""
, expected = True
}
, Case { description = "with mixed case"
, input = "the quick brown fox jumps over with lazy FX"
, expected = False
}
, Case { description = "with missing character and non-ascii letters"
, input = "abcdefghijklmnopqrstuvwxyÃ"
, expected = False
}
, Case { description = "with additional non-ascii letters"
, input = "abcdefghijklmnopqrstuvwxyzÃ"
, expected = True
}
{-
-- The following test can be enabled for String-based solutions:
, Case { description = "with termination as soon as all letters have occurred"
, input = "abcdefghijklmnopqrstuvwxyz" ++ [undefined]
, expected = True
}
-- -}
]
-- 73e37723b154f0c741d227c43af09d23dc7e5e44
|
exercism/xhaskell
|
exercises/practice/pangram/test/Tests.hs
|
mit
| 3,253 | 0 | 11 | 1,317 | 473 | 294 | 179 | 52 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module Database.Neo4j.Batch (
-- * Usage
-- $use
-- * General
Batch, runBatch, BatchFuture(..), NodeBatchIdentifier, RelBatchIdentifier, BatchEntity,
-- * Nodes
createNode, createNamedNode, getNode, getNamedNode, deleteNode,
-- * Relationships
createRelationship, createNamedRelationship, getRelationship, getNamedRelationship, getRelationshipFrom,
getRelationshipTo, deleteRelationship, getRelationships,
-- * Properties
setProperties, setProperty, deleteProperties, deleteProperty,
-- * Labels
getLabels, getNodesByLabelAndProperty, addLabels, changeLabels, removeLabel
)where
import Database.Neo4j.Batch.Label
import Database.Neo4j.Batch.Node
import Database.Neo4j.Batch.Property
import Database.Neo4j.Batch.Relationship
import Database.Neo4j.Batch.Types
-- $use
--
-- With batch mode you can issue several commands to Neo4j at once.
-- In order to issue batches you must use the Batch monad, parameters in batch mode can be actual entities already
-- obtained by issuing regular commands or previous batch commands, or even batch futures, that is you can refer
-- to entities created in the same batch, for instance:
--
-- > withConnection "127.0.0.1" 7474 $ do
-- > g <- B.runBatch $ do
-- > neo <- B.createNode M.empty
-- > cypher <- B.createNode M.empty
-- > B.createRelationship "KNOWS" M.empty neo cypher
-- > ...
--
-- Batch commands return a "Database.Neo4j.Graph" object that holds all the information about relationships,
-- nodes and their labels that can be inferred from running a batch command.
|
asilvestre/haskell-neo4j-rest-client
|
src/Database/Neo4j/Batch.hs
|
mit
| 1,675 | 0 | 5 | 295 | 157 | 115 | 42 | 14 | 0 |
{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, DoAndIfThenElse #-}
module System.USB.HID ( hidInit
, hidOpen
, hidClose
, hidRead
, hidWrite
, HidDevice
) where
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable
import Foreign.C.String
import Foreign.Marshal.Alloc
import Control.Exception
import Control.Monad
import Data.Typeable
import qualified Data.ByteString as B
newtype HidDevice = HidDevice (Ptr HidDevice)
data HidError = HidError deriving (Show, Typeable)
instance Exception HidError
foreign import ccall safe "hidapi/hidapi.h hid_init"
c_hid_init :: IO CInt
hidInit :: IO ()
hidInit = do res <- c_hid_init
if res /= 0 then throwIO HidError
else return ()
foreign import ccall safe "hidapi/hidapi.h hid_open"
c_hid_open :: CUShort -> CUShort -> Ptr CInt -> IO HidDevice
hidOpen :: CUShort -> CUShort -> IO HidDevice
hidOpen vendor product = do h@(HidDevice x) <- c_hid_open vendor product nullPtr
if x == nullPtr then throwIO HidError
else return h
foreign import ccall safe "hidapi/hidapi.h hid_close"
hid_close :: HidDevice -> IO ()
hidClose :: HidDevice -> IO ()
hidClose = hid_close
foreign import ccall safe "hidapi/hidapi.h hid_write"
c_hid_write :: HidDevice -> CString -> Int -> IO CInt
hidWrite :: HidDevice -> B.ByteString -> IO Int
hidWrite dev msg = B.useAsCStringLen msg (\(ptr, len) -> do res <- c_hid_write dev ptr len
if res == -1 then throwIO HidError
else return $ fromIntegral res)
foreign import ccall safe "hidapi/hidapi.h hid_read"
c_hid_read :: HidDevice -> CString -> Int -> IO CInt
hidRead :: HidDevice -> Int -> IO B.ByteString
hidRead dev size = allocaBytes size $ (\ptr -> do res <- c_hid_read dev ptr size
if res == -1 then throwIO HidError
else B.packCStringLen (ptr, fromIntegral res))
|
gaeldeest/himinn
|
System/USB/HID.hs
|
mit
| 2,213 | 0 | 13 | 719 | 563 | 296 | 267 | 47 | 2 |
module Main where
import Protolude
import Grafs.Cli
import Grafs.Webserver
main :: IO ()
main = do
(CLIOptions p) <- getOpts
runWebserver p
|
uwap/Grafs
|
src/Main.hs
|
mit
| 150 | 0 | 9 | 32 | 51 | 27 | 24 | 8 | 1 |
{-# LANGUAGE ScopedTypeVariables, MultiWayIf, TupleSections #-}
{-
The GHCJS-specific parts of the frontend (ghcjs program)
Our main frontend is copied from GHC, Compiler.Program
-}
module Compiler.GhcjsProgram where
import GHC
import GhcMonad
import DynFlags
import ErrUtils (fatalErrorMsg'')
import Panic (handleGhcException)
import Exception
import Packages (initPackages)
import Prelude
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.ByteString as B
import Data.List (isPrefixOf)
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy.IO as TL
import Distribution.System (buildOS, OS(..), buildPlatform)
import Distribution.Verbosity (deafening, intToVerbosity)
import Distribution.Simple.BuildPaths (exeExtension)
import Distribution.Simple.Utils (installExecutableFile, installDirectoryContents)
import Distribution.Simple.Program (runProgramInvocation, simpleProgramInvocation)
import Options.Applicative
import System.Directory (doesFileExist, doesDirectoryExist, createDirectoryIfMissing)
import System.Environment (getArgs)
import System.Exit
import System.FilePath
import System.IO
import System.Process
import Compiler.Compat
import Compiler.GhcjsPlatform
import Compiler.Info
import Compiler.Settings
import Compiler.Utils
import qualified Compiler.Platform as Platform
-- fixme, make frontend independent of backend
import qualified Gen2.Object as Object
import qualified Gen2.ClosureInfo as Gen2
import qualified Gen2.Shim as Gen2
import qualified Gen2.Rts as Gen2
import qualified Gen2.TH as Gen2
getGhcjsSettings :: [Located String] -> IO ([Located String], GhcjsSettings)
getGhcjsSettings args =
case p of
Failure failure -> do
let (msg, code) = renderFailure failure "ghcjs"
hPutStrLn stderr msg
exitWith code
Success gs1 -> do
gs2 <- envSettings
return (args', gs1 <> gs2)
CompletionInvoked _ -> exitWith (ExitFailure 1)
where
(ga,args') = partArgs args -- partition (\a -> any (`isPrefixOf` unLoc a) as) args
p = execParserPure (prefs mempty) optParser' ga
partArgs :: [Located String] -> ([String], [Located String])
partArgs [] = ([],[])
partArgs (x:xs)
| unLoc x `elem` ghcjsFlags =
let (g,o) = partArgs xs in (('-':unLoc x):g,o)
partArgs (x1:x2:xs) | unLoc x1 `elem` ghcjsOpts =
let (g,o) = partArgs xs in (('-':unLoc x1++"="++unLoc x2):g,o)
partArgs (x:xs) =
let (g,o) = partArgs xs in (g,x:o)
ghcjsFlags = [ "-native-executables"
, "-native-too"
, "-build-runner"
, "-no-js-executables"
, "-only-out"
, "-no-rts"
, "-no-stats"
, "-dedupe"
]
ghcjsOpts = [ "-strip-program"
, "-log-commandline"
, "-with-ghc"
, "-generate-base"
, "-use-base"
, "-link-js-lib"
, "-js-lib-outputdir"
, "-js-lib-src"
]
envSettings = GhcjsSettings <$> getEnvOpt "GHCJS_NATIVE_EXECUTABLES"
<*> getEnvOpt "GHCJS_NATIVE_TOO"
<*> pure False
<*> pure False
<*> pure Nothing
<*> getEnvMay "GHCJS_LOG_COMMANDLINE_NAME"
<*> getEnvMay "GHCJS_WITH_GHC"
<*> pure False
<*> pure False
<*> pure False
<*> pure Nothing
<*> pure NoBase
<*> pure Nothing
<*> pure Nothing
<*> pure []
<*> pure False
optParser' :: ParserInfo GhcjsSettings
optParser' = info (helper <*> optParser) fullDesc
optParser :: Parser GhcjsSettings
optParser = GhcjsSettings
<$> switch ( long "native-executables" )
<*> switch ( long "native-too" )
<*> switch ( long "build-runner" )
<*> switch ( long "no-js-executables" )
<*> optStr ( long "strip-program" )
<*> optStr ( long "log-commandline" )
<*> optStr ( long "with-ghc" )
<*> switch ( long "only-out" )
<*> switch ( long "no-rts" )
<*> switch ( long "no-stats" )
<*> optStr ( long "generate-base" )
<*> (maybe NoBase BaseFile <$> optStr ( long "use-base" ))
<*> optStr ( long "link-js-lib" )
<*> optStr ( long "js-lib-outputdir" )
<*> strings ( long "js-lib-src" )
<*> switch ( long "dedupe" )
strings :: Mod OptionFields String -> Parser [String]
strings = many <$> option str
optStr :: Mod OptionFields String -> Parser (Maybe String)
optStr = optional . option str
printVersion :: IO ()
printVersion = putStrLn $
"The Glorious Glasgow Haskell Compilation System for JavaScript, version " ++
getCompilerVersion ++ " (GHC " ++ getGhcCompilerVersion ++ ")"
printNumericVersion :: IO ()
printNumericVersion = putStrLn getCompilerVersion
printRts :: DynFlags -> IO ()
printRts dflags = TL.putStrLn (Gen2.rtsText dflags $ Gen2.dfCgSettings dflags) >> exitSuccess
printDeps :: FilePath -> IO ()
printDeps = Object.readDepsFile >=> TL.putStrLn . Object.showDeps
printObj :: FilePath -> IO ()
printObj = Object.readObjectFile >=> TL.putStrLn . Object.showObject
runJsProgram :: Maybe String -> [String] -> IO ()
runJsProgram Nothing _ = error noTopDirErrorMsg
runJsProgram (Just topDir) args
| (_:script:scriptArgs) <- dropWhile (/="--run") args = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering
node <- T.strip <$> T.readFile (topDir </> "node")
ph <- runProcess (T.unpack node) (script:scriptArgs) Nothing Nothing Nothing Nothing Nothing
exitWith =<< waitForProcess ph
| otherwise = error "usage: ghcjs --run [script] [arguments]"
-- | when booting GHCJS, we pretend to have the Cabal lib installed
-- call GHC to compile our Setup.hs
bootstrapFallback :: IO ()
bootstrapFallback = do
ghc <- fmap (fromMaybe "ghc") $ getEnvMay "GHCJS_WITH_GHC"
as <- ghcArgs <$> getArgs
e <- rawSystem ghc $ as -- run without GHCJS library prefix arg
case (e, getOutput as) of
(ExitSuccess, Just o) ->
createDirectoryIfMissing False (o <.> "jsexe")
_ -> return ()
exitWith e
where
ignoreArg a = "-B" `isPrefixOf` a || a == "-build-runner"
ghcArgs args = filter (not . ignoreArg) args ++ ["-threaded"]
getOutput [] = Nothing
getOutput ("-o":x:_) = Just x
getOutput (_:xs) = getOutput xs
installExecutable :: DynFlags -> GhcjsSettings -> [String] -> IO ()
installExecutable dflags settings srcs =
case (srcs, outputFile dflags) of
([from], Just to) -> do
let v = fromMaybe deafening . intToVerbosity $ verbosity dflags
nativeExists <- doesFileExist $ from <.> exeExtension buildPlatform
when nativeExists $ do
installExecutableFile v (from <.> exeExtension buildPlatform) (to <.> exeExtension buildPlatform)
let stripFlags = if buildOS == OSX then ["-x"] else []
case gsStripProgram settings of
Just strip -> runProgramInvocation v . simpleProgramInvocation strip $
stripFlags ++ [to <.> exeExtension buildPlatform]
Nothing -> return ()
jsExists <- doesDirectoryExist $ from <.> jsexeExtension
when jsExists $ installDirectoryContents v (from <.> jsexeExtension) (to <.> jsexeExtension)
unless (nativeExists || jsExists) $ do
hPutStrLn stderr $ "No executable found to install at " ++ from
exitFailure
_ -> do
hPutStrLn stderr "Usage: ghcjs --install-executable <from> -o <to>"
exitFailure
{-
Generate lib.js and lib1.js for the latest version of all installed
packages
fixme: make this variant-aware?
-}
generateLib :: GhcjsSettings -> Ghc ()
generateLib _settings = do
dflags1 <- getSessionDynFlags
liftIO $ do
(dflags2, pkgs0) <- initPackages dflags1
let pkgs = mapMaybe (\p -> fmap (T.pack (getInstalledPackageName dflags2 p),)
(getInstalledPackageVersion dflags2 p))
pkgs0
base = getDataDir (getLibDir dflags2) </> "shims"
pkgs' :: [(T.Text, Version)]
pkgs' = M.toList $ M.fromListWith max pkgs
(beforeFiles, afterFiles) <- Gen2.collectShims base pkgs'
B.writeFile "lib.js" . mconcat =<< mapM B.readFile beforeFiles
B.writeFile "lib1.js" . mconcat =<< mapM B.readFile afterFiles
putStrLn "generated lib.js and lib1.js for:"
mapM_ (\(p,v) -> putStrLn $ " " ++ T.unpack p ++
if isEmptyVersion v then "" else ("-" ++ T.unpack (showVersion v))) pkgs'
setGhcjsSuffixes :: Bool -- oneshot option, -c
-> DynFlags
-> DynFlags
setGhcjsSuffixes oneshot df = df
{ objectSuf = mkGhcjsSuf (objectSuf df)
, dynObjectSuf = mkGhcjsSuf (dynObjectSuf df)
, hiSuf = mkGhcjsSuf (hiSuf df)
, dynHiSuf = mkGhcjsSuf (dynHiSuf df)
, outputFile = fmap mkGhcjsOutput (outputFile df)
, dynOutputFile = fmap mkGhcjsOutput (dynOutputFile df)
, outputHi = fmap mkGhcjsOutput (outputHi df)
, ghcLink = if oneshot then NoLink else ghcLink df
}
-- | make sure we don't show panic messages with the "report GHC bug" text, since
-- those are probably our fault.
ghcjsErrorHandler :: (ExceptionMonad m, MonadIO m)
=> FatalMessager -> FlushOut -> m a -> m a
ghcjsErrorHandler fm (FlushOut flushOut) inner =
-- top-level exception handler: any unrecognised exception is a compiler bug.
ghandle (\exception -> liftIO $ do
flushOut
case fromException exception of
-- an IO exception probably isn't our fault, so don't panic
Just (ioe :: IOException) ->
fatalErrorMsg'' fm (show ioe)
_ -> case fromException exception of
Just UserInterrupt ->
-- Important to let this one propagate out so our
-- calling process knows we were interrupted by ^C
liftIO $ throwIO UserInterrupt
Just StackOverflow ->
fatalErrorMsg'' fm "stack overflow: use +RTS -K<size> to increase it"
_ -> case fromException exception of
Just (ex :: ExitCode) -> liftIO $ throwIO ex
_ -> fatalErrorMsg'' fm (ghcjsShowException exception)
exitWith (ExitFailure 1)
) $
-- error messages propagated as exceptions
handleGhcException
(\ge -> liftIO $ do
flushOut
case ge of
Signal _ -> exitWith (ExitFailure 1)
_ -> do fatalErrorMsg'' fm (ghcjsShowException $ toException ge)
exitWith (ExitFailure 1)
) $
inner
ghcjsShowException :: SomeException -> String
ghcjsShowException e = case fromException e of
Just (PprPanic s _) -> ghcjsShowException $ toException (Panic (s ++ "\n<<details unavailable>>"))
Just (Panic s) -> "panic! (the 'impossible' happened)\n"
++ " (GHCJS version " ++ getCompilerVersion ++ ", GHC version " ++ getGhcCompilerVersion ++ "):\n\t"
++ s ++ "\n\n"
++ "Please report this as a GHCJS bug: https://github.com/ghcjs/ghcjs/issues\n"
Just (PprSorry s _) -> ghcjsShowException $ toException (Sorry (s ++ "\n<<details unavailable>>"))
Just (Sorry s) -> "sorry! (unimplemented feature or known bug)\n"
++ " (GHCJS version " ++ getCompilerVersion ++ ", GHC version " ++ getGhcCompilerVersion ++ "):\n\t"
++ s ++ "\n"
_ -> show e
ghcjsCleanupHandler :: (ExceptionMonad m, MonadIO m)
=> DynFlags -> GhcjsEnv -> m a -> m a
ghcjsCleanupHandler dflags env inner =
defaultCleanupHandler dflags inner `gfinally`
(liftIO $ Gen2.finishTHAll env)
runGhcjsSession :: Maybe FilePath -- ^ Directory with library files,
-- like GHC's -B argument
-> GhcjsSettings
-> Ghc b -- ^ Action to perform
-> IO b
runGhcjsSession mbMinusB settings m = runGhc mbMinusB $ do
setupSessionForGhcjs settings
m
-- | modifies a Ghc session to use the GHCJS target
setupSessionForGhcjs :: GhcjsSettings
-> Ghc ()
setupSessionForGhcjs ghcjsSettings = do
dflags <- getSessionDynFlags
let base = getLibDir dflags
jsEnv <- liftIO newGhcjsEnv
_ <- setSessionDynFlags
$ setGhcjsPlatform ghcjsSettings jsEnv [] base
$ updateWays $ addWay' (WayCustom "js")
$ setGhcjsSuffixes False dflags
pure ()
{-|
get the command line arguments for GHCJS by adding the ones specified in the
ghcjs.exe.options file on Windows, since we cannot run wrapper scripts there
also handles some location information queries for Setup.hs and ghcjs-boot,
that would otherwise fail due to missing boot libraries or a wrapper interfering
-}
getWrappedArgs :: IO ([String], Bool, Bool)
getWrappedArgs = do
booting <- getEnvOpt "GHCJS_BOOTING" -- do not check that we're booted
booting1 <- getEnvOpt "GHCJS_BOOTING_STAGE1" -- enable GHC fallback
as <- getArgs
if | "--ghcjs-setup-print" `elem` as -> printBootInfo as >> exitSuccess
| "--ghcjs-booting-print" `elem` as -> getArgs >>= printBootInfo >> exitSuccess
| otherwise -> do
fas <- getArgs
return (fas, booting, booting1)
printBootInfo :: [String] -> IO ()
printBootInfo v
| "--print-topdir" `elem` v = putStrLn t
| "--print-libdir" `elem` v = putStrLn t
| "--print-global-db" `elem` v = putStrLn (getGlobalPackageDB t)
| "--print-user-db-dir" `elem` v = putStrLn . fromMaybe "<none>" =<< getUserPackageDir
| "--numeric-ghc-version" `elem` v = putStrLn getGhcCompilerVersion
| "--print-rts-profiled" `elem` v = print rtsIsProfiled
| otherwise = error "no --ghcjs-setup-print or --ghcjs-booting-print options found"
where
t = fromMaybe (error noTopDirErrorMsg) (getArgsTopDir v)
noTopDirErrorMsg :: String
noTopDirErrorMsg = "Cannot determine library directory.\n\nGHCJS requires a -B argument to specify the library directory. " ++
if Platform.isWindows
then
"On Windows, GHCJS reads the `ghcjs.exe.options' and `ghcjs-[version].exe.options' files from the " ++
"program directory for extra command line arguments."
else
"Usually this argument is provided added by a shell script wrapper. Verify that you are not accidentally " ++
"invoking the executable directly."
getArgsTopDir :: [String] -> Maybe String
getArgsTopDir xs
| null minusB_args = Nothing
| otherwise = Just (drop 2 $ last minusB_args)
where
minusB_args = filter ("-B" `isPrefixOf`) xs
buildJsLibrary :: DynFlags -> [FilePath] -> [FilePath] -> [FilePath] -> IO ()
buildJsLibrary _dflags srcs js_objs objs = do
print srcs
print js_objs
print objs
exitFailure
|
ghcjs/ghcjs
|
src/Compiler/GhcjsProgram.hs
|
mit
| 16,084 | 0 | 24 | 4,890 | 3,851 | 1,948 | 1,903 | -1 | -1 |
module MonadicMICL where
import Control.Monad
import Control.Monad.State
import MICL
-- | stateful operators and combinators
-- movement: takes a signal, and updates the state status.
-- switchAgent: takes a signal, and updates the state status.
-- switchMode: takes a signal, and updates the state status.
--
move :: Program Input
move sig = do (t,(loc,dis,opm)) <- get
put (time (addTime tick (t,(loc,dis,opm)))
,(locate sig loc,dis,opm))
(t,(loc,dis,opm)) <- get
put (t,(loc,clearWaypoint loc dis,opm))
newTask :: Program Output
newTask sig = do (t,(loc,dis,opm)) <- get
put (t,(loc,addTask sig dis,opm))
removeTask :: Program Output
removeTask sig = do (t,(loc,dis,opm)) <- get
put (t,(loc,deleteTask sig dis,opm))
updateAgent :: Program Input
updateAgent sig = do (t,(loc,dis,opm)) <- get
put (t,(loc,dis,(changeAgent opm,snd opm)))
updateMode :: Program Input
updateMode sig = do (t,(loc,dis,opm)) <- get
put (t,(loc,dis,(fst opm,changeMode opm)))
-- given a signal and a desired ending location, move until the
-- location matches the desired one
to :: Input -> Float -> State (Time,Status) ()
to inp f = do (t,s) <- get
case (projectLoc inp s /= f) of
True -> move inp >> to inp f
False -> return ()
-- this is to inject an instruction, or change the status at a
-- given time
at :: Program Input -> Time -> Input -> State (Time,Status) ()
at prg t inp = do (t',s) <- get
case (t == t') of
True -> prg inp
False -> return ()
interrupt :: Program Input -> Time -> Input -> State (Time,Status) ()
interrupt = undefined
while :: Program a -> Program a -> Program a
while p1 p2 a = do (t,s) <- get
p2 a >> p1 a
return ()
untilW :: [Input] -> Waypoint -> State (Time,Status) ()
untilW [] wpt = do return ()
untilW (i:is) wpt = do (t,(loc,dis,opm)) <- get
case (wpt == loc) of
False -> i `to` (projectLoc i (wpt,dis,opm)) >> untilW is wpt
True -> return ()
untilT :: [Input] -> Time -> State (Time,Status) ()
untilT [] tme = do return ()
untilT (i:is) tme = do (t,s) <- get
case (t == tme) of
False -> i `to` (projectLoc i s) >> untilT is tme
True -> return ()
untilO :: Input -> OpMode -> State (Time,Status) ()
untilO inp opm = do (t,(loc,dis,opm')) <- get
case (opm' == opm) of
False -> updateMode inp
True -> return ()
-- | semantic domain for the state
--
type Program a = a -> State (Time,Status) ()
-- | helper functions
--
projectLoc :: Input -> Status -> Float
projectLoc inp (loc,_,_) = let (n,e,d) = loc in
if (pitch inp) /= 0
then n
else if (roll inp) /= 0
then e
else if (gaz inp) /= 0
then d
else 0
addTime :: Time -> (Time,Status) -> (Time,Status)
addTime t (t',s) = (t + t',s)
time :: (Time,Status) -> Time
time (t,s) = t
-- | default values
--
inputDefault = Input { channel = (fst opModeDefault)
, mode = (snd opModeDefault)
, enable = enabled
, roll = zeroPower
, pitch = zeroPower
, gaz = zeroPower
, yaw = zeroPower
}
displayDefault = []
opModeDefault = (Computer,Normal)
homeLocation = (north 0.0,east 0.0,down 0.0)
type Time = Double
statusDefault = (startTime,(homeLocation,displayDefault,opModeDefault))
-- | smart constructors
--
-- movement signals
ascend f = inputDefault { gaz = f }
descend f = inputDefault { gaz = (negate f) }
strafeL f = inputDefault { roll = (negate f) }
strafeR f = inputDefault { roll = f }
forward f = inputDefault { pitch = f }
backward f = inputDefault { pitch = (negate f) }
spinL f = inputDefault { enable = disabled
, yaw = (negate f)
}
spinR f = inputDefault { enable = disabled
, yaw = f
}
-- display signals
waypoint l = Left l
instruction i = Right i
-- opmode signals
-- opmodes
wait a = inputDefault { channel = a
, mode = Wait
}
reinstate a = inputDefault { channel = a
, mode = Return
}
exception a = inputDefault { channel = a
, mode = Recovery
}
-- dead-reckoning directions
north :: Float -> Float
north f = f
east :: Float -> Float
east f = f
down :: Float -> Float
down f = f
-- time increments
seconds :: Time -> Time
seconds s = s
-- distance
meters :: Distance -> Distance
meters m = m
type Distance = Float
-- | constructed values
--
fullPower :: Float
fullPower = 1.0
threeQtrPower :: Float
threeQtrPower = 0.75
halfPower :: Float
halfPower = 0.5
quarterPower :: Float
quarterPower = 0.25
zeroPower :: Float
zeroPower = 0.0
enabled = True
disabled = False
tick :: Double
tick = 1
startTime :: Double
startTime = 0
|
abbottk/MICL
|
DSL/MonadicMICL.hs
|
cc0-1.0
| 5,314 | 0 | 14 | 1,820 | 1,885 | 1,040 | 845 | 126 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Glance.Model.Image
where
import Common (skipUnderscoreOptions, capitalize, underscoreOptions, (<.>))
import Control.Monad.Catch (MonadCatch(catch), MonadThrow(throwM))
import Control.Monad.Trans.Maybe (MaybeT(..))
import Data.Aeson (FromJSON(..), ToJSON(..), Value(..))
import Data.Aeson.TH (deriveJSON)
import Data.Aeson.Types (typeMismatch)
import Data.Bson ((=:))
import Data.Bson.Mapping (Bson(..), deriveBson)
import Data.Char (toLower)
import Data.Data (Typeable)
import Data.String (IsString(fromString))
import Data.Text (pack, unpack)
import Language.Haskell.TH.Syntax (nameBase)
import Model.Mongo.Common (idF) -- Import ObjectId fromJson instance
import Text.Read (readMaybe)
import qualified Error as E
import qualified Database.MongoDB as M
collectionName :: M.Collection
collectionName = "image"
data Image = Image
{ _id :: M.ObjectId
, name :: String
, visibility :: Visibility
, status :: Status
, tags :: [String]
, containerFormat :: String
, diskFormat :: String
, minDisk :: Int
, minRam :: Int
, protected :: Bool
} deriving (Show, Read, Eq, Ord, Typeable)
data Visibility = Public
| Private
deriving (Show, Read, Eq, Ord, Typeable)
data Status = Queued
| Saving
| Active
| Deactivated
| Killed
| Deleted
| PendingDelete
deriving (Show, Read, Eq, Ord, Typeable)
newtype ImageId = ImageId M.ObjectId
deriving (Show, Typeable, Eq)
instance M.Val Status where
val s = M.String $ fromString $ show s
cast' (M.String s) = readMaybe $ unpack s
cast' _ = Nothing
instance FromJSON Status where
parseJSON (String s) =
case readMaybe $ capitalize $ unpack s of
Just v -> return v
Nothing -> fail $ "Unknown Status " ++ (unpack s)
parseJSON v = typeMismatch (nameBase ''Status) v
instance ToJSON Status where
toJSON v = String $ pack $ map toLower $ show v
instance M.Val Visibility where
val s = M.String $ fromString $ show s
cast' (M.String s) = readMaybe $ unpack s
cast' _ = Nothing
instance FromJSON Visibility where
parseJSON (String s) =
case readMaybe $ capitalize $ unpack s of
Just v -> return v
Nothing -> fail $ "Unknown Visibility " ++ (unpack s)
parseJSON v = typeMismatch (nameBase ''Visibility) v
instance ToJSON Visibility where
toJSON v = String $ pack $ map toLower $ show v
instance M.Val ImageId where
val (ImageId uid) = M.ObjId uid
cast' (M.ObjId uid) = return $ ImageId uid
cast' _ = Nothing
$(deriveBson id ''Image)
$(deriveJSON (underscoreOptions <.> skipUnderscoreOptions) ''Image)
listImages :: (Maybe String) -> M.Action IO [Image]
listImages mName = do
let nameFilter = case mName of
Nothing -> []
Just nm -> [(pack $ nameBase 'name) =: (M.String $ pack nm)]
cur <- M.find $ M.select nameFilter collectionName
docs <- M.rest cur
mapM fromBson docs
createImage :: Image -> M.Action IO (Either E.Error M.ObjectId)
createImage i =
(do
M.ObjId pid <- M.insert collectionName $ toBson i
return $ Right pid
) `catch` (\f -> do
case f of
M.WriteFailure duplicateE message ->
return $ Left $ E.conflict $ "Insert of project with the duplicate " ++ (nameBase 'name) ++ " is not allowed."
_ -> throwM f
)
findImageById :: M.ObjectId -> M.Action IO (Maybe Image)
findImageById pid = runMaybeT $ do
mImage <- MaybeT $ M.findOne (M.select [idF =: pid] collectionName)
fromBson mImage
|
VictorDenisov/keystone
|
src/Glance/Model/Image.hs
|
gpl-2.0
| 3,838 | 0 | 17 | 1,021 | 1,277 | 683 | 594 | 100 | 2 |
module Types ( Phocid(..)
, Photo(..)
) where
data Phocid = Phocid
{ inputDir :: FilePath
, outputPath :: FilePath
, verbose :: Bool
, title :: String
} deriving (Show)
data Photo = Photo
{ getPath :: FilePath }
deriving (Show, Eq)
instance Ord Photo where
p1 `compare` p2 = (getPath p1) `compare` (getPath p2)
|
mjhoy/phocid
|
src/Types.hs
|
gpl-2.0
| 359 | 0 | 8 | 104 | 125 | 75 | 50 | 13 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module TAP (
planTests, planNoPlan, planSkipAll,
is, isnt, like, unlike, pass, fail, ok,
skip, skipIf, toDo,
diag, bailOut, runTests
) where
import Prelude hiding (fail)
import System.IO
import System.Exit
import Control.Monad.State hiding (fail)
import Control.Exception
import Text.Regex.Posix
data TAPState = TAPState {
planSet :: Bool,
noPlan :: Bool,
skipAll :: Bool,
testDied :: Bool,
expectedTests :: Int,
executedTests :: Int,
failedTests :: Int,
toDoReason :: Maybe String,
exitCode :: Int
} deriving (Show)
initState = TAPState {
planSet = False,
noPlan = False,
skipAll = False,
testDied = False,
expectedTests = 0,
executedTests = 0,
failedTests = 0,
toDoReason = Nothing,
exitCode = 0
}
newtype TAP a = TAP {
runTAP :: StateT TAPState IO a
} deriving (Monad, MonadIO, MonadState TAPState)
_assertNotPlanned :: TAP ()
_assertNotPlanned = do
ts <- get
when (planSet ts) $ _die "You tried to plan twice!"
_assertPlanned :: TAP ()
_assertPlanned = do
ts <- get
when (not $ planSet ts) $ _die $ "You tried to run a test without a plan!"
++ " Gotta have a plan."
_printPlan :: Int -> Maybe String -> IO ()
_printPlan n plan = do
putStrLn $ "1.." ++ show n ++
case plan of
Just plan -> " # " ++ plan
otherwise -> ""
planTests :: Int -> TAP ()
planTests n = do
_assertNotPlanned
when (n == 0) $ _die $ "You said to run 0 tests!"
++ " You've got to run something."
liftIO $ _printPlan n Nothing
modify (\x -> x {planSet = True, expectedTests = n})
planNoPlan :: TAP ()
planNoPlan = do
_assertNotPlanned
modify (\x -> x {planSet = True, noPlan = True})
planSkipAll :: String -> TAP ()
planSkipAll plan = do
_assertNotPlanned
liftIO . _printPlan 0 . Just $ "Skip " ++ plan
modify (\x -> x {planSet = True, skipAll = True})
_exit $ Just 0
return ()
_matches :: String -> String -> Bool
_matches "" _ = False
_matches _ "" = False
_matches target pattern = target =~ pattern :: Bool
ok :: Bool -> Maybe String -> TAP Bool
ok result msg = do
_assertPlanned
modify (\x -> x {executedTests = executedTests x + 1})
case msg of
Just s -> when (_matches s "^[0-9]+$") $ do
diag $ " You named your test '" ++ s
++ "'. You shouldn't use numbers for your test names."
diag $ " Very confusing."
otherwise -> return ()
when (not result) $ do
liftIO $ putStr "not "
modify (\x -> x {failedTests = failedTests x + 1})
ts <- get
liftIO . putStr $ "ok " ++ (show $ executedTests ts)
case msg of
-- TODO: Escape s
Just s -> liftIO . putStr $ " - " ++ s
otherwise -> return ()
case (toDoReason ts) of
Just r -> liftIO . putStr $ " # TODO " ++ r
otherwise -> return ()
when (not result) $ do
modify (\x -> x {failedTests = failedTests x - 1})
liftIO $ putStrLn ""
-- TODO: STACK TRACE?
return result
is :: (Show a, Eq a) => a -> a -> Maybe String -> TAP Bool
is result expected msg = do
rc <- ok (result == expected) msg
when (not rc) $ do
diag $ " got: '" ++ (show result) ++ "'"
diag $ " expected: '" ++ (show expected) ++ "'"
return rc
isnt :: (Show a, Eq a) => a -> a -> Maybe String -> TAP Bool
isnt result expected msg = do
rc <- ok (result /= expected) msg
when (not rc) $ do
diag $ " got: '" ++ (show result) ++ "'"
diag $ " didn't expect: '" ++ (show expected) ++ "'"
return rc
like :: String -> String -> Maybe String -> TAP Bool
like target pattern msg = do
rc <- ok (_matches target pattern) msg
when (not rc) $ diag $ " '" ++ target ++ "' doesn't match '"
++ pattern ++ "'"
return rc
unlike :: String -> String -> Maybe String -> TAP Bool
unlike target pattern msg = do
rc <- ok (not $ _matches target pattern) msg
when (not rc) $ diag $ " '" ++ target ++ "' matches '"
++ pattern ++ "'"
return rc
pass :: Maybe String -> TAP Bool
pass s = ok True s
fail :: Maybe String -> TAP Bool
fail s = ok False s
skip :: Int -> String -> TAP ()
skip n reason = do
forM_ [1 .. n] (\n' -> do
modify (\x -> x {executedTests = executedTests x + 1})
ts <- get
liftIO . putStrLn $ "ok " ++ (show $ executedTests ts)
++ " # skip: " ++ reason)
return ()
skipIf :: Bool -> Int -> String -> TAP a -> TAP ()
skipIf cond n reason tap = do
if cond
then skip n reason
else do
tap
return ()
toDo :: String -> TAP a -> TAP ()
toDo reason tap = do
modify (\x -> x {toDoReason = Just reason})
a <- tap
modify (\x -> x {toDoReason = Nothing})
return ()
diag :: String -> TAP ()
diag s = do
liftIO . putStrLn $ "# " ++ s
bailOut :: String -> TAP a
bailOut s = do
liftIO $ hPutStrLn stderr s
_exit $ Just 255
_die :: String -> TAP a
_die s = do
liftIO $ hPutStrLn stderr s
modify (\x -> x {testDied = True})
_exit $ Just 255
_wrapup :: TAP ()
_wrapup = do
ts <- get
let s n = if (n > 1) then "s" else ""
let err | not $ planSet ts = diag "Looks like your test died before it could output anything." >> return True
| testDied ts = diag ("Looks like your test died just after " ++ (show $ executedTests ts)) >> return True
| otherwise = return False
stop <- err
if stop
then return ()
else do
when ((not $ noPlan ts)&&((expectedTests ts) < (executedTests ts))) $ do
let extra = (executedTests ts) - (expectedTests ts)
diag $ "Looks like you planned " ++ (show $ expectedTests ts)
++ " test" ++ (s $ expectedTests ts)
++ " but ran " ++ (show extra) ++ " extra."
modify (\x -> x {exitCode = -1})
when ((not $ noPlan ts)&&((expectedTests ts) > (executedTests ts))) $ do
diag $ "Looks like you planned " ++ (show $ expectedTests ts)
++ " test" ++ (s $ expectedTests ts)
++ " but only ran " ++ (show $ executedTests ts)
when (failedTests ts > 0) $ do
diag $ "Looks like you failed " ++ (show $ failedTests ts)
++ " test" ++ (s $ failedTests ts)
++ " of " ++ (show $ executedTests ts)
_exit :: Maybe Int -> TAP a
_exit mrc = do
case mrc of
Just rc -> modify (\x -> x {exitCode = rc})
otherwise -> return ()
ts <- get
when (exitCode ts == 0) $ do
rc <- if ((noPlan ts)||(not $ planSet ts))
then return $ failedTests ts
else if ((expectedTests ts) < (executedTests ts))
then return $ (executedTests ts) - (expectedTests ts)
else return $ ((failedTests ts)
+ ((expectedTests ts) - (executedTests ts)))
modify (\x -> x {exitCode = rc})
_wrapup
ts <- get
let rc = exitCode ts
liftIO . exitWith $ if (rc == 0) then ExitSuccess else ExitFailure rc
runTests :: TAP a -> IO (a, TAPState)
-- TODO: Add exception handling here?
runTests s = runStateT (runTAP (s >> _exit Nothing)) initState
|
epsilonhalbe/TAP
|
TAP.hs
|
gpl-2.0
| 7,430 | 0 | 21 | 2,418 | 2,858 | 1,424 | 1,434 | 206 | 5 |
module HLinear.Matrix.Invertible
where
import HLinear.Utility.Prelude
import qualified Data.Vector as V
import HLinear.Matrix.Algebra ()
import HLinear.Matrix.Definition
import HLinear.Hook.PLEHook.Definition ( PLEHook(..), PLUEHook(..) )
import HLinear.Hook.EchelonForm.PivotStructure ( hasUnitDiagonal, pivotEntryVector )
import HLinear.NormalForm.PLE ( HasPLE, ple )
import HLinear.NormalForm.RREF ( HasRREF, rref )
type MatrixInvertible a = Unit (Matrix a)
instance IsMatrix (MatrixInvertible a) a where
toMatrix = fromUnit
deriving instance HasNmbRows (Unit (Matrix a))
deriving instance HasNmbCols (Unit (Matrix a))
instance
( Ring a, DecidableZero a, DecidableUnit a, HasPLE a )
=> DecidableUnit (Matrix a)
where
toUnit = Unit
isUnit m@(Matrix nrs ncs _)
| nrs == ncs = let PLEHook _ _ e = ple m in hasUnitDiagonal e
| otherwise = False
instance
( Ring a, DecidableZero a, DecidableUnit a, HasRREF a )
=> MultiplicativeGroup (Unit (Matrix a))
where
recip (Unit m) =
let PLUEHook p l r e = rref m
(Matrix nrs ncs rs') = ((recip r) *. (toMatrix $ recip l)) .* (recip p)
in Unit $ Matrix nrs ncs $
V.zipWith (\a -> fmap ((fromUnit $ recip $ toUnit a) *)) (pivotEntryVector e) rs'
|
martinra/hlinear
|
src/HLinear/Matrix/Invertible.hs
|
gpl-3.0
| 1,256 | 0 | 16 | 249 | 481 | 257 | 224 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Lamdu.CodeEdit.Settings
( Settings(..), sInfoMode, InfoMode(..), defaultInfoMode
) where
import qualified Control.Lens as Lens
data InfoMode = None | Types | Examples
deriving (Show)
defaultInfoMode :: InfoMode
defaultInfoMode = None
newtype Settings = Settings
{ _sInfoMode :: InfoMode
}
Lens.makeLenses ''Settings
|
Mathnerd314/lamdu
|
src/Lamdu/CodeEdit/Settings.hs
|
gpl-3.0
| 370 | 0 | 6 | 59 | 91 | 58 | 33 | 11 | 1 |
module Main where
import Ampersand
import Data.List
import qualified Data.List.NonEmpty as NEL (toList)
main :: IO ()
main =
do opts <- getOptions
sequence_ . map snd . filter fst $ actionsWithoutScript opts -- There are commands that do not need a single filename to be speciied
case fileName opts of
Just _ -> do -- An Ampersand script is provided that can be processed
{ putStrLn "Processing your model..."
; gMulti <- createMulti opts
; case gMulti of
Errors err ->
exitWith . NoValidFSpec . intersperse (replicate 30 '=')
. fmap showErr . NEL.toList $ err
Checked multi ws -> do
showWarnings ws
generateAmpersandOutput multi
putStrLn "Finished processing your model"
putStrLn . ("Your script has no errors " ++) $
case ws of
[] -> "and no warnings"
[_] -> ", but one warning was found"
_ -> ", but "++show (length ws)++" warnings were found"
}
Nothing -> -- No Ampersand script is provided
if or (map fst $ actionsWithoutScript opts)
then verboseLn opts $ "No further actions, because no ampersand script is provided"
else putStrLn "No ampersand script provided. Use --help for usage information"
where
actionsWithoutScript :: Options -> [(Bool, IO())]
actionsWithoutScript options =
[ ( test options , putStrLn $ "Executable: " ++ show (dirExec options) )
, ( showVersion options || verboseP options , putStrLn $ versionText options )
, ( genSampleConfigFile options , writeConfigFile )
, ( showHelp options , putStrLn $ usageInfo' options )
]
versionText :: Options -> String
versionText opts = preVersion opts ++ ampersandVersionStr ++ postVersion opts
|
AmpersandTarski/ampersand
|
app/Main.hs
|
gpl-3.0
| 2,065 | 0 | 25 | 761 | 444 | 222 | 222 | 37 | 6 |
module Vector where
type Vec2D = (Int, Int)
vecAdd :: Vec2D -> Vec2D -> Vec2D
vecAdd (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
vecSub a (x, y) = vecAdd a (-x, -y)
-- get a unit vector (rounded heavily into Ints)
vecUnit :: Vec2D -> Vec2D
vecUnit (ix, iy) = (newX, newY)
where
x = fromIntegral ix :: Float
y = fromIntegral iy :: Float
newX = round $ x/magnitude :: Int
newY = round $ y/magnitude :: Int
magnitude = sqrt (x^2 + y^2)
|
lordcirth/haskell-rogue
|
src/Vector.hs
|
gpl-3.0
| 455 | 0 | 11 | 116 | 205 | 117 | 88 | 12 | 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.Cloudlatencytest.Statscollection.Updatestats
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- RPC to update the new TCP stats.
--
-- /See:/ < Google Cloud Network Performance Monitoring API Reference> for @cloudlatencytest.statscollection.updatestats@.
module Network.Google.Resource.Cloudlatencytest.Statscollection.Updatestats
(
-- * REST Resource
StatscollectionUpdatestatsResource
-- * Creating a Request
, statscollectionUpdatestats
, StatscollectionUpdatestats
-- * Request Lenses
, suPayload
) where
import Network.Google.LatencyTest.Types
import Network.Google.Prelude
-- | A resource alias for @cloudlatencytest.statscollection.updatestats@ method which the
-- 'StatscollectionUpdatestats' request conforms to.
type StatscollectionUpdatestatsResource =
"v2" :>
"statscollection" :>
"updatestats" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Stats :> Post '[JSON] StatsReply
-- | RPC to update the new TCP stats.
--
-- /See:/ 'statscollectionUpdatestats' smart constructor.
newtype StatscollectionUpdatestats = StatscollectionUpdatestats'
{ _suPayload :: Stats
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'StatscollectionUpdatestats' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'suPayload'
statscollectionUpdatestats
:: Stats -- ^ 'suPayload'
-> StatscollectionUpdatestats
statscollectionUpdatestats pSuPayload_ =
StatscollectionUpdatestats'
{ _suPayload = pSuPayload_
}
-- | Multipart request metadata.
suPayload :: Lens' StatscollectionUpdatestats Stats
suPayload
= lens _suPayload (\ s a -> s{_suPayload = a})
instance GoogleRequest StatscollectionUpdatestats
where
type Rs StatscollectionUpdatestats = StatsReply
type Scopes StatscollectionUpdatestats =
'["https://www.googleapis.com/auth/monitoring.readonly"]
requestClient StatscollectionUpdatestats'{..}
= go (Just AltJSON) _suPayload latencyTestService
where go
= buildClient
(Proxy :: Proxy StatscollectionUpdatestatsResource)
mempty
|
rueshyna/gogol
|
gogol-latencytest/gen/Network/Google/Resource/Cloudlatencytest/Statscollection/Updatestats.hs
|
mpl-2.0
| 2,983 | 0 | 12 | 624 | 304 | 187 | 117 | 48 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.StorageTransfer.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.StorageTransfer.Types.Product where
import Network.Google.Prelude
import Network.Google.StorageTransfer.Types.Sum
-- | A summary of errors by error code, plus a count and sample error log
-- entries.
--
-- /See:/ 'errorSummary' smart constructor.
data ErrorSummary =
ErrorSummary'
{ _esErrorCount :: !(Maybe (Textual Int64))
, _esErrorCode :: !(Maybe ErrorSummaryErrorCode)
, _esErrorLogEntries :: !(Maybe [ErrorLogEntry])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ErrorSummary' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'esErrorCount'
--
-- * 'esErrorCode'
--
-- * 'esErrorLogEntries'
errorSummary
:: ErrorSummary
errorSummary =
ErrorSummary'
{ _esErrorCount = Nothing
, _esErrorCode = Nothing
, _esErrorLogEntries = Nothing
}
-- | Required. Count of this type of error.
esErrorCount :: Lens' ErrorSummary (Maybe Int64)
esErrorCount
= lens _esErrorCount (\ s a -> s{_esErrorCount = a})
. mapping _Coerce
-- | Required.
esErrorCode :: Lens' ErrorSummary (Maybe ErrorSummaryErrorCode)
esErrorCode
= lens _esErrorCode (\ s a -> s{_esErrorCode = a})
-- | Error samples. At most 5 error log entries are recorded for a given
-- error code for a single transfer operation.
esErrorLogEntries :: Lens' ErrorSummary [ErrorLogEntry]
esErrorLogEntries
= lens _esErrorLogEntries
(\ s a -> s{_esErrorLogEntries = a})
. _Default
. _Coerce
instance FromJSON ErrorSummary where
parseJSON
= withObject "ErrorSummary"
(\ o ->
ErrorSummary' <$>
(o .:? "errorCount") <*> (o .:? "errorCode") <*>
(o .:? "errorLogEntries" .!= mempty))
instance ToJSON ErrorSummary where
toJSON ErrorSummary'{..}
= object
(catMaybes
[("errorCount" .=) <$> _esErrorCount,
("errorCode" .=) <$> _esErrorCode,
("errorLogEntries" .=) <$> _esErrorLogEntries])
-- | Request passed to RunTransferJob.
--
-- /See:/ 'runTransferJobRequest' smart constructor.
newtype RunTransferJobRequest =
RunTransferJobRequest'
{ _rtjrProjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RunTransferJobRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rtjrProjectId'
runTransferJobRequest
:: RunTransferJobRequest
runTransferJobRequest = RunTransferJobRequest' {_rtjrProjectId = Nothing}
-- | Required. The ID of the Google Cloud Platform Console project that owns
-- the transfer job.
rtjrProjectId :: Lens' RunTransferJobRequest (Maybe Text)
rtjrProjectId
= lens _rtjrProjectId
(\ s a -> s{_rtjrProjectId = a})
instance FromJSON RunTransferJobRequest where
parseJSON
= withObject "RunTransferJobRequest"
(\ o ->
RunTransferJobRequest' <$> (o .:? "projectId"))
instance ToJSON RunTransferJobRequest where
toJSON RunTransferJobRequest'{..}
= object
(catMaybes [("projectId" .=) <$> _rtjrProjectId])
-- | The \`Status\` type defines a logical error model that is suitable for
-- different programming environments, including REST APIs and RPC APIs. It
-- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message
-- contains three pieces of data: error code, error message, and error
-- details. You can find out more about this error model and how to work
-- with it in the [API Design
-- Guide](https:\/\/cloud.google.com\/apis\/design\/errors).
--
-- /See:/ 'status' smart constructor.
data Status =
Status'
{ _sDetails :: !(Maybe [StatusDetailsItem])
, _sCode :: !(Maybe (Textual Int32))
, _sMessage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Status' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sDetails'
--
-- * 'sCode'
--
-- * 'sMessage'
status
:: Status
status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing}
-- | A list of messages that carry the error details. There is a common set
-- of message types for APIs to use.
sDetails :: Lens' Status [StatusDetailsItem]
sDetails
= lens _sDetails (\ s a -> s{_sDetails = a}) .
_Default
. _Coerce
-- | The status code, which should be an enum value of google.rpc.Code.
sCode :: Lens' Status (Maybe Int32)
sCode
= lens _sCode (\ s a -> s{_sCode = a}) .
mapping _Coerce
-- | A developer-facing error message, which should be in English. Any
-- user-facing error message should be localized and sent in the
-- google.rpc.Status.details field, or localized by the client.
sMessage :: Lens' Status (Maybe Text)
sMessage = lens _sMessage (\ s a -> s{_sMessage = a})
instance FromJSON Status where
parseJSON
= withObject "Status"
(\ o ->
Status' <$>
(o .:? "details" .!= mempty) <*> (o .:? "code") <*>
(o .:? "message"))
instance ToJSON Status where
toJSON Status'{..}
= object
(catMaybes
[("details" .=) <$> _sDetails,
("code" .=) <$> _sCode,
("message" .=) <$> _sMessage])
-- | Specification to configure notifications published to Pub\/Sub.
-- Notifications are published to the customer-provided topic using the
-- following \`PubsubMessage.attributes\`: * \`\"eventType\"\`: one of the
-- EventType values * \`\"payloadFormat\"\`: one of the PayloadFormat
-- values * \`\"projectId\"\`: the project_id of the \`TransferOperation\`
-- * \`\"transferJobName\"\`: the transfer_job_name of the
-- \`TransferOperation\` * \`\"transferOperationName\"\`: the name of the
-- \`TransferOperation\` The \`PubsubMessage.data\` contains a
-- TransferOperation resource formatted according to the specified
-- \`PayloadFormat\`.
--
-- /See:/ 'notificationConfig' smart constructor.
data NotificationConfig =
NotificationConfig'
{ _ncEventTypes :: !(Maybe [NotificationConfigEventTypesItem])
, _ncPubsubTopic :: !(Maybe Text)
, _ncPayloadFormat :: !(Maybe NotificationConfigPayloadFormat)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'NotificationConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ncEventTypes'
--
-- * 'ncPubsubTopic'
--
-- * 'ncPayloadFormat'
notificationConfig
:: NotificationConfig
notificationConfig =
NotificationConfig'
{ _ncEventTypes = Nothing
, _ncPubsubTopic = Nothing
, _ncPayloadFormat = Nothing
}
-- | Event types for which a notification is desired. If empty, send
-- notifications for all event types.
ncEventTypes :: Lens' NotificationConfig [NotificationConfigEventTypesItem]
ncEventTypes
= lens _ncEventTypes (\ s a -> s{_ncEventTypes = a})
. _Default
. _Coerce
-- | Required. The \`Topic.name\` of the Pub\/Sub topic to which to publish
-- notifications. Must be of the format:
-- \`projects\/{project}\/topics\/{topic}\`. Not matching this format
-- results in an INVALID_ARGUMENT error.
ncPubsubTopic :: Lens' NotificationConfig (Maybe Text)
ncPubsubTopic
= lens _ncPubsubTopic
(\ s a -> s{_ncPubsubTopic = a})
-- | Required. The desired format of the notification message payloads.
ncPayloadFormat :: Lens' NotificationConfig (Maybe NotificationConfigPayloadFormat)
ncPayloadFormat
= lens _ncPayloadFormat
(\ s a -> s{_ncPayloadFormat = a})
instance FromJSON NotificationConfig where
parseJSON
= withObject "NotificationConfig"
(\ o ->
NotificationConfig' <$>
(o .:? "eventTypes" .!= mempty) <*>
(o .:? "pubsubTopic")
<*> (o .:? "payloadFormat"))
instance ToJSON NotificationConfig where
toJSON NotificationConfig'{..}
= object
(catMaybes
[("eventTypes" .=) <$> _ncEventTypes,
("pubsubTopic" .=) <$> _ncPubsubTopic,
("payloadFormat" .=) <$> _ncPayloadFormat])
-- | The response message for Operations.ListOperations.
--
-- /See:/ 'listOperationsResponse' smart constructor.
data ListOperationsResponse =
ListOperationsResponse'
{ _lorNextPageToken :: !(Maybe Text)
, _lorOperations :: !(Maybe [Operation])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lorNextPageToken'
--
-- * 'lorOperations'
listOperationsResponse
:: ListOperationsResponse
listOperationsResponse =
ListOperationsResponse'
{_lorNextPageToken = Nothing, _lorOperations = Nothing}
-- | The standard List next-page token.
lorNextPageToken :: Lens' ListOperationsResponse (Maybe Text)
lorNextPageToken
= lens _lorNextPageToken
(\ s a -> s{_lorNextPageToken = a})
-- | A list of operations that matches the specified filter in the request.
lorOperations :: Lens' ListOperationsResponse [Operation]
lorOperations
= lens _lorOperations
(\ s a -> s{_lorOperations = a})
. _Default
. _Coerce
instance FromJSON ListOperationsResponse where
parseJSON
= withObject "ListOperationsResponse"
(\ o ->
ListOperationsResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "operations" .!= mempty))
instance ToJSON ListOperationsResponse where
toJSON ListOperationsResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lorNextPageToken,
("operations" .=) <$> _lorOperations])
-- | The request message for Operations.CancelOperation.
--
-- /See:/ 'cancelOperationRequest' smart constructor.
data CancelOperationRequest =
CancelOperationRequest'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CancelOperationRequest' with the minimum fields required to make a request.
--
cancelOperationRequest
:: CancelOperationRequest
cancelOperationRequest = CancelOperationRequest'
instance FromJSON CancelOperationRequest where
parseJSON
= withObject "CancelOperationRequest"
(\ o -> pure CancelOperationRequest')
instance ToJSON CancelOperationRequest where
toJSON = const emptyObject
-- | Transfers can be scheduled to recur or to run just once.
--
-- /See:/ 'schedule' smart constructor.
data Schedule =
Schedule'
{ _sRepeatInterval :: !(Maybe GDuration)
, _sScheduleEndDate :: !(Maybe Date)
, _sScheduleStartDate :: !(Maybe Date)
, _sEndTimeOfDay :: !(Maybe TimeOfDay')
, _sStartTimeOfDay :: !(Maybe TimeOfDay')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Schedule' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sRepeatInterval'
--
-- * 'sScheduleEndDate'
--
-- * 'sScheduleStartDate'
--
-- * 'sEndTimeOfDay'
--
-- * 'sStartTimeOfDay'
schedule
:: Schedule
schedule =
Schedule'
{ _sRepeatInterval = Nothing
, _sScheduleEndDate = Nothing
, _sScheduleStartDate = Nothing
, _sEndTimeOfDay = Nothing
, _sStartTimeOfDay = Nothing
}
-- | Interval between the start of each scheduled TransferOperation. If
-- unspecified, the default value is 24 hours. This value may not be less
-- than 1 hour.
sRepeatInterval :: Lens' Schedule (Maybe Scientific)
sRepeatInterval
= lens _sRepeatInterval
(\ s a -> s{_sRepeatInterval = a})
. mapping _GDuration
-- | The last day a transfer runs. Date boundaries are determined relative to
-- UTC time. A job runs once per 24 hours within the following guidelines:
-- * If \`schedule_end_date\` and schedule_start_date are the same and in
-- the future relative to UTC, the transfer is executed only one time. * If
-- \`schedule_end_date\` is later than \`schedule_start_date\` and
-- \`schedule_end_date\` is in the future relative to UTC, the job runs
-- each day at start_time_of_day through \`schedule_end_date\`.
sScheduleEndDate :: Lens' Schedule (Maybe Date)
sScheduleEndDate
= lens _sScheduleEndDate
(\ s a -> s{_sScheduleEndDate = a})
-- | Required. The start date of a transfer. Date boundaries are determined
-- relative to UTC time. If \`schedule_start_date\` and start_time_of_day
-- are in the past relative to the job\'s creation time, the transfer
-- starts the day after you schedule the transfer request. **Note:** When
-- starting jobs at or near midnight UTC it is possible that a job starts
-- later than expected. For example, if you send an outbound request on
-- June 1 one millisecond prior to midnight UTC and the Storage Transfer
-- Service server receives the request on June 2, then it creates a
-- TransferJob with \`schedule_start_date\` set to June 2 and a
-- \`start_time_of_day\` set to midnight UTC. The first scheduled
-- TransferOperation takes place on June 3 at midnight UTC.
sScheduleStartDate :: Lens' Schedule (Maybe Date)
sScheduleStartDate
= lens _sScheduleStartDate
(\ s a -> s{_sScheduleStartDate = a})
-- | The time in UTC that no further transfer operations are scheduled.
-- Combined with schedule_end_date, \`end_time_of_day\` specifies the end
-- date and time for starting new transfer operations. This field must be
-- greater than or equal to the timestamp corresponding to the combintation
-- of schedule_start_date and start_time_of_day, and is subject to the
-- following: * If \`end_time_of_day\` is not set and \`schedule_end_date\`
-- is set, then a default value of \`23:59:59\` is used for
-- \`end_time_of_day\`. * If \`end_time_of_day\` is set and
-- \`schedule_end_date\` is not set, then INVALID_ARGUMENT is returned.
sEndTimeOfDay :: Lens' Schedule (Maybe TimeOfDay')
sEndTimeOfDay
= lens _sEndTimeOfDay
(\ s a -> s{_sEndTimeOfDay = a})
-- | The time in UTC that a transfer job is scheduled to run. Transfers may
-- start later than this time. If \`start_time_of_day\` is not specified: *
-- One-time transfers run immediately. * Recurring transfers run
-- immediately, and each day at midnight UTC, through schedule_end_date. If
-- \`start_time_of_day\` is specified: * One-time transfers run at the
-- specified time. * Recurring transfers run at the specified time each
-- day, through \`schedule_end_date\`.
sStartTimeOfDay :: Lens' Schedule (Maybe TimeOfDay')
sStartTimeOfDay
= lens _sStartTimeOfDay
(\ s a -> s{_sStartTimeOfDay = a})
instance FromJSON Schedule where
parseJSON
= withObject "Schedule"
(\ o ->
Schedule' <$>
(o .:? "repeatInterval") <*>
(o .:? "scheduleEndDate")
<*> (o .:? "scheduleStartDate")
<*> (o .:? "endTimeOfDay")
<*> (o .:? "startTimeOfDay"))
instance ToJSON Schedule where
toJSON Schedule'{..}
= object
(catMaybes
[("repeatInterval" .=) <$> _sRepeatInterval,
("scheduleEndDate" .=) <$> _sScheduleEndDate,
("scheduleStartDate" .=) <$> _sScheduleStartDate,
("endTimeOfDay" .=) <$> _sEndTimeOfDay,
("startTimeOfDay" .=) <$> _sStartTimeOfDay])
-- | Conditions that determine which objects are transferred. Applies only to
-- Cloud Data Sources such as S3, Azure, and Cloud Storage. The \"last
-- modification time\" refers to the time of the last change to the
-- object\'s content or metadata — specifically, this is the \`updated\`
-- property of Cloud Storage objects, the \`LastModified\` field of S3
-- objects, and the \`Last-Modified\` header of Azure blobs. This is not
-- supported for transfers involving PosixFilesystem.
--
-- /See:/ 'objectConditions' smart constructor.
data ObjectConditions =
ObjectConditions'
{ _ocLastModifiedBefore :: !(Maybe DateTime')
, _ocMinTimeElapsedSinceLastModification :: !(Maybe GDuration)
, _ocIncludePrefixes :: !(Maybe [Text])
, _ocMaxTimeElapsedSinceLastModification :: !(Maybe GDuration)
, _ocExcludePrefixes :: !(Maybe [Text])
, _ocLastModifiedSince :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ObjectConditions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ocLastModifiedBefore'
--
-- * 'ocMinTimeElapsedSinceLastModification'
--
-- * 'ocIncludePrefixes'
--
-- * 'ocMaxTimeElapsedSinceLastModification'
--
-- * 'ocExcludePrefixes'
--
-- * 'ocLastModifiedSince'
objectConditions
:: ObjectConditions
objectConditions =
ObjectConditions'
{ _ocLastModifiedBefore = Nothing
, _ocMinTimeElapsedSinceLastModification = Nothing
, _ocIncludePrefixes = Nothing
, _ocMaxTimeElapsedSinceLastModification = Nothing
, _ocExcludePrefixes = Nothing
, _ocLastModifiedSince = Nothing
}
-- | If specified, only objects with a \"last modification time\" before this
-- timestamp and objects that don\'t have a \"last modification time\" are
-- transferred.
ocLastModifiedBefore :: Lens' ObjectConditions (Maybe UTCTime)
ocLastModifiedBefore
= lens _ocLastModifiedBefore
(\ s a -> s{_ocLastModifiedBefore = a})
. mapping _DateTime
-- | If specified, only objects with a \"last modification time\" before
-- \`NOW\` - \`min_time_elapsed_since_last_modification\` and objects that
-- don\'t have a \"last modification time\" are transferred. For each
-- TransferOperation started by this TransferJob, \`NOW\` refers to the
-- start_time of the \`TransferOperation\`.
ocMinTimeElapsedSinceLastModification :: Lens' ObjectConditions (Maybe Scientific)
ocMinTimeElapsedSinceLastModification
= lens _ocMinTimeElapsedSinceLastModification
(\ s a ->
s{_ocMinTimeElapsedSinceLastModification = a})
. mapping _GDuration
-- | If you specify \`include_prefixes\`, Storage Transfer Service uses the
-- items in the \`include_prefixes\` array to determine which objects to
-- include in a transfer. Objects must start with one of the matching
-- \`include_prefixes\` for inclusion in the transfer. If exclude_prefixes
-- is specified, objects must not start with any of the
-- \`exclude_prefixes\` specified for inclusion in the transfer. The
-- following are requirements of \`include_prefixes\`: * Each
-- include-prefix can contain any sequence of Unicode characters, to a max
-- length of 1024 bytes when UTF8-encoded, and must not contain Carriage
-- Return or Line Feed characters. Wildcard matching and regular expression
-- matching are not supported. * Each include-prefix must omit the leading
-- slash. For example, to include the object
-- \`s3:\/\/my-aws-bucket\/logs\/y=2015\/requests.gz\`, specify the
-- include-prefix as \`logs\/y=2015\/requests.gz\`. * None of the
-- include-prefix values can be empty, if specified. * Each include-prefix
-- must include a distinct portion of the object namespace. No
-- include-prefix may be a prefix of another include-prefix. The max size
-- of \`include_prefixes\` is 1000. For more information, see [Filtering
-- objects from
-- transfers](\/storage-transfer\/docs\/filtering-objects-from-transfers).
ocIncludePrefixes :: Lens' ObjectConditions [Text]
ocIncludePrefixes
= lens _ocIncludePrefixes
(\ s a -> s{_ocIncludePrefixes = a})
. _Default
. _Coerce
-- | If specified, only objects with a \"last modification time\" on or after
-- \`NOW\` - \`max_time_elapsed_since_last_modification\` and objects that
-- don\'t have a \"last modification time\" are transferred. For each
-- TransferOperation started by this TransferJob, \`NOW\` refers to the
-- start_time of the \`TransferOperation\`.
ocMaxTimeElapsedSinceLastModification :: Lens' ObjectConditions (Maybe Scientific)
ocMaxTimeElapsedSinceLastModification
= lens _ocMaxTimeElapsedSinceLastModification
(\ s a ->
s{_ocMaxTimeElapsedSinceLastModification = a})
. mapping _GDuration
-- | If you specify \`exclude_prefixes\`, Storage Transfer Service uses the
-- items in the \`exclude_prefixes\` array to determine which objects to
-- exclude from a transfer. Objects must not start with one of the matching
-- \`exclude_prefixes\` for inclusion in a transfer. The following are
-- requirements of \`exclude_prefixes\`: * Each exclude-prefix can contain
-- any sequence of Unicode characters, to a max length of 1024 bytes when
-- UTF8-encoded, and must not contain Carriage Return or Line Feed
-- characters. Wildcard matching and regular expression matching are not
-- supported. * Each exclude-prefix must omit the leading slash. For
-- example, to exclude the object
-- \`s3:\/\/my-aws-bucket\/logs\/y=2015\/requests.gz\`, specify the
-- exclude-prefix as \`logs\/y=2015\/requests.gz\`. * None of the
-- exclude-prefix values can be empty, if specified. * Each exclude-prefix
-- must exclude a distinct portion of the object namespace. No
-- exclude-prefix may be a prefix of another exclude-prefix. * If
-- include_prefixes is specified, then each exclude-prefix must start with
-- the value of a path explicitly included by \`include_prefixes\`. The max
-- size of \`exclude_prefixes\` is 1000. For more information, see
-- [Filtering objects from
-- transfers](\/storage-transfer\/docs\/filtering-objects-from-transfers).
ocExcludePrefixes :: Lens' ObjectConditions [Text]
ocExcludePrefixes
= lens _ocExcludePrefixes
(\ s a -> s{_ocExcludePrefixes = a})
. _Default
. _Coerce
-- | If specified, only objects with a \"last modification time\" on or after
-- this timestamp and objects that don\'t have a \"last modification time\"
-- are transferred. The \`last_modified_since\` and
-- \`last_modified_before\` fields can be used together for chunked data
-- processing. For example, consider a script that processes each day\'s
-- worth of data at a time. For that you\'d set each of the fields as
-- follows: * \`last_modified_since\` to the start of the day *
-- \`last_modified_before\` to the end of the day
ocLastModifiedSince :: Lens' ObjectConditions (Maybe UTCTime)
ocLastModifiedSince
= lens _ocLastModifiedSince
(\ s a -> s{_ocLastModifiedSince = a})
. mapping _DateTime
instance FromJSON ObjectConditions where
parseJSON
= withObject "ObjectConditions"
(\ o ->
ObjectConditions' <$>
(o .:? "lastModifiedBefore") <*>
(o .:? "minTimeElapsedSinceLastModification")
<*> (o .:? "includePrefixes" .!= mempty)
<*> (o .:? "maxTimeElapsedSinceLastModification")
<*> (o .:? "excludePrefixes" .!= mempty)
<*> (o .:? "lastModifiedSince"))
instance ToJSON ObjectConditions where
toJSON ObjectConditions'{..}
= object
(catMaybes
[("lastModifiedBefore" .=) <$> _ocLastModifiedBefore,
("minTimeElapsedSinceLastModification" .=) <$>
_ocMinTimeElapsedSinceLastModification,
("includePrefixes" .=) <$> _ocIncludePrefixes,
("maxTimeElapsedSinceLastModification" .=) <$>
_ocMaxTimeElapsedSinceLastModification,
("excludePrefixes" .=) <$> _ocExcludePrefixes,
("lastModifiedSince" .=) <$> _ocLastModifiedSince])
-- | This resource represents a long-running operation that is the result of
-- a network API call.
--
-- /See:/ 'operation' smart constructor.
data Operation =
Operation'
{ _oDone :: !(Maybe Bool)
, _oError :: !(Maybe Status)
, _oResponse :: !(Maybe OperationResponse)
, _oName :: !(Maybe Text)
, _oMetadata :: !(Maybe OperationMetadata)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Operation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oDone'
--
-- * 'oError'
--
-- * 'oResponse'
--
-- * 'oName'
--
-- * 'oMetadata'
operation
:: Operation
operation =
Operation'
{ _oDone = Nothing
, _oError = Nothing
, _oResponse = Nothing
, _oName = Nothing
, _oMetadata = Nothing
}
-- | If the value is \`false\`, it means the operation is still in progress.
-- If \`true\`, the operation is completed, and either \`error\` or
-- \`response\` is available.
oDone :: Lens' Operation (Maybe Bool)
oDone = lens _oDone (\ s a -> s{_oDone = a})
-- | The error result of the operation in case of failure or cancellation.
oError :: Lens' Operation (Maybe Status)
oError = lens _oError (\ s a -> s{_oError = a})
-- | The normal response of the operation in case of success. If the original
-- method returns no data on success, such as \`Delete\`, the response is
-- \`google.protobuf.Empty\`. If the original method is standard
-- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource.
-- For other methods, the response should have the type \`XxxResponse\`,
-- where \`Xxx\` is the original method name. For example, if the original
-- method name is \`TakeSnapshot()\`, the inferred response type is
-- \`TakeSnapshotResponse\`.
oResponse :: Lens' Operation (Maybe OperationResponse)
oResponse
= lens _oResponse (\ s a -> s{_oResponse = a})
-- | The server-assigned unique name. The format of \`name\` is
-- \`transferOperations\/some\/unique\/name\`.
oName :: Lens' Operation (Maybe Text)
oName = lens _oName (\ s a -> s{_oName = a})
-- | Represents the transfer operation object. To request a TransferOperation
-- object, use transferOperations.get.
oMetadata :: Lens' Operation (Maybe OperationMetadata)
oMetadata
= lens _oMetadata (\ s a -> s{_oMetadata = a})
instance FromJSON Operation where
parseJSON
= withObject "Operation"
(\ o ->
Operation' <$>
(o .:? "done") <*> (o .:? "error") <*>
(o .:? "response")
<*> (o .:? "name")
<*> (o .:? "metadata"))
instance ToJSON Operation where
toJSON Operation'{..}
= object
(catMaybes
[("done" .=) <$> _oDone, ("error" .=) <$> _oError,
("response" .=) <$> _oResponse,
("name" .=) <$> _oName,
("metadata" .=) <$> _oMetadata])
-- | A generic empty message that you can re-use to avoid defining duplicated
-- empty messages in your APIs. A typical example is to use it as the
-- request or the response type of an API method. For instance: service Foo
-- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The
-- JSON representation for \`Empty\` is empty JSON object \`{}\`.
--
-- /See:/ 'empty' smart constructor.
data Empty =
Empty'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Empty' with the minimum fields required to make a request.
--
empty
:: Empty
empty = Empty'
instance FromJSON Empty where
parseJSON = withObject "Empty" (\ o -> pure Empty')
instance ToJSON Empty where
toJSON = const emptyObject
-- | Request passed to PauseTransferOperation.
--
-- /See:/ 'pauseTransferOperationRequest' smart constructor.
data PauseTransferOperationRequest =
PauseTransferOperationRequest'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PauseTransferOperationRequest' with the minimum fields required to make a request.
--
pauseTransferOperationRequest
:: PauseTransferOperationRequest
pauseTransferOperationRequest = PauseTransferOperationRequest'
instance FromJSON PauseTransferOperationRequest where
parseJSON
= withObject "PauseTransferOperationRequest"
(\ o -> pure PauseTransferOperationRequest')
instance ToJSON PauseTransferOperationRequest where
toJSON = const emptyObject
-- | Google service account
--
-- /See:/ 'googleServiceAccount' smart constructor.
data GoogleServiceAccount =
GoogleServiceAccount'
{ _gsaAccountEmail :: !(Maybe Text)
, _gsaSubjectId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleServiceAccount' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gsaAccountEmail'
--
-- * 'gsaSubjectId'
googleServiceAccount
:: GoogleServiceAccount
googleServiceAccount =
GoogleServiceAccount' {_gsaAccountEmail = Nothing, _gsaSubjectId = Nothing}
-- | Email address of the service account.
gsaAccountEmail :: Lens' GoogleServiceAccount (Maybe Text)
gsaAccountEmail
= lens _gsaAccountEmail
(\ s a -> s{_gsaAccountEmail = a})
-- | Unique identifier for the service account.
gsaSubjectId :: Lens' GoogleServiceAccount (Maybe Text)
gsaSubjectId
= lens _gsaSubjectId (\ s a -> s{_gsaSubjectId = a})
instance FromJSON GoogleServiceAccount where
parseJSON
= withObject "GoogleServiceAccount"
(\ o ->
GoogleServiceAccount' <$>
(o .:? "accountEmail") <*> (o .:? "subjectId"))
instance ToJSON GoogleServiceAccount where
toJSON GoogleServiceAccount'{..}
= object
(catMaybes
[("accountEmail" .=) <$> _gsaAccountEmail,
("subjectId" .=) <$> _gsaSubjectId])
--
-- /See:/ 'statusDetailsItem' smart constructor.
newtype StatusDetailsItem =
StatusDetailsItem'
{ _sdiAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sdiAddtional'
statusDetailsItem
:: HashMap Text JSONValue -- ^ 'sdiAddtional'
-> StatusDetailsItem
statusDetailsItem pSdiAddtional_ =
StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue)
sdiAddtional
= lens _sdiAddtional (\ s a -> s{_sdiAddtional = a})
. _Coerce
instance FromJSON StatusDetailsItem where
parseJSON
= withObject "StatusDetailsItem"
(\ o -> StatusDetailsItem' <$> (parseJSONObject o))
instance ToJSON StatusDetailsItem where
toJSON = toJSON . _sdiAddtional
-- | Azure credentials For information on our data retention policy for user
-- credentials, see [User
-- credentials](\/storage-transfer\/docs\/data-retention#user-credentials).
--
-- /See:/ 'azureCredentials' smart constructor.
newtype AzureCredentials =
AzureCredentials'
{ _acSasToken :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AzureCredentials' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acSasToken'
azureCredentials
:: AzureCredentials
azureCredentials = AzureCredentials' {_acSasToken = Nothing}
-- | Required. Azure shared access signature (SAS). *Note:*Copying data from
-- Azure Data Lake Storage (ADLS) Gen 2 is in
-- [Preview](\/products\/#product-launch-stages). During Preview, if you
-- are copying data from ADLS Gen 2, you must use an account SAS. For more
-- information about SAS, see [Grant limited access to Azure Storage
-- resources using shared access signatures
-- (SAS)](https:\/\/docs.microsoft.com\/en-us\/azure\/storage\/common\/storage-sas-overview).
acSasToken :: Lens' AzureCredentials (Maybe Text)
acSasToken
= lens _acSasToken (\ s a -> s{_acSasToken = a})
instance FromJSON AzureCredentials where
parseJSON
= withObject "AzureCredentials"
(\ o -> AzureCredentials' <$> (o .:? "sasToken"))
instance ToJSON AzureCredentials where
toJSON AzureCredentials'{..}
= object
(catMaybes [("sasToken" .=) <$> _acSasToken])
-- | Represents a whole or partial calendar date, such as a birthday. The
-- time of day and time zone are either specified elsewhere or are
-- insignificant. The date is relative to the Gregorian Calendar. This can
-- represent one of the following: * A full date, with non-zero year,
-- month, and day values * A month and day value, with a zero year, such as
-- an anniversary * A year on its own, with zero month and day values * A
-- year and month value, with a zero day, such as a credit card expiration
-- date Related types are google.type.TimeOfDay and
-- \`google.protobuf.Timestamp\`.
--
-- /See:/ 'date' smart constructor.
data Date =
Date'
{ _dDay :: !(Maybe (Textual Int32))
, _dYear :: !(Maybe (Textual Int32))
, _dMonth :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Date' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dDay'
--
-- * 'dYear'
--
-- * 'dMonth'
date
:: Date
date = Date' {_dDay = Nothing, _dYear = Nothing, _dMonth = Nothing}
-- | Day of a month. Must be from 1 to 31 and valid for the year and month,
-- or 0 to specify a year by itself or a year and month where the day
-- isn\'t significant.
dDay :: Lens' Date (Maybe Int32)
dDay
= lens _dDay (\ s a -> s{_dDay = a}) .
mapping _Coerce
-- | Year of the date. Must be from 1 to 9999, or 0 to specify a date without
-- a year.
dYear :: Lens' Date (Maybe Int32)
dYear
= lens _dYear (\ s a -> s{_dYear = a}) .
mapping _Coerce
-- | Month of a year. Must be from 1 to 12, or 0 to specify a year without a
-- month and day.
dMonth :: Lens' Date (Maybe Int32)
dMonth
= lens _dMonth (\ s a -> s{_dMonth = a}) .
mapping _Coerce
instance FromJSON Date where
parseJSON
= withObject "Date"
(\ o ->
Date' <$>
(o .:? "day") <*> (o .:? "year") <*> (o .:? "month"))
instance ToJSON Date where
toJSON Date'{..}
= object
(catMaybes
[("day" .=) <$> _dDay, ("year" .=) <$> _dYear,
("month" .=) <$> _dMonth])
-- | Request passed to UpdateTransferJob.
--
-- /See:/ 'updateTransferJobRequest' smart constructor.
data UpdateTransferJobRequest =
UpdateTransferJobRequest'
{ _utjrTransferJob :: !(Maybe TransferJob)
, _utjrProjectId :: !(Maybe Text)
, _utjrUpdateTransferJobFieldMask :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateTransferJobRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utjrTransferJob'
--
-- * 'utjrProjectId'
--
-- * 'utjrUpdateTransferJobFieldMask'
updateTransferJobRequest
:: UpdateTransferJobRequest
updateTransferJobRequest =
UpdateTransferJobRequest'
{ _utjrTransferJob = Nothing
, _utjrProjectId = Nothing
, _utjrUpdateTransferJobFieldMask = Nothing
}
-- | Required. The job to update. \`transferJob\` is expected to specify only
-- four fields: description, transfer_spec, notification_config, and
-- status. An \`UpdateTransferJobRequest\` that specifies other fields are
-- rejected with the error INVALID_ARGUMENT. Updating a job status to
-- DELETED requires \`storagetransfer.jobs.delete\` permissions.
utjrTransferJob :: Lens' UpdateTransferJobRequest (Maybe TransferJob)
utjrTransferJob
= lens _utjrTransferJob
(\ s a -> s{_utjrTransferJob = a})
-- | Required. The ID of the Google Cloud Platform Console project that owns
-- the job.
utjrProjectId :: Lens' UpdateTransferJobRequest (Maybe Text)
utjrProjectId
= lens _utjrProjectId
(\ s a -> s{_utjrProjectId = a})
-- | The field mask of the fields in \`transferJob\` that are to be updated
-- in this request. Fields in \`transferJob\` that can be updated are:
-- description, transfer_spec, notification_config, and status. To update
-- the \`transfer_spec\` of the job, a complete transfer specification must
-- be provided. An incomplete specification missing any required fields is
-- rejected with the error INVALID_ARGUMENT.
utjrUpdateTransferJobFieldMask :: Lens' UpdateTransferJobRequest (Maybe GFieldMask)
utjrUpdateTransferJobFieldMask
= lens _utjrUpdateTransferJobFieldMask
(\ s a -> s{_utjrUpdateTransferJobFieldMask = a})
instance FromJSON UpdateTransferJobRequest where
parseJSON
= withObject "UpdateTransferJobRequest"
(\ o ->
UpdateTransferJobRequest' <$>
(o .:? "transferJob") <*> (o .:? "projectId") <*>
(o .:? "updateTransferJobFieldMask"))
instance ToJSON UpdateTransferJobRequest where
toJSON UpdateTransferJobRequest'{..}
= object
(catMaybes
[("transferJob" .=) <$> _utjrTransferJob,
("projectId" .=) <$> _utjrProjectId,
("updateTransferJobFieldMask" .=) <$>
_utjrUpdateTransferJobFieldMask])
-- | A collection of counters that report the progress of a transfer
-- operation.
--
-- /See:/ 'transferCounters' smart constructor.
data TransferCounters =
TransferCounters'
{ _tcBytesFoundOnlyFromSink :: !(Maybe (Textual Int64))
, _tcBytesDeletedFromSink :: !(Maybe (Textual Int64))
, _tcObjectsDeletedFromSource :: !(Maybe (Textual Int64))
, _tcObjectsFoundFromSource :: !(Maybe (Textual Int64))
, _tcBytesFailedToDeleteFromSink :: !(Maybe (Textual Int64))
, _tcBytesFromSourceFailed :: !(Maybe (Textual Int64))
, _tcBytesCopiedToSink :: !(Maybe (Textual Int64))
, _tcBytesFoundFromSource :: !(Maybe (Textual Int64))
, _tcBytesDeletedFromSource :: !(Maybe (Textual Int64))
, _tcObjectsDeletedFromSink :: !(Maybe (Textual Int64))
, _tcObjectsFoundOnlyFromSink :: !(Maybe (Textual Int64))
, _tcBytesFromSourceSkippedBySync :: !(Maybe (Textual Int64))
, _tcObjectsCopiedToSink :: !(Maybe (Textual Int64))
, _tcObjectsFromSourceFailed :: !(Maybe (Textual Int64))
, _tcObjectsFailedToDeleteFromSink :: !(Maybe (Textual Int64))
, _tcObjectsFromSourceSkippedBySync :: !(Maybe (Textual Int64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TransferCounters' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcBytesFoundOnlyFromSink'
--
-- * 'tcBytesDeletedFromSink'
--
-- * 'tcObjectsDeletedFromSource'
--
-- * 'tcObjectsFoundFromSource'
--
-- * 'tcBytesFailedToDeleteFromSink'
--
-- * 'tcBytesFromSourceFailed'
--
-- * 'tcBytesCopiedToSink'
--
-- * 'tcBytesFoundFromSource'
--
-- * 'tcBytesDeletedFromSource'
--
-- * 'tcObjectsDeletedFromSink'
--
-- * 'tcObjectsFoundOnlyFromSink'
--
-- * 'tcBytesFromSourceSkippedBySync'
--
-- * 'tcObjectsCopiedToSink'
--
-- * 'tcObjectsFromSourceFailed'
--
-- * 'tcObjectsFailedToDeleteFromSink'
--
-- * 'tcObjectsFromSourceSkippedBySync'
transferCounters
:: TransferCounters
transferCounters =
TransferCounters'
{ _tcBytesFoundOnlyFromSink = Nothing
, _tcBytesDeletedFromSink = Nothing
, _tcObjectsDeletedFromSource = Nothing
, _tcObjectsFoundFromSource = Nothing
, _tcBytesFailedToDeleteFromSink = Nothing
, _tcBytesFromSourceFailed = Nothing
, _tcBytesCopiedToSink = Nothing
, _tcBytesFoundFromSource = Nothing
, _tcBytesDeletedFromSource = Nothing
, _tcObjectsDeletedFromSink = Nothing
, _tcObjectsFoundOnlyFromSink = Nothing
, _tcBytesFromSourceSkippedBySync = Nothing
, _tcObjectsCopiedToSink = Nothing
, _tcObjectsFromSourceFailed = Nothing
, _tcObjectsFailedToDeleteFromSink = Nothing
, _tcObjectsFromSourceSkippedBySync = Nothing
}
-- | Bytes found only in the data sink that are scheduled to be deleted.
tcBytesFoundOnlyFromSink :: Lens' TransferCounters (Maybe Int64)
tcBytesFoundOnlyFromSink
= lens _tcBytesFoundOnlyFromSink
(\ s a -> s{_tcBytesFoundOnlyFromSink = a})
. mapping _Coerce
-- | Bytes that are deleted from the data sink.
tcBytesDeletedFromSink :: Lens' TransferCounters (Maybe Int64)
tcBytesDeletedFromSink
= lens _tcBytesDeletedFromSink
(\ s a -> s{_tcBytesDeletedFromSink = a})
. mapping _Coerce
-- | Objects that are deleted from the data source.
tcObjectsDeletedFromSource :: Lens' TransferCounters (Maybe Int64)
tcObjectsDeletedFromSource
= lens _tcObjectsDeletedFromSource
(\ s a -> s{_tcObjectsDeletedFromSource = a})
. mapping _Coerce
-- | Objects found in the data source that are scheduled to be transferred,
-- excluding any that are filtered based on object conditions or skipped
-- due to sync.
tcObjectsFoundFromSource :: Lens' TransferCounters (Maybe Int64)
tcObjectsFoundFromSource
= lens _tcObjectsFoundFromSource
(\ s a -> s{_tcObjectsFoundFromSource = a})
. mapping _Coerce
-- | Bytes that failed to be deleted from the data sink.
tcBytesFailedToDeleteFromSink :: Lens' TransferCounters (Maybe Int64)
tcBytesFailedToDeleteFromSink
= lens _tcBytesFailedToDeleteFromSink
(\ s a -> s{_tcBytesFailedToDeleteFromSink = a})
. mapping _Coerce
-- | Bytes in the data source that failed to be transferred or that failed to
-- be deleted after being transferred.
tcBytesFromSourceFailed :: Lens' TransferCounters (Maybe Int64)
tcBytesFromSourceFailed
= lens _tcBytesFromSourceFailed
(\ s a -> s{_tcBytesFromSourceFailed = a})
. mapping _Coerce
-- | Bytes that are copied to the data sink.
tcBytesCopiedToSink :: Lens' TransferCounters (Maybe Int64)
tcBytesCopiedToSink
= lens _tcBytesCopiedToSink
(\ s a -> s{_tcBytesCopiedToSink = a})
. mapping _Coerce
-- | Bytes found in the data source that are scheduled to be transferred,
-- excluding any that are filtered based on object conditions or skipped
-- due to sync.
tcBytesFoundFromSource :: Lens' TransferCounters (Maybe Int64)
tcBytesFoundFromSource
= lens _tcBytesFoundFromSource
(\ s a -> s{_tcBytesFoundFromSource = a})
. mapping _Coerce
-- | Bytes that are deleted from the data source.
tcBytesDeletedFromSource :: Lens' TransferCounters (Maybe Int64)
tcBytesDeletedFromSource
= lens _tcBytesDeletedFromSource
(\ s a -> s{_tcBytesDeletedFromSource = a})
. mapping _Coerce
-- | Objects that are deleted from the data sink.
tcObjectsDeletedFromSink :: Lens' TransferCounters (Maybe Int64)
tcObjectsDeletedFromSink
= lens _tcObjectsDeletedFromSink
(\ s a -> s{_tcObjectsDeletedFromSink = a})
. mapping _Coerce
-- | Objects found only in the data sink that are scheduled to be deleted.
tcObjectsFoundOnlyFromSink :: Lens' TransferCounters (Maybe Int64)
tcObjectsFoundOnlyFromSink
= lens _tcObjectsFoundOnlyFromSink
(\ s a -> s{_tcObjectsFoundOnlyFromSink = a})
. mapping _Coerce
-- | Bytes in the data source that are not transferred because they already
-- exist in the data sink.
tcBytesFromSourceSkippedBySync :: Lens' TransferCounters (Maybe Int64)
tcBytesFromSourceSkippedBySync
= lens _tcBytesFromSourceSkippedBySync
(\ s a -> s{_tcBytesFromSourceSkippedBySync = a})
. mapping _Coerce
-- | Objects that are copied to the data sink.
tcObjectsCopiedToSink :: Lens' TransferCounters (Maybe Int64)
tcObjectsCopiedToSink
= lens _tcObjectsCopiedToSink
(\ s a -> s{_tcObjectsCopiedToSink = a})
. mapping _Coerce
-- | Objects in the data source that failed to be transferred or that failed
-- to be deleted after being transferred.
tcObjectsFromSourceFailed :: Lens' TransferCounters (Maybe Int64)
tcObjectsFromSourceFailed
= lens _tcObjectsFromSourceFailed
(\ s a -> s{_tcObjectsFromSourceFailed = a})
. mapping _Coerce
-- | Objects that failed to be deleted from the data sink.
tcObjectsFailedToDeleteFromSink :: Lens' TransferCounters (Maybe Int64)
tcObjectsFailedToDeleteFromSink
= lens _tcObjectsFailedToDeleteFromSink
(\ s a -> s{_tcObjectsFailedToDeleteFromSink = a})
. mapping _Coerce
-- | Objects in the data source that are not transferred because they already
-- exist in the data sink.
tcObjectsFromSourceSkippedBySync :: Lens' TransferCounters (Maybe Int64)
tcObjectsFromSourceSkippedBySync
= lens _tcObjectsFromSourceSkippedBySync
(\ s a -> s{_tcObjectsFromSourceSkippedBySync = a})
. mapping _Coerce
instance FromJSON TransferCounters where
parseJSON
= withObject "TransferCounters"
(\ o ->
TransferCounters' <$>
(o .:? "bytesFoundOnlyFromSink") <*>
(o .:? "bytesDeletedFromSink")
<*> (o .:? "objectsDeletedFromSource")
<*> (o .:? "objectsFoundFromSource")
<*> (o .:? "bytesFailedToDeleteFromSink")
<*> (o .:? "bytesFromSourceFailed")
<*> (o .:? "bytesCopiedToSink")
<*> (o .:? "bytesFoundFromSource")
<*> (o .:? "bytesDeletedFromSource")
<*> (o .:? "objectsDeletedFromSink")
<*> (o .:? "objectsFoundOnlyFromSink")
<*> (o .:? "bytesFromSourceSkippedBySync")
<*> (o .:? "objectsCopiedToSink")
<*> (o .:? "objectsFromSourceFailed")
<*> (o .:? "objectsFailedToDeleteFromSink")
<*> (o .:? "objectsFromSourceSkippedBySync"))
instance ToJSON TransferCounters where
toJSON TransferCounters'{..}
= object
(catMaybes
[("bytesFoundOnlyFromSink" .=) <$>
_tcBytesFoundOnlyFromSink,
("bytesDeletedFromSink" .=) <$>
_tcBytesDeletedFromSink,
("objectsDeletedFromSource" .=) <$>
_tcObjectsDeletedFromSource,
("objectsFoundFromSource" .=) <$>
_tcObjectsFoundFromSource,
("bytesFailedToDeleteFromSink" .=) <$>
_tcBytesFailedToDeleteFromSink,
("bytesFromSourceFailed" .=) <$>
_tcBytesFromSourceFailed,
("bytesCopiedToSink" .=) <$> _tcBytesCopiedToSink,
("bytesFoundFromSource" .=) <$>
_tcBytesFoundFromSource,
("bytesDeletedFromSource" .=) <$>
_tcBytesDeletedFromSource,
("objectsDeletedFromSink" .=) <$>
_tcObjectsDeletedFromSink,
("objectsFoundOnlyFromSink" .=) <$>
_tcObjectsFoundOnlyFromSink,
("bytesFromSourceSkippedBySync" .=) <$>
_tcBytesFromSourceSkippedBySync,
("objectsCopiedToSink" .=) <$>
_tcObjectsCopiedToSink,
("objectsFromSourceFailed" .=) <$>
_tcObjectsFromSourceFailed,
("objectsFailedToDeleteFromSink" .=) <$>
_tcObjectsFailedToDeleteFromSink,
("objectsFromSourceSkippedBySync" .=) <$>
_tcObjectsFromSourceSkippedBySync])
-- | This resource represents the configuration of a transfer job that runs
-- periodically.
--
-- /See:/ 'transferJob' smart constructor.
data TransferJob =
TransferJob'
{ _tjCreationTime :: !(Maybe DateTime')
, _tjStatus :: !(Maybe TransferJobStatus)
, _tjNotificationConfig :: !(Maybe NotificationConfig)
, _tjSchedule :: !(Maybe Schedule)
, _tjDeletionTime :: !(Maybe DateTime')
, _tjName :: !(Maybe Text)
, _tjProjectId :: !(Maybe Text)
, _tjTransferSpec :: !(Maybe TransferSpec)
, _tjDescription :: !(Maybe Text)
, _tjLastModificationTime :: !(Maybe DateTime')
, _tjLatestOperationName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TransferJob' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tjCreationTime'
--
-- * 'tjStatus'
--
-- * 'tjNotificationConfig'
--
-- * 'tjSchedule'
--
-- * 'tjDeletionTime'
--
-- * 'tjName'
--
-- * 'tjProjectId'
--
-- * 'tjTransferSpec'
--
-- * 'tjDescription'
--
-- * 'tjLastModificationTime'
--
-- * 'tjLatestOperationName'
transferJob
:: TransferJob
transferJob =
TransferJob'
{ _tjCreationTime = Nothing
, _tjStatus = Nothing
, _tjNotificationConfig = Nothing
, _tjSchedule = Nothing
, _tjDeletionTime = Nothing
, _tjName = Nothing
, _tjProjectId = Nothing
, _tjTransferSpec = Nothing
, _tjDescription = Nothing
, _tjLastModificationTime = Nothing
, _tjLatestOperationName = Nothing
}
-- | Output only. The time that the transfer job was created.
tjCreationTime :: Lens' TransferJob (Maybe UTCTime)
tjCreationTime
= lens _tjCreationTime
(\ s a -> s{_tjCreationTime = a})
. mapping _DateTime
-- | Status of the job. This value MUST be specified for
-- \`CreateTransferJobRequests\`. **Note:** The effect of the new job
-- status takes place during a subsequent job run. For example, if you
-- change the job status from ENABLED to DISABLED, and an operation spawned
-- by the transfer is running, the status change would not affect the
-- current operation.
tjStatus :: Lens' TransferJob (Maybe TransferJobStatus)
tjStatus = lens _tjStatus (\ s a -> s{_tjStatus = a})
-- | Notification configuration. This is not supported for transfers
-- involving PosixFilesystem.
tjNotificationConfig :: Lens' TransferJob (Maybe NotificationConfig)
tjNotificationConfig
= lens _tjNotificationConfig
(\ s a -> s{_tjNotificationConfig = a})
-- | Specifies schedule for the transfer job. This is an optional field. When
-- the field is not set, the job never executes a transfer, unless you
-- invoke RunTransferJob or update the job to have a non-empty schedule.
tjSchedule :: Lens' TransferJob (Maybe Schedule)
tjSchedule
= lens _tjSchedule (\ s a -> s{_tjSchedule = a})
-- | Output only. The time that the transfer job was deleted.
tjDeletionTime :: Lens' TransferJob (Maybe UTCTime)
tjDeletionTime
= lens _tjDeletionTime
(\ s a -> s{_tjDeletionTime = a})
. mapping _DateTime
-- | A unique name (within the transfer project) assigned when the job is
-- created. If this field is empty in a CreateTransferJobRequest, Storage
-- Transfer Service assigns a unique name. Otherwise, the specified name is
-- used as the unique name for this job. If the specified name is in use by
-- a job, the creation request fails with an ALREADY_EXISTS error. This
-- name must start with \`\"transferJobs\/\"\` prefix and end with a letter
-- or a number, and should be no more than 128 characters. For transfers
-- involving PosixFilesystem, this name must start with
-- \'transferJobs\/OPI\' specifically. For all other transfer types, this
-- name must not start with \'transferJobs\/OPI\'. \'transferJobs\/OPI\' is
-- a reserved prefix for PosixFilesystem transfers. Non-PosixFilesystem
-- example: \`\"transferJobs\/^(?!OPI)[A-Za-z0-9-._~]*[A-Za-z0-9]$\"\`
-- PosixFilesystem example:
-- \`\"transferJobs\/OPI^[A-Za-z0-9-._~]*[A-Za-z0-9]$\"\` Applications must
-- not rely on the enforcement of naming requirements involving OPI.
-- Invalid job names fail with an INVALID_ARGUMENT error.
tjName :: Lens' TransferJob (Maybe Text)
tjName = lens _tjName (\ s a -> s{_tjName = a})
-- | The ID of the Google Cloud Platform Project that owns the job.
tjProjectId :: Lens' TransferJob (Maybe Text)
tjProjectId
= lens _tjProjectId (\ s a -> s{_tjProjectId = a})
-- | Transfer specification.
tjTransferSpec :: Lens' TransferJob (Maybe TransferSpec)
tjTransferSpec
= lens _tjTransferSpec
(\ s a -> s{_tjTransferSpec = a})
-- | A description provided by the user for the job. Its max length is 1024
-- bytes when Unicode-encoded.
tjDescription :: Lens' TransferJob (Maybe Text)
tjDescription
= lens _tjDescription
(\ s a -> s{_tjDescription = a})
-- | Output only. The time that the transfer job was last modified.
tjLastModificationTime :: Lens' TransferJob (Maybe UTCTime)
tjLastModificationTime
= lens _tjLastModificationTime
(\ s a -> s{_tjLastModificationTime = a})
. mapping _DateTime
-- | The name of the most recently started TransferOperation of this
-- JobConfig. Present if a TransferOperation has been created for this
-- JobConfig.
tjLatestOperationName :: Lens' TransferJob (Maybe Text)
tjLatestOperationName
= lens _tjLatestOperationName
(\ s a -> s{_tjLatestOperationName = a})
instance FromJSON TransferJob where
parseJSON
= withObject "TransferJob"
(\ o ->
TransferJob' <$>
(o .:? "creationTime") <*> (o .:? "status") <*>
(o .:? "notificationConfig")
<*> (o .:? "schedule")
<*> (o .:? "deletionTime")
<*> (o .:? "name")
<*> (o .:? "projectId")
<*> (o .:? "transferSpec")
<*> (o .:? "description")
<*> (o .:? "lastModificationTime")
<*> (o .:? "latestOperationName"))
instance ToJSON TransferJob where
toJSON TransferJob'{..}
= object
(catMaybes
[("creationTime" .=) <$> _tjCreationTime,
("status" .=) <$> _tjStatus,
("notificationConfig" .=) <$> _tjNotificationConfig,
("schedule" .=) <$> _tjSchedule,
("deletionTime" .=) <$> _tjDeletionTime,
("name" .=) <$> _tjName,
("projectId" .=) <$> _tjProjectId,
("transferSpec" .=) <$> _tjTransferSpec,
("description" .=) <$> _tjDescription,
("lastModificationTime" .=) <$>
_tjLastModificationTime,
("latestOperationName" .=) <$>
_tjLatestOperationName])
-- | In a GcsData resource, an object\'s name is the Cloud Storage object\'s
-- name and its \"last modification time\" refers to the object\'s
-- \`updated\` property of Cloud Storage objects, which changes when the
-- content or the metadata of the object is updated.
--
-- /See:/ 'gcsData' smart constructor.
data GcsData =
GcsData'
{ _gdPath :: !(Maybe Text)
, _gdBucketName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GcsData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gdPath'
--
-- * 'gdBucketName'
gcsData
:: GcsData
gcsData = GcsData' {_gdPath = Nothing, _gdBucketName = Nothing}
-- | Root path to transfer objects. Must be an empty string or full path name
-- that ends with a \'\/\'. This field is treated as an object prefix. As
-- such, it should generally not begin with a \'\/\'. The root path value
-- must meet [Object Name
-- Requirements](\/storage\/docs\/naming#objectnames).
gdPath :: Lens' GcsData (Maybe Text)
gdPath = lens _gdPath (\ s a -> s{_gdPath = a})
-- | Required. Cloud Storage bucket name. Must meet [Bucket Name
-- Requirements](\/storage\/docs\/naming#requirements).
gdBucketName :: Lens' GcsData (Maybe Text)
gdBucketName
= lens _gdBucketName (\ s a -> s{_gdBucketName = a})
instance FromJSON GcsData where
parseJSON
= withObject "GcsData"
(\ o ->
GcsData' <$> (o .:? "path") <*> (o .:? "bucketName"))
instance ToJSON GcsData where
toJSON GcsData'{..}
= object
(catMaybes
[("path" .=) <$> _gdPath,
("bucketName" .=) <$> _gdBucketName])
-- | An AwsS3Data resource can be a data source, but not a data sink. In an
-- AwsS3Data resource, an object\'s name is the S3 object\'s key name.
--
-- /See:/ 'awsS3Data' smart constructor.
data AwsS3Data =
AwsS3Data'
{ _asdPath :: !(Maybe Text)
, _asdBucketName :: !(Maybe Text)
, _asdAwsAccessKey :: !(Maybe AwsAccessKey)
, _asdRoleArn :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AwsS3Data' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'asdPath'
--
-- * 'asdBucketName'
--
-- * 'asdAwsAccessKey'
--
-- * 'asdRoleArn'
awsS3Data
:: AwsS3Data
awsS3Data =
AwsS3Data'
{ _asdPath = Nothing
, _asdBucketName = Nothing
, _asdAwsAccessKey = Nothing
, _asdRoleArn = Nothing
}
-- | Root path to transfer objects. Must be an empty string or full path name
-- that ends with a \'\/\'. This field is treated as an object prefix. As
-- such, it should generally not begin with a \'\/\'.
asdPath :: Lens' AwsS3Data (Maybe Text)
asdPath = lens _asdPath (\ s a -> s{_asdPath = a})
-- | Required. S3 Bucket name (see [Creating a
-- bucket](https:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/dev\/create-bucket-get-location-example.html)).
asdBucketName :: Lens' AwsS3Data (Maybe Text)
asdBucketName
= lens _asdBucketName
(\ s a -> s{_asdBucketName = a})
-- | Input only. AWS access key used to sign the API requests to the AWS S3
-- bucket. Permissions on the bucket must be granted to the access ID of
-- the AWS access key. This field is required. For information on our data
-- retention policy for user credentials, see [User
-- credentials](\/storage-transfer\/docs\/data-retention#user-credentials).
asdAwsAccessKey :: Lens' AwsS3Data (Maybe AwsAccessKey)
asdAwsAccessKey
= lens _asdAwsAccessKey
(\ s a -> s{_asdAwsAccessKey = a})
-- | Input only. The Amazon Resource Name (ARN) of the role to support
-- temporary credentials via \`AssumeRoleWithWebIdentity\`. For more
-- information about ARNs, see [IAM
-- ARNs](https:\/\/docs.aws.amazon.com\/IAM\/latest\/UserGuide\/reference_identifiers.html#identifiers-arns).
-- When a role ARN is provided, Transfer Service fetches temporary
-- credentials for the session using a \`AssumeRoleWithWebIdentity\` call
-- for the provided role using the GoogleServiceAccount for this project.
asdRoleArn :: Lens' AwsS3Data (Maybe Text)
asdRoleArn
= lens _asdRoleArn (\ s a -> s{_asdRoleArn = a})
instance FromJSON AwsS3Data where
parseJSON
= withObject "AwsS3Data"
(\ o ->
AwsS3Data' <$>
(o .:? "path") <*> (o .:? "bucketName") <*>
(o .:? "awsAccessKey")
<*> (o .:? "roleArn"))
instance ToJSON AwsS3Data where
toJSON AwsS3Data'{..}
= object
(catMaybes
[("path" .=) <$> _asdPath,
("bucketName" .=) <$> _asdBucketName,
("awsAccessKey" .=) <$> _asdAwsAccessKey,
("roleArn" .=) <$> _asdRoleArn])
-- | An HttpData resource specifies a list of objects on the web to be
-- transferred over HTTP. The information of the objects to be transferred
-- is contained in a file referenced by a URL. The first line in the file
-- must be \`\"TsvHttpData-1.0\"\`, which specifies the format of the file.
-- Subsequent lines specify the information of the list of objects, one
-- object per list entry. Each entry has the following tab-delimited
-- fields: * **HTTP URL** — The location of the object. * **Length** — The
-- size of the object in bytes. * **MD5** — The base64-encoded MD5 hash of
-- the object. For an example of a valid TSV file, see [Transferring data
-- from
-- URLs](https:\/\/cloud.google.com\/storage-transfer\/docs\/create-url-list).
-- When transferring data based on a URL list, keep the following in mind:
-- * When an object located at \`http(s):\/\/hostname:port\/\` is
-- transferred to a data sink, the name of the object at the data sink is
-- \`\/\`. * If the specified size of an object does not match the actual
-- size of the object fetched, the object is not transferred. * If the
-- specified MD5 does not match the MD5 computed from the transferred
-- bytes, the object transfer fails. * Ensure that each URL you specify is
-- publicly accessible. For example, in Cloud Storage you can [share an
-- object publicly] (\/storage\/docs\/cloud-console#_sharingdata) and get a
-- link to it. * Storage Transfer Service obeys \`robots.txt\` rules and
-- requires the source HTTP server to support \`Range\` requests and to
-- return a \`Content-Length\` header in each response. * ObjectConditions
-- have no effect when filtering objects to transfer.
--
-- /See:/ 'hTTPData' smart constructor.
newtype HTTPData =
HTTPData'
{ _httpdListURL :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'HTTPData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'httpdListURL'
hTTPData
:: HTTPData
hTTPData = HTTPData' {_httpdListURL = Nothing}
-- | Required. The URL that points to the file that stores the object list
-- entries. This file must allow public access. Currently, only URLs with
-- HTTP and HTTPS schemes are supported.
httpdListURL :: Lens' HTTPData (Maybe Text)
httpdListURL
= lens _httpdListURL (\ s a -> s{_httpdListURL = a})
instance FromJSON HTTPData where
parseJSON
= withObject "HTTPData"
(\ o -> HTTPData' <$> (o .:? "listUrl"))
instance ToJSON HTTPData where
toJSON HTTPData'{..}
= object
(catMaybes [("listUrl" .=) <$> _httpdListURL])
-- | Represents a time of day. The date and time zone are either not
-- significant or are specified elsewhere. An API may choose to allow leap
-- seconds. Related types are google.type.Date and
-- \`google.protobuf.Timestamp\`.
--
-- /See:/ 'timeOfDay' smart constructor.
data TimeOfDay' =
TimeOfDay''
{ _todNanos :: !(Maybe (Textual Int32))
, _todHours :: !(Maybe (Textual Int32))
, _todMinutes :: !(Maybe (Textual Int32))
, _todSeconds :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TimeOfDay' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'todNanos'
--
-- * 'todHours'
--
-- * 'todMinutes'
--
-- * 'todSeconds'
timeOfDay
:: TimeOfDay'
timeOfDay =
TimeOfDay''
{ _todNanos = Nothing
, _todHours = Nothing
, _todMinutes = Nothing
, _todSeconds = Nothing
}
-- | Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.
todNanos :: Lens' TimeOfDay' (Maybe Int32)
todNanos
= lens _todNanos (\ s a -> s{_todNanos = a}) .
mapping _Coerce
-- | Hours of day in 24 hour format. Should be from 0 to 23. An API may
-- choose to allow the value \"24:00:00\" for scenarios like business
-- closing time.
todHours :: Lens' TimeOfDay' (Maybe Int32)
todHours
= lens _todHours (\ s a -> s{_todHours = a}) .
mapping _Coerce
-- | Minutes of hour of day. Must be from 0 to 59.
todMinutes :: Lens' TimeOfDay' (Maybe Int32)
todMinutes
= lens _todMinutes (\ s a -> s{_todMinutes = a}) .
mapping _Coerce
-- | Seconds of minutes of the time. Must normally be from 0 to 59. An API
-- may allow the value 60 if it allows leap-seconds.
todSeconds :: Lens' TimeOfDay' (Maybe Int32)
todSeconds
= lens _todSeconds (\ s a -> s{_todSeconds = a}) .
mapping _Coerce
instance FromJSON TimeOfDay' where
parseJSON
= withObject "TimeOfDay"
(\ o ->
TimeOfDay'' <$>
(o .:? "nanos") <*> (o .:? "hours") <*>
(o .:? "minutes")
<*> (o .:? "seconds"))
instance ToJSON TimeOfDay' where
toJSON TimeOfDay''{..}
= object
(catMaybes
[("nanos" .=) <$> _todNanos,
("hours" .=) <$> _todHours,
("minutes" .=) <$> _todMinutes,
("seconds" .=) <$> _todSeconds])
-- | An entry describing an error that has occurred.
--
-- /See:/ 'errorLogEntry' smart constructor.
data ErrorLogEntry =
ErrorLogEntry'
{ _eleURL :: !(Maybe Text)
, _eleErrorDetails :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ErrorLogEntry' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eleURL'
--
-- * 'eleErrorDetails'
errorLogEntry
:: ErrorLogEntry
errorLogEntry = ErrorLogEntry' {_eleURL = Nothing, _eleErrorDetails = Nothing}
-- | Required. A URL that refers to the target (a data source, a data sink,
-- or an object) with which the error is associated.
eleURL :: Lens' ErrorLogEntry (Maybe Text)
eleURL = lens _eleURL (\ s a -> s{_eleURL = a})
-- | A list of messages that carry the error details.
eleErrorDetails :: Lens' ErrorLogEntry [Text]
eleErrorDetails
= lens _eleErrorDetails
(\ s a -> s{_eleErrorDetails = a})
. _Default
. _Coerce
instance FromJSON ErrorLogEntry where
parseJSON
= withObject "ErrorLogEntry"
(\ o ->
ErrorLogEntry' <$>
(o .:? "url") <*> (o .:? "errorDetails" .!= mempty))
instance ToJSON ErrorLogEntry where
toJSON ErrorLogEntry'{..}
= object
(catMaybes
[("url" .=) <$> _eleURL,
("errorDetails" .=) <$> _eleErrorDetails])
-- | Represents the transfer operation object. To request a TransferOperation
-- object, use transferOperations.get.
--
-- /See:/ 'operationMetadata' smart constructor.
newtype OperationMetadata =
OperationMetadata'
{ _omAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'omAddtional'
operationMetadata
:: HashMap Text JSONValue -- ^ 'omAddtional'
-> OperationMetadata
operationMetadata pOmAddtional_ =
OperationMetadata' {_omAddtional = _Coerce # pOmAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
omAddtional :: Lens' OperationMetadata (HashMap Text JSONValue)
omAddtional
= lens _omAddtional (\ s a -> s{_omAddtional = a}) .
_Coerce
instance FromJSON OperationMetadata where
parseJSON
= withObject "OperationMetadata"
(\ o -> OperationMetadata' <$> (parseJSONObject o))
instance ToJSON OperationMetadata where
toJSON = toJSON . _omAddtional
-- | An AzureBlobStorageData resource can be a data source, but not a data
-- sink. An AzureBlobStorageData resource represents one Azure container.
-- The storage account determines the [Azure
-- endpoint](https:\/\/docs.microsoft.com\/en-us\/azure\/storage\/common\/storage-create-storage-account#storage-account-endpoints).
-- In an AzureBlobStorageData resource, a blobs\'s name is the [Azure Blob
-- Storage blob\'s key
-- name](https:\/\/docs.microsoft.com\/en-us\/rest\/api\/storageservices\/naming-and-referencing-containers--blobs--and-metadata#blob-names).
--
-- /See:/ 'azureBlobStorageData' smart constructor.
data AzureBlobStorageData =
AzureBlobStorageData'
{ _absdPath :: !(Maybe Text)
, _absdAzureCredentials :: !(Maybe AzureCredentials)
, _absdContainer :: !(Maybe Text)
, _absdStorageAccount :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AzureBlobStorageData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'absdPath'
--
-- * 'absdAzureCredentials'
--
-- * 'absdContainer'
--
-- * 'absdStorageAccount'
azureBlobStorageData
:: AzureBlobStorageData
azureBlobStorageData =
AzureBlobStorageData'
{ _absdPath = Nothing
, _absdAzureCredentials = Nothing
, _absdContainer = Nothing
, _absdStorageAccount = Nothing
}
-- | Root path to transfer objects. Must be an empty string or full path name
-- that ends with a \'\/\'. This field is treated as an object prefix. As
-- such, it should generally not begin with a \'\/\'.
absdPath :: Lens' AzureBlobStorageData (Maybe Text)
absdPath = lens _absdPath (\ s a -> s{_absdPath = a})
-- | Required. Input only. Credentials used to authenticate API requests to
-- Azure. For information on our data retention policy for user
-- credentials, see [User
-- credentials](\/storage-transfer\/docs\/data-retention#user-credentials).
absdAzureCredentials :: Lens' AzureBlobStorageData (Maybe AzureCredentials)
absdAzureCredentials
= lens _absdAzureCredentials
(\ s a -> s{_absdAzureCredentials = a})
-- | Required. The container to transfer from the Azure Storage account.
absdContainer :: Lens' AzureBlobStorageData (Maybe Text)
absdContainer
= lens _absdContainer
(\ s a -> s{_absdContainer = a})
-- | Required. The name of the Azure Storage account.
absdStorageAccount :: Lens' AzureBlobStorageData (Maybe Text)
absdStorageAccount
= lens _absdStorageAccount
(\ s a -> s{_absdStorageAccount = a})
instance FromJSON AzureBlobStorageData where
parseJSON
= withObject "AzureBlobStorageData"
(\ o ->
AzureBlobStorageData' <$>
(o .:? "path") <*> (o .:? "azureCredentials") <*>
(o .:? "container")
<*> (o .:? "storageAccount"))
instance ToJSON AzureBlobStorageData where
toJSON AzureBlobStorageData'{..}
= object
(catMaybes
[("path" .=) <$> _absdPath,
("azureCredentials" .=) <$> _absdAzureCredentials,
("container" .=) <$> _absdContainer,
("storageAccount" .=) <$> _absdStorageAccount])
-- | TransferOptions define the actions to be performed on objects in a
-- transfer.
--
-- /See:/ 'transferOptions' smart constructor.
data TransferOptions =
TransferOptions'
{ _toDeleteObjectsUniqueInSink :: !(Maybe Bool)
, _toDeleteObjectsFromSourceAfterTransfer :: !(Maybe Bool)
, _toOverwriteObjectsAlreadyExistingInSink :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TransferOptions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'toDeleteObjectsUniqueInSink'
--
-- * 'toDeleteObjectsFromSourceAfterTransfer'
--
-- * 'toOverwriteObjectsAlreadyExistingInSink'
transferOptions
:: TransferOptions
transferOptions =
TransferOptions'
{ _toDeleteObjectsUniqueInSink = Nothing
, _toDeleteObjectsFromSourceAfterTransfer = Nothing
, _toOverwriteObjectsAlreadyExistingInSink = Nothing
}
-- | Whether objects that exist only in the sink should be deleted. **Note:**
-- This option and delete_objects_from_source_after_transfer are mutually
-- exclusive.
toDeleteObjectsUniqueInSink :: Lens' TransferOptions (Maybe Bool)
toDeleteObjectsUniqueInSink
= lens _toDeleteObjectsUniqueInSink
(\ s a -> s{_toDeleteObjectsUniqueInSink = a})
-- | Whether objects should be deleted from the source after they are
-- transferred to the sink. **Note:** This option and
-- delete_objects_unique_in_sink are mutually exclusive.
toDeleteObjectsFromSourceAfterTransfer :: Lens' TransferOptions (Maybe Bool)
toDeleteObjectsFromSourceAfterTransfer
= lens _toDeleteObjectsFromSourceAfterTransfer
(\ s a ->
s{_toDeleteObjectsFromSourceAfterTransfer = a})
-- | When to overwrite objects that already exist in the sink. The default is
-- that only objects that are different from the source are ovewritten. If
-- true, all objects in the sink whose name matches an object in the source
-- are overwritten with the source object.
toOverwriteObjectsAlreadyExistingInSink :: Lens' TransferOptions (Maybe Bool)
toOverwriteObjectsAlreadyExistingInSink
= lens _toOverwriteObjectsAlreadyExistingInSink
(\ s a ->
s{_toOverwriteObjectsAlreadyExistingInSink = a})
instance FromJSON TransferOptions where
parseJSON
= withObject "TransferOptions"
(\ o ->
TransferOptions' <$>
(o .:? "deleteObjectsUniqueInSink") <*>
(o .:? "deleteObjectsFromSourceAfterTransfer")
<*> (o .:? "overwriteObjectsAlreadyExistingInSink"))
instance ToJSON TransferOptions where
toJSON TransferOptions'{..}
= object
(catMaybes
[("deleteObjectsUniqueInSink" .=) <$>
_toDeleteObjectsUniqueInSink,
("deleteObjectsFromSourceAfterTransfer" .=) <$>
_toDeleteObjectsFromSourceAfterTransfer,
("overwriteObjectsAlreadyExistingInSink" .=) <$>
_toOverwriteObjectsAlreadyExistingInSink])
-- | A description of the execution of a transfer.
--
-- /See:/ 'transferOperation' smart constructor.
data TransferOperation =
TransferOperation'
{ _toStatus :: !(Maybe TransferOperationStatus)
, _toCounters :: !(Maybe TransferCounters)
, _toNotificationConfig :: !(Maybe NotificationConfig)
, _toStartTime :: !(Maybe DateTime')
, _toTransferJobName :: !(Maybe Text)
, _toName :: !(Maybe Text)
, _toEndTime :: !(Maybe DateTime')
, _toProjectId :: !(Maybe Text)
, _toTransferSpec :: !(Maybe TransferSpec)
, _toErrorBreakdowns :: !(Maybe [ErrorSummary])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TransferOperation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'toStatus'
--
-- * 'toCounters'
--
-- * 'toNotificationConfig'
--
-- * 'toStartTime'
--
-- * 'toTransferJobName'
--
-- * 'toName'
--
-- * 'toEndTime'
--
-- * 'toProjectId'
--
-- * 'toTransferSpec'
--
-- * 'toErrorBreakdowns'
transferOperation
:: TransferOperation
transferOperation =
TransferOperation'
{ _toStatus = Nothing
, _toCounters = Nothing
, _toNotificationConfig = Nothing
, _toStartTime = Nothing
, _toTransferJobName = Nothing
, _toName = Nothing
, _toEndTime = Nothing
, _toProjectId = Nothing
, _toTransferSpec = Nothing
, _toErrorBreakdowns = Nothing
}
-- | Status of the transfer operation.
toStatus :: Lens' TransferOperation (Maybe TransferOperationStatus)
toStatus = lens _toStatus (\ s a -> s{_toStatus = a})
-- | Information about the progress of the transfer operation.
toCounters :: Lens' TransferOperation (Maybe TransferCounters)
toCounters
= lens _toCounters (\ s a -> s{_toCounters = a})
-- | Notification configuration.
toNotificationConfig :: Lens' TransferOperation (Maybe NotificationConfig)
toNotificationConfig
= lens _toNotificationConfig
(\ s a -> s{_toNotificationConfig = a})
-- | Start time of this transfer execution.
toStartTime :: Lens' TransferOperation (Maybe UTCTime)
toStartTime
= lens _toStartTime (\ s a -> s{_toStartTime = a}) .
mapping _DateTime
-- | The name of the transfer job that triggers this transfer operation.
toTransferJobName :: Lens' TransferOperation (Maybe Text)
toTransferJobName
= lens _toTransferJobName
(\ s a -> s{_toTransferJobName = a})
-- | A globally unique ID assigned by the system.
toName :: Lens' TransferOperation (Maybe Text)
toName = lens _toName (\ s a -> s{_toName = a})
-- | End time of this transfer execution.
toEndTime :: Lens' TransferOperation (Maybe UTCTime)
toEndTime
= lens _toEndTime (\ s a -> s{_toEndTime = a}) .
mapping _DateTime
-- | The ID of the Google Cloud Platform Project that owns the operation.
toProjectId :: Lens' TransferOperation (Maybe Text)
toProjectId
= lens _toProjectId (\ s a -> s{_toProjectId = a})
-- | Transfer specification.
toTransferSpec :: Lens' TransferOperation (Maybe TransferSpec)
toTransferSpec
= lens _toTransferSpec
(\ s a -> s{_toTransferSpec = a})
-- | Summarizes errors encountered with sample error log entries.
toErrorBreakdowns :: Lens' TransferOperation [ErrorSummary]
toErrorBreakdowns
= lens _toErrorBreakdowns
(\ s a -> s{_toErrorBreakdowns = a})
. _Default
. _Coerce
instance FromJSON TransferOperation where
parseJSON
= withObject "TransferOperation"
(\ o ->
TransferOperation' <$>
(o .:? "status") <*> (o .:? "counters") <*>
(o .:? "notificationConfig")
<*> (o .:? "startTime")
<*> (o .:? "transferJobName")
<*> (o .:? "name")
<*> (o .:? "endTime")
<*> (o .:? "projectId")
<*> (o .:? "transferSpec")
<*> (o .:? "errorBreakdowns" .!= mempty))
instance ToJSON TransferOperation where
toJSON TransferOperation'{..}
= object
(catMaybes
[("status" .=) <$> _toStatus,
("counters" .=) <$> _toCounters,
("notificationConfig" .=) <$> _toNotificationConfig,
("startTime" .=) <$> _toStartTime,
("transferJobName" .=) <$> _toTransferJobName,
("name" .=) <$> _toName,
("endTime" .=) <$> _toEndTime,
("projectId" .=) <$> _toProjectId,
("transferSpec" .=) <$> _toTransferSpec,
("errorBreakdowns" .=) <$> _toErrorBreakdowns])
-- | Configuration for running a transfer.
--
-- /See:/ 'transferSpec' smart constructor.
data TransferSpec =
TransferSpec'
{ _tsGcsDataSource :: !(Maybe GcsData)
, _tsObjectConditions :: !(Maybe ObjectConditions)
, _tsHTTPDataSource :: !(Maybe HTTPData)
, _tsAwsS3DataSource :: !(Maybe AwsS3Data)
, _tsGcsDataSink :: !(Maybe GcsData)
, _tsTransferOptions :: !(Maybe TransferOptions)
, _tsAzureBlobStorageDataSource :: !(Maybe AzureBlobStorageData)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TransferSpec' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tsGcsDataSource'
--
-- * 'tsObjectConditions'
--
-- * 'tsHTTPDataSource'
--
-- * 'tsAwsS3DataSource'
--
-- * 'tsGcsDataSink'
--
-- * 'tsTransferOptions'
--
-- * 'tsAzureBlobStorageDataSource'
transferSpec
:: TransferSpec
transferSpec =
TransferSpec'
{ _tsGcsDataSource = Nothing
, _tsObjectConditions = Nothing
, _tsHTTPDataSource = Nothing
, _tsAwsS3DataSource = Nothing
, _tsGcsDataSink = Nothing
, _tsTransferOptions = Nothing
, _tsAzureBlobStorageDataSource = Nothing
}
-- | A Cloud Storage data source.
tsGcsDataSource :: Lens' TransferSpec (Maybe GcsData)
tsGcsDataSource
= lens _tsGcsDataSource
(\ s a -> s{_tsGcsDataSource = a})
-- | Only objects that satisfy these object conditions are included in the
-- set of data source and data sink objects. Object conditions based on
-- objects\' \"last modification time\" do not exclude objects in a data
-- sink.
tsObjectConditions :: Lens' TransferSpec (Maybe ObjectConditions)
tsObjectConditions
= lens _tsObjectConditions
(\ s a -> s{_tsObjectConditions = a})
-- | An HTTP URL data source.
tsHTTPDataSource :: Lens' TransferSpec (Maybe HTTPData)
tsHTTPDataSource
= lens _tsHTTPDataSource
(\ s a -> s{_tsHTTPDataSource = a})
-- | An AWS S3 data source.
tsAwsS3DataSource :: Lens' TransferSpec (Maybe AwsS3Data)
tsAwsS3DataSource
= lens _tsAwsS3DataSource
(\ s a -> s{_tsAwsS3DataSource = a})
-- | A Cloud Storage data sink.
tsGcsDataSink :: Lens' TransferSpec (Maybe GcsData)
tsGcsDataSink
= lens _tsGcsDataSink
(\ s a -> s{_tsGcsDataSink = a})
-- | If the option delete_objects_unique_in_sink is \`true\` and time-based
-- object conditions such as \'last modification time\' are specified, the
-- request fails with an INVALID_ARGUMENT error.
tsTransferOptions :: Lens' TransferSpec (Maybe TransferOptions)
tsTransferOptions
= lens _tsTransferOptions
(\ s a -> s{_tsTransferOptions = a})
-- | An Azure Blob Storage data source.
tsAzureBlobStorageDataSource :: Lens' TransferSpec (Maybe AzureBlobStorageData)
tsAzureBlobStorageDataSource
= lens _tsAzureBlobStorageDataSource
(\ s a -> s{_tsAzureBlobStorageDataSource = a})
instance FromJSON TransferSpec where
parseJSON
= withObject "TransferSpec"
(\ o ->
TransferSpec' <$>
(o .:? "gcsDataSource") <*>
(o .:? "objectConditions")
<*> (o .:? "httpDataSource")
<*> (o .:? "awsS3DataSource")
<*> (o .:? "gcsDataSink")
<*> (o .:? "transferOptions")
<*> (o .:? "azureBlobStorageDataSource"))
instance ToJSON TransferSpec where
toJSON TransferSpec'{..}
= object
(catMaybes
[("gcsDataSource" .=) <$> _tsGcsDataSource,
("objectConditions" .=) <$> _tsObjectConditions,
("httpDataSource" .=) <$> _tsHTTPDataSource,
("awsS3DataSource" .=) <$> _tsAwsS3DataSource,
("gcsDataSink" .=) <$> _tsGcsDataSink,
("transferOptions" .=) <$> _tsTransferOptions,
("azureBlobStorageDataSource" .=) <$>
_tsAzureBlobStorageDataSource])
-- | Response from ListTransferJobs.
--
-- /See:/ 'listTransferJobsResponse' smart constructor.
data ListTransferJobsResponse =
ListTransferJobsResponse'
{ _ltjrNextPageToken :: !(Maybe Text)
, _ltjrTransferJobs :: !(Maybe [TransferJob])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListTransferJobsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltjrNextPageToken'
--
-- * 'ltjrTransferJobs'
listTransferJobsResponse
:: ListTransferJobsResponse
listTransferJobsResponse =
ListTransferJobsResponse'
{_ltjrNextPageToken = Nothing, _ltjrTransferJobs = Nothing}
-- | The list next page token.
ltjrNextPageToken :: Lens' ListTransferJobsResponse (Maybe Text)
ltjrNextPageToken
= lens _ltjrNextPageToken
(\ s a -> s{_ltjrNextPageToken = a})
-- | A list of transfer jobs.
ltjrTransferJobs :: Lens' ListTransferJobsResponse [TransferJob]
ltjrTransferJobs
= lens _ltjrTransferJobs
(\ s a -> s{_ltjrTransferJobs = a})
. _Default
. _Coerce
instance FromJSON ListTransferJobsResponse where
parseJSON
= withObject "ListTransferJobsResponse"
(\ o ->
ListTransferJobsResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "transferJobs" .!= mempty))
instance ToJSON ListTransferJobsResponse where
toJSON ListTransferJobsResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _ltjrNextPageToken,
("transferJobs" .=) <$> _ltjrTransferJobs])
-- | The normal response of the operation in case of success. If the original
-- method returns no data on success, such as \`Delete\`, the response is
-- \`google.protobuf.Empty\`. If the original method is standard
-- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource.
-- For other methods, the response should have the type \`XxxResponse\`,
-- where \`Xxx\` is the original method name. For example, if the original
-- method name is \`TakeSnapshot()\`, the inferred response type is
-- \`TakeSnapshotResponse\`.
--
-- /See:/ 'operationResponse' smart constructor.
newtype OperationResponse =
OperationResponse'
{ _orAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'orAddtional'
operationResponse
:: HashMap Text JSONValue -- ^ 'orAddtional'
-> OperationResponse
operationResponse pOrAddtional_ =
OperationResponse' {_orAddtional = _Coerce # pOrAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
orAddtional :: Lens' OperationResponse (HashMap Text JSONValue)
orAddtional
= lens _orAddtional (\ s a -> s{_orAddtional = a}) .
_Coerce
instance FromJSON OperationResponse where
parseJSON
= withObject "OperationResponse"
(\ o -> OperationResponse' <$> (parseJSONObject o))
instance ToJSON OperationResponse where
toJSON = toJSON . _orAddtional
-- | Request passed to ResumeTransferOperation.
--
-- /See:/ 'resumeTransferOperationRequest' smart constructor.
data ResumeTransferOperationRequest =
ResumeTransferOperationRequest'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ResumeTransferOperationRequest' with the minimum fields required to make a request.
--
resumeTransferOperationRequest
:: ResumeTransferOperationRequest
resumeTransferOperationRequest = ResumeTransferOperationRequest'
instance FromJSON ResumeTransferOperationRequest
where
parseJSON
= withObject "ResumeTransferOperationRequest"
(\ o -> pure ResumeTransferOperationRequest')
instance ToJSON ResumeTransferOperationRequest where
toJSON = const emptyObject
-- | AWS access key (see [AWS Security
-- Credentials](https:\/\/docs.aws.amazon.com\/general\/latest\/gr\/aws-security-credentials.html)).
-- For information on our data retention policy for user credentials, see
-- [User
-- credentials](\/storage-transfer\/docs\/data-retention#user-credentials).
--
-- /See:/ 'awsAccessKey' smart constructor.
data AwsAccessKey =
AwsAccessKey'
{ _aakSecretAccessKey :: !(Maybe Text)
, _aakAccessKeyId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AwsAccessKey' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aakSecretAccessKey'
--
-- * 'aakAccessKeyId'
awsAccessKey
:: AwsAccessKey
awsAccessKey =
AwsAccessKey' {_aakSecretAccessKey = Nothing, _aakAccessKeyId = Nothing}
-- | Required. AWS secret access key. This field is not returned in RPC
-- responses.
aakSecretAccessKey :: Lens' AwsAccessKey (Maybe Text)
aakSecretAccessKey
= lens _aakSecretAccessKey
(\ s a -> s{_aakSecretAccessKey = a})
-- | Required. AWS access key ID.
aakAccessKeyId :: Lens' AwsAccessKey (Maybe Text)
aakAccessKeyId
= lens _aakAccessKeyId
(\ s a -> s{_aakAccessKeyId = a})
instance FromJSON AwsAccessKey where
parseJSON
= withObject "AwsAccessKey"
(\ o ->
AwsAccessKey' <$>
(o .:? "secretAccessKey") <*> (o .:? "accessKeyId"))
instance ToJSON AwsAccessKey where
toJSON AwsAccessKey'{..}
= object
(catMaybes
[("secretAccessKey" .=) <$> _aakSecretAccessKey,
("accessKeyId" .=) <$> _aakAccessKeyId])
|
brendanhay/gogol
|
gogol-storage-transfer/gen/Network/Google/StorageTransfer/Types/Product.hs
|
mpl-2.0
| 88,646 | 0 | 26 | 19,772 | 13,652 | 7,907 | 5,745 | 1,537 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE KindSignatures #-}
module Spark.MapRDDIO
(
-- * Map RDD
MapRDDIO (),
mapRDDIO,
-- * Remote Table
__remoteTable
)
where
import Spark.Context
import Spark.RDD
import Spark.SeedRDD hiding (__remoteTable)
import Spark.Block
import Control.Distributed.Process
import Control.Distributed.Process.Closure
import Control.Distributed.Static
import Control.Distributed.Process.Serializable
import qualified Data.Map as M
import Data.Typeable
import GHC.Generics
import Data.Binary
import Control.Monad
-- | RDD representing a pure map between a base with a function
data MapRDDIO a b c = MapRDDIO { _baseM :: a b
, _cFunM :: Closure (b -> IO c)
, _tdict :: Static (SerializableDict [c])
}
-- | Create map RDD from a function closure and base RDD
mapRDDIO :: (RDD a b, Serializable c) =>
Context
-> a b
-> Static (SerializableDict [c])
-> Closure (b -> IO c)
-> MapRDDIO a b c
mapRDDIO sc base dict action = MapRDDIO { _baseM = base, _cFunM = action, _tdict = dict }
rddIOMap :: SerializableDict [a]
-> SerializableDict [b]
-> (Int, ProcessId)
-> (a -> IO b)
-> Process ()
rddIOMap dictA dictB (i, pid) f = do
thispid <- getSelfPid
sendFetch dictA pid (Fetch thispid)
dt <- receiveWait [ matchSeed dictA $ \xs -> return (Just xs)
, match $ \() -> return Nothing
]
case dt of
Just ys -> do
xs <- liftIO $ mapM f ys
receiveWait [ matchFetch dictB $ \(Fetch sender) -> sendSeed dictB sender xs
, match $ \() -> return ()
]
Nothing -> return ()
partitionIOPair :: SerializableDict (Int, ProcessId)
partitionIOPair = SerializableDict
remotable [ 'rddIOMap, 'partitionIOPair ]
rddIOMapClosure :: (Serializable a, Serializable b) =>
Static (SerializableDict [a])
-> Static (SerializableDict [b])
-> (Int, ProcessId)
-> Closure (a -> IO b)
-> Closure (Process ())
rddIOMapClosure dictA dictB partition cfun =
closure decoder (encode partition) `closureApply` cfun
where
decoder = ( $(mkStatic 'rddIOMap) `staticApply` dictA `staticApply` dictB )
`staticCompose`
staticDecode $(mkStatic 'partitionIOPair)
instance (RDD a b, Serializable c) => RDD (MapRDDIO a b) c where
exec sc mr = undefined
rddDictS mr = _tdict mr
rddDict _ = SerializableDict
flow sc (MapRDDIO base cfun tdict) = do
-- Get the process IDs of the base process
(Blocks pmap) <- flow sc base
say "MapRDDIO : Map IO Stage"
-- For each process, try to spawn process on the same node.
mpids <- forM (M.toList pmap) $ \(i, pid) -> do
(Just pi) <- getProcessInfo pid
spawn (infoNode pi) (rddIOMapClosure (rddDictS base) tdict (i, pid) cfun )
-- close the process
-- mapM_ (\pid -> send pid () ) pmap
return $ Blocks $ M.fromList (zip [0..] mpids)
|
yogeshsajanikar/hspark
|
src/Spark/MapRDDIO.hs
|
apache-2.0
| 3,371 | 0 | 17 | 1,070 | 945 | 502 | 443 | 77 | 2 |
module Miscellaneous.A261863Spec (main, spec) where
import Test.Hspec
import Miscellaneous.A261863 (a261863)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A261863" $
it "correctly computes the first 20 elements" $
take 20 (map a261863 [1..]) `shouldBe` expectedValue where
expectedValue = [1,2,3,4,5,12,7,13,9,16,11,29,11,23,19,22,13,36,17,40]
|
peterokagey/haskellOEIS
|
test/Miscellaneous/A261863Spec.hs
|
apache-2.0
| 374 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
{-# LANGUAGE
NoImplicitPrelude,
FlexibleContexts,
NoMonomorphismRestriction,
FlexibleInstances,
MultiParamTypeClasses
#-}
module DDF.IO (module DDF.IO, module DDF.List, module DDF.Char, module DDF.Unit) where
import DDF.List
import DDF.Char
import DDF.Unit
import qualified Prelude as M
string [] = nil
string (c:str) = cons2 (char c) (string str)
class (List r, Unit r, Char r) => IO r where
putStrLn :: r h (String -> M.IO ())
ioMap :: r h ((a -> b) -> M.IO a -> M.IO b)
ioPure :: r h (a -> M.IO a)
ioAP :: r h (M.IO (a -> b) -> M.IO a -> M.IO b)
ioBind :: r h (M.IO a -> (a -> M.IO b) -> M.IO b)
ioBind = lam2 $ \m f -> join1 (map2 f m)
ioJoin :: r h (M.IO (M.IO a) -> M.IO a)
ioJoin = lam $ \m -> bind2 m id
{-# MINIMAL putStrLn, ioMap, ioPure, ioAP, (ioBind | ioJoin) #-}
instance IO r => Functor r M.IO where
map = ioMap
instance IO r => Applicative r M.IO where
pure = ioPure
ap = ioAP
instance IO r => Monad r M.IO where
join = ioJoin
bind = ioBind
putStrLn1 = app putStrLn
|
ThoughtWorksInc/DeepDarkFantasy
|
DDF/IO.hs
|
apache-2.0
| 1,029 | 0 | 14 | 240 | 468 | 244 | 224 | 32 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Marvin.API.Table.ParseSpec where
import Test.Hspec
import Marvin.API as Marvin
import Marvin.API.Table.Parse
spec :: Spec
spec = do
readDesc
parseDesc
readDesc =
describe "reading" $ do
it "handles empty" $
bsToRawTable "" ',' NoHeader `shouldSatisfy` \x -> case x of
Left (ReadError _) -> True
_ -> False
it "handles new lines" $
bsToRawTable "\n\n\n\n" ',' NoHeader `shouldSatisfy` \x -> case x of
Left (ReadError _) -> True
_ -> False
it "handles new lines with header" $
bsToRawTable "\n\n\n\n" ',' HasHeader `shouldSatisfy` \x -> case x of
Left (ReadError _) -> True
_ -> False
it "handles row length mismatch" $
bsToRawTable "1,2,3\n2,3\n1,2,3" ',' NoHeader `shouldSatisfy` \x -> case x of
Left (RowLengthMismatch _) -> True
_ -> False
parseDesc =
describe "parsing" $ do
it "with scheme" $
(fromRowsToRaw [["1.2", "1", "0"], ["3", "x", "1"]]
>>= parseWithScheme [Numeric, Nominal, Binary]) `shouldBe`
(sequence [
asDataColumn <$> fromList [1.2 :: Double, 3],
asDataColumn <$> fromList ["1" :: String, "x"],
asDataColumn <$> fromList [False, True]] >>= fromColumns)
it "with scheme fails on wrong types" $
(fromRowsToRaw [["1.2", "1", "0"], ["3", "x", "1"]]
>>= parseWithScheme [Natural, Nominal, Binary]) `shouldSatisfy` \x -> case x of
Left CannotParseColumn -> True
_ -> False
it "smart parsing binary" $
smartParseColumn <$> fromListToRaw ["0","1","1"]
`shouldBe` asDataColumn <$> fromList [False,True,True]
it "smart parsing natural" $
smartParseColumn <$> fromListToRaw ["0","2","1"]
`shouldBe` asDataColumn <$> (fromList [0,2,1] :: Fallible NaturalColumn)
it "smart parsing numeric" $
smartParseColumn <$> fromListToRaw ["0","1.1","1"]
`shouldBe` asDataColumn <$> (fromList [0,1.1,1] :: Fallible NumericColumn)
it "smart parsing nominal" $
smartParseColumn <$> fromListToRaw ["0","1","x"]
`shouldBe` asDataColumn <$> (fromList ["0","1","x"] :: Fallible NominalColumn)
|
gaborhermann/marvin
|
test-suite/Marvin/API/Table/ParseSpec.hs
|
apache-2.0
| 2,215 | 0 | 15 | 559 | 711 | 383 | 328 | 53 | 5 |
import Prelude
import System.Random
-- when selecting a generator, choose newStdGen instead of genStdGen in order
-- for the generator to be initialized with a different seed every time
randomSelect :: [a] -> Int -> IO [a]
randomSelect [] _ = return []
randomSelect xs n
| n < 0 = error "n must be non-negative."
| otherwise = do
gen <- newStdGen
return (take n [ xs !! indx | indx <- randomRs (0, (length xs) - 1) gen])
|
2dor/99-problems-Haskell
|
21-28-lists-again/problem-23.hs
|
bsd-2-clause
| 446 | 0 | 18 | 105 | 139 | 69 | 70 | 9 | 1 |
{-# LANGUAGE TypeFamilies, KindSignatures, MultiParamTypeClasses, DataKinds, FlexibleContexts, GADTs, TypeOperators, PolyKinds, UndecidableInstances, FlexibleInstances, DefaultSignatures, ScopedTypeVariables, ConstraintKinds, TemplateHaskell, OverloadedStrings, DeriveGeneric #-}
module Main where
import qualified Network.Wai as Wai
import WebApi
import WebApi.Internal
import GHC.Generics
import Data.Int
import Data.Word
import Data.Text (Text)
import Data.ByteString (ByteString)
import Data.Time.Calendar (Day)
import Data.Vector (Vector)
import Data.Time.Clock (UTCTime)
import Network.Wai.Handler.Warp (run)
import Network.HTTP.Types
import Network.Wai.Test (defaultRequest, request,
runSession, simpleBody)
import Test.Hspec
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Wai ( get, liftIO, matchHeaders,
matchStatus, post, request,
shouldRespondWith, with, (<:>))
import Test.QuickCheck
import WebApi.RouteSpec
import WebApi.RequestSpec
import WebApi.ResponseSpec
data FourSquare = FourSquare
data FourSquareImpl = FourSquareImpl
type UserPhotos = "users":/Int:/"photos":/Int
type UserCheckins = "users":/Int:/"checkins"
type StaticT = Static ""
instance WebApiImplementation FourSquareImpl where
type HandlerM FourSquareImpl = IO
type ApiInterface FourSquareImpl = FourSquare
instance ApiContract FourSquare GET UserPhotos where
type ApiOut GET UserPhotos = ()
instance ApiContract FourSquare POST UserPhotos where
type ApiOut POST UserPhotos = ()
instance ApiContract FourSquare GET UserCheckins where
type ApiOut GET UserCheckins = ()
data QP1 = QP1
{ query :: Int
, key :: Int
} deriving (Show)
{-
instance ToParam Int par => ToParam QP1 par where
toParam pt pfx (QP1 q k) = concat [ toParam pt (pfx `nest` "query") q
, toParam pt (pfx `nest` "key") k
]
-}
instance (FromParam Int par) => FromParam QP1 par where
fromParam pt pfx kvs = QP1 <$> (fromParam pt (pfx `nest` "query") kvs)
<*> (fromParam pt (pfx `nest` "key") kvs)
instance ApiContract FourSquare GET StaticT where
type QueryParam GET StaticT = QP1
type ApiOut GET StaticT = ()
instance WebApi FourSquare where
type Version FourSquare = MajorMinor '(0, 1)
type Apis FourSquare = '[ Route GET UserPhotos
, Route POST UserPhotos
, Route GET UserCheckins
, Route GET StaticT
]
instance ApiHandler FourSquareImpl GET UserPhotos where
handler _ _ req = print (pathParam req) >> respond ()
instance ApiHandler FourSquareImpl POST UserPhotos where
handler _ _ = error "@ POST UserPhotos"
instance ApiHandler FourSquareImpl GET UserCheckins where
handler _ _ _req = putStrLn "@UserCheckings" >> respond ()
instance ApiHandler FourSquareImpl GET StaticT where
handler _ _ req = print (queryParam req) >> respond ()
test :: Wai.Application
test = serverApp serverSettings FourSquareImpl
spec1 :: Spec
spec1 = do
with (return test) $ do
it "should be 200 ok" $ do
get "?key=1&query=2" `shouldRespondWith` 200
it "should be 200 ok" $ do
get "users/10/checkins" `shouldRespondWith` 200
it "should be 200 ok" $ do
get "users/10/photos/1" `shouldRespondWith` 200
data U = U | V
deriving (Show, Eq, Generic)
data Foo = Foo { bar :: Bool, baz :: Char }
deriving (Show, Generic, Eq)
data Bar = Bar1 { barr :: Foo, other :: Either Int Bool }
| Bar2 { barr :: Foo, otherOne :: Int }
deriving (Show, Generic, Eq)
data Zap = Zap { zap :: Foo, paz :: Bar , nullary :: U}
deriving (Show, Generic, Eq)
data PrimTys = PrimTys { pInt :: Int
, pInt8 :: Int8
, pInt16 :: Int16
, pInt32 :: Int32
, pInt64 :: Int64
, pInteger :: Integer
, pWord :: Word
, pWord8 :: Word8
, pWord16 :: Word16
, pWord32 :: Word32
, pWord64 :: Word64
--, pFloat :: Float
--, pDouble :: Double
, pChar :: Char
, pText :: Text
--, pDay :: Day
--, pUTCTime :: UTCTime
, pBool :: Bool
, pEither :: Either Int Bool
, pMaybe :: Maybe Bool
, pList :: [Char]
--, pVector :: Vector Text
--, pByteString :: ByteString
} deriving (Generic, Show, Eq)
instance Arbitrary PrimTys where
arbitrary = PrimTys <$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
-- <*> arbitrary
-- <*> arbitrary
<*> arbitrary
<*> elements ["foo", "Ελλάδα", "français"]
-- <*> elements [
-- <*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
-- <*> arbitrary
-- <*> arbitrary
instance ToParam PrimTys 'QueryParam where
instance ToParam PrimTys 'FormParam where
instance FromParam PrimTys 'QueryParam where
instance FromParam PrimTys 'FormParam where
instance ToParam U 'QueryParam where
instance ToParam U 'FormParam where
instance FromParam U 'QueryParam where
instance FromParam U 'FormParam where
instance ToParam Foo 'QueryParam where
instance ToParam Foo 'FormParam where
instance FromParam Foo 'QueryParam where
instance FromParam Foo 'FormParam where
instance ToParam Bar 'QueryParam where
instance ToParam Bar 'FormParam where
instance FromParam Bar 'QueryParam where
instance FromParam Bar 'FormParam where
instance ToParam Zap 'QueryParam where
instance ToParam Zap 'FormParam where
instance FromParam Zap 'QueryParam where
instance FromParam Zap 'FormParam where
propParamsPrimSpec :: Spec
propParamsPrimSpec = do
describe "Params for prims : QueryParams" $ do
it "works for all prims" $ do
property $ \v -> fromQueryParam (toQueryParam v) == Validation (Right (v :: PrimTys))
paramsGenericSpec :: Spec
paramsGenericSpec = do
describe "Generic derivation for params QueryParams" $ do
it "works for unit type" $ do
let v = U
fromQueryParam (toQueryParam v) `shouldBe` (Validation (Right v))
it "works for product types" $ do
let v = Foo True 'c'
fromQueryParam (toQueryParam v) `shouldBe` (Validation (Right v))
it "works for sum types 1" $ do
let v = Bar1 (Foo False 'd') (Left 8)
fromQueryParam (toQueryParam v) `shouldBe` (Validation (Right v))
it "works for sum types 2" $ do
let v = Bar2 (Foo False 'd') 7
fromQueryParam (toQueryParam v) `shouldBe` (Validation (Right v))
it "works for a complex type" $ do
let v = Zap (Foo False 'f') (Bar2 (Foo False 'f') 7) U
fromQueryParam (toQueryParam v) `shouldBe` (Validation (Right v))
describe "Generic derivation for params FormParams" $ do
it "works for unit type" $ do
let v = U
fromFormParam (toFormParam v) `shouldBe` (Validation (Right v))
it "works for product types" $ do
let v = Foo False 'f'
fromFormParam (toFormParam v) `shouldBe` (Validation (Right v))
it "works for sum types 1" $ do
let v = Bar1 (Foo False 'f') (Right True)
fromFormParam (toFormParam v) `shouldBe` (Validation (Right v))
it "works for sum types 2" $ do
let v = Bar2 (Foo False 'f') 7
fromFormParam (toFormParam v) `shouldBe` (Validation (Right v))
it "works for a complex type" $ do
let v = Zap (Foo False 'f') (Bar2 (Foo False 'f') 7) U
fromFormParam (toFormParam v) `shouldBe` (Validation (Right v))
main :: IO ()
main = do
-- run 8000 app
hspec spec1
-- hspec paramsGenericSpec
-- hspec propParamsPrimSpec
-- hspec routeSpec
-- hspec reqSpec
hspec respSpec
-- return ()
|
byteally/webapi
|
webapi/tests/main.hs
|
bsd-3-clause
| 8,760 | 0 | 22 | 2,869 | 2,234 | 1,175 | 1,059 | 183 | 1 |
module Main where
import System.Environment (getProgName)
import qualified Kiwi.API as API
import qualified Kiwi.Config as Config
import qualified Kiwi.Generate as Generate
import qualified Kiwi.Server as Server
import qualified Kiwi.ServerAndAPI as ServerAndAPI
import Kiwi.Data
import qualified Kiwi.Storage as Storage
import qualified Data.Text as T
main :: IO ()
main = do
Storage.createTablesIfNecessary
target <- Config.target
case target of
Config.API -> API.main
Config.Server -> Server.main
Config.ServerAndAPI -> ServerAndAPI.main
Config.Generate -> Generate.main
|
acieroid/kiwi
|
Main.hs
|
bsd-3-clause
| 599 | 0 | 10 | 94 | 151 | 91 | 60 | 19 | 4 |
-- |Generate Haskell source files for ROS .msg types.
{-# LANGUAGE OverloadedStrings #-}
module Gen (generateMsgType, generateSrvTypes) where
import Control.Applicative ((<$>), (<*>))
import Data.ByteString.Char8 (pack, ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Char (toUpper)
import Analysis (MsgInfo, SerialInfo(..), withMsg, getTypeInfo)
import Types
import FieldImports
import Instances.Binary
import Instances.Storable
import MD5
data GenArgs = GenArgs {genExtraImport :: ByteString
, genPkgPath :: ByteString
, genPkgMsgs :: [ByteString]}
-- | pkgMsgs is a list of all the Mesages defined in the package (can be refered to
-- | with unqualified names)
generateSrvTypes :: ByteString -> [ByteString] -> Srv -> MsgInfo (ByteString, ByteString)
generateSrvTypes pkgPath pkgMsgs srv = do
let msgs = [srvRequest srv, srvResponse srv]
srvInfo <- mapM (genSrvInfo srv) msgs
requestResponseMsgs <-
mapM (generateMsgTypeExtraImport GenArgs{genExtraImport = "import Ros.Internal.Msg.SrvInfo\n"
, genPkgPath=pkgPath
, genPkgMsgs=pkgMsgs})
msgs
let [requestType, responseType] = zipWith B.append requestResponseMsgs srvInfo
return (requestType, responseType)
generateMsgType :: ByteString -> [ByteString] -> Msg -> MsgInfo ByteString
generateMsgType pkgPath pkgMsgs =
generateMsgTypeExtraImport GenArgs {genExtraImport=""
, genPkgPath=pkgPath
, genPkgMsgs=pkgMsgs}
generateMsgTypeExtraImport :: GenArgs -> Msg -> MsgInfo ByteString
generateMsgTypeExtraImport (GenArgs {genExtraImport=extraImport, genPkgPath=pkgPath, genPkgMsgs=pkgMsgs}) msg =
do (fDecls, binInst, st, cons) <- withMsg msg $
(,,,) <$> mapM generateField (fields msg)
<*> genBinaryInstance msg
<*> genStorableInstance msg
<*> genConstants msg
let fieldSpecs = B.intercalate lineSep fDecls
(storableImport, storableInstance) = st
--msgHash <- liftIO $ genHasHash msg
msgHash <- genHasHash msg
return $ B.concat [ modLine, "\n"
, imports
, storableImport
, if null fDecls
then dataSingleton
else B.concat [ dataLine
, fieldSpecs
, "\n"
, fieldIndent
, "} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)\n\n"]
, binInst, "\n\n"
, storableInstance
--, genNFDataInstance msg
, genHasHeader msg
, msgHash
, genDefault msg
, cons ]
where name = shortName msg
tName = pack $ toUpper (head name) : tail name
modLine = B.concat ["{-# LANGUAGE OverloadedStrings, DeriveDataTypeable, DeriveGeneric #-}\n",
"module ", pkgPath, tName, " where"]
imports = B.concat ["import qualified Prelude as P\n",
"import Prelude ((.), (+), (*))\n",
"import qualified Data.Typeable as T\n",
"import Control.Applicative\n",
"import Ros.Internal.RosBinary\n",
"import Ros.Internal.Msg.MsgInfo\n",
"import qualified GHC.Generics as G\n",
"import qualified Data.Default.Generics as D\n",
extraImport,
genImports pkgPath pkgMsgs
(map fieldType (fields msg))]
--nfImport]
dataLine = B.concat ["\ndata ", tName, " = ", tName, " { "]
dataSingleton = B.concat ["\ndata ", tName, " = ", tName,
" deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)\n\n"]
fieldIndent = B.replicate (B.length dataLine - 3) ' '
lineSep = B.concat ["\n", fieldIndent, ", "]
genHasHeader :: Msg -> ByteString
genHasHeader m =
if hasHeader m
then let hn = fieldName (head (fields m)) -- The header field name
in B.concat ["instance HasHeader ", pack (shortName m), " where\n",
" getSequence = Header.seq . ", hn, "\n",
" getFrame = Header.frame_id . ", hn, "\n",
" getStamp = Header.stamp . " , hn, "\n",
" setSequence seq x' = x' { ", hn,
" = (", hn, " x') { Header.seq = seq } }\n\n"]
else ""
genDefault :: Msg -> ByteString
genDefault m = B.concat["instance D.Default ", pack (shortName m), "\n\n"]
genHasHash :: Msg -> MsgInfo ByteString
genHasHash m = fmap aux (msgMD5 m)
where aux md5 = B.concat ["instance MsgInfo ", pack (shortName m),
" where\n sourceMD5 _ = \"", pack md5,
"\"\n msgTypeName _ = \"", pack (fullRosMsgName m),
"\"\n\n"]
genSrvInfo :: Srv -> Msg -> MsgInfo ByteString
genSrvInfo s m = fmap aux (srvMD5 s)
where aux md5 = B.concat ["instance SrvInfo ", pack (shortName m),
" where\n srvMD5 _ = \"", pack md5,
"\"\n srvTypeName _ = \"", pack (fullRosSrvName s),
"\"\n\n"]
generateField :: MsgField -> MsgInfo ByteString
generateField (MsgField name t _) = do t' <- hType <$> getTypeInfo t
return $ B.concat [name, " :: ", t']
genConstants :: Msg -> MsgInfo ByteString
genConstants = fmap B.concat . mapM buildLine . constants
where escapeQuotes RString x =
B.concat [ "\""
, B.intercalate "\\\"" (B.split '"' x)
, "\"" ]
escapeQuotes _ x = x
buildLine (MsgConst name rosType val _) =
do t <- hType <$> getTypeInfo rosType
return $ B.concat [ name, " :: ", t, "\n"
, name, " = "
, escapeQuotes rosType val, "\n\n"]
|
rgleichman/roshask
|
src/executable/Gen.hs
|
bsd-3-clause
| 6,562 | 0 | 14 | 2,567 | 1,372 | 749 | 623 | 117 | 2 |
-- © 2002 Peter Thiemann
module Main where
import WASH.CGI.CGI hiding (head, div, span, map)
import qualified WASH.CGI.CGI as CGI
import System.Random
import qualified WASH.CGI.Persistent2 as P
import qualified WASH.CGI.Cookie as C
import WASH.CGI.Types -- for nhc98
main =
run helo0
--
helo0 =
standardQuery "Select an Example" $
activate exAction (selectSingle exName Nothing examples) empty
-- do exampleF <- selectSingle exName Nothing examples empty
-- submit exampleF dispatch (attr "value" "GO")
data Example = Example {exName :: String, exAction :: CGI ()}
instance Eq Example where
e1 == e2 = exName e1 == exName e2
examples =
[Example "Simple Hello World" helo1
,Example "Hello World with a little HTML" helo2
,Example "Hello World with a little Color" helo4
,Example "Hello World Personalized" helo5
,Example "Multiplication Table" helo6
,Example "Multiplication Drill" helo7
,Example "Multiplication Drill with Selection Box" helo8
,Example "Multiplication Drill with Radio Buttons" helo9
,Example "Multiplication Drill with Email Address" helo10
,Example "Multiplication Drill with Cookies" helo11
]
--
helo1 = ask $
standardPage "Hello" $
text "This is my first CGI program!"
--
helo2 = ask $
standardPage "Hello" $
do p (text "This is my second CGI program!")
p (do text "My hobbies are"
ul (do li (text "swimming")
li (text "music")
li (text "skiing")))
--
fgRed = "color" :=: "red"
bgGreen = "background" :=: "green"
styleImportant = fgRed :^: bgGreen
important x = using styleImportant x
helo4 = ask $
standardPage "Hello" $
important p (text "This is important!")
--
helo5 = standardQuery "What's your name?" $
p (do text "Hi there! What's your name?"
activate greeting textInputField empty)
greeting :: String -> CGI ()
greeting name =
standardQuery "Hello" $
do text "Hello "
text name
text ". This is my first interactive CGI program!"
--
helo6 = standardQuery "What's your name?" $
p (do text "Hi there! What's your name?"
activate mtable textInputField empty)
mtable name =
standardQuery "Multiplication Table" $
do p (text "Hello " >> text name >> text "!")
p (text "Let's see a multiplication table!")
p (text "Give me a multiplier " >>
activate ptable inputField empty)
ptable :: Integer -> CGI ()
ptable mpy =
standardQuery "Multiplication Table" $
table (mapM_ pLine [1..12])
where
align = attr "align" "right"
pLine i = tr (do
td (text (show i) ## align)
td (text "*")
td (text (show mpy))
td (text "=")
td (text (show (i * mpy)) ## align))
--
helo7 = standardQuery "What's your name?" $
p (do text "Hi there! What's your name?"
activate mdrill textInputField empty)
mdrill name =
standardQuery "Multiplication" $
do p (text "Hello ">> text name >> text "!")
p (text "Let's exercise some multiplication!")
mpyF <- p (text "Give me a multiplier " >>
inputField (attr "value" "2"))
rptF <- p (text "Number of exercises " >>
inputField (attr "value" "10"))
submit (F2 mpyF rptF) (firstExercise name) empty
firstExercise name (F2 mpyF rptF) =
runExercises 1 [] []
where
mpy, rpt :: Integer
mpy = CGI.value mpyF
rpt = CGI.value rptF
--
runExercises nr successes failures =
if nr > rpt then
finalReport
else
do factor <- io (randomRIO (0,12))
standardQuery ("Question " ++ show nr ++ " of " ++ show rpt) $
do text (show factor ++ " * " ++ show mpy ++ " = ")
activate (checkAnswer factor) inputField empty
where
checkAnswer factor answer =
let correct = answer == factor * mpy
message = if correct then "correct! " else "wrong! "
continue F0 = if correct then
runExercises (nr+1) (factor:successes) failures
else
runExercises (nr+1) successes (factor:failures)
in standardQuery ("Answer " ++ show nr ++ " of " ++ show rpt) $
do p (text (show factor ++ " * " ++ show mpy ++ " = " ++ show (factor * mpy)))
text ("Your answer " ++ show answer ++ " was " ++ message)
submit F0 continue (attr "value" "CONTINUE")
--
finalReport =
let lenSucc = length successes
pItem (m, l, r) = li (text ("Multiplier " ++ show m ++
" : " ++ show l ++
" correct out of " ++ show r))
in
do initialHandle <- P.init ("multi-" ++ name) []
currentHandle <- P.add initialHandle (mpy, lenSucc, rpt)
hiScores <- P.get currentHandle
standardQuery "Final Report" $
do p (text "Here are your recent scores.")
ul (mapM_ pItem hiScores)
--
helo8 = standardQuery "What's your name?" $
p (do text "Hi there! What's your name?"
activate mdrillSelect textInputField empty)
mdrillSelect name =
standardQuery "Multiplication" $
do p (text "Hello ">> text name >> text "!")
p (text "Let's exercise some multiplication!")
mpyF <- p (text "Give me a multiplier " >>
selectSingle show Nothing [2..12] empty)
rptF <- p (text "Number of exercises " >>
inputField (attr "value" "10"))
defaultSubmit (F2 mpyF rptF) (firstExercise name) empty
--
helo9 = standardQuery "What's your name?" $
p (do text "Hi there! What's your name?"
activate mdrillRadio textInputField empty)
mdrillRadio name =
standardQuery "Multiplication" $
do p (text "Hello ">> text name >> text "!")
p (text "Let's exercise some multiplication!")
mpyF <- p (text "Give me a multiplier " >>
selectSingle show Nothing [2..12] empty)
rptF <- radioGroup
p (text "Number of exercises " >>
text " 5 " ## radioButton rptF 5 empty >>
text " 10 " ## radioButton rptF 10 empty >>
text " 20 " ## radioButton rptF 20 empty >>
radioError rptF)
submit (F2 mpyF rptF) (firstExercise name) empty
--
helo10 = standardQuery "What's your name?" $
p (do text "Hi there! What's your email address?"
activate mdrillEmail inputField empty
-- inf <- inputField empty
-- submit inf mdrillEmailHandle empty
)
mdrillEmailHandle emailH =
mdrillEmail (value emailH)
mdrillEmail email =
let name = unEmailAddress email in
standardQuery "Multiplication" $
do p (text "Hello ">> text name >> text "!")
p (text "Let's exercise some multiplication!")
mpyF <- p (text "Give me a multiplier " >>
selectSingle show Nothing [2..12] empty)
rptF <- p (text "Number of exercises " >>
inputField (attr "value" "10"))
submit (F2 mpyF rptF) (firstExercise name) empty
--
helo11 =
C.check "name" >>= \mNameH ->
case mNameH of
Nothing ->
standardQuery "What's your name?" $
p (do text "Hi there! What's your name?"
activate mdrillCookie textInputField empty)
Just nameC ->
do mname <- C.get nameC
case mname of
Nothing ->
helo11 -- retry if outdated
Just name ->
mdrill name
mdrillCookie name =
do C.create "name" name
mdrill name
|
nh2/WashNGo
|
Examples/old/Tutorial.hs
|
bsd-3-clause
| 7,067 | 68 | 18 | 1,801 | 2,286 | 1,105 | 1,181 | 177 | 4 |
import Prelude hiding (FilePath)
import Data.Maybe
import Control.Monad
import Data.Monoid
import Shelly
import System.Exit
import Text.Regex
import Data.Text (Text)
import qualified Data.Text as T
default(Text)
main :: IO ()
main = do
results <- forM tests id
if and results then exitSuccess else exitFailure
where
tests = [ test "echo one" echoOne_
, test "edit one" editOne_
, test "echo chain" echoChain_
, test "edit chain" editChain_
, test "echo diamond" echoDiamond_
-- TODO test edit the script file
-- TODO test new script file
]
echoOne_ :: Sh Bool
echoOne_ = withRedo ("test" </> "echo") $ do
cmd "redo-ifchange" "out"
a <- catIn <$> lastStderr
cmd "redo-ifchange" "out"
b <- catIn <$> lastStderr
pure $ a && not b
editOne_ :: Sh Bool
editOne_ = withRedo ("test" </> "echo") $ do
cmd "redo-ifchange" "out"
a <- catIn <$> lastStderr
saveFile "in" $ do
writefile "in" "Mesdames, messieurres, bon soir!"
cmd "redo-ifchange" "out"
b <- catIn <$> lastStderr
pure $ a && b
echoChain_ :: Sh Bool
echoChain_ = withRedo ("test" </> "mid") $ do
cmd "redo-ifchange" "out"
a <- catIn <$> lastStderr
cmd "redo-ifchange" "out"
b <- catIn <$> lastStderr
pure $ a && not b
editChain_ :: Sh Bool
editChain_ = withRedo ("test" </> "mid") $ do
cmd "redo-ifchange" "out"
a <- catIn <$> lastStderr
saveFile "in" $ do
writefile "in" "Mesdames, messieurres, bon soir!"
cmd "redo-ifchange" "out"
b <- catIn <$> lastStderr
pure $ a && b
echoDiamond_ :: Sh Bool
echoDiamond_ = withRedo ("test" </> "diamond") $ do
cmd "redo-ifchange" "out"
a <- length . filter catIn . T.lines <$> lastStderr
pure $ a == 1
test :: Text -> Sh Bool -> IO Bool
test testName action = shelly $ do
echo ""
echo $ "###### \x1b[33mTESTING\x1b[0m: " <> testName <> " ######"
r <- action
if r
then echo $ "\x1b[32mOK\x1b[0m: " <> testName
else echo $ "\x1b[31mFAILURE\x1b[0m: " <> testName
pure r
withRedo :: FilePath -> Sh a -> Sh a
withRedo dir action = do
cd dir
rm_rf ".redo/"
cmd "redo-init"
action
catIn :: Text -> Bool
catIn = isJust . matchRegex r . T.unpack
where
r = mkRegex "^\\+\\s*cat in"
saveFile :: FilePath -> Sh a -> Sh a
saveFile = saveFiles . (:[])
saveFiles :: [FilePath] -> Sh a -> Sh a
saveFiles files action = do
originals <- forM files $ \filename -> do
content <- readfile filename
pure (filename, content)
action `finally_sh` (uncurry writefile `mapM_` originals)
|
Zankoku-Okuno/redo
|
test/test.hs
|
bsd-3-clause
| 2,672 | 0 | 13 | 730 | 879 | 423 | 456 | 82 | 2 |
{-# LANGUAGE KindSignatures,
TypeFamilies,
UndecidableInstances,
GADTs,
MultiParamTypeClasses, FunctionalDependencies
, TypeOperators, EmptyDataDecls, Rank2Types
, FlexibleInstances
#-}
module Basil.Data.HList where
import Basil.Data.TBoolean
import Control.Monad (liftM2)
infixr 5 :*:
infixr 5 .*.
infixr 5 .**.
-- Type for a non-empty list
data (:*:) a b
-- Type for a nil-list
data Nil
-- Handy combinators
(.*.) :: a -> HList b -> HList (a :*: b)
(.*.) = Cons
(.**.) :: f a -> HList2 f b -> HList2 f (a :*: b)
(.**.) = Cons2
-- Simple heterogenous lists
data HList a where
Nil :: HList Nil
Cons :: a -> HList b -> HList (a :*: b)
-- Heterogenous lists that contain functors
data HList2 f a where
Nil2 :: HList2 f Nil
Cons2 :: f a -> HList2 f b -> HList2 f (a :*: b)
-- Typed indexes into the lists
data Ix phi ix where
Zero :: Ix (a :*: b) a
Suc :: Ix xs a -> Ix (x :*: xs) a
-- Type-level map
type family TMap (f :: * -> *) phi :: *
type instance TMap f Nil = Nil
type instance TMap f (a :*: b) = f a :*: TMap f b
data Witnesses finalEnv env where
WNil :: Witnesses finalEnv Nil
WCons :: Ix finalEnv ix -> Witnesses finalEnv env -> Witnesses finalEnv (ix :*: env)
-- Head and tail
hHead :: HList (x :*: xs) -> x
hHead (Cons x _) = x
hTail :: HList (x :*: xs) -> HList xs
hTail (Cons _ xs) = xs
-- Looking up in lists
lookupHList :: Ix phi ix -> HList phi -> ix
lookupHList Zero (Cons y _ ) = y
lookupHList (Suc x) (Cons _ ys) = lookupHList x ys
lookupHList _ _ = error "lookupHList: absurd case."
lookupHList2 :: Ix phi ix -> HList2 f phi -> f ix
lookupHList2 Zero (Cons2 y _ ) = y
lookupHList2 (Suc x) (Cons2 _ ys) = lookupHList2 x ys
lookupHList2 _ _ = error "lookupHList: absurd case."
lookupMapHList :: Ix phi ix -> HList (TMap f phi) -> f ix
lookupMapHList Zero (Cons y _ ) = y
lookupMapHList (Suc x) (Cons _ ys) = lookupMapHList x ys
lookupMapHList _ _ = error "lookupMapHList: absurd case."
-- Mapping lists
mapMHList2 :: Monad m => (forall a . f a -> m b) -> HList2 f phi -> m [b]
mapMHList2 _ Nil2 = return []
mapMHList2 f (Cons2 x xs) = liftM2 (:) (f x) $ mapMHList2 f xs
-- Modifying a list at the position given by the |Ix|
modHList :: (f ix -> f ix)
-> Ix phi ix
-> HList (TMap f phi)
-> HList (TMap f phi)
modHList f Zero (Cons a b) = f a .*. b
modHList f (Suc x) (Cons a b) = a .*. modHList f x b
modHList _ _ _ = error "modHList: absurd case."
-- Folding a list
foldHList :: (forall ix . f ix -> r -> r)
-> r
-> HList2 f phi
-> r
foldHList _ r Nil2 = r
foldHList f r (Cons2 x xs) = f x (foldHList f r xs)
-- Zipping an |HList| with an |HList2|:
zipHlistWithHList2 :: HList a -> HList2 f a -> HList2 (WithMeta f) a
zipHlistWithHList2 Nil Nil2 = Nil2
zipHlistWithHList2 (Cons x xs) (Cons2 y ys) = Combined x y .**. zipHlistWithHList2 xs ys
zipHlistWithHList2 _ _ = error "zipHlistWithHList2: should not happen."
data WithMeta f a = Combined a (f a)
-- The |AppendIfTrue| type-level function
type family AppendIfTrue bool x xs :: *
type instance AppendIfTrue True x xs = x :*: xs
type instance AppendIfTrue False x xs = xs
-- Some show instances
instance Show (HList Nil) where
show Nil = "Nil"
instance (Show a, Show (HList as)) => Show (HList (a :*: as)) where
show (Cons a b) = "Cons (" ++ show a ++ ") (" ++ show b ++ ")"
instance Show (HList2 f Nil) where
show Nil2 = "Nil2"
instance (Show (f a), Show (HList2 f b)) => Show (HList2 f (a :*: b)) where
show (Cons2 a b) = "Cons2 (" ++ show a ++ ") (" ++ show b ++ ")"
|
chriseidhof/Basil
|
src/Basil/Data/HList.hs
|
bsd-3-clause
| 3,821 | 0 | 10 | 1,086 | 1,424 | 739 | 685 | -1 | -1 |
{-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.Functions.F17
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- Raw functions from the
-- <http://www.opengl.org/registry/ OpenGL registry>.
--
--------------------------------------------------------------------------------
module Graphics.GL.Functions.F17 (
glMultMatrixf,
glMultMatrixx,
glMultMatrixxOES,
glMultTransposeMatrixd,
glMultTransposeMatrixdARB,
glMultTransposeMatrixf,
glMultTransposeMatrixfARB,
glMultTransposeMatrixxOES,
glMultiDrawArrays,
glMultiDrawArraysEXT,
glMultiDrawArraysIndirect,
glMultiDrawArraysIndirectAMD,
glMultiDrawArraysIndirectBindlessCountNV,
glMultiDrawArraysIndirectBindlessNV,
glMultiDrawArraysIndirectCount,
glMultiDrawArraysIndirectCountARB,
glMultiDrawArraysIndirectEXT,
glMultiDrawElementArrayAPPLE,
glMultiDrawElements,
glMultiDrawElementsBaseVertex,
glMultiDrawElementsBaseVertexEXT,
glMultiDrawElementsEXT,
glMultiDrawElementsIndirect,
glMultiDrawElementsIndirectAMD,
glMultiDrawElementsIndirectBindlessCountNV,
glMultiDrawElementsIndirectBindlessNV,
glMultiDrawElementsIndirectCount,
glMultiDrawElementsIndirectCountARB,
glMultiDrawElementsIndirectEXT,
glMultiDrawMeshTasksIndirectCountNV,
glMultiDrawMeshTasksIndirectNV,
glMultiDrawRangeElementArrayAPPLE,
glMultiModeDrawArraysIBM,
glMultiModeDrawElementsIBM,
glMultiTexBufferEXT,
glMultiTexCoord1bOES,
glMultiTexCoord1bvOES,
glMultiTexCoord1d,
glMultiTexCoord1dARB,
glMultiTexCoord1dv,
glMultiTexCoord1dvARB,
glMultiTexCoord1f,
glMultiTexCoord1fARB,
glMultiTexCoord1fv,
glMultiTexCoord1fvARB,
glMultiTexCoord1hNV,
glMultiTexCoord1hvNV,
glMultiTexCoord1i,
glMultiTexCoord1iARB,
glMultiTexCoord1iv,
glMultiTexCoord1ivARB,
glMultiTexCoord1s,
glMultiTexCoord1sARB,
glMultiTexCoord1sv,
glMultiTexCoord1svARB,
glMultiTexCoord1xOES,
glMultiTexCoord1xvOES,
glMultiTexCoord2bOES,
glMultiTexCoord2bvOES,
glMultiTexCoord2d,
glMultiTexCoord2dARB,
glMultiTexCoord2dv,
glMultiTexCoord2dvARB,
glMultiTexCoord2f,
glMultiTexCoord2fARB,
glMultiTexCoord2fv,
glMultiTexCoord2fvARB,
glMultiTexCoord2hNV,
glMultiTexCoord2hvNV,
glMultiTexCoord2i,
glMultiTexCoord2iARB,
glMultiTexCoord2iv,
glMultiTexCoord2ivARB,
glMultiTexCoord2s,
glMultiTexCoord2sARB,
glMultiTexCoord2sv,
glMultiTexCoord2svARB,
glMultiTexCoord2xOES,
glMultiTexCoord2xvOES,
glMultiTexCoord3bOES,
glMultiTexCoord3bvOES,
glMultiTexCoord3d,
glMultiTexCoord3dARB,
glMultiTexCoord3dv,
glMultiTexCoord3dvARB,
glMultiTexCoord3f,
glMultiTexCoord3fARB,
glMultiTexCoord3fv,
glMultiTexCoord3fvARB,
glMultiTexCoord3hNV,
glMultiTexCoord3hvNV,
glMultiTexCoord3i,
glMultiTexCoord3iARB,
glMultiTexCoord3iv,
glMultiTexCoord3ivARB,
glMultiTexCoord3s,
glMultiTexCoord3sARB,
glMultiTexCoord3sv,
glMultiTexCoord3svARB,
glMultiTexCoord3xOES
) where
import Control.Monad.IO.Class ( MonadIO(..) )
import Foreign.Ptr
import Graphics.GL.Foreign
import Graphics.GL.Types
import System.IO.Unsafe ( unsafePerformIO )
-- glMultMatrixf ---------------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultMatrix.xml OpenGL 2.x>.
glMultMatrixf
:: MonadIO m
=> Ptr GLfloat -- ^ @m@ pointing to @16@ elements of type @GLfloat@.
-> m ()
glMultMatrixf v1 = liftIO $ dyn44 ptr_glMultMatrixf v1
{-# NOINLINE ptr_glMultMatrixf #-}
ptr_glMultMatrixf :: FunPtr (Ptr GLfloat -> IO ())
ptr_glMultMatrixf = unsafePerformIO $ getCommand "glMultMatrixf"
-- glMultMatrixx ---------------------------------------------------------------
glMultMatrixx
:: MonadIO m
=> Ptr GLfixed -- ^ @m@ pointing to @16@ elements of type @GLfixed@.
-> m ()
glMultMatrixx v1 = liftIO $ dyn114 ptr_glMultMatrixx v1
{-# NOINLINE ptr_glMultMatrixx #-}
ptr_glMultMatrixx :: FunPtr (Ptr GLfixed -> IO ())
ptr_glMultMatrixx = unsafePerformIO $ getCommand "glMultMatrixx"
-- glMultMatrixxOES ------------------------------------------------------------
glMultMatrixxOES
:: MonadIO m
=> Ptr GLfixed -- ^ @m@ pointing to @16@ elements of type @GLfixed@.
-> m ()
glMultMatrixxOES v1 = liftIO $ dyn114 ptr_glMultMatrixxOES v1
{-# NOINLINE ptr_glMultMatrixxOES #-}
ptr_glMultMatrixxOES :: FunPtr (Ptr GLfixed -> IO ())
ptr_glMultMatrixxOES = unsafePerformIO $ getCommand "glMultMatrixxOES"
-- glMultTransposeMatrixd ------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultTransposeMatrix.xml OpenGL 2.x>.
glMultTransposeMatrixd
:: MonadIO m
=> Ptr GLdouble -- ^ @m@ pointing to @16@ elements of type @GLdouble@.
-> m ()
glMultTransposeMatrixd v1 = liftIO $ dyn42 ptr_glMultTransposeMatrixd v1
{-# NOINLINE ptr_glMultTransposeMatrixd #-}
ptr_glMultTransposeMatrixd :: FunPtr (Ptr GLdouble -> IO ())
ptr_glMultTransposeMatrixd = unsafePerformIO $ getCommand "glMultTransposeMatrixd"
-- glMultTransposeMatrixdARB ---------------------------------------------------
-- | This command is an alias for 'glMultTransposeMatrixd'.
glMultTransposeMatrixdARB
:: MonadIO m
=> Ptr GLdouble -- ^ @m@ pointing to @16@ elements of type @GLdouble@.
-> m ()
glMultTransposeMatrixdARB v1 = liftIO $ dyn42 ptr_glMultTransposeMatrixdARB v1
{-# NOINLINE ptr_glMultTransposeMatrixdARB #-}
ptr_glMultTransposeMatrixdARB :: FunPtr (Ptr GLdouble -> IO ())
ptr_glMultTransposeMatrixdARB = unsafePerformIO $ getCommand "glMultTransposeMatrixdARB"
-- glMultTransposeMatrixf ------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultTransposeMatrix.xml OpenGL 2.x>.
glMultTransposeMatrixf
:: MonadIO m
=> Ptr GLfloat -- ^ @m@ pointing to @16@ elements of type @GLfloat@.
-> m ()
glMultTransposeMatrixf v1 = liftIO $ dyn44 ptr_glMultTransposeMatrixf v1
{-# NOINLINE ptr_glMultTransposeMatrixf #-}
ptr_glMultTransposeMatrixf :: FunPtr (Ptr GLfloat -> IO ())
ptr_glMultTransposeMatrixf = unsafePerformIO $ getCommand "glMultTransposeMatrixf"
-- glMultTransposeMatrixfARB ---------------------------------------------------
-- | This command is an alias for 'glMultTransposeMatrixf'.
glMultTransposeMatrixfARB
:: MonadIO m
=> Ptr GLfloat -- ^ @m@ pointing to @16@ elements of type @GLfloat@.
-> m ()
glMultTransposeMatrixfARB v1 = liftIO $ dyn44 ptr_glMultTransposeMatrixfARB v1
{-# NOINLINE ptr_glMultTransposeMatrixfARB #-}
ptr_glMultTransposeMatrixfARB :: FunPtr (Ptr GLfloat -> IO ())
ptr_glMultTransposeMatrixfARB = unsafePerformIO $ getCommand "glMultTransposeMatrixfARB"
-- glMultTransposeMatrixxOES ---------------------------------------------------
glMultTransposeMatrixxOES
:: MonadIO m
=> Ptr GLfixed -- ^ @m@ pointing to @16@ elements of type @GLfixed@.
-> m ()
glMultTransposeMatrixxOES v1 = liftIO $ dyn114 ptr_glMultTransposeMatrixxOES v1
{-# NOINLINE ptr_glMultTransposeMatrixxOES #-}
ptr_glMultTransposeMatrixxOES :: FunPtr (Ptr GLfixed -> IO ())
ptr_glMultTransposeMatrixxOES = unsafePerformIO $ getCommand "glMultTransposeMatrixxOES"
-- glMultiDrawArrays -----------------------------------------------------------
-- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiDrawArrays.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man3/xhtml/glMultiDrawArrays.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glMultiDrawArrays.xhtml OpenGL 4.x>.
glMultiDrawArrays
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLint -- ^ @first@ pointing to @COMPSIZE(drawcount)@ elements of type @GLint@.
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(drawcount)@ elements of type @GLsizei@.
-> GLsizei -- ^ @drawcount@.
-> m ()
glMultiDrawArrays v1 v2 v3 v4 = liftIO $ dyn551 ptr_glMultiDrawArrays v1 v2 v3 v4
{-# NOINLINE ptr_glMultiDrawArrays #-}
ptr_glMultiDrawArrays :: FunPtr (GLenum -> Ptr GLint -> Ptr GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawArrays = unsafePerformIO $ getCommand "glMultiDrawArrays"
-- glMultiDrawArraysEXT --------------------------------------------------------
-- | This command is an alias for 'glMultiDrawArrays'.
glMultiDrawArraysEXT
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLint -- ^ @first@ pointing to @COMPSIZE(primcount)@ elements of type @GLint@.
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(primcount)@ elements of type @GLsizei@.
-> GLsizei -- ^ @primcount@.
-> m ()
glMultiDrawArraysEXT v1 v2 v3 v4 = liftIO $ dyn551 ptr_glMultiDrawArraysEXT v1 v2 v3 v4
{-# NOINLINE ptr_glMultiDrawArraysEXT #-}
ptr_glMultiDrawArraysEXT :: FunPtr (GLenum -> Ptr GLint -> Ptr GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawArraysEXT = unsafePerformIO $ getCommand "glMultiDrawArraysEXT"
-- glMultiDrawArraysIndirect ---------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glMultiDrawArraysIndirect.xhtml OpenGL 4.x>.
glMultiDrawArraysIndirect
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr a -- ^ @indirect@ pointing to @COMPSIZE(drawcount,stride)@ elements of type @a@.
-> GLsizei -- ^ @drawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawArraysIndirect v1 v2 v3 v4 = liftIO $ dyn552 ptr_glMultiDrawArraysIndirect v1 v2 v3 v4
{-# NOINLINE ptr_glMultiDrawArraysIndirect #-}
ptr_glMultiDrawArraysIndirect :: FunPtr (GLenum -> Ptr a -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawArraysIndirect = unsafePerformIO $ getCommand "glMultiDrawArraysIndirect"
-- glMultiDrawArraysIndirectAMD ------------------------------------------------
-- | This command is an alias for 'glMultiDrawArraysIndirect'.
glMultiDrawArraysIndirectAMD
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr a -- ^ @indirect@.
-> GLsizei -- ^ @primcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawArraysIndirectAMD v1 v2 v3 v4 = liftIO $ dyn552 ptr_glMultiDrawArraysIndirectAMD v1 v2 v3 v4
{-# NOINLINE ptr_glMultiDrawArraysIndirectAMD #-}
ptr_glMultiDrawArraysIndirectAMD :: FunPtr (GLenum -> Ptr a -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawArraysIndirectAMD = unsafePerformIO $ getCommand "glMultiDrawArraysIndirectAMD"
-- glMultiDrawArraysIndirectBindlessCountNV ------------------------------------
glMultiDrawArraysIndirectBindlessCountNV
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr a -- ^ @indirect@.
-> GLsizei -- ^ @drawCount@.
-> GLsizei -- ^ @maxDrawCount@.
-> GLsizei -- ^ @stride@.
-> GLint -- ^ @vertexBufferCount@.
-> m ()
glMultiDrawArraysIndirectBindlessCountNV v1 v2 v3 v4 v5 v6 = liftIO $ dyn553 ptr_glMultiDrawArraysIndirectBindlessCountNV v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiDrawArraysIndirectBindlessCountNV #-}
ptr_glMultiDrawArraysIndirectBindlessCountNV :: FunPtr (GLenum -> Ptr a -> GLsizei -> GLsizei -> GLsizei -> GLint -> IO ())
ptr_glMultiDrawArraysIndirectBindlessCountNV = unsafePerformIO $ getCommand "glMultiDrawArraysIndirectBindlessCountNV"
-- glMultiDrawArraysIndirectBindlessNV -----------------------------------------
glMultiDrawArraysIndirectBindlessNV
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr a -- ^ @indirect@.
-> GLsizei -- ^ @drawCount@.
-> GLsizei -- ^ @stride@.
-> GLint -- ^ @vertexBufferCount@.
-> m ()
glMultiDrawArraysIndirectBindlessNV v1 v2 v3 v4 v5 = liftIO $ dyn554 ptr_glMultiDrawArraysIndirectBindlessNV v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawArraysIndirectBindlessNV #-}
ptr_glMultiDrawArraysIndirectBindlessNV :: FunPtr (GLenum -> Ptr a -> GLsizei -> GLsizei -> GLint -> IO ())
ptr_glMultiDrawArraysIndirectBindlessNV = unsafePerformIO $ getCommand "glMultiDrawArraysIndirectBindlessNV"
-- glMultiDrawArraysIndirectCount ----------------------------------------------
glMultiDrawArraysIndirectCount
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr a -- ^ @indirect@.
-> GLintptr -- ^ @drawcount@.
-> GLsizei -- ^ @maxdrawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawArraysIndirectCount v1 v2 v3 v4 v5 = liftIO $ dyn555 ptr_glMultiDrawArraysIndirectCount v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawArraysIndirectCount #-}
ptr_glMultiDrawArraysIndirectCount :: FunPtr (GLenum -> Ptr a -> GLintptr -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawArraysIndirectCount = unsafePerformIO $ getCommand "glMultiDrawArraysIndirectCount"
-- glMultiDrawArraysIndirectCountARB -------------------------------------------
-- | This command is an alias for 'glMultiDrawArraysIndirectCount'.
glMultiDrawArraysIndirectCountARB
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr a -- ^ @indirect@.
-> GLintptr -- ^ @drawcount@.
-> GLsizei -- ^ @maxdrawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawArraysIndirectCountARB v1 v2 v3 v4 v5 = liftIO $ dyn555 ptr_glMultiDrawArraysIndirectCountARB v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawArraysIndirectCountARB #-}
ptr_glMultiDrawArraysIndirectCountARB :: FunPtr (GLenum -> Ptr a -> GLintptr -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawArraysIndirectCountARB = unsafePerformIO $ getCommand "glMultiDrawArraysIndirectCountARB"
-- glMultiDrawArraysIndirectEXT ------------------------------------------------
-- | This command is an alias for 'glMultiDrawArraysIndirect'.
glMultiDrawArraysIndirectEXT
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr a -- ^ @indirect@ pointing to @COMPSIZE(drawcount,stride)@ elements of type @a@.
-> GLsizei -- ^ @drawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawArraysIndirectEXT v1 v2 v3 v4 = liftIO $ dyn552 ptr_glMultiDrawArraysIndirectEXT v1 v2 v3 v4
{-# NOINLINE ptr_glMultiDrawArraysIndirectEXT #-}
ptr_glMultiDrawArraysIndirectEXT :: FunPtr (GLenum -> Ptr a -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawArraysIndirectEXT = unsafePerformIO $ getCommand "glMultiDrawArraysIndirectEXT"
-- glMultiDrawElementArrayAPPLE ------------------------------------------------
glMultiDrawElementArrayAPPLE
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLint -- ^ @first@ pointing to @primcount@ elements of type @GLint@.
-> Ptr GLsizei -- ^ @count@ pointing to @primcount@ elements of type @GLsizei@.
-> GLsizei -- ^ @primcount@.
-> m ()
glMultiDrawElementArrayAPPLE v1 v2 v3 v4 = liftIO $ dyn551 ptr_glMultiDrawElementArrayAPPLE v1 v2 v3 v4
{-# NOINLINE ptr_glMultiDrawElementArrayAPPLE #-}
ptr_glMultiDrawElementArrayAPPLE :: FunPtr (GLenum -> Ptr GLint -> Ptr GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawElementArrayAPPLE = unsafePerformIO $ getCommand "glMultiDrawElementArrayAPPLE"
-- glMultiDrawElements ---------------------------------------------------------
-- | Manual pages for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiDrawElements.xml OpenGL 2.x> or <https://www.opengl.org/sdk/docs/man3/xhtml/glMultiDrawElements.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glMultiDrawElements.xhtml OpenGL 4.x>.
glMultiDrawElements
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(drawcount)@ elements of type @GLsizei@.
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr (Ptr a) -- ^ @indices@ pointing to @COMPSIZE(drawcount)@ elements of type @Ptr a@.
-> GLsizei -- ^ @drawcount@.
-> m ()
glMultiDrawElements v1 v2 v3 v4 v5 = liftIO $ dyn556 ptr_glMultiDrawElements v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawElements #-}
ptr_glMultiDrawElements :: FunPtr (GLenum -> Ptr GLsizei -> GLenum -> Ptr (Ptr a) -> GLsizei -> IO ())
ptr_glMultiDrawElements = unsafePerformIO $ getCommand "glMultiDrawElements"
-- glMultiDrawElementsBaseVertex -----------------------------------------------
-- | Manual pages for <https://www.opengl.org/sdk/docs/man3/xhtml/glMultiDrawElementsBaseVertex.xml OpenGL 3.x> or <https://www.opengl.org/sdk/docs/man4/html/glMultiDrawElementsBaseVertex.xhtml OpenGL 4.x>.
glMultiDrawElementsBaseVertex
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(drawcount)@ elements of type @GLsizei@.
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr (Ptr a) -- ^ @indices@ pointing to @COMPSIZE(drawcount)@ elements of type @Ptr a@.
-> GLsizei -- ^ @drawcount@.
-> Ptr GLint -- ^ @basevertex@ pointing to @COMPSIZE(drawcount)@ elements of type @GLint@.
-> m ()
glMultiDrawElementsBaseVertex v1 v2 v3 v4 v5 v6 = liftIO $ dyn557 ptr_glMultiDrawElementsBaseVertex v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiDrawElementsBaseVertex #-}
ptr_glMultiDrawElementsBaseVertex :: FunPtr (GLenum -> Ptr GLsizei -> GLenum -> Ptr (Ptr a) -> GLsizei -> Ptr GLint -> IO ())
ptr_glMultiDrawElementsBaseVertex = unsafePerformIO $ getCommand "glMultiDrawElementsBaseVertex"
-- glMultiDrawElementsBaseVertexEXT --------------------------------------------
-- | This command is an alias for 'glMultiDrawElementsBaseVertex'.
glMultiDrawElementsBaseVertexEXT
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(drawcount)@ elements of type @GLsizei@.
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr (Ptr a) -- ^ @indices@ pointing to @COMPSIZE(drawcount)@ elements of type @Ptr a@.
-> GLsizei -- ^ @primcount@.
-> Ptr GLint -- ^ @basevertex@ pointing to @COMPSIZE(drawcount)@ elements of type @GLint@.
-> m ()
glMultiDrawElementsBaseVertexEXT v1 v2 v3 v4 v5 v6 = liftIO $ dyn557 ptr_glMultiDrawElementsBaseVertexEXT v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiDrawElementsBaseVertexEXT #-}
ptr_glMultiDrawElementsBaseVertexEXT :: FunPtr (GLenum -> Ptr GLsizei -> GLenum -> Ptr (Ptr a) -> GLsizei -> Ptr GLint -> IO ())
ptr_glMultiDrawElementsBaseVertexEXT = unsafePerformIO $ getCommand "glMultiDrawElementsBaseVertexEXT"
-- glMultiDrawElementsEXT ------------------------------------------------------
-- | This command is an alias for 'glMultiDrawElements'.
glMultiDrawElementsEXT
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(primcount)@ elements of type @GLsizei@.
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr (Ptr a) -- ^ @indices@ pointing to @COMPSIZE(primcount)@ elements of type @Ptr a@.
-> GLsizei -- ^ @primcount@.
-> m ()
glMultiDrawElementsEXT v1 v2 v3 v4 v5 = liftIO $ dyn556 ptr_glMultiDrawElementsEXT v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawElementsEXT #-}
ptr_glMultiDrawElementsEXT :: FunPtr (GLenum -> Ptr GLsizei -> GLenum -> Ptr (Ptr a) -> GLsizei -> IO ())
ptr_glMultiDrawElementsEXT = unsafePerformIO $ getCommand "glMultiDrawElementsEXT"
-- glMultiDrawElementsIndirect -------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man4/html/glMultiDrawElementsIndirect.xhtml OpenGL 4.x>.
glMultiDrawElementsIndirect
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr a -- ^ @indirect@ pointing to @COMPSIZE(drawcount,stride)@ elements of type @a@.
-> GLsizei -- ^ @drawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawElementsIndirect v1 v2 v3 v4 v5 = liftIO $ dyn558 ptr_glMultiDrawElementsIndirect v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawElementsIndirect #-}
ptr_glMultiDrawElementsIndirect :: FunPtr (GLenum -> GLenum -> Ptr a -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawElementsIndirect = unsafePerformIO $ getCommand "glMultiDrawElementsIndirect"
-- glMultiDrawElementsIndirectAMD ----------------------------------------------
-- | This command is an alias for 'glMultiDrawElementsIndirect'.
glMultiDrawElementsIndirectAMD
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr a -- ^ @indirect@.
-> GLsizei -- ^ @primcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawElementsIndirectAMD v1 v2 v3 v4 v5 = liftIO $ dyn558 ptr_glMultiDrawElementsIndirectAMD v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawElementsIndirectAMD #-}
ptr_glMultiDrawElementsIndirectAMD :: FunPtr (GLenum -> GLenum -> Ptr a -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawElementsIndirectAMD = unsafePerformIO $ getCommand "glMultiDrawElementsIndirectAMD"
-- glMultiDrawElementsIndirectBindlessCountNV ----------------------------------
glMultiDrawElementsIndirectBindlessCountNV
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr a -- ^ @indirect@.
-> GLsizei -- ^ @drawCount@.
-> GLsizei -- ^ @maxDrawCount@.
-> GLsizei -- ^ @stride@.
-> GLint -- ^ @vertexBufferCount@.
-> m ()
glMultiDrawElementsIndirectBindlessCountNV v1 v2 v3 v4 v5 v6 v7 = liftIO $ dyn559 ptr_glMultiDrawElementsIndirectBindlessCountNV v1 v2 v3 v4 v5 v6 v7
{-# NOINLINE ptr_glMultiDrawElementsIndirectBindlessCountNV #-}
ptr_glMultiDrawElementsIndirectBindlessCountNV :: FunPtr (GLenum -> GLenum -> Ptr a -> GLsizei -> GLsizei -> GLsizei -> GLint -> IO ())
ptr_glMultiDrawElementsIndirectBindlessCountNV = unsafePerformIO $ getCommand "glMultiDrawElementsIndirectBindlessCountNV"
-- glMultiDrawElementsIndirectBindlessNV ---------------------------------------
glMultiDrawElementsIndirectBindlessNV
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr a -- ^ @indirect@.
-> GLsizei -- ^ @drawCount@.
-> GLsizei -- ^ @stride@.
-> GLint -- ^ @vertexBufferCount@.
-> m ()
glMultiDrawElementsIndirectBindlessNV v1 v2 v3 v4 v5 v6 = liftIO $ dyn560 ptr_glMultiDrawElementsIndirectBindlessNV v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiDrawElementsIndirectBindlessNV #-}
ptr_glMultiDrawElementsIndirectBindlessNV :: FunPtr (GLenum -> GLenum -> Ptr a -> GLsizei -> GLsizei -> GLint -> IO ())
ptr_glMultiDrawElementsIndirectBindlessNV = unsafePerformIO $ getCommand "glMultiDrawElementsIndirectBindlessNV"
-- glMultiDrawElementsIndirectCount --------------------------------------------
glMultiDrawElementsIndirectCount
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr a -- ^ @indirect@.
-> GLintptr -- ^ @drawcount@.
-> GLsizei -- ^ @maxdrawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawElementsIndirectCount v1 v2 v3 v4 v5 v6 = liftIO $ dyn561 ptr_glMultiDrawElementsIndirectCount v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiDrawElementsIndirectCount #-}
ptr_glMultiDrawElementsIndirectCount :: FunPtr (GLenum -> GLenum -> Ptr a -> GLintptr -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawElementsIndirectCount = unsafePerformIO $ getCommand "glMultiDrawElementsIndirectCount"
-- glMultiDrawElementsIndirectCountARB -----------------------------------------
-- | This command is an alias for 'glMultiDrawElementsIndirectCount'.
glMultiDrawElementsIndirectCountARB
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr a -- ^ @indirect@.
-> GLintptr -- ^ @drawcount@.
-> GLsizei -- ^ @maxdrawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawElementsIndirectCountARB v1 v2 v3 v4 v5 v6 = liftIO $ dyn561 ptr_glMultiDrawElementsIndirectCountARB v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiDrawElementsIndirectCountARB #-}
ptr_glMultiDrawElementsIndirectCountARB :: FunPtr (GLenum -> GLenum -> Ptr a -> GLintptr -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawElementsIndirectCountARB = unsafePerformIO $ getCommand "glMultiDrawElementsIndirectCountARB"
-- glMultiDrawElementsIndirectEXT ----------------------------------------------
-- | This command is an alias for 'glMultiDrawElementsIndirect'.
glMultiDrawElementsIndirectEXT
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr a -- ^ @indirect@ pointing to @COMPSIZE(drawcount,stride)@ elements of type @a@.
-> GLsizei -- ^ @drawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawElementsIndirectEXT v1 v2 v3 v4 v5 = liftIO $ dyn558 ptr_glMultiDrawElementsIndirectEXT v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiDrawElementsIndirectEXT #-}
ptr_glMultiDrawElementsIndirectEXT :: FunPtr (GLenum -> GLenum -> Ptr a -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawElementsIndirectEXT = unsafePerformIO $ getCommand "glMultiDrawElementsIndirectEXT"
-- glMultiDrawMeshTasksIndirectCountNV -----------------------------------------
glMultiDrawMeshTasksIndirectCountNV
:: MonadIO m
=> GLintptr -- ^ @indirect@.
-> GLintptr -- ^ @drawcount@.
-> GLsizei -- ^ @maxdrawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawMeshTasksIndirectCountNV v1 v2 v3 v4 = liftIO $ dyn562 ptr_glMultiDrawMeshTasksIndirectCountNV v1 v2 v3 v4
{-# NOINLINE ptr_glMultiDrawMeshTasksIndirectCountNV #-}
ptr_glMultiDrawMeshTasksIndirectCountNV :: FunPtr (GLintptr -> GLintptr -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawMeshTasksIndirectCountNV = unsafePerformIO $ getCommand "glMultiDrawMeshTasksIndirectCountNV"
-- glMultiDrawMeshTasksIndirectNV ----------------------------------------------
glMultiDrawMeshTasksIndirectNV
:: MonadIO m
=> GLintptr -- ^ @indirect@.
-> GLsizei -- ^ @drawcount@.
-> GLsizei -- ^ @stride@.
-> m ()
glMultiDrawMeshTasksIndirectNV v1 v2 v3 = liftIO $ dyn563 ptr_glMultiDrawMeshTasksIndirectNV v1 v2 v3
{-# NOINLINE ptr_glMultiDrawMeshTasksIndirectNV #-}
ptr_glMultiDrawMeshTasksIndirectNV :: FunPtr (GLintptr -> GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawMeshTasksIndirectNV = unsafePerformIO $ getCommand "glMultiDrawMeshTasksIndirectNV"
-- glMultiDrawRangeElementArrayAPPLE -------------------------------------------
glMultiDrawRangeElementArrayAPPLE
:: MonadIO m
=> GLenum -- ^ @mode@ of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> GLuint -- ^ @start@.
-> GLuint -- ^ @end@.
-> Ptr GLint -- ^ @first@ pointing to @primcount@ elements of type @GLint@.
-> Ptr GLsizei -- ^ @count@ pointing to @primcount@ elements of type @GLsizei@.
-> GLsizei -- ^ @primcount@.
-> m ()
glMultiDrawRangeElementArrayAPPLE v1 v2 v3 v4 v5 v6 = liftIO $ dyn564 ptr_glMultiDrawRangeElementArrayAPPLE v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiDrawRangeElementArrayAPPLE #-}
ptr_glMultiDrawRangeElementArrayAPPLE :: FunPtr (GLenum -> GLuint -> GLuint -> Ptr GLint -> Ptr GLsizei -> GLsizei -> IO ())
ptr_glMultiDrawRangeElementArrayAPPLE = unsafePerformIO $ getCommand "glMultiDrawRangeElementArrayAPPLE"
-- glMultiModeDrawArraysIBM ----------------------------------------------------
glMultiModeDrawArraysIBM
:: MonadIO m
=> Ptr GLenum -- ^ @mode@ pointing to @COMPSIZE(primcount)@ elements of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLint -- ^ @first@ pointing to @COMPSIZE(primcount)@ elements of type @GLint@.
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(primcount)@ elements of type @GLsizei@.
-> GLsizei -- ^ @primcount@.
-> GLint -- ^ @modestride@.
-> m ()
glMultiModeDrawArraysIBM v1 v2 v3 v4 v5 = liftIO $ dyn565 ptr_glMultiModeDrawArraysIBM v1 v2 v3 v4 v5
{-# NOINLINE ptr_glMultiModeDrawArraysIBM #-}
ptr_glMultiModeDrawArraysIBM :: FunPtr (Ptr GLenum -> Ptr GLint -> Ptr GLsizei -> GLsizei -> GLint -> IO ())
ptr_glMultiModeDrawArraysIBM = unsafePerformIO $ getCommand "glMultiModeDrawArraysIBM"
-- glMultiModeDrawElementsIBM --------------------------------------------------
glMultiModeDrawElementsIBM
:: MonadIO m
=> Ptr GLenum -- ^ @mode@ pointing to @COMPSIZE(primcount)@ elements of type [PrimitiveType](Graphics-GL-Groups.html#PrimitiveType).
-> Ptr GLsizei -- ^ @count@ pointing to @COMPSIZE(primcount)@ elements of type @GLsizei@.
-> GLenum -- ^ @type@ of type [DrawElementsType](Graphics-GL-Groups.html#DrawElementsType).
-> Ptr (Ptr a) -- ^ @indices@ pointing to @COMPSIZE(primcount)@ elements of type @Ptr a@.
-> GLsizei -- ^ @primcount@.
-> GLint -- ^ @modestride@.
-> m ()
glMultiModeDrawElementsIBM v1 v2 v3 v4 v5 v6 = liftIO $ dyn566 ptr_glMultiModeDrawElementsIBM v1 v2 v3 v4 v5 v6
{-# NOINLINE ptr_glMultiModeDrawElementsIBM #-}
ptr_glMultiModeDrawElementsIBM :: FunPtr (Ptr GLenum -> Ptr GLsizei -> GLenum -> Ptr (Ptr a) -> GLsizei -> GLint -> IO ())
ptr_glMultiModeDrawElementsIBM = unsafePerformIO $ getCommand "glMultiModeDrawElementsIBM"
-- glMultiTexBufferEXT ---------------------------------------------------------
glMultiTexBufferEXT
:: MonadIO m
=> GLenum -- ^ @texunit@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLenum -- ^ @target@ of type [TextureTarget](Graphics-GL-Groups.html#TextureTarget).
-> GLenum -- ^ @internalformat@.
-> GLuint -- ^ @buffer@.
-> m ()
glMultiTexBufferEXT v1 v2 v3 v4 = liftIO $ dyn296 ptr_glMultiTexBufferEXT v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexBufferEXT #-}
ptr_glMultiTexBufferEXT :: FunPtr (GLenum -> GLenum -> GLenum -> GLuint -> IO ())
ptr_glMultiTexBufferEXT = unsafePerformIO $ getCommand "glMultiTexBufferEXT"
-- glMultiTexCoord1bOES --------------------------------------------------------
glMultiTexCoord1bOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLbyte -- ^ @s@.
-> m ()
glMultiTexCoord1bOES v1 v2 = liftIO $ dyn567 ptr_glMultiTexCoord1bOES v1 v2
{-# NOINLINE ptr_glMultiTexCoord1bOES #-}
ptr_glMultiTexCoord1bOES :: FunPtr (GLenum -> GLbyte -> IO ())
ptr_glMultiTexCoord1bOES = unsafePerformIO $ getCommand "glMultiTexCoord1bOES"
-- glMultiTexCoord1bvOES -------------------------------------------------------
glMultiTexCoord1bvOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLbyte -- ^ @coords@ pointing to @1@ element of type @GLbyte@.
-> m ()
glMultiTexCoord1bvOES v1 v2 = liftIO $ dyn568 ptr_glMultiTexCoord1bvOES v1 v2
{-# NOINLINE ptr_glMultiTexCoord1bvOES #-}
ptr_glMultiTexCoord1bvOES :: FunPtr (GLenum -> Ptr GLbyte -> IO ())
ptr_glMultiTexCoord1bvOES = unsafePerformIO $ getCommand "glMultiTexCoord1bvOES"
-- glMultiTexCoord1d -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord1dv'.
glMultiTexCoord1d
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLdouble -- ^ @s@ of type @CoordD@.
-> m ()
glMultiTexCoord1d v1 v2 = liftIO $ dyn569 ptr_glMultiTexCoord1d v1 v2
{-# NOINLINE ptr_glMultiTexCoord1d #-}
ptr_glMultiTexCoord1d :: FunPtr (GLenum -> GLdouble -> IO ())
ptr_glMultiTexCoord1d = unsafePerformIO $ getCommand "glMultiTexCoord1d"
-- glMultiTexCoord1dARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord1dv'. This command is an alias for 'glMultiTexCoord1d'.
glMultiTexCoord1dARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLdouble -- ^ @s@ of type @CoordD@.
-> m ()
glMultiTexCoord1dARB v1 v2 = liftIO $ dyn569 ptr_glMultiTexCoord1dARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1dARB #-}
ptr_glMultiTexCoord1dARB :: FunPtr (GLenum -> GLdouble -> IO ())
ptr_glMultiTexCoord1dARB = unsafePerformIO $ getCommand "glMultiTexCoord1dARB"
-- glMultiTexCoord1dv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord1dv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLdouble -- ^ @v@ pointing to @1@ element of type @CoordD@.
-> m ()
glMultiTexCoord1dv v1 v2 = liftIO $ dyn100 ptr_glMultiTexCoord1dv v1 v2
{-# NOINLINE ptr_glMultiTexCoord1dv #-}
ptr_glMultiTexCoord1dv :: FunPtr (GLenum -> Ptr GLdouble -> IO ())
ptr_glMultiTexCoord1dv = unsafePerformIO $ getCommand "glMultiTexCoord1dv"
-- glMultiTexCoord1dvARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord1dv'.
glMultiTexCoord1dvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLdouble -- ^ @v@ pointing to @1@ element of type @CoordD@.
-> m ()
glMultiTexCoord1dvARB v1 v2 = liftIO $ dyn100 ptr_glMultiTexCoord1dvARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1dvARB #-}
ptr_glMultiTexCoord1dvARB :: FunPtr (GLenum -> Ptr GLdouble -> IO ())
ptr_glMultiTexCoord1dvARB = unsafePerformIO $ getCommand "glMultiTexCoord1dvARB"
-- glMultiTexCoord1f -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord1fv'.
glMultiTexCoord1f
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfloat -- ^ @s@ of type @CoordF@.
-> m ()
glMultiTexCoord1f v1 v2 = liftIO $ dyn0 ptr_glMultiTexCoord1f v1 v2
{-# NOINLINE ptr_glMultiTexCoord1f #-}
ptr_glMultiTexCoord1f :: FunPtr (GLenum -> GLfloat -> IO ())
ptr_glMultiTexCoord1f = unsafePerformIO $ getCommand "glMultiTexCoord1f"
-- glMultiTexCoord1fARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord1fv'. This command is an alias for 'glMultiTexCoord1f'.
glMultiTexCoord1fARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfloat -- ^ @s@ of type @CoordF@.
-> m ()
glMultiTexCoord1fARB v1 v2 = liftIO $ dyn0 ptr_glMultiTexCoord1fARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1fARB #-}
ptr_glMultiTexCoord1fARB :: FunPtr (GLenum -> GLfloat -> IO ())
ptr_glMultiTexCoord1fARB = unsafePerformIO $ getCommand "glMultiTexCoord1fARB"
-- glMultiTexCoord1fv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord1fv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfloat -- ^ @v@ pointing to @1@ element of type @CoordF@.
-> m ()
glMultiTexCoord1fv v1 v2 = liftIO $ dyn101 ptr_glMultiTexCoord1fv v1 v2
{-# NOINLINE ptr_glMultiTexCoord1fv #-}
ptr_glMultiTexCoord1fv :: FunPtr (GLenum -> Ptr GLfloat -> IO ())
ptr_glMultiTexCoord1fv = unsafePerformIO $ getCommand "glMultiTexCoord1fv"
-- glMultiTexCoord1fvARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord1fv'.
glMultiTexCoord1fvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfloat -- ^ @v@ pointing to @1@ element of type @CoordF@.
-> m ()
glMultiTexCoord1fvARB v1 v2 = liftIO $ dyn101 ptr_glMultiTexCoord1fvARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1fvARB #-}
ptr_glMultiTexCoord1fvARB :: FunPtr (GLenum -> Ptr GLfloat -> IO ())
ptr_glMultiTexCoord1fvARB = unsafePerformIO $ getCommand "glMultiTexCoord1fvARB"
-- glMultiTexCoord1hNV ---------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord1hvNV'.
glMultiTexCoord1hNV
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLhalfNV -- ^ @s@ of type @Half16NV@.
-> m ()
glMultiTexCoord1hNV v1 v2 = liftIO $ dyn570 ptr_glMultiTexCoord1hNV v1 v2
{-# NOINLINE ptr_glMultiTexCoord1hNV #-}
ptr_glMultiTexCoord1hNV :: FunPtr (GLenum -> GLhalfNV -> IO ())
ptr_glMultiTexCoord1hNV = unsafePerformIO $ getCommand "glMultiTexCoord1hNV"
-- glMultiTexCoord1hvNV --------------------------------------------------------
glMultiTexCoord1hvNV
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLhalfNV -- ^ @v@ pointing to @1@ element of type @Half16NV@.
-> m ()
glMultiTexCoord1hvNV v1 v2 = liftIO $ dyn571 ptr_glMultiTexCoord1hvNV v1 v2
{-# NOINLINE ptr_glMultiTexCoord1hvNV #-}
ptr_glMultiTexCoord1hvNV :: FunPtr (GLenum -> Ptr GLhalfNV -> IO ())
ptr_glMultiTexCoord1hvNV = unsafePerformIO $ getCommand "glMultiTexCoord1hvNV"
-- glMultiTexCoord1i -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord1iv'.
glMultiTexCoord1i
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLint -- ^ @s@ of type @CoordI@.
-> m ()
glMultiTexCoord1i v1 v2 = liftIO $ dyn58 ptr_glMultiTexCoord1i v1 v2
{-# NOINLINE ptr_glMultiTexCoord1i #-}
ptr_glMultiTexCoord1i :: FunPtr (GLenum -> GLint -> IO ())
ptr_glMultiTexCoord1i = unsafePerformIO $ getCommand "glMultiTexCoord1i"
-- glMultiTexCoord1iARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord1iv'. This command is an alias for 'glMultiTexCoord1i'.
glMultiTexCoord1iARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLint -- ^ @s@ of type @CoordI@.
-> m ()
glMultiTexCoord1iARB v1 v2 = liftIO $ dyn58 ptr_glMultiTexCoord1iARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1iARB #-}
ptr_glMultiTexCoord1iARB :: FunPtr (GLenum -> GLint -> IO ())
ptr_glMultiTexCoord1iARB = unsafePerformIO $ getCommand "glMultiTexCoord1iARB"
-- glMultiTexCoord1iv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord1iv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLint -- ^ @v@ pointing to @1@ element of type @CoordI@.
-> m ()
glMultiTexCoord1iv v1 v2 = liftIO $ dyn143 ptr_glMultiTexCoord1iv v1 v2
{-# NOINLINE ptr_glMultiTexCoord1iv #-}
ptr_glMultiTexCoord1iv :: FunPtr (GLenum -> Ptr GLint -> IO ())
ptr_glMultiTexCoord1iv = unsafePerformIO $ getCommand "glMultiTexCoord1iv"
-- glMultiTexCoord1ivARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord1iv'.
glMultiTexCoord1ivARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLint -- ^ @v@ pointing to @1@ element of type @CoordI@.
-> m ()
glMultiTexCoord1ivARB v1 v2 = liftIO $ dyn143 ptr_glMultiTexCoord1ivARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1ivARB #-}
ptr_glMultiTexCoord1ivARB :: FunPtr (GLenum -> Ptr GLint -> IO ())
ptr_glMultiTexCoord1ivARB = unsafePerformIO $ getCommand "glMultiTexCoord1ivARB"
-- glMultiTexCoord1s -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord1sv'.
glMultiTexCoord1s
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLshort -- ^ @s@ of type @CoordS@.
-> m ()
glMultiTexCoord1s v1 v2 = liftIO $ dyn572 ptr_glMultiTexCoord1s v1 v2
{-# NOINLINE ptr_glMultiTexCoord1s #-}
ptr_glMultiTexCoord1s :: FunPtr (GLenum -> GLshort -> IO ())
ptr_glMultiTexCoord1s = unsafePerformIO $ getCommand "glMultiTexCoord1s"
-- glMultiTexCoord1sARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord1sv'. This command is an alias for 'glMultiTexCoord1s'.
glMultiTexCoord1sARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLshort -- ^ @s@ of type @CoordS@.
-> m ()
glMultiTexCoord1sARB v1 v2 = liftIO $ dyn572 ptr_glMultiTexCoord1sARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1sARB #-}
ptr_glMultiTexCoord1sARB :: FunPtr (GLenum -> GLshort -> IO ())
ptr_glMultiTexCoord1sARB = unsafePerformIO $ getCommand "glMultiTexCoord1sARB"
-- glMultiTexCoord1sv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord1sv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLshort -- ^ @v@ pointing to @1@ element of type @CoordS@.
-> m ()
glMultiTexCoord1sv v1 v2 = liftIO $ dyn573 ptr_glMultiTexCoord1sv v1 v2
{-# NOINLINE ptr_glMultiTexCoord1sv #-}
ptr_glMultiTexCoord1sv :: FunPtr (GLenum -> Ptr GLshort -> IO ())
ptr_glMultiTexCoord1sv = unsafePerformIO $ getCommand "glMultiTexCoord1sv"
-- glMultiTexCoord1svARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord1sv'.
glMultiTexCoord1svARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLshort -- ^ @v@ pointing to @1@ element of type @CoordS@.
-> m ()
glMultiTexCoord1svARB v1 v2 = liftIO $ dyn573 ptr_glMultiTexCoord1svARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord1svARB #-}
ptr_glMultiTexCoord1svARB :: FunPtr (GLenum -> Ptr GLshort -> IO ())
ptr_glMultiTexCoord1svARB = unsafePerformIO $ getCommand "glMultiTexCoord1svARB"
-- glMultiTexCoord1xOES --------------------------------------------------------
glMultiTexCoord1xOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfixed -- ^ @s@.
-> m ()
glMultiTexCoord1xOES v1 v2 = liftIO $ dyn1 ptr_glMultiTexCoord1xOES v1 v2
{-# NOINLINE ptr_glMultiTexCoord1xOES #-}
ptr_glMultiTexCoord1xOES :: FunPtr (GLenum -> GLfixed -> IO ())
ptr_glMultiTexCoord1xOES = unsafePerformIO $ getCommand "glMultiTexCoord1xOES"
-- glMultiTexCoord1xvOES -------------------------------------------------------
glMultiTexCoord1xvOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfixed -- ^ @coords@ pointing to @1@ element of type @GLfixed@.
-> m ()
glMultiTexCoord1xvOES v1 v2 = liftIO $ dyn102 ptr_glMultiTexCoord1xvOES v1 v2
{-# NOINLINE ptr_glMultiTexCoord1xvOES #-}
ptr_glMultiTexCoord1xvOES :: FunPtr (GLenum -> Ptr GLfixed -> IO ())
ptr_glMultiTexCoord1xvOES = unsafePerformIO $ getCommand "glMultiTexCoord1xvOES"
-- glMultiTexCoord2bOES --------------------------------------------------------
glMultiTexCoord2bOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLbyte -- ^ @s@.
-> GLbyte -- ^ @t@.
-> m ()
glMultiTexCoord2bOES v1 v2 v3 = liftIO $ dyn574 ptr_glMultiTexCoord2bOES v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2bOES #-}
ptr_glMultiTexCoord2bOES :: FunPtr (GLenum -> GLbyte -> GLbyte -> IO ())
ptr_glMultiTexCoord2bOES = unsafePerformIO $ getCommand "glMultiTexCoord2bOES"
-- glMultiTexCoord2bvOES -------------------------------------------------------
glMultiTexCoord2bvOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLbyte -- ^ @coords@ pointing to @2@ elements of type @GLbyte@.
-> m ()
glMultiTexCoord2bvOES v1 v2 = liftIO $ dyn568 ptr_glMultiTexCoord2bvOES v1 v2
{-# NOINLINE ptr_glMultiTexCoord2bvOES #-}
ptr_glMultiTexCoord2bvOES :: FunPtr (GLenum -> Ptr GLbyte -> IO ())
ptr_glMultiTexCoord2bvOES = unsafePerformIO $ getCommand "glMultiTexCoord2bvOES"
-- glMultiTexCoord2d -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord2dv'.
glMultiTexCoord2d
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLdouble -- ^ @s@ of type @CoordD@.
-> GLdouble -- ^ @t@ of type @CoordD@.
-> m ()
glMultiTexCoord2d v1 v2 v3 = liftIO $ dyn575 ptr_glMultiTexCoord2d v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2d #-}
ptr_glMultiTexCoord2d :: FunPtr (GLenum -> GLdouble -> GLdouble -> IO ())
ptr_glMultiTexCoord2d = unsafePerformIO $ getCommand "glMultiTexCoord2d"
-- glMultiTexCoord2dARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord2dv'. This command is an alias for 'glMultiTexCoord2d'.
glMultiTexCoord2dARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLdouble -- ^ @s@ of type @CoordD@.
-> GLdouble -- ^ @t@ of type @CoordD@.
-> m ()
glMultiTexCoord2dARB v1 v2 v3 = liftIO $ dyn575 ptr_glMultiTexCoord2dARB v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2dARB #-}
ptr_glMultiTexCoord2dARB :: FunPtr (GLenum -> GLdouble -> GLdouble -> IO ())
ptr_glMultiTexCoord2dARB = unsafePerformIO $ getCommand "glMultiTexCoord2dARB"
-- glMultiTexCoord2dv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord2dv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLdouble -- ^ @v@ pointing to @2@ elements of type @CoordD@.
-> m ()
glMultiTexCoord2dv v1 v2 = liftIO $ dyn100 ptr_glMultiTexCoord2dv v1 v2
{-# NOINLINE ptr_glMultiTexCoord2dv #-}
ptr_glMultiTexCoord2dv :: FunPtr (GLenum -> Ptr GLdouble -> IO ())
ptr_glMultiTexCoord2dv = unsafePerformIO $ getCommand "glMultiTexCoord2dv"
-- glMultiTexCoord2dvARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord2dv'.
glMultiTexCoord2dvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLdouble -- ^ @v@ pointing to @2@ elements of type @CoordD@.
-> m ()
glMultiTexCoord2dvARB v1 v2 = liftIO $ dyn100 ptr_glMultiTexCoord2dvARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord2dvARB #-}
ptr_glMultiTexCoord2dvARB :: FunPtr (GLenum -> Ptr GLdouble -> IO ())
ptr_glMultiTexCoord2dvARB = unsafePerformIO $ getCommand "glMultiTexCoord2dvARB"
-- glMultiTexCoord2f -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord2fv'.
glMultiTexCoord2f
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfloat -- ^ @s@ of type @CoordF@.
-> GLfloat -- ^ @t@ of type @CoordF@.
-> m ()
glMultiTexCoord2f v1 v2 v3 = liftIO $ dyn576 ptr_glMultiTexCoord2f v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2f #-}
ptr_glMultiTexCoord2f :: FunPtr (GLenum -> GLfloat -> GLfloat -> IO ())
ptr_glMultiTexCoord2f = unsafePerformIO $ getCommand "glMultiTexCoord2f"
-- glMultiTexCoord2fARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord2fv'. This command is an alias for 'glMultiTexCoord2f'.
glMultiTexCoord2fARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfloat -- ^ @s@ of type @CoordF@.
-> GLfloat -- ^ @t@ of type @CoordF@.
-> m ()
glMultiTexCoord2fARB v1 v2 v3 = liftIO $ dyn576 ptr_glMultiTexCoord2fARB v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2fARB #-}
ptr_glMultiTexCoord2fARB :: FunPtr (GLenum -> GLfloat -> GLfloat -> IO ())
ptr_glMultiTexCoord2fARB = unsafePerformIO $ getCommand "glMultiTexCoord2fARB"
-- glMultiTexCoord2fv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord2fv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfloat -- ^ @v@ pointing to @2@ elements of type @CoordF@.
-> m ()
glMultiTexCoord2fv v1 v2 = liftIO $ dyn101 ptr_glMultiTexCoord2fv v1 v2
{-# NOINLINE ptr_glMultiTexCoord2fv #-}
ptr_glMultiTexCoord2fv :: FunPtr (GLenum -> Ptr GLfloat -> IO ())
ptr_glMultiTexCoord2fv = unsafePerformIO $ getCommand "glMultiTexCoord2fv"
-- glMultiTexCoord2fvARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord2fv'.
glMultiTexCoord2fvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfloat -- ^ @v@ pointing to @2@ elements of type @CoordF@.
-> m ()
glMultiTexCoord2fvARB v1 v2 = liftIO $ dyn101 ptr_glMultiTexCoord2fvARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord2fvARB #-}
ptr_glMultiTexCoord2fvARB :: FunPtr (GLenum -> Ptr GLfloat -> IO ())
ptr_glMultiTexCoord2fvARB = unsafePerformIO $ getCommand "glMultiTexCoord2fvARB"
-- glMultiTexCoord2hNV ---------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord2hvNV'.
glMultiTexCoord2hNV
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLhalfNV -- ^ @s@ of type @Half16NV@.
-> GLhalfNV -- ^ @t@ of type @Half16NV@.
-> m ()
glMultiTexCoord2hNV v1 v2 v3 = liftIO $ dyn577 ptr_glMultiTexCoord2hNV v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2hNV #-}
ptr_glMultiTexCoord2hNV :: FunPtr (GLenum -> GLhalfNV -> GLhalfNV -> IO ())
ptr_glMultiTexCoord2hNV = unsafePerformIO $ getCommand "glMultiTexCoord2hNV"
-- glMultiTexCoord2hvNV --------------------------------------------------------
glMultiTexCoord2hvNV
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLhalfNV -- ^ @v@ pointing to @2@ elements of type @Half16NV@.
-> m ()
glMultiTexCoord2hvNV v1 v2 = liftIO $ dyn571 ptr_glMultiTexCoord2hvNV v1 v2
{-# NOINLINE ptr_glMultiTexCoord2hvNV #-}
ptr_glMultiTexCoord2hvNV :: FunPtr (GLenum -> Ptr GLhalfNV -> IO ())
ptr_glMultiTexCoord2hvNV = unsafePerformIO $ getCommand "glMultiTexCoord2hvNV"
-- glMultiTexCoord2i -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord2iv'.
glMultiTexCoord2i
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLint -- ^ @s@ of type @CoordI@.
-> GLint -- ^ @t@ of type @CoordI@.
-> m ()
glMultiTexCoord2i v1 v2 v3 = liftIO $ dyn275 ptr_glMultiTexCoord2i v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2i #-}
ptr_glMultiTexCoord2i :: FunPtr (GLenum -> GLint -> GLint -> IO ())
ptr_glMultiTexCoord2i = unsafePerformIO $ getCommand "glMultiTexCoord2i"
-- glMultiTexCoord2iARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord2iv'. This command is an alias for 'glMultiTexCoord2i'.
glMultiTexCoord2iARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLint -- ^ @s@ of type @CoordI@.
-> GLint -- ^ @t@ of type @CoordI@.
-> m ()
glMultiTexCoord2iARB v1 v2 v3 = liftIO $ dyn275 ptr_glMultiTexCoord2iARB v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2iARB #-}
ptr_glMultiTexCoord2iARB :: FunPtr (GLenum -> GLint -> GLint -> IO ())
ptr_glMultiTexCoord2iARB = unsafePerformIO $ getCommand "glMultiTexCoord2iARB"
-- glMultiTexCoord2iv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord2iv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLint -- ^ @v@ pointing to @2@ elements of type @CoordI@.
-> m ()
glMultiTexCoord2iv v1 v2 = liftIO $ dyn143 ptr_glMultiTexCoord2iv v1 v2
{-# NOINLINE ptr_glMultiTexCoord2iv #-}
ptr_glMultiTexCoord2iv :: FunPtr (GLenum -> Ptr GLint -> IO ())
ptr_glMultiTexCoord2iv = unsafePerformIO $ getCommand "glMultiTexCoord2iv"
-- glMultiTexCoord2ivARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord2iv'.
glMultiTexCoord2ivARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLint -- ^ @v@ pointing to @2@ elements of type @CoordI@.
-> m ()
glMultiTexCoord2ivARB v1 v2 = liftIO $ dyn143 ptr_glMultiTexCoord2ivARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord2ivARB #-}
ptr_glMultiTexCoord2ivARB :: FunPtr (GLenum -> Ptr GLint -> IO ())
ptr_glMultiTexCoord2ivARB = unsafePerformIO $ getCommand "glMultiTexCoord2ivARB"
-- glMultiTexCoord2s -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord2sv'.
glMultiTexCoord2s
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLshort -- ^ @s@ of type @CoordS@.
-> GLshort -- ^ @t@ of type @CoordS@.
-> m ()
glMultiTexCoord2s v1 v2 v3 = liftIO $ dyn578 ptr_glMultiTexCoord2s v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2s #-}
ptr_glMultiTexCoord2s :: FunPtr (GLenum -> GLshort -> GLshort -> IO ())
ptr_glMultiTexCoord2s = unsafePerformIO $ getCommand "glMultiTexCoord2s"
-- glMultiTexCoord2sARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord2sv'. This command is an alias for 'glMultiTexCoord2s'.
glMultiTexCoord2sARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLshort -- ^ @s@ of type @CoordS@.
-> GLshort -- ^ @t@ of type @CoordS@.
-> m ()
glMultiTexCoord2sARB v1 v2 v3 = liftIO $ dyn578 ptr_glMultiTexCoord2sARB v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2sARB #-}
ptr_glMultiTexCoord2sARB :: FunPtr (GLenum -> GLshort -> GLshort -> IO ())
ptr_glMultiTexCoord2sARB = unsafePerformIO $ getCommand "glMultiTexCoord2sARB"
-- glMultiTexCoord2sv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord2sv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLshort -- ^ @v@ pointing to @2@ elements of type @CoordS@.
-> m ()
glMultiTexCoord2sv v1 v2 = liftIO $ dyn573 ptr_glMultiTexCoord2sv v1 v2
{-# NOINLINE ptr_glMultiTexCoord2sv #-}
ptr_glMultiTexCoord2sv :: FunPtr (GLenum -> Ptr GLshort -> IO ())
ptr_glMultiTexCoord2sv = unsafePerformIO $ getCommand "glMultiTexCoord2sv"
-- glMultiTexCoord2svARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord2sv'.
glMultiTexCoord2svARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLshort -- ^ @v@ pointing to @2@ elements of type @CoordS@.
-> m ()
glMultiTexCoord2svARB v1 v2 = liftIO $ dyn573 ptr_glMultiTexCoord2svARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord2svARB #-}
ptr_glMultiTexCoord2svARB :: FunPtr (GLenum -> Ptr GLshort -> IO ())
ptr_glMultiTexCoord2svARB = unsafePerformIO $ getCommand "glMultiTexCoord2svARB"
-- glMultiTexCoord2xOES --------------------------------------------------------
glMultiTexCoord2xOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfixed -- ^ @s@.
-> GLfixed -- ^ @t@.
-> m ()
glMultiTexCoord2xOES v1 v2 v3 = liftIO $ dyn579 ptr_glMultiTexCoord2xOES v1 v2 v3
{-# NOINLINE ptr_glMultiTexCoord2xOES #-}
ptr_glMultiTexCoord2xOES :: FunPtr (GLenum -> GLfixed -> GLfixed -> IO ())
ptr_glMultiTexCoord2xOES = unsafePerformIO $ getCommand "glMultiTexCoord2xOES"
-- glMultiTexCoord2xvOES -------------------------------------------------------
glMultiTexCoord2xvOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfixed -- ^ @coords@ pointing to @2@ elements of type @GLfixed@.
-> m ()
glMultiTexCoord2xvOES v1 v2 = liftIO $ dyn102 ptr_glMultiTexCoord2xvOES v1 v2
{-# NOINLINE ptr_glMultiTexCoord2xvOES #-}
ptr_glMultiTexCoord2xvOES :: FunPtr (GLenum -> Ptr GLfixed -> IO ())
ptr_glMultiTexCoord2xvOES = unsafePerformIO $ getCommand "glMultiTexCoord2xvOES"
-- glMultiTexCoord3bOES --------------------------------------------------------
glMultiTexCoord3bOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLbyte -- ^ @s@.
-> GLbyte -- ^ @t@.
-> GLbyte -- ^ @r@.
-> m ()
glMultiTexCoord3bOES v1 v2 v3 v4 = liftIO $ dyn580 ptr_glMultiTexCoord3bOES v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3bOES #-}
ptr_glMultiTexCoord3bOES :: FunPtr (GLenum -> GLbyte -> GLbyte -> GLbyte -> IO ())
ptr_glMultiTexCoord3bOES = unsafePerformIO $ getCommand "glMultiTexCoord3bOES"
-- glMultiTexCoord3bvOES -------------------------------------------------------
glMultiTexCoord3bvOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLbyte -- ^ @coords@ pointing to @3@ elements of type @GLbyte@.
-> m ()
glMultiTexCoord3bvOES v1 v2 = liftIO $ dyn568 ptr_glMultiTexCoord3bvOES v1 v2
{-# NOINLINE ptr_glMultiTexCoord3bvOES #-}
ptr_glMultiTexCoord3bvOES :: FunPtr (GLenum -> Ptr GLbyte -> IO ())
ptr_glMultiTexCoord3bvOES = unsafePerformIO $ getCommand "glMultiTexCoord3bvOES"
-- glMultiTexCoord3d -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord3dv'.
glMultiTexCoord3d
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLdouble -- ^ @s@ of type @CoordD@.
-> GLdouble -- ^ @t@ of type @CoordD@.
-> GLdouble -- ^ @r@ of type @CoordD@.
-> m ()
glMultiTexCoord3d v1 v2 v3 v4 = liftIO $ dyn548 ptr_glMultiTexCoord3d v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3d #-}
ptr_glMultiTexCoord3d :: FunPtr (GLenum -> GLdouble -> GLdouble -> GLdouble -> IO ())
ptr_glMultiTexCoord3d = unsafePerformIO $ getCommand "glMultiTexCoord3d"
-- glMultiTexCoord3dARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord3dv'. This command is an alias for 'glMultiTexCoord3d'.
glMultiTexCoord3dARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLdouble -- ^ @s@ of type @CoordD@.
-> GLdouble -- ^ @t@ of type @CoordD@.
-> GLdouble -- ^ @r@ of type @CoordD@.
-> m ()
glMultiTexCoord3dARB v1 v2 v3 v4 = liftIO $ dyn548 ptr_glMultiTexCoord3dARB v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3dARB #-}
ptr_glMultiTexCoord3dARB :: FunPtr (GLenum -> GLdouble -> GLdouble -> GLdouble -> IO ())
ptr_glMultiTexCoord3dARB = unsafePerformIO $ getCommand "glMultiTexCoord3dARB"
-- glMultiTexCoord3dv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord3dv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLdouble -- ^ @v@ pointing to @3@ elements of type @CoordD@.
-> m ()
glMultiTexCoord3dv v1 v2 = liftIO $ dyn100 ptr_glMultiTexCoord3dv v1 v2
{-# NOINLINE ptr_glMultiTexCoord3dv #-}
ptr_glMultiTexCoord3dv :: FunPtr (GLenum -> Ptr GLdouble -> IO ())
ptr_glMultiTexCoord3dv = unsafePerformIO $ getCommand "glMultiTexCoord3dv"
-- glMultiTexCoord3dvARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord3dv'.
glMultiTexCoord3dvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLdouble -- ^ @v@ pointing to @3@ elements of type @CoordD@.
-> m ()
glMultiTexCoord3dvARB v1 v2 = liftIO $ dyn100 ptr_glMultiTexCoord3dvARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord3dvARB #-}
ptr_glMultiTexCoord3dvARB :: FunPtr (GLenum -> Ptr GLdouble -> IO ())
ptr_glMultiTexCoord3dvARB = unsafePerformIO $ getCommand "glMultiTexCoord3dvARB"
-- glMultiTexCoord3f -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord3fv'.
glMultiTexCoord3f
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfloat -- ^ @s@ of type @CoordF@.
-> GLfloat -- ^ @t@ of type @CoordF@.
-> GLfloat -- ^ @r@ of type @CoordF@.
-> m ()
glMultiTexCoord3f v1 v2 v3 v4 = liftIO $ dyn549 ptr_glMultiTexCoord3f v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3f #-}
ptr_glMultiTexCoord3f :: FunPtr (GLenum -> GLfloat -> GLfloat -> GLfloat -> IO ())
ptr_glMultiTexCoord3f = unsafePerformIO $ getCommand "glMultiTexCoord3f"
-- glMultiTexCoord3fARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord3fv'. This command is an alias for 'glMultiTexCoord3f'.
glMultiTexCoord3fARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfloat -- ^ @s@ of type @CoordF@.
-> GLfloat -- ^ @t@ of type @CoordF@.
-> GLfloat -- ^ @r@ of type @CoordF@.
-> m ()
glMultiTexCoord3fARB v1 v2 v3 v4 = liftIO $ dyn549 ptr_glMultiTexCoord3fARB v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3fARB #-}
ptr_glMultiTexCoord3fARB :: FunPtr (GLenum -> GLfloat -> GLfloat -> GLfloat -> IO ())
ptr_glMultiTexCoord3fARB = unsafePerformIO $ getCommand "glMultiTexCoord3fARB"
-- glMultiTexCoord3fv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord3fv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfloat -- ^ @v@ pointing to @3@ elements of type @CoordF@.
-> m ()
glMultiTexCoord3fv v1 v2 = liftIO $ dyn101 ptr_glMultiTexCoord3fv v1 v2
{-# NOINLINE ptr_glMultiTexCoord3fv #-}
ptr_glMultiTexCoord3fv :: FunPtr (GLenum -> Ptr GLfloat -> IO ())
ptr_glMultiTexCoord3fv = unsafePerformIO $ getCommand "glMultiTexCoord3fv"
-- glMultiTexCoord3fvARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord3fv'.
glMultiTexCoord3fvARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLfloat -- ^ @v@ pointing to @3@ elements of type @CoordF@.
-> m ()
glMultiTexCoord3fvARB v1 v2 = liftIO $ dyn101 ptr_glMultiTexCoord3fvARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord3fvARB #-}
ptr_glMultiTexCoord3fvARB :: FunPtr (GLenum -> Ptr GLfloat -> IO ())
ptr_glMultiTexCoord3fvARB = unsafePerformIO $ getCommand "glMultiTexCoord3fvARB"
-- glMultiTexCoord3hNV ---------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord3hvNV'.
glMultiTexCoord3hNV
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLhalfNV -- ^ @s@ of type @Half16NV@.
-> GLhalfNV -- ^ @t@ of type @Half16NV@.
-> GLhalfNV -- ^ @r@ of type @Half16NV@.
-> m ()
glMultiTexCoord3hNV v1 v2 v3 v4 = liftIO $ dyn581 ptr_glMultiTexCoord3hNV v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3hNV #-}
ptr_glMultiTexCoord3hNV :: FunPtr (GLenum -> GLhalfNV -> GLhalfNV -> GLhalfNV -> IO ())
ptr_glMultiTexCoord3hNV = unsafePerformIO $ getCommand "glMultiTexCoord3hNV"
-- glMultiTexCoord3hvNV --------------------------------------------------------
glMultiTexCoord3hvNV
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLhalfNV -- ^ @v@ pointing to @3@ elements of type @Half16NV@.
-> m ()
glMultiTexCoord3hvNV v1 v2 = liftIO $ dyn571 ptr_glMultiTexCoord3hvNV v1 v2
{-# NOINLINE ptr_glMultiTexCoord3hvNV #-}
ptr_glMultiTexCoord3hvNV :: FunPtr (GLenum -> Ptr GLhalfNV -> IO ())
ptr_glMultiTexCoord3hvNV = unsafePerformIO $ getCommand "glMultiTexCoord3hvNV"
-- glMultiTexCoord3i -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord3iv'.
glMultiTexCoord3i
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLint -- ^ @s@ of type @CoordI@.
-> GLint -- ^ @t@ of type @CoordI@.
-> GLint -- ^ @r@ of type @CoordI@.
-> m ()
glMultiTexCoord3i v1 v2 v3 v4 = liftIO $ dyn582 ptr_glMultiTexCoord3i v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3i #-}
ptr_glMultiTexCoord3i :: FunPtr (GLenum -> GLint -> GLint -> GLint -> IO ())
ptr_glMultiTexCoord3i = unsafePerformIO $ getCommand "glMultiTexCoord3i"
-- glMultiTexCoord3iARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord3iv'. This command is an alias for 'glMultiTexCoord3i'.
glMultiTexCoord3iARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLint -- ^ @s@ of type @CoordI@.
-> GLint -- ^ @t@ of type @CoordI@.
-> GLint -- ^ @r@ of type @CoordI@.
-> m ()
glMultiTexCoord3iARB v1 v2 v3 v4 = liftIO $ dyn582 ptr_glMultiTexCoord3iARB v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3iARB #-}
ptr_glMultiTexCoord3iARB :: FunPtr (GLenum -> GLint -> GLint -> GLint -> IO ())
ptr_glMultiTexCoord3iARB = unsafePerformIO $ getCommand "glMultiTexCoord3iARB"
-- glMultiTexCoord3iv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord3iv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLint -- ^ @v@ pointing to @3@ elements of type @CoordI@.
-> m ()
glMultiTexCoord3iv v1 v2 = liftIO $ dyn143 ptr_glMultiTexCoord3iv v1 v2
{-# NOINLINE ptr_glMultiTexCoord3iv #-}
ptr_glMultiTexCoord3iv :: FunPtr (GLenum -> Ptr GLint -> IO ())
ptr_glMultiTexCoord3iv = unsafePerformIO $ getCommand "glMultiTexCoord3iv"
-- glMultiTexCoord3ivARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord3iv'.
glMultiTexCoord3ivARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLint -- ^ @v@ pointing to @3@ elements of type @CoordI@.
-> m ()
glMultiTexCoord3ivARB v1 v2 = liftIO $ dyn143 ptr_glMultiTexCoord3ivARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord3ivARB #-}
ptr_glMultiTexCoord3ivARB :: FunPtr (GLenum -> Ptr GLint -> IO ())
ptr_glMultiTexCoord3ivARB = unsafePerformIO $ getCommand "glMultiTexCoord3ivARB"
-- glMultiTexCoord3s -----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>. The vector equivalent of this command is 'glMultiTexCoord3sv'.
glMultiTexCoord3s
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLshort -- ^ @s@ of type @CoordS@.
-> GLshort -- ^ @t@ of type @CoordS@.
-> GLshort -- ^ @r@ of type @CoordS@.
-> m ()
glMultiTexCoord3s v1 v2 v3 v4 = liftIO $ dyn583 ptr_glMultiTexCoord3s v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3s #-}
ptr_glMultiTexCoord3s :: FunPtr (GLenum -> GLshort -> GLshort -> GLshort -> IO ())
ptr_glMultiTexCoord3s = unsafePerformIO $ getCommand "glMultiTexCoord3s"
-- glMultiTexCoord3sARB --------------------------------------------------------
-- | The vector equivalent of this command is 'glMultiTexCoord3sv'. This command is an alias for 'glMultiTexCoord3s'.
glMultiTexCoord3sARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLshort -- ^ @s@ of type @CoordS@.
-> GLshort -- ^ @t@ of type @CoordS@.
-> GLshort -- ^ @r@ of type @CoordS@.
-> m ()
glMultiTexCoord3sARB v1 v2 v3 v4 = liftIO $ dyn583 ptr_glMultiTexCoord3sARB v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3sARB #-}
ptr_glMultiTexCoord3sARB :: FunPtr (GLenum -> GLshort -> GLshort -> GLshort -> IO ())
ptr_glMultiTexCoord3sARB = unsafePerformIO $ getCommand "glMultiTexCoord3sARB"
-- glMultiTexCoord3sv ----------------------------------------------------------
-- | Manual page for <https://www.opengl.org/sdk/docs/man2/xhtml/glMultiTexCoord.xml OpenGL 2.x>.
glMultiTexCoord3sv
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLshort -- ^ @v@ pointing to @3@ elements of type @CoordS@.
-> m ()
glMultiTexCoord3sv v1 v2 = liftIO $ dyn573 ptr_glMultiTexCoord3sv v1 v2
{-# NOINLINE ptr_glMultiTexCoord3sv #-}
ptr_glMultiTexCoord3sv :: FunPtr (GLenum -> Ptr GLshort -> IO ())
ptr_glMultiTexCoord3sv = unsafePerformIO $ getCommand "glMultiTexCoord3sv"
-- glMultiTexCoord3svARB -------------------------------------------------------
-- | This command is an alias for 'glMultiTexCoord3sv'.
glMultiTexCoord3svARB
:: MonadIO m
=> GLenum -- ^ @target@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> Ptr GLshort -- ^ @v@ pointing to @3@ elements of type @CoordS@.
-> m ()
glMultiTexCoord3svARB v1 v2 = liftIO $ dyn573 ptr_glMultiTexCoord3svARB v1 v2
{-# NOINLINE ptr_glMultiTexCoord3svARB #-}
ptr_glMultiTexCoord3svARB :: FunPtr (GLenum -> Ptr GLshort -> IO ())
ptr_glMultiTexCoord3svARB = unsafePerformIO $ getCommand "glMultiTexCoord3svARB"
-- glMultiTexCoord3xOES --------------------------------------------------------
glMultiTexCoord3xOES
:: MonadIO m
=> GLenum -- ^ @texture@ of type [TextureUnit](Graphics-GL-Groups.html#TextureUnit).
-> GLfixed -- ^ @s@.
-> GLfixed -- ^ @t@.
-> GLfixed -- ^ @r@.
-> m ()
glMultiTexCoord3xOES v1 v2 v3 v4 = liftIO $ dyn584 ptr_glMultiTexCoord3xOES v1 v2 v3 v4
{-# NOINLINE ptr_glMultiTexCoord3xOES #-}
ptr_glMultiTexCoord3xOES :: FunPtr (GLenum -> GLfixed -> GLfixed -> GLfixed -> IO ())
ptr_glMultiTexCoord3xOES = unsafePerformIO $ getCommand "glMultiTexCoord3xOES"
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/Functions/F17.hs
|
bsd-3-clause
| 71,974 | 0 | 15 | 9,484 | 10,945 | 5,649 | 5,296 | 1,113 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Celebrating the release of the 4chan API at https://github.com/4chan/4chan-API
-- One bug in the API documentation is that 'tim' is optional.
module FourChan
( thread
, threadT
, threadV
, threadP
, Post(..)
)
where
-- Imports:
import Data.Aeson as A
import Network.HTTP.Conduit
import Control.Exception as X
import Data.ByteString.Lazy hiding (putStrLn, map)
import Control.Applicative
import Control.Monad
-- Exported Functions:
thread :: (ByteString -> Maybe a) -> Board -> Thread -> IO (Maybe a)
thread f board threadid = flip X.catch errorCase $ fmap f $ simpleHttp ("http://api.4chan.org/" ++ board ++ "/res/" ++ threadid ++ ".json")
where
errorCase :: HttpException -> IO (Maybe a)
errorCase = return $ return Nothing
threadT :: Board -> Thread -> IO (Maybe ByteString)
threadT b t = thread Just b t
threadV :: Board -> Thread -> IO (Maybe Value)
threadV b t = thread decode b t
threadP :: Board -> Thread -> IO (Maybe [Post])
threadP b t = fmap (fmap unTop) $ thread decode b t
-- Type Synonyms:
type Board = String
type Thread = String
-- Instances:
instance FromJSON Top where
parseJSON (Object t) = Top <$> t .: "posts"
parseJSON _ = mzero
instance FromJSON Post where
parseJSON (Object p) = parsePost p
parseJSON _ = mzero
-- Data Types:
data Top = Top { unTop :: [ Post ] } deriving Show
data Post = Post { post_no :: Integer
, post_resto :: Integer
, post_sticky :: Maybe Integer
, post_closed :: Maybe Integer
, post_now :: String
, post_time :: Integer
, post_name :: String
, post_trip :: Maybe String
, post_id :: Maybe String
, post_capcode :: Maybe String
, post_country :: Maybe String
, post_country_name :: Maybe String
, post_email :: Maybe String
, post_sub :: Maybe String
, post_com :: Maybe String
, post_tim :: Maybe Integer
, post_filename :: Maybe String
, post_ext :: Maybe String
, post_fsize :: Maybe Integer
, post_md5 :: Maybe String
, post_w :: Maybe Integer
, post_h :: Maybe Integer
, post_tn_w :: Maybe Integer
, post_tn_h :: Maybe Integer
, post_filedeleted :: Maybe Integer
, post_spoiler :: Maybe Integer
}
deriving Show
-- Helpers:
parsePost p = Post <$> p .: "no"
<*> p .: "resto"
<*> p .:? "sticky"
<*> p .:? "closed"
<*> p .: "now"
<*> p .: "time"
<*> p .: "name"
<*> p .:? "trip"
<*> p .:? "id"
<*> p .:? "capcode"
<*> p .:? "country"
<*> p .:? "country_name"
<*> p .:? "email"
<*> p .:? "sub"
<*> p .:? "com"
<*> p .:? "tim"
<*> p .:? "filename"
<*> p .:? "ext"
<*> p .:? "fsize"
<*> p .:? "md5"
<*> p .:? "w"
<*> p .:? "h"
<*> p .:? "tn_w"
<*> p .:? "tn_h"
<*> p .:? "filedeleted"
<*> p .:? "spoiler"
|
sordina/fourchan
|
FourChan.hs
|
bsd-3-clause
| 3,799 | 0 | 56 | 1,680 | 883 | 476 | 407 | 85 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Shlurp.Config
(
Config(..),
loadSettings,
GitHub,
executeGitHub
)
where
import Control.Monad.State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.Text (Text)
import qualified Data.Text as T
import GitHub.Data
import GitHub.Request
import System.Environment
data Config = Config {
configToken :: Auth,
configOwner :: Name Owner,
configRepo :: Name Repo
} deriving Show
loadSettings :: Text -> Text -> IO Config
loadSettings owner repo = do
possibletoken <- lookupEnv "GITHUB_TOKEN"
let token = case possibletoken of
Just token' -> S.pack token'
Nothing -> error "Need to set GITHUB_TOKEN with a valid GitHub personal access token"
return $ Config {
configToken = OAuth token,
configOwner = mkOwnerName owner,
configRepo = mkRepoName repo
}
newtype GitHub a = Wrap (StateT Config IO a)
deriving (Functor, Applicative, Monad, MonadState Config, MonadIO)
--
-- | Carry out GitHub commands
--
executeGitHub :: Config -> GitHub a -> IO a
executeGitHub config (Wrap monad) = do
evalStateT monad config
|
afcowie/shlurp
|
lib/Shlurp/Config.hs
|
bsd-3-clause
| 1,219 | 0 | 14 | 285 | 317 | 175 | 142 | 35 | 2 |
{-# LANGUAGE FlexibleContexts #-}
--
-- Fluid simulation
--
module Fluid.Fluid (
fluid
) where
import Fluid.Type
import Prelude as P
import Data.Array.Accelerate as A
fluid
:: Int
-> Timestep
-> Viscosity
-> Diffusion
-> (Acc DensityField, Acc VelocityField)
-> (Acc DensityField, Acc VelocityField)
fluid steps dt dp dn (df,vf) =
let
vf' = velocity steps dt dp vf
df' = density steps dt dn vf' df
in
(df', vf')
-- The velocity over a timestep evolves due to three causes:
-- 1. the addition of forces
-- 2. viscous diffusion
-- 3. self-advection
--
velocity
:: Int
-> Timestep
-> Viscosity
-> Acc VelocityField
-> Acc VelocityField
velocity steps dt dp
= project steps
. (\vf' -> advect dt vf' vf')
. project steps
. diffuse steps dt dp
-- Ensure the velocity field conserves mass
--
project :: Int -> Acc VelocityField -> Acc VelocityField
project steps vf = A.stencil2 poisson (A.Constant zero) vf (A.Constant zero) p
where
grad = A.stencil divF (A.Constant zero) vf
p1 = A.stencil2 pF (A.Constant zero) grad (A.Constant zero)
p = foldl1 (.) (P.replicate steps p1) grad
poisson :: A.Stencil3x3 Velocity -> A.Stencil3x3 Float -> Exp Velocity
poisson (_,(_,uv,_),_) ((_,t,_), (l,_,r), (_,b,_)) = uv .-. 0.5 .*. A.lift (r-l, b-t)
divF :: A.Stencil3x3 Velocity -> Exp Float
divF ((_,t,_), (l,_,r), (_,b,_)) = -0.5 * (A.fst r - A.fst l + A.snd b - A.snd t)
pF :: A.Stencil3x3 Float -> A.Stencil3x3 Float -> Exp Float
pF (_,(_,x,_),_) ((_,t,_), (l,_,r), (_,b,_)) = 0.25 * (x + l + t + r + b)
-- The density over a timestep evolves due to three causes:
-- 1. the addition of source particles
-- 2. self-diffusion
-- 3. motion through the velocity field
--
density
:: Int
-> Timestep
-> Diffusion
-> Acc VelocityField
-> Acc DensityField
-> Acc DensityField
density steps dt dn vf
= advect dt vf
. diffuse steps dt dn
-- The core of the fluid flow algorithm is a finite time step simulation on the
-- grid, implemented as a matrix relaxation involving the discrete Laplace
-- operator \nabla^2. This step, know as the linear solver, is used to diffuse
-- the density and velocity fields throughout the grid.
--
diffuse
:: FieldElt e
=> Int
-> Timestep
-> Diffusion
-> Acc (Field e)
-> Acc (Field e)
diffuse steps dt dn df0 =
a A.== 0
?| ( df0 , foldl1 (.) (P.replicate steps diffuse1) df0 )
where
a = A.constant dt * A.constant dn * (A.fromIntegral (A.size df0))
c = 1 + 4*a
diffuse1 df = A.stencil2 relax (A.Constant zero) df0 (A.Constant zero) df
relax :: FieldElt e => A.Stencil3x3 e -> A.Stencil3x3 e -> Exp e
relax (_,(_,x0,_),_) ((_,t,_), (l,_,r), (_,b,_)) = (x0 .+. a .*. (l.+.t.+.r.+.b)) ./. c
advect
:: FieldElt e
=> Timestep
-> Acc VelocityField
-> Acc (Field e)
-> Acc (Field e)
advect dt vf df = A.generate sh backtrace
where
sh = A.shape vf
Z :. h :. w = A.unlift sh
width = A.fromIntegral w
height = A.fromIntegral h
backtrace ix = s0.*.(t0.*.d00 .+. t1.*.d10) .+. s1.*.(t0.*.d01 .+. t1.*.d11)
where
Z:.j:.i = A.unlift ix
(u, v) = A.unlift (vf A.! ix)
-- backtrack densities based on velocity field
clamp z = A.max (-0.5) . A.min (z + 0.5)
x = width `clamp` (A.fromIntegral i - A.constant dt * width * u)
y = height `clamp` (A.fromIntegral j - A.constant dt * height * v)
-- discrete locations surrounding point
i0 = A.truncate (x + 1) - 1
j0 = A.truncate (y + 1) - 1
i1 = i0 + 1
j1 = j0 + 1
-- weighting based on location between the discrete points
s1 = x - A.fromIntegral i0
t1 = y - A.fromIntegral j0
s0 = 1 - s1
t0 = 1 - t1
-- read the density values surrounding the calculated advection point
get ix'@(Z :. j' :. i')
= (j' A.< 0 A.|| i' A.< 0 A.|| j' A.>= h A.|| i' A.>= w)
? (A.constant zero, df A.! A.lift ix')
d00 = get (Z :. j0 :. i0)
d10 = get (Z :. j1 :. i0)
d01 = get (Z :. j0 :. i1)
d11 = get (Z :. j1 :. i1)
|
cpdurham/accelerate-camera-sandbox
|
src/Fluid/Fluid.hs
|
bsd-3-clause
| 4,344 | 0 | 17 | 1,317 | 1,686 | 896 | 790 | 97 | 1 |
-- |
-- Module : Text.Eros.Phrase
-- Description : Pure interface for 'Phrase's and 'PhraseTree's.
-- Copyright : 2014, Peter Harpending.
-- License : BSD3
-- Maintainer : Peter Harpending <[email protected]>
-- Stability : experimental
-- Portability : archlinux
--
module Text.Eros.Phrase where
import qualified Data.Map as M
import Data.Ord (comparing)
import Data.Text.Lazy (Text)
import Data.Tree
-- |A Phrase is a piece of Text, with an int representing its
-- weight. These are the used internally within 'eros', in
-- 'Tree's.
data Phrase = Phrase { phrase :: Text
, score :: Int
}
deriving (Read, Show)
instance Eq Phrase where
a == b = (score a) == (score b)
a /= b = (score a) /= (score b)
instance Ord Phrase where
-- |To compare 'Phrases', just compare their 'score's
compare = comparing score
-- |A 'Tree' of 'Phrase's
type PhraseTree = Tree Phrase
-- |A 'Forest' of 'Phrase's
type PhraseForest = Forest Phrase
-- |A Map of text values the appropriate tree
type PhraseMap = M.Map Text PhraseTree
-- |The 'score' of the 'PhraseTree' is the sum of the 'score's of its 'Node's.
treeScore :: PhraseTree -> Int
treeScore = sum . map score . flatten
-- |Given a list of 'PhraseTree's, return the top-level 'phrase's.
forestPhrases :: [PhraseTree] -> [Text]
forestPhrases = map forestPhrase
-- |Given a 'PhraseTree', return the top-level 'phrase'.
forestPhrase :: PhraseTree -> Text
forestPhrase (Node phr subf) = phrase phr
-- |Given a list of 'PhraseTree's, return a map of each phrase with
-- the appropriate tree.
mkMap :: PhraseForest -> PhraseMap
mkMap = M.fromList . phraseTreeAlist
where phraseTreeAlist frs = zip (forestPhrases frs) frs
|
pharpend/eros
|
src/Text/Eros/Phrase.hs
|
bsd-3-clause
| 1,773 | 0 | 9 | 390 | 320 | 183 | 137 | 25 | 1 |
{-------------------------------------------------------------------------------
DerivBase.LemmaItem
(c) 2014 Jan Snajder <[email protected]>
-------------------------------------------------------------------------------}
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, OverloadedStrings #-}
module DerivBase.LemmaItem
( LemmaItem (..)
, Lemma
, LemmaPos (LP)
, LemmaPosOpt (LPO)
, removePos
, setPos ) where
import Data.Text (Text)
import qualified Data.Text as T
class LemmaItem l where
readLemmaItem :: Text -> l
showLemmaItem :: l -> Text
lemma :: l -> Text
type Lemma = Text
instance LemmaItem Lemma where
readLemmaItem = id
showLemmaItem = id
lemma = id
------------------------------------------------------------------------------
-- Lemma-POS
data LemmaPos p = LP Lemma p deriving (Show, Ord, Eq)
instance (Read p, Show p) => LemmaItem (LemmaPos p) where
readLemmaItem s = case T.splitOn "_" s of
[l,p] -> LP l (read $ T.unpack p)
_ -> error "no parse"
showLemmaItem (LP l p) = T.concat [l, "_", T.pack $ show p]
lemma (LP l p) = l
-- Lemma-POS with an optional POS tag
data LemmaPosOpt p = LPO Lemma (Maybe p) deriving (Show, Ord, Eq)
instance (Read p, Show p) => LemmaItem (LemmaPosOpt p) where
readLemmaItem s = case T.splitOn "_" s of
[l,p] -> LPO l . Just . read $ T.unpack p
[l] -> LPO l Nothing
_ -> error "no parse"
showLemmaItem (LPO l Nothing) = l
showLemmaItem (LPO l (Just p)) = T.concat [l, "_", T.pack $ show p]
lemma (LPO l _ ) = l
removePos :: LemmaPosOpt p -> LemmaPosOpt p
removePos (LPO l _) = LPO l Nothing
setPos :: p -> LemmaPosOpt p -> LemmaPosOpt p
setPos p (LPO l _) = LPO l (Just p)
|
jsnajder/derivbase
|
src/DerivBase/LemmaItem.hs
|
bsd-3-clause
| 1,832 | 0 | 13 | 460 | 591 | 313 | 278 | 44 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.