code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.Sizes.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of sizes, possibly filtered.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.sizes.list@.
module Network.Google.Resource.DFAReporting.Sizes.List
(
-- * REST Resource
SizesListResource
-- * Creating a Request
, sizesList
, SizesList
-- * Request Lenses
, slHeight
, slIds
, slWidth
, slProFileId
, slIabStandard
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.sizes.list@ method which the
-- 'SizesList' request conforms to.
type SizesListResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"sizes" :>
QueryParam "height" (Textual Int32) :>
QueryParams "ids" (Textual Int64) :>
QueryParam "width" (Textual Int32) :>
QueryParam "iabStandard" Bool :>
QueryParam "alt" AltJSON :>
Get '[JSON] SizesListResponse
-- | Retrieves a list of sizes, possibly filtered.
--
-- /See:/ 'sizesList' smart constructor.
data SizesList = SizesList'
{ _slHeight :: !(Maybe (Textual Int32))
, _slIds :: !(Maybe [Textual Int64])
, _slWidth :: !(Maybe (Textual Int32))
, _slProFileId :: !(Textual Int64)
, _slIabStandard :: !(Maybe Bool)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SizesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'slHeight'
--
-- * 'slIds'
--
-- * 'slWidth'
--
-- * 'slProFileId'
--
-- * 'slIabStandard'
sizesList
:: Int64 -- ^ 'slProFileId'
-> SizesList
sizesList pSlProFileId_ =
SizesList'
{ _slHeight = Nothing
, _slIds = Nothing
, _slWidth = Nothing
, _slProFileId = _Coerce # pSlProFileId_
, _slIabStandard = Nothing
}
-- | Select only sizes with this height.
slHeight :: Lens' SizesList (Maybe Int32)
slHeight
= lens _slHeight (\ s a -> s{_slHeight = a}) .
mapping _Coerce
-- | Select only sizes with these IDs.
slIds :: Lens' SizesList [Int64]
slIds
= lens _slIds (\ s a -> s{_slIds = a}) . _Default .
_Coerce
-- | Select only sizes with this width.
slWidth :: Lens' SizesList (Maybe Int32)
slWidth
= lens _slWidth (\ s a -> s{_slWidth = a}) .
mapping _Coerce
-- | User profile ID associated with this request.
slProFileId :: Lens' SizesList Int64
slProFileId
= lens _slProFileId (\ s a -> s{_slProFileId = a}) .
_Coerce
-- | Select only IAB standard sizes.
slIabStandard :: Lens' SizesList (Maybe Bool)
slIabStandard
= lens _slIabStandard
(\ s a -> s{_slIabStandard = a})
instance GoogleRequest SizesList where
type Rs SizesList = SizesListResponse
type Scopes SizesList =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient SizesList'{..}
= go _slProFileId _slHeight (_slIds ^. _Default)
_slWidth
_slIabStandard
(Just AltJSON)
dFAReportingService
where go
= buildClient (Proxy :: Proxy SizesListResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Sizes/List.hs | mpl-2.0 | 4,165 | 0 | 17 | 1,087 | 708 | 407 | 301 | 96 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Partners.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.Partners.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | Type of the offer
data OfferCustomerOfferType
= OfferTypeUnspecified
-- ^ @OFFER_TYPE_UNSPECIFIED@
-- Unset.
| OfferTypeSpendXGetY
-- ^ @OFFER_TYPE_SPEND_X_GET_Y@
-- AdWords spend X get Y.
| OfferTypeVideo
-- ^ @OFFER_TYPE_VIDEO@
-- Youtube video.
| OfferTypeSpendMatch
-- ^ @OFFER_TYPE_SPEND_MATCH@
-- Spend Match up to Y.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable OfferCustomerOfferType
instance FromHttpApiData OfferCustomerOfferType where
parseQueryParam = \case
"OFFER_TYPE_UNSPECIFIED" -> Right OfferTypeUnspecified
"OFFER_TYPE_SPEND_X_GET_Y" -> Right OfferTypeSpendXGetY
"OFFER_TYPE_VIDEO" -> Right OfferTypeVideo
"OFFER_TYPE_SPEND_MATCH" -> Right OfferTypeSpendMatch
x -> Left ("Unable to parse OfferCustomerOfferType from: " <> x)
instance ToHttpApiData OfferCustomerOfferType where
toQueryParam = \case
OfferTypeUnspecified -> "OFFER_TYPE_UNSPECIFIED"
OfferTypeSpendXGetY -> "OFFER_TYPE_SPEND_X_GET_Y"
OfferTypeVideo -> "OFFER_TYPE_VIDEO"
OfferTypeSpendMatch -> "OFFER_TYPE_SPEND_MATCH"
instance FromJSON OfferCustomerOfferType where
parseJSON = parseJSONText "OfferCustomerOfferType"
instance ToJSON OfferCustomerOfferType where
toJSON = toJSONText
-- | Type of lead.
data LeadType
= LeadTypeUnspecified
-- ^ @LEAD_TYPE_UNSPECIFIED@
-- Unchosen.
| LtGps
-- ^ @LT_GPS@
-- Google Partner Search.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LeadType
instance FromHttpApiData LeadType where
parseQueryParam = \case
"LEAD_TYPE_UNSPECIFIED" -> Right LeadTypeUnspecified
"LT_GPS" -> Right LtGps
x -> Left ("Unable to parse LeadType from: " <> x)
instance ToHttpApiData LeadType where
toQueryParam = \case
LeadTypeUnspecified -> "LEAD_TYPE_UNSPECIFIED"
LtGps -> "LT_GPS"
instance FromJSON LeadType where
parseJSON = parseJSONText "LeadType"
instance ToJSON LeadType where
toJSON = toJSONText
-- | Level of this offer.
data AvailableOfferOfferLevel
= OfferLevelUnspecified
-- ^ @OFFER_LEVEL_UNSPECIFIED@
-- Unset.
| OfferLevelDenyProblem
-- ^ @OFFER_LEVEL_DENY_PROBLEM@
-- Users\/Agencies that have no offers because of a problem.
| OfferLevelDenyContract
-- ^ @OFFER_LEVEL_DENY_CONTRACT@
-- Users\/Agencies that have no offers due to contractural agreements.
| OfferLevelManual
-- ^ @OFFER_LEVEL_MANUAL@
-- Users\/Agencies that have a manually-configured limit.
| OfferLevelLimit0
-- ^ @OFFER_LEVEL_LIMIT_0@
-- Some Agencies don\'t get any offers.
| OfferLevelLimit5
-- ^ @OFFER_LEVEL_LIMIT_5@
-- Basic level gets 5 per month.
| OfferLevelLimit15
-- ^ @OFFER_LEVEL_LIMIT_15@
-- Agencies with adequate AHI and spend get 15\/month.
| OfferLevelLimit50
-- ^ @OFFER_LEVEL_LIMIT_50@
-- Badged partners (even in grace) get 50 per month.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AvailableOfferOfferLevel
instance FromHttpApiData AvailableOfferOfferLevel where
parseQueryParam = \case
"OFFER_LEVEL_UNSPECIFIED" -> Right OfferLevelUnspecified
"OFFER_LEVEL_DENY_PROBLEM" -> Right OfferLevelDenyProblem
"OFFER_LEVEL_DENY_CONTRACT" -> Right OfferLevelDenyContract
"OFFER_LEVEL_MANUAL" -> Right OfferLevelManual
"OFFER_LEVEL_LIMIT_0" -> Right OfferLevelLimit0
"OFFER_LEVEL_LIMIT_5" -> Right OfferLevelLimit5
"OFFER_LEVEL_LIMIT_15" -> Right OfferLevelLimit15
"OFFER_LEVEL_LIMIT_50" -> Right OfferLevelLimit50
x -> Left ("Unable to parse AvailableOfferOfferLevel from: " <> x)
instance ToHttpApiData AvailableOfferOfferLevel where
toQueryParam = \case
OfferLevelUnspecified -> "OFFER_LEVEL_UNSPECIFIED"
OfferLevelDenyProblem -> "OFFER_LEVEL_DENY_PROBLEM"
OfferLevelDenyContract -> "OFFER_LEVEL_DENY_CONTRACT"
OfferLevelManual -> "OFFER_LEVEL_MANUAL"
OfferLevelLimit0 -> "OFFER_LEVEL_LIMIT_0"
OfferLevelLimit5 -> "OFFER_LEVEL_LIMIT_5"
OfferLevelLimit15 -> "OFFER_LEVEL_LIMIT_15"
OfferLevelLimit50 -> "OFFER_LEVEL_LIMIT_50"
instance FromJSON AvailableOfferOfferLevel where
parseJSON = parseJSONText "AvailableOfferOfferLevel"
instance ToJSON AvailableOfferOfferLevel where
toJSON = toJSONText
-- | The action that occurred.
data LogUserEventRequestEventAction
= EventActionUnspecified
-- ^ @EVENT_ACTION_UNSPECIFIED@
-- Unchosen.
| SmbClickedFindAPartnerButtonBottom
-- ^ @SMB_CLICKED_FIND_A_PARTNER_BUTTON_BOTTOM@
-- Advertiser clicked \`Find a partner\` bottom button.
| SmbClickedFindAPartnerButtonTop
-- ^ @SMB_CLICKED_FIND_A_PARTNER_BUTTON_TOP@
-- Advertiser clicked \`Find a partner\` top button.
| AgencyClickedJoinNowButtonBottom
-- ^ @AGENCY_CLICKED_JOIN_NOW_BUTTON_BOTTOM@
-- Agency clicked \`Join now\` bottom button.
| AgencyClickedJoinNowButtonTop
-- ^ @AGENCY_CLICKED_JOIN_NOW_BUTTON_TOP@
-- Agency clicked \`Join now\` top button.
| SmbCanceledPartnerContactForm
-- ^ @SMB_CANCELED_PARTNER_CONTACT_FORM@
-- Advertiser canceled partner contact form.
| SmbClickedContactAPartner
-- ^ @SMB_CLICKED_CONTACT_A_PARTNER@
-- Advertiser started partner contact form.
| SmbCompletedPartnerContactForm
-- ^ @SMB_COMPLETED_PARTNER_CONTACT_FORM@
-- Advertiser completed partner contact form.
| SmbEnteredEmailInContactPartnerForm
-- ^ @SMB_ENTERED_EMAIL_IN_CONTACT_PARTNER_FORM@
-- Advertiser entered email in contact form.
| SmbEnteredNameInContactPartnerForm
-- ^ @SMB_ENTERED_NAME_IN_CONTACT_PARTNER_FORM@
-- Advertiser entered name in contact form.
| SmbEnteredPhoneInContactPartnerForm
-- ^ @SMB_ENTERED_PHONE_IN_CONTACT_PARTNER_FORM@
-- Advertiser entered phone in contact form.
| SmbFailedRecaptchaInContactPartnerForm
-- ^ @SMB_FAILED_RECAPTCHA_IN_CONTACT_PARTNER_FORM@
-- Advertiser failed <https://www.google.com/recaptcha/ reCaptcha> in
-- contact form.
| PartnerViewedBySmb
-- ^ @PARTNER_VIEWED_BY_SMB@
-- Company viewed by advertiser.
| SmbCanceledPartnerContactFormOnGps
-- ^ @SMB_CANCELED_PARTNER_CONTACT_FORM_ON_GPS@
-- Advertiser canceled partner contact form on Google Partner Search.
| SmbChangedASearchParameterTop
-- ^ @SMB_CHANGED_A_SEARCH_PARAMETER_TOP@
-- Advertiser changed a top search parameter.
| SmbClickedContactAPartnerOnGps
-- ^ @SMB_CLICKED_CONTACT_A_PARTNER_ON_GPS@
-- Advertiser started partner contact form on Google Partner Search.
| SmbClickedShowMorePartnersButtonBottom
-- ^ @SMB_CLICKED_SHOW_MORE_PARTNERS_BUTTON_BOTTOM@
-- Advertiser clicked \`Show more partners\` bottom button.
| SmbCompletedPartnerContactFormOnGps
-- ^ @SMB_COMPLETED_PARTNER_CONTACT_FORM_ON_GPS@
-- Advertiser completed partner contact form on Google Partner Search.
| SmbNoPartnersAvailableWithSearchCriteria
-- ^ @SMB_NO_PARTNERS_AVAILABLE_WITH_SEARCH_CRITERIA@
-- Advertiser saw no partners available with search criteria.
| SmbPerformedSearchOnGps
-- ^ @SMB_PERFORMED_SEARCH_ON_GPS@
-- Advertiser performed search on Google Partner Search.
| SmbViewedAPartnerOnGps
-- ^ @SMB_VIEWED_A_PARTNER_ON_GPS@
-- Advertiser viewed a partner on Google Partner Search.
| SmbCanceledPartnerContactFormOnProFilePage
-- ^ @SMB_CANCELED_PARTNER_CONTACT_FORM_ON_PROFILE_PAGE@
-- Advertiser canceled partner contact form on profile page.
| SmbClickedContactAPartnerOnProFilePage
-- ^ @SMB_CLICKED_CONTACT_A_PARTNER_ON_PROFILE_PAGE@
-- Advertiser started partner contact form on profile page.
| SmbClickedPartnerWebsite
-- ^ @SMB_CLICKED_PARTNER_WEBSITE@
-- Advertiser clicked partner website.
| SmbCompletedPartnerContactFormOnProFilePage
-- ^ @SMB_COMPLETED_PARTNER_CONTACT_FORM_ON_PROFILE_PAGE@
-- Advertiser completed contact form on profile page.
| SmbViewedAPartnerProFile
-- ^ @SMB_VIEWED_A_PARTNER_PROFILE@
-- Advertiser viewed a partner profile.
| AgencyClickedAcceptTosButton
-- ^ @AGENCY_CLICKED_ACCEPT_TOS_BUTTON@
-- Agency clicked \`accept Terms Of Service\` button.
| AgencyChangedTosCountry
-- ^ @AGENCY_CHANGED_TOS_COUNTRY@
-- Agency changed Terms Of Service country.
| AgencyAddedAddressInMyProFilePortal
-- ^ @AGENCY_ADDED_ADDRESS_IN_MY_PROFILE_PORTAL@
-- Agency added address in profile portal.
| AgencyAddedPhoneNumberInMyProFilePortal
-- ^ @AGENCY_ADDED_PHONE_NUMBER_IN_MY_PROFILE_PORTAL@
-- Agency added phone number in profile portal.
| AgencyChangedPrimaryAccountAssociation
-- ^ @AGENCY_CHANGED_PRIMARY_ACCOUNT_ASSOCIATION@
-- Agency changed primary account association.
| AgencyChangedPrimaryCountryAssociation
-- ^ @AGENCY_CHANGED_PRIMARY_COUNTRY_ASSOCIATION@
-- Agency changed primary country association.
| AgencyClickedAffiliateButtonInMyProFileInPortal
-- ^ @AGENCY_CLICKED_AFFILIATE_BUTTON_IN_MY_PROFILE_IN_PORTAL@
-- Agency clicked \`affiliate\` button in profile portal.
| AgencyClickedGiveEditAccessInMyProFilePortal
-- ^ @AGENCY_CLICKED_GIVE_EDIT_ACCESS_IN_MY_PROFILE_PORTAL@
-- Agency clicked \`give edit access\` in profile portal.
| AgencyClickedLogOutInMyProFilePortal
-- ^ @AGENCY_CLICKED_LOG_OUT_IN_MY_PROFILE_PORTAL@
-- Agency clicked \`log out\` in profile portal.
| AgencyClickedMyProFileLeftNavInPortal
-- ^ @AGENCY_CLICKED_MY_PROFILE_LEFT_NAV_IN_PORTAL@
-- Agency clicked profile portal left nav.
| AgencyClickedSaveAndContinueAtBotOfCompleteProFile
-- ^ @AGENCY_CLICKED_SAVE_AND_CONTINUE_AT_BOT_OF_COMPLETE_PROFILE@
-- Agency clicked \`save and continue\` at bottom of complete profile.
| AgencyClickedUnaffiliateInMyProFilePortal
-- ^ @AGENCY_CLICKED_UNAFFILIATE_IN_MY_PROFILE_PORTAL@
-- Agency clicked \`unaffiliate\` in profile portal.
| AgencyFilledOutCompAffiliationInMyProFilePortal
-- ^ @AGENCY_FILLED_OUT_COMP_AFFILIATION_IN_MY_PROFILE_PORTAL@
-- Agency filled out company affiliation in profile portal.
| AgencySuccessfullyConnectedWithCompanyInMyProFile
-- ^ @AGENCY_SUCCESSFULLY_CONNECTED_WITH_COMPANY_IN_MY_PROFILE@
-- Agency successfully connected with company in profile portal.
| AgencyClickedCreateMccInMyProFilePortal
-- ^ @AGENCY_CLICKED_CREATE_MCC_IN_MY_PROFILE_PORTAL@
-- Agency clicked create MCC in profile portal.
| AgencyDidntHaveAnMccAssociatedOnCompleteProFile
-- ^ @AGENCY_DIDNT_HAVE_AN_MCC_ASSOCIATED_ON_COMPLETE_PROFILE@
-- Agency did not have an MCC associated on profile portal.
| AgencyHadAnMccAssociatedOnCompleteProFile
-- ^ @AGENCY_HAD_AN_MCC_ASSOCIATED_ON_COMPLETE_PROFILE@
-- Agency had an MCC associated on profile portal.
| AgencyAddedJobFunctionInMyProFilePortal
-- ^ @AGENCY_ADDED_JOB_FUNCTION_IN_MY_PROFILE_PORTAL@
-- Agency added job function in profile portal.
| AgencyLookedAtJobFunctionDropDown
-- ^ @AGENCY_LOOKED_AT_JOB_FUNCTION_DROP_DOWN@
-- Agency looked at job function drop-down.
| AgencySelectedAccountManagerAsJobFunction
-- ^ @AGENCY_SELECTED_ACCOUNT_MANAGER_AS_JOB_FUNCTION@
-- Agency selected \`account manage\` as job function.
| AgencySelectedAccountPlannerAsJobFunction
-- ^ @AGENCY_SELECTED_ACCOUNT_PLANNER_AS_JOB_FUNCTION@
-- Agency selected \`account planner\` as job function.
| AgencySelectedAnalyticsAsJobFunction
-- ^ @AGENCY_SELECTED_ANALYTICS_AS_JOB_FUNCTION@
-- Agency selected \`Analytics\` as job function.
| AgencySelectedCreativeAsJobFunction
-- ^ @AGENCY_SELECTED_CREATIVE_AS_JOB_FUNCTION@
-- Agency selected \`creative\` as job function.
| AgencySelectedMediaBuyerAsJobFunction
-- ^ @AGENCY_SELECTED_MEDIA_BUYER_AS_JOB_FUNCTION@
-- Agency selected \`media buyer\` as job function.
| AgencySelectedMediaPlannerAsJobFunction
-- ^ @AGENCY_SELECTED_MEDIA_PLANNER_AS_JOB_FUNCTION@
-- Agency selected \`media planner\` as job function.
| AgencySelectedOtherAsJobFunction
-- ^ @AGENCY_SELECTED_OTHER_AS_JOB_FUNCTION@
-- Agency selected \`other\` as job function.
| AgencySelectedProductionAsJobFunction
-- ^ @AGENCY_SELECTED_PRODUCTION_AS_JOB_FUNCTION@
-- Agency selected \`production\` as job function.
| AgencySelectedSeoAsJobFunction
-- ^ @AGENCY_SELECTED_SEO_AS_JOB_FUNCTION@
-- Agency selected \`SEO\` as job function.
| AgencySelectedSalesRepAsJobFunction
-- ^ @AGENCY_SELECTED_SALES_REP_AS_JOB_FUNCTION@
-- Agency selected \`sales rep\` as job function.
| AgencySelectedSearchSpeciaListAsJobFunction
-- ^ @AGENCY_SELECTED_SEARCH_SPECIALIST_AS_JOB_FUNCTION@
-- Agency selected \`search specialist\` as job function.
| AgencyAddedChannelsInMyProFilePortal
-- ^ @AGENCY_ADDED_CHANNELS_IN_MY_PROFILE_PORTAL@
-- Agency added channels in profile portal.
| AgencyLookedAtAddChannelDropDown
-- ^ @AGENCY_LOOKED_AT_ADD_CHANNEL_DROP_DOWN@
-- Agency looked at \`add channel\` drop-down.
| AgencySelectedCrossChannelFromAddChannel
-- ^ @AGENCY_SELECTED_CROSS_CHANNEL_FROM_ADD_CHANNEL@
-- Agency selected \`cross channel\` from add channel drop-down.
| AgencySelectedDisplayFromAddChannel
-- ^ @AGENCY_SELECTED_DISPLAY_FROM_ADD_CHANNEL@
-- Agency selected \`display\` from add channel drop-down.
| AgencySelectedMobileFromAddChannel
-- ^ @AGENCY_SELECTED_MOBILE_FROM_ADD_CHANNEL@
-- Agency selected \`mobile\` from add channel drop-down.
| AgencySelectedSearchFromAddChannel
-- ^ @AGENCY_SELECTED_SEARCH_FROM_ADD_CHANNEL@
-- Agency selected \`search\` from add channel drop-down.
| AgencySelectedSocialFromAddChannel
-- ^ @AGENCY_SELECTED_SOCIAL_FROM_ADD_CHANNEL@
-- Agency selected \`social\` from add channel drop-down.
| AgencySelectedToolsFromAddChannel
-- ^ @AGENCY_SELECTED_TOOLS_FROM_ADD_CHANNEL@
-- Agency selected \`tools\` from add channel drop-down.
| AgencySelectedYouTubeFromAddChannel
-- ^ @AGENCY_SELECTED_YOUTUBE_FROM_ADD_CHANNEL@
-- Agency selected \`YouTube\` from add channel drop-down.
| AgencyAddedIndustriesInMyProFilePortal
-- ^ @AGENCY_ADDED_INDUSTRIES_IN_MY_PROFILE_PORTAL@
-- Agency added industries in profile portal.
| AgencyChangedAddIndustriesDropDown
-- ^ @AGENCY_CHANGED_ADD_INDUSTRIES_DROP_DOWN@
-- Agency changed \`add industries\` drop-down.
| AgencyAddedMarketsInMyProFilePortal
-- ^ @AGENCY_ADDED_MARKETS_IN_MY_PROFILE_PORTAL@
-- Agency added markets in profile portal.
| AgencyChangedAddMarketsDropDown
-- ^ @AGENCY_CHANGED_ADD_MARKETS_DROP_DOWN@
-- Agency changed \`add markets\` drop-down.
| AgencyCheckedRecieveMailPromotionsMyproFile
-- ^ @AGENCY_CHECKED_RECIEVE_MAIL_PROMOTIONS_MYPROFILE@
-- Agency checked \`recieve mail promotions\` in profile portal.
| AgencyCheckedRecieveMailPromotionsSignup
-- ^ @AGENCY_CHECKED_RECIEVE_MAIL_PROMOTIONS_SIGNUP@
-- Agency checked \`recieve mail promotions\` in sign-up.
| AgencySelectedOptInBetaTestsAndMktResearch
-- ^ @AGENCY_SELECTED_OPT_IN_BETA_TESTS_AND_MKT_RESEARCH@
-- Agency selected \`opt-in beta tests and market research\`.
| AgencySelectedOptInBetaTestsInMyProFilePortal
-- ^ @AGENCY_SELECTED_OPT_IN_BETA_TESTS_IN_MY_PROFILE_PORTAL@
-- Agency selected \`opt-in beta tests\` in profile portal.
| AgencySelectedOptInNewsInMyProFilePortal
-- ^ @AGENCY_SELECTED_OPT_IN_NEWS_IN_MY_PROFILE_PORTAL@
-- Agency selected \`opt-in news\` in profile portal.
| AgencySelectedOptInNewsInvitationsAndPromos
-- ^ @AGENCY_SELECTED_OPT_IN_NEWS_INVITATIONS_AND_PROMOS@
-- Agency selected \`opt-in news invitations and promotions\`.
| AgencySelectedOptInPerformanceSugInMyProFilePortal
-- ^ @AGENCY_SELECTED_OPT_IN_PERFORMANCE_SUG_IN_MY_PROFILE_PORTAL@
-- Agency selected \`opt-in performance SUG\` in profile portal.
| AgencySelectedOptInPerformanceSuggestions
-- ^ @AGENCY_SELECTED_OPT_IN_PERFORMANCE_SUGGESTIONS@
-- Agency selected \`opt-in performance suggestions\`.
| AgencySelectedOptInSelectAllEmailNotifications
-- ^ @AGENCY_SELECTED_OPT_IN_SELECT_ALL_EMAIL_NOTIFICATIONS@
-- Agency selected \`opt-in select all email notifications\`.
| AgencySelectedSelectAllOptInsInMyProFilePortal
-- ^ @AGENCY_SELECTED_SELECT_ALL_OPT_INS_IN_MY_PROFILE_PORTAL@
-- Agency selected \`select all opt-ins\` in profile portal.
| AgencyClickedBackButtonOnConnectWithCompany
-- ^ @AGENCY_CLICKED_BACK_BUTTON_ON_CONNECT_WITH_COMPANY@
-- Agency clicked back button on \`connect with company\`.
| AgencyClickedContinueToOverviewOnConnectWithCompany
-- ^ @AGENCY_CLICKED_CONTINUE_TO_OVERVIEW_ON_CONNECT_WITH_COMPANY@
-- Agency clicked continue to overview on \`connect with company\`.
| AgecnyClickedCreateMccConnectWithCompanyNotFound
-- ^ @AGECNY_CLICKED_CREATE_MCC_CONNECT_WITH_COMPANY_NOT_FOUND@
-- Agency clicked \`create MCC connect with company not found\`.
| AgecnyClickedGiveEditAccessConnectWithCompanyNotFound
-- ^ @AGECNY_CLICKED_GIVE_EDIT_ACCESS_CONNECT_WITH_COMPANY_NOT_FOUND@
-- Agency clicked \`give edit access connect with company not found\`.
| AgecnyClickedLogOutConnectWithCompanyNotFound
-- ^ @AGECNY_CLICKED_LOG_OUT_CONNECT_WITH_COMPANY_NOT_FOUND@
-- Agency clicked \`log out connect with company not found\`.
| AgencyClickedSkipForNowOnConnectWithCompanyPage
-- ^ @AGENCY_CLICKED_SKIP_FOR_NOW_ON_CONNECT_WITH_COMPANY_PAGE@
-- Agency clicked \`skip for now on connect with company page\`.
| AgencyClosedConnectedToCompanyXButtonWrongCompany
-- ^ @AGENCY_CLOSED_CONNECTED_TO_COMPANY_X_BUTTON_WRONG_COMPANY@
-- Agency closed connection to company.
| AgencyCompletedFieldConnectWithCompany
-- ^ @AGENCY_COMPLETED_FIELD_CONNECT_WITH_COMPANY@
-- Agency completed field connect with company.
| AgecnyFoundCompanyToConnectWith
-- ^ @AGECNY_FOUND_COMPANY_TO_CONNECT_WITH@
-- Agency found company to connect with.
| AgencySuccessfullyCreatedCompany
-- ^ @AGENCY_SUCCESSFULLY_CREATED_COMPANY@
-- Agency successfully created company.
| AgencyAddedNewCompanyLocation
-- ^ @AGENCY_ADDED_NEW_COMPANY_LOCATION@
-- Agency added new company location.
| AgencyClickedCommUnityJoinNowLinkInPortalNotifications
-- ^ @AGENCY_CLICKED_COMMUNITY_JOIN_NOW_LINK_IN_PORTAL_NOTIFICATIONS@
-- Agency clicked community \`join now link\` in portal notifications.
| AgencyClickedConnectToCompanyLinkInPortalNotifications
-- ^ @AGENCY_CLICKED_CONNECT_TO_COMPANY_LINK_IN_PORTAL_NOTIFICATIONS@
-- Agency clicked \`connect to company\` link in portal notifications.
| AgencyClickedGetCertifiedLinkInPortalNotifications
-- ^ @AGENCY_CLICKED_GET_CERTIFIED_LINK_IN_PORTAL_NOTIFICATIONS@
-- Agency cliecked \`get certified\` link in portal notifications.
| AgencyClickedGetVideoAdsCertifiedLinkInPortalNotifications
-- ^ @AGENCY_CLICKED_GET_VIDEO_ADS_CERTIFIED_LINK_IN_PORTAL_NOTIFICATIONS@
-- Agency clicked \`get VideoAds certified\` link in portal notifications.
| AgencyClickedLinkToMccLinkInPortalNotifications
-- ^ @AGENCY_CLICKED_LINK_TO_MCC_LINK_IN_PORTAL_NOTIFICATIONS@
-- Agency clicked \`link to MCC\` link in portal notifications.
| AgencyClickedInsightContentInPortal
-- ^ @AGENCY_CLICKED_INSIGHT_CONTENT_IN_PORTAL@
-- Agency clicked \`insight content\` in portal.
| AgencyClickedInsightsViewNowPitchDecksInPortal
-- ^ @AGENCY_CLICKED_INSIGHTS_VIEW_NOW_PITCH_DECKS_IN_PORTAL@
-- Agency clicked \`insights view now pitch decks\` in portal.
| AgencyClickedInsightsLeftNavInPortal
-- ^ @AGENCY_CLICKED_INSIGHTS_LEFT_NAV_IN_PORTAL@
-- Agency clicked \`insights\` left nav in portal.
| AgencyClickedInsightsUploadContent
-- ^ @AGENCY_CLICKED_INSIGHTS_UPLOAD_CONTENT@
-- Agency clicked \`insights upload content\`.
| AgencyClickedInsightsViewedDeprecated
-- ^ @AGENCY_CLICKED_INSIGHTS_VIEWED_DEPRECATED@
-- Agency clicked \`insights viewed deprecated\`.
| AgencyClickedCommUnityLeftNavInPortal
-- ^ @AGENCY_CLICKED_COMMUNITY_LEFT_NAV_IN_PORTAL@
-- Agency clicked \`community\` left nav in portal.
| AgencyClickedJoinCommUnityButtonCommUnityPortal
-- ^ @AGENCY_CLICKED_JOIN_COMMUNITY_BUTTON_COMMUNITY_PORTAL@
-- Agency clicked \`join community\` button in community portal.
| AgencyClickedCertificationsLeftNavInPortal
-- ^ @AGENCY_CLICKED_CERTIFICATIONS_LEFT_NAV_IN_PORTAL@
-- Agency clicked \`certifications\` left nav in portal.
| AgencyClickedCertificationsProductLeftNavInPortal
-- ^ @AGENCY_CLICKED_CERTIFICATIONS_PRODUCT_LEFT_NAV_IN_PORTAL@
-- Agency clicked \`certifications product\` left nav in portal.
| AgencyClickedPartnerStatusLeftNavInPortal
-- ^ @AGENCY_CLICKED_PARTNER_STATUS_LEFT_NAV_IN_PORTAL@
-- Agency clicked \`partner status\` left nav in portal.
| AgencyClickedPartnerStatusProductLeftNavInPortal
-- ^ @AGENCY_CLICKED_PARTNER_STATUS_PRODUCT_LEFT_NAV_IN_PORTAL@
-- Agency clicked \`partner status product\` left nav in portal.
| AgencyClickedOffersLeftNavInPortal
-- ^ @AGENCY_CLICKED_OFFERS_LEFT_NAV_IN_PORTAL@
-- Agency clicked \`offers\` left nav in portal.
| AgencyClickedSendButtonOnOffersPage
-- ^ @AGENCY_CLICKED_SEND_BUTTON_ON_OFFERS_PAGE@
-- Agency clicked \`send\` button on offers page.
| AgencyClickedExamDetailsOnCertAdwordsPage
-- ^ @AGENCY_CLICKED_EXAM_DETAILS_ON_CERT_ADWORDS_PAGE@
-- Agency clicked \`exam details\` on certifications AdWords page.
| AgencyClickedSeeExamsCertificationMainPage
-- ^ @AGENCY_CLICKED_SEE_EXAMS_CERTIFICATION_MAIN_PAGE@
-- Agency clicked \`see exams\` certifications main page.
| AgencyClickedTakeExamOnCertExamPage
-- ^ @AGENCY_CLICKED_TAKE_EXAM_ON_CERT_EXAM_PAGE@
-- Agency clicked \`take exam\` on certifications exam page.
| AgencyOpenedLastAdminDialog
-- ^ @AGENCY_OPENED_LAST_ADMIN_DIALOG@
-- Agency opened \`last admin\` dialog.
| AgencyOpenedDialogWithNoUsers
-- ^ @AGENCY_OPENED_DIALOG_WITH_NO_USERS@
-- Agency opened dialog with no users.
| AgencyPromotedUserToAdmin
-- ^ @AGENCY_PROMOTED_USER_TO_ADMIN@
-- Agency promoted user to admin.
| AgencyUnaffiliated
-- ^ @AGENCY_UNAFFILIATED@
-- Agency unaffiliated.
| AgencyChangedRoles
-- ^ @AGENCY_CHANGED_ROLES@
-- Agency changed roles.
| SmbClickedCompanyNameLinkToProFile
-- ^ @SMB_CLICKED_COMPANY_NAME_LINK_TO_PROFILE@
-- Advertiser clicked \`company name\` link to profile.
| SmbViewedAdwordsCertificate
-- ^ @SMB_VIEWED_ADWORDS_CERTIFICATE@
-- Advertiser viewed AdWords certificate.
| SmbViewedAdwordsSearchCertificate
-- ^ @SMB_VIEWED_ADWORDS_SEARCH_CERTIFICATE@
-- Advertiser viewed AdWords Search certificate.
| SmbViewedAdwordsDisplayCertificate
-- ^ @SMB_VIEWED_ADWORDS_DISPLAY_CERTIFICATE@
-- Advertiser viewed AdWords Display certificate.
| SmbClickedAdwordsCertificateHelpIcon
-- ^ @SMB_CLICKED_ADWORDS_CERTIFICATE_HELP_ICON@
-- Advertiser clicked AdWords certificate help icon.
| SmbViewedAnalyticsCertificate
-- ^ @SMB_VIEWED_ANALYTICS_CERTIFICATE@
-- Advertiser viewed Analytics certificate.
| SmbViewedDoubleClickCertificate
-- ^ @SMB_VIEWED_DOUBLECLICK_CERTIFICATE@
-- Advertiser viewed DoubleClick certificate.
| SmbViewedMobileSitesCertificate
-- ^ @SMB_VIEWED_MOBILE_SITES_CERTIFICATE@
-- Advertiser viewed Mobile Sites certificate.
| SmbViewedVideoAdsCertificate
-- ^ @SMB_VIEWED_VIDEO_ADS_CERTIFICATE@
-- Advertiser viewed VideoAds certificate.
| SmbViewedShoppingCertificate
-- ^ @SMB_VIEWED_SHOPPING_CERTIFICATE@
-- Advertiser clicked Shopping certificate help icon.
| SmbClickedVideoAdsCertificateHelpIcon
-- ^ @SMB_CLICKED_VIDEO_ADS_CERTIFICATE_HELP_ICON@
-- Advertiser clicked VideoAds certificate help icon.
| SmbViewedDigitalSalesCertificate
-- ^ @SMB_VIEWED_DIGITAL_SALES_CERTIFICATE@
-- Advertiser viewed Digital Sales certificate.
| ClickedHelpAtBottom
-- ^ @CLICKED_HELP_AT_BOTTOM@
-- Clicked \`help\` at bottom.
| ClickedHelpAtTop
-- ^ @CLICKED_HELP_AT_TOP@
-- Clicked \`help\` at top.
| ClientError
-- ^ @CLIENT_ERROR@
-- Client error occurred.
| AgencyClickedLeftNavStories
-- ^ @AGENCY_CLICKED_LEFT_NAV_STORIES@
-- Agency clicked left nav \`stories\`.
| Clicked
-- ^ @CLICKED@
-- Click occured.
| SmbViewedMobileCertificate
-- ^ @SMB_VIEWED_MOBILE_CERTIFICATE@
-- Advertiser clicked Mobile certificate help icon.
| AgencyFailedCompanyVerification
-- ^ @AGENCY_FAILED_COMPANY_VERIFICATION@
-- Agency failed the company verification.
| VisitedLanding
-- ^ @VISITED_LANDING@
-- User visited the landing portion of Google Partners.
| VisitedGps
-- ^ @VISITED_GPS@
-- User visited the Google Partner Search portion of Google Partners.
| VisitedAgencyPortal
-- ^ @VISITED_AGENCY_PORTAL@
-- User visited the agency portal portion of Google Partners.
| CancelledIndividualSignUp
-- ^ @CANCELLED_INDIVIDUAL_SIGN_UP@
-- User cancelled signing up.
| CancelledCompanySignUp
-- ^ @CANCELLED_COMPANY_SIGN_UP@
-- User cancelled signing up their company.
| AgencyClickedSignInButtonTop
-- ^ @AGENCY_CLICKED_SIGN_IN_BUTTON_TOP@
-- Agency clicked \`Sign in\` top button.
| AgencyClickedSaveAndContinueAtBotOfIncompleteProFile
-- ^ @AGENCY_CLICKED_SAVE_AND_CONTINUE_AT_BOT_OF_INCOMPLETE_PROFILE@
-- Agency clicked \`save and continue\` at bottom of incomplete profile.
| AgencyUnselectedOptInNewsInvitationsAndPromos
-- ^ @AGENCY_UNSELECTED_OPT_IN_NEWS_INVITATIONS_AND_PROMOS@
-- Agency unselected \`opt-in news invitations and promotions\`.
| AgencyUnselectedOptInBetaTestsAndMktResearch
-- ^ @AGENCY_UNSELECTED_OPT_IN_BETA_TESTS_AND_MKT_RESEARCH@
-- Agency unselected \`opt-in beta tests and market research\`.
| AgencyUnselectedOptInPerformanceSuggestions
-- ^ @AGENCY_UNSELECTED_OPT_IN_PERFORMANCE_SUGGESTIONS@
-- Agency unselected \`opt-in performance suggestions\`.
| AgencySelectedOptOutUnselectAllEmailNotifications
-- ^ @AGENCY_SELECTED_OPT_OUT_UNSELECT_ALL_EMAIL_NOTIFICATIONS@
-- Agency selected \`opt-out unselect all email notifications\`.
| AgencyLinkedIndividualMcc
-- ^ @AGENCY_LINKED_INDIVIDUAL_MCC@
-- Agency linked their individual MCC.
| AgencySuggestedToUser
-- ^ @AGENCY_SUGGESTED_TO_USER@
-- Agency was suggested to user for affiliation.
| AgencyIgnoredSuggestedAgenciesAndSearched
-- ^ @AGENCY_IGNORED_SUGGESTED_AGENCIES_AND_SEARCHED@
-- Agency ignored suggested agencies and begin searching.
| AgencyPickedSuggestedAgency
-- ^ @AGENCY_PICKED_SUGGESTED_AGENCY@
-- Agency picked a suggested agency.
| AgencySearchedForAgencies
-- ^ @AGENCY_SEARCHED_FOR_AGENCIES@
-- Agency searched for agencies.
| AgencyPickedSearchedAgency
-- ^ @AGENCY_PICKED_SEARCHED_AGENCY@
-- Agency picked a searched agency.
| AgencyDismissedAffiliationWidget
-- ^ @AGENCY_DISMISSED_AFFILIATION_WIDGET@
-- Agency dismissed affiliation widget.
| AgencyClickedInsightsDownloadContent
-- ^ @AGENCY_CLICKED_INSIGHTS_DOWNLOAD_CONTENT@
-- Agency clicked on the download link for downloading content.
| AgencyProgressInsightsViewContent
-- ^ @AGENCY_PROGRESS_INSIGHTS_VIEW_CONTENT@
-- Agency user is maklingg progress viewing a content item.
| AgencyClickedCancelAcceptTosButton
-- ^ @AGENCY_CLICKED_CANCEL_ACCEPT_TOS_BUTTON@
-- Agency clicked \`cancel Terms Of Service\` button.
| SmbEnteredWebsiteInContactPartnerForm
-- ^ @SMB_ENTERED_WEBSITE_IN_CONTACT_PARTNER_FORM@
-- Advertiser entered website in contact form.
| AgencySelectedOptInAfaMigration
-- ^ @AGENCY_SELECTED_OPT_IN_AFA_MIGRATION@
-- Agency opted in for migrating their exams to Academy for Ads.
| AgencySelectedOptOutAfaMigration
-- ^ @AGENCY_SELECTED_OPT_OUT_AFA_MIGRATION@
-- Agency opted out for migrating their exams to Academy for Ads.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LogUserEventRequestEventAction
instance FromHttpApiData LogUserEventRequestEventAction where
parseQueryParam = \case
"EVENT_ACTION_UNSPECIFIED" -> Right EventActionUnspecified
"SMB_CLICKED_FIND_A_PARTNER_BUTTON_BOTTOM" -> Right SmbClickedFindAPartnerButtonBottom
"SMB_CLICKED_FIND_A_PARTNER_BUTTON_TOP" -> Right SmbClickedFindAPartnerButtonTop
"AGENCY_CLICKED_JOIN_NOW_BUTTON_BOTTOM" -> Right AgencyClickedJoinNowButtonBottom
"AGENCY_CLICKED_JOIN_NOW_BUTTON_TOP" -> Right AgencyClickedJoinNowButtonTop
"SMB_CANCELED_PARTNER_CONTACT_FORM" -> Right SmbCanceledPartnerContactForm
"SMB_CLICKED_CONTACT_A_PARTNER" -> Right SmbClickedContactAPartner
"SMB_COMPLETED_PARTNER_CONTACT_FORM" -> Right SmbCompletedPartnerContactForm
"SMB_ENTERED_EMAIL_IN_CONTACT_PARTNER_FORM" -> Right SmbEnteredEmailInContactPartnerForm
"SMB_ENTERED_NAME_IN_CONTACT_PARTNER_FORM" -> Right SmbEnteredNameInContactPartnerForm
"SMB_ENTERED_PHONE_IN_CONTACT_PARTNER_FORM" -> Right SmbEnteredPhoneInContactPartnerForm
"SMB_FAILED_RECAPTCHA_IN_CONTACT_PARTNER_FORM" -> Right SmbFailedRecaptchaInContactPartnerForm
"PARTNER_VIEWED_BY_SMB" -> Right PartnerViewedBySmb
"SMB_CANCELED_PARTNER_CONTACT_FORM_ON_GPS" -> Right SmbCanceledPartnerContactFormOnGps
"SMB_CHANGED_A_SEARCH_PARAMETER_TOP" -> Right SmbChangedASearchParameterTop
"SMB_CLICKED_CONTACT_A_PARTNER_ON_GPS" -> Right SmbClickedContactAPartnerOnGps
"SMB_CLICKED_SHOW_MORE_PARTNERS_BUTTON_BOTTOM" -> Right SmbClickedShowMorePartnersButtonBottom
"SMB_COMPLETED_PARTNER_CONTACT_FORM_ON_GPS" -> Right SmbCompletedPartnerContactFormOnGps
"SMB_NO_PARTNERS_AVAILABLE_WITH_SEARCH_CRITERIA" -> Right SmbNoPartnersAvailableWithSearchCriteria
"SMB_PERFORMED_SEARCH_ON_GPS" -> Right SmbPerformedSearchOnGps
"SMB_VIEWED_A_PARTNER_ON_GPS" -> Right SmbViewedAPartnerOnGps
"SMB_CANCELED_PARTNER_CONTACT_FORM_ON_PROFILE_PAGE" -> Right SmbCanceledPartnerContactFormOnProFilePage
"SMB_CLICKED_CONTACT_A_PARTNER_ON_PROFILE_PAGE" -> Right SmbClickedContactAPartnerOnProFilePage
"SMB_CLICKED_PARTNER_WEBSITE" -> Right SmbClickedPartnerWebsite
"SMB_COMPLETED_PARTNER_CONTACT_FORM_ON_PROFILE_PAGE" -> Right SmbCompletedPartnerContactFormOnProFilePage
"SMB_VIEWED_A_PARTNER_PROFILE" -> Right SmbViewedAPartnerProFile
"AGENCY_CLICKED_ACCEPT_TOS_BUTTON" -> Right AgencyClickedAcceptTosButton
"AGENCY_CHANGED_TOS_COUNTRY" -> Right AgencyChangedTosCountry
"AGENCY_ADDED_ADDRESS_IN_MY_PROFILE_PORTAL" -> Right AgencyAddedAddressInMyProFilePortal
"AGENCY_ADDED_PHONE_NUMBER_IN_MY_PROFILE_PORTAL" -> Right AgencyAddedPhoneNumberInMyProFilePortal
"AGENCY_CHANGED_PRIMARY_ACCOUNT_ASSOCIATION" -> Right AgencyChangedPrimaryAccountAssociation
"AGENCY_CHANGED_PRIMARY_COUNTRY_ASSOCIATION" -> Right AgencyChangedPrimaryCountryAssociation
"AGENCY_CLICKED_AFFILIATE_BUTTON_IN_MY_PROFILE_IN_PORTAL" -> Right AgencyClickedAffiliateButtonInMyProFileInPortal
"AGENCY_CLICKED_GIVE_EDIT_ACCESS_IN_MY_PROFILE_PORTAL" -> Right AgencyClickedGiveEditAccessInMyProFilePortal
"AGENCY_CLICKED_LOG_OUT_IN_MY_PROFILE_PORTAL" -> Right AgencyClickedLogOutInMyProFilePortal
"AGENCY_CLICKED_MY_PROFILE_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedMyProFileLeftNavInPortal
"AGENCY_CLICKED_SAVE_AND_CONTINUE_AT_BOT_OF_COMPLETE_PROFILE" -> Right AgencyClickedSaveAndContinueAtBotOfCompleteProFile
"AGENCY_CLICKED_UNAFFILIATE_IN_MY_PROFILE_PORTAL" -> Right AgencyClickedUnaffiliateInMyProFilePortal
"AGENCY_FILLED_OUT_COMP_AFFILIATION_IN_MY_PROFILE_PORTAL" -> Right AgencyFilledOutCompAffiliationInMyProFilePortal
"AGENCY_SUCCESSFULLY_CONNECTED_WITH_COMPANY_IN_MY_PROFILE" -> Right AgencySuccessfullyConnectedWithCompanyInMyProFile
"AGENCY_CLICKED_CREATE_MCC_IN_MY_PROFILE_PORTAL" -> Right AgencyClickedCreateMccInMyProFilePortal
"AGENCY_DIDNT_HAVE_AN_MCC_ASSOCIATED_ON_COMPLETE_PROFILE" -> Right AgencyDidntHaveAnMccAssociatedOnCompleteProFile
"AGENCY_HAD_AN_MCC_ASSOCIATED_ON_COMPLETE_PROFILE" -> Right AgencyHadAnMccAssociatedOnCompleteProFile
"AGENCY_ADDED_JOB_FUNCTION_IN_MY_PROFILE_PORTAL" -> Right AgencyAddedJobFunctionInMyProFilePortal
"AGENCY_LOOKED_AT_JOB_FUNCTION_DROP_DOWN" -> Right AgencyLookedAtJobFunctionDropDown
"AGENCY_SELECTED_ACCOUNT_MANAGER_AS_JOB_FUNCTION" -> Right AgencySelectedAccountManagerAsJobFunction
"AGENCY_SELECTED_ACCOUNT_PLANNER_AS_JOB_FUNCTION" -> Right AgencySelectedAccountPlannerAsJobFunction
"AGENCY_SELECTED_ANALYTICS_AS_JOB_FUNCTION" -> Right AgencySelectedAnalyticsAsJobFunction
"AGENCY_SELECTED_CREATIVE_AS_JOB_FUNCTION" -> Right AgencySelectedCreativeAsJobFunction
"AGENCY_SELECTED_MEDIA_BUYER_AS_JOB_FUNCTION" -> Right AgencySelectedMediaBuyerAsJobFunction
"AGENCY_SELECTED_MEDIA_PLANNER_AS_JOB_FUNCTION" -> Right AgencySelectedMediaPlannerAsJobFunction
"AGENCY_SELECTED_OTHER_AS_JOB_FUNCTION" -> Right AgencySelectedOtherAsJobFunction
"AGENCY_SELECTED_PRODUCTION_AS_JOB_FUNCTION" -> Right AgencySelectedProductionAsJobFunction
"AGENCY_SELECTED_SEO_AS_JOB_FUNCTION" -> Right AgencySelectedSeoAsJobFunction
"AGENCY_SELECTED_SALES_REP_AS_JOB_FUNCTION" -> Right AgencySelectedSalesRepAsJobFunction
"AGENCY_SELECTED_SEARCH_SPECIALIST_AS_JOB_FUNCTION" -> Right AgencySelectedSearchSpeciaListAsJobFunction
"AGENCY_ADDED_CHANNELS_IN_MY_PROFILE_PORTAL" -> Right AgencyAddedChannelsInMyProFilePortal
"AGENCY_LOOKED_AT_ADD_CHANNEL_DROP_DOWN" -> Right AgencyLookedAtAddChannelDropDown
"AGENCY_SELECTED_CROSS_CHANNEL_FROM_ADD_CHANNEL" -> Right AgencySelectedCrossChannelFromAddChannel
"AGENCY_SELECTED_DISPLAY_FROM_ADD_CHANNEL" -> Right AgencySelectedDisplayFromAddChannel
"AGENCY_SELECTED_MOBILE_FROM_ADD_CHANNEL" -> Right AgencySelectedMobileFromAddChannel
"AGENCY_SELECTED_SEARCH_FROM_ADD_CHANNEL" -> Right AgencySelectedSearchFromAddChannel
"AGENCY_SELECTED_SOCIAL_FROM_ADD_CHANNEL" -> Right AgencySelectedSocialFromAddChannel
"AGENCY_SELECTED_TOOLS_FROM_ADD_CHANNEL" -> Right AgencySelectedToolsFromAddChannel
"AGENCY_SELECTED_YOUTUBE_FROM_ADD_CHANNEL" -> Right AgencySelectedYouTubeFromAddChannel
"AGENCY_ADDED_INDUSTRIES_IN_MY_PROFILE_PORTAL" -> Right AgencyAddedIndustriesInMyProFilePortal
"AGENCY_CHANGED_ADD_INDUSTRIES_DROP_DOWN" -> Right AgencyChangedAddIndustriesDropDown
"AGENCY_ADDED_MARKETS_IN_MY_PROFILE_PORTAL" -> Right AgencyAddedMarketsInMyProFilePortal
"AGENCY_CHANGED_ADD_MARKETS_DROP_DOWN" -> Right AgencyChangedAddMarketsDropDown
"AGENCY_CHECKED_RECIEVE_MAIL_PROMOTIONS_MYPROFILE" -> Right AgencyCheckedRecieveMailPromotionsMyproFile
"AGENCY_CHECKED_RECIEVE_MAIL_PROMOTIONS_SIGNUP" -> Right AgencyCheckedRecieveMailPromotionsSignup
"AGENCY_SELECTED_OPT_IN_BETA_TESTS_AND_MKT_RESEARCH" -> Right AgencySelectedOptInBetaTestsAndMktResearch
"AGENCY_SELECTED_OPT_IN_BETA_TESTS_IN_MY_PROFILE_PORTAL" -> Right AgencySelectedOptInBetaTestsInMyProFilePortal
"AGENCY_SELECTED_OPT_IN_NEWS_IN_MY_PROFILE_PORTAL" -> Right AgencySelectedOptInNewsInMyProFilePortal
"AGENCY_SELECTED_OPT_IN_NEWS_INVITATIONS_AND_PROMOS" -> Right AgencySelectedOptInNewsInvitationsAndPromos
"AGENCY_SELECTED_OPT_IN_PERFORMANCE_SUG_IN_MY_PROFILE_PORTAL" -> Right AgencySelectedOptInPerformanceSugInMyProFilePortal
"AGENCY_SELECTED_OPT_IN_PERFORMANCE_SUGGESTIONS" -> Right AgencySelectedOptInPerformanceSuggestions
"AGENCY_SELECTED_OPT_IN_SELECT_ALL_EMAIL_NOTIFICATIONS" -> Right AgencySelectedOptInSelectAllEmailNotifications
"AGENCY_SELECTED_SELECT_ALL_OPT_INS_IN_MY_PROFILE_PORTAL" -> Right AgencySelectedSelectAllOptInsInMyProFilePortal
"AGENCY_CLICKED_BACK_BUTTON_ON_CONNECT_WITH_COMPANY" -> Right AgencyClickedBackButtonOnConnectWithCompany
"AGENCY_CLICKED_CONTINUE_TO_OVERVIEW_ON_CONNECT_WITH_COMPANY" -> Right AgencyClickedContinueToOverviewOnConnectWithCompany
"AGECNY_CLICKED_CREATE_MCC_CONNECT_WITH_COMPANY_NOT_FOUND" -> Right AgecnyClickedCreateMccConnectWithCompanyNotFound
"AGECNY_CLICKED_GIVE_EDIT_ACCESS_CONNECT_WITH_COMPANY_NOT_FOUND" -> Right AgecnyClickedGiveEditAccessConnectWithCompanyNotFound
"AGECNY_CLICKED_LOG_OUT_CONNECT_WITH_COMPANY_NOT_FOUND" -> Right AgecnyClickedLogOutConnectWithCompanyNotFound
"AGENCY_CLICKED_SKIP_FOR_NOW_ON_CONNECT_WITH_COMPANY_PAGE" -> Right AgencyClickedSkipForNowOnConnectWithCompanyPage
"AGENCY_CLOSED_CONNECTED_TO_COMPANY_X_BUTTON_WRONG_COMPANY" -> Right AgencyClosedConnectedToCompanyXButtonWrongCompany
"AGENCY_COMPLETED_FIELD_CONNECT_WITH_COMPANY" -> Right AgencyCompletedFieldConnectWithCompany
"AGECNY_FOUND_COMPANY_TO_CONNECT_WITH" -> Right AgecnyFoundCompanyToConnectWith
"AGENCY_SUCCESSFULLY_CREATED_COMPANY" -> Right AgencySuccessfullyCreatedCompany
"AGENCY_ADDED_NEW_COMPANY_LOCATION" -> Right AgencyAddedNewCompanyLocation
"AGENCY_CLICKED_COMMUNITY_JOIN_NOW_LINK_IN_PORTAL_NOTIFICATIONS" -> Right AgencyClickedCommUnityJoinNowLinkInPortalNotifications
"AGENCY_CLICKED_CONNECT_TO_COMPANY_LINK_IN_PORTAL_NOTIFICATIONS" -> Right AgencyClickedConnectToCompanyLinkInPortalNotifications
"AGENCY_CLICKED_GET_CERTIFIED_LINK_IN_PORTAL_NOTIFICATIONS" -> Right AgencyClickedGetCertifiedLinkInPortalNotifications
"AGENCY_CLICKED_GET_VIDEO_ADS_CERTIFIED_LINK_IN_PORTAL_NOTIFICATIONS" -> Right AgencyClickedGetVideoAdsCertifiedLinkInPortalNotifications
"AGENCY_CLICKED_LINK_TO_MCC_LINK_IN_PORTAL_NOTIFICATIONS" -> Right AgencyClickedLinkToMccLinkInPortalNotifications
"AGENCY_CLICKED_INSIGHT_CONTENT_IN_PORTAL" -> Right AgencyClickedInsightContentInPortal
"AGENCY_CLICKED_INSIGHTS_VIEW_NOW_PITCH_DECKS_IN_PORTAL" -> Right AgencyClickedInsightsViewNowPitchDecksInPortal
"AGENCY_CLICKED_INSIGHTS_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedInsightsLeftNavInPortal
"AGENCY_CLICKED_INSIGHTS_UPLOAD_CONTENT" -> Right AgencyClickedInsightsUploadContent
"AGENCY_CLICKED_INSIGHTS_VIEWED_DEPRECATED" -> Right AgencyClickedInsightsViewedDeprecated
"AGENCY_CLICKED_COMMUNITY_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedCommUnityLeftNavInPortal
"AGENCY_CLICKED_JOIN_COMMUNITY_BUTTON_COMMUNITY_PORTAL" -> Right AgencyClickedJoinCommUnityButtonCommUnityPortal
"AGENCY_CLICKED_CERTIFICATIONS_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedCertificationsLeftNavInPortal
"AGENCY_CLICKED_CERTIFICATIONS_PRODUCT_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedCertificationsProductLeftNavInPortal
"AGENCY_CLICKED_PARTNER_STATUS_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedPartnerStatusLeftNavInPortal
"AGENCY_CLICKED_PARTNER_STATUS_PRODUCT_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedPartnerStatusProductLeftNavInPortal
"AGENCY_CLICKED_OFFERS_LEFT_NAV_IN_PORTAL" -> Right AgencyClickedOffersLeftNavInPortal
"AGENCY_CLICKED_SEND_BUTTON_ON_OFFERS_PAGE" -> Right AgencyClickedSendButtonOnOffersPage
"AGENCY_CLICKED_EXAM_DETAILS_ON_CERT_ADWORDS_PAGE" -> Right AgencyClickedExamDetailsOnCertAdwordsPage
"AGENCY_CLICKED_SEE_EXAMS_CERTIFICATION_MAIN_PAGE" -> Right AgencyClickedSeeExamsCertificationMainPage
"AGENCY_CLICKED_TAKE_EXAM_ON_CERT_EXAM_PAGE" -> Right AgencyClickedTakeExamOnCertExamPage
"AGENCY_OPENED_LAST_ADMIN_DIALOG" -> Right AgencyOpenedLastAdminDialog
"AGENCY_OPENED_DIALOG_WITH_NO_USERS" -> Right AgencyOpenedDialogWithNoUsers
"AGENCY_PROMOTED_USER_TO_ADMIN" -> Right AgencyPromotedUserToAdmin
"AGENCY_UNAFFILIATED" -> Right AgencyUnaffiliated
"AGENCY_CHANGED_ROLES" -> Right AgencyChangedRoles
"SMB_CLICKED_COMPANY_NAME_LINK_TO_PROFILE" -> Right SmbClickedCompanyNameLinkToProFile
"SMB_VIEWED_ADWORDS_CERTIFICATE" -> Right SmbViewedAdwordsCertificate
"SMB_VIEWED_ADWORDS_SEARCH_CERTIFICATE" -> Right SmbViewedAdwordsSearchCertificate
"SMB_VIEWED_ADWORDS_DISPLAY_CERTIFICATE" -> Right SmbViewedAdwordsDisplayCertificate
"SMB_CLICKED_ADWORDS_CERTIFICATE_HELP_ICON" -> Right SmbClickedAdwordsCertificateHelpIcon
"SMB_VIEWED_ANALYTICS_CERTIFICATE" -> Right SmbViewedAnalyticsCertificate
"SMB_VIEWED_DOUBLECLICK_CERTIFICATE" -> Right SmbViewedDoubleClickCertificate
"SMB_VIEWED_MOBILE_SITES_CERTIFICATE" -> Right SmbViewedMobileSitesCertificate
"SMB_VIEWED_VIDEO_ADS_CERTIFICATE" -> Right SmbViewedVideoAdsCertificate
"SMB_VIEWED_SHOPPING_CERTIFICATE" -> Right SmbViewedShoppingCertificate
"SMB_CLICKED_VIDEO_ADS_CERTIFICATE_HELP_ICON" -> Right SmbClickedVideoAdsCertificateHelpIcon
"SMB_VIEWED_DIGITAL_SALES_CERTIFICATE" -> Right SmbViewedDigitalSalesCertificate
"CLICKED_HELP_AT_BOTTOM" -> Right ClickedHelpAtBottom
"CLICKED_HELP_AT_TOP" -> Right ClickedHelpAtTop
"CLIENT_ERROR" -> Right ClientError
"AGENCY_CLICKED_LEFT_NAV_STORIES" -> Right AgencyClickedLeftNavStories
"CLICKED" -> Right Clicked
"SMB_VIEWED_MOBILE_CERTIFICATE" -> Right SmbViewedMobileCertificate
"AGENCY_FAILED_COMPANY_VERIFICATION" -> Right AgencyFailedCompanyVerification
"VISITED_LANDING" -> Right VisitedLanding
"VISITED_GPS" -> Right VisitedGps
"VISITED_AGENCY_PORTAL" -> Right VisitedAgencyPortal
"CANCELLED_INDIVIDUAL_SIGN_UP" -> Right CancelledIndividualSignUp
"CANCELLED_COMPANY_SIGN_UP" -> Right CancelledCompanySignUp
"AGENCY_CLICKED_SIGN_IN_BUTTON_TOP" -> Right AgencyClickedSignInButtonTop
"AGENCY_CLICKED_SAVE_AND_CONTINUE_AT_BOT_OF_INCOMPLETE_PROFILE" -> Right AgencyClickedSaveAndContinueAtBotOfIncompleteProFile
"AGENCY_UNSELECTED_OPT_IN_NEWS_INVITATIONS_AND_PROMOS" -> Right AgencyUnselectedOptInNewsInvitationsAndPromos
"AGENCY_UNSELECTED_OPT_IN_BETA_TESTS_AND_MKT_RESEARCH" -> Right AgencyUnselectedOptInBetaTestsAndMktResearch
"AGENCY_UNSELECTED_OPT_IN_PERFORMANCE_SUGGESTIONS" -> Right AgencyUnselectedOptInPerformanceSuggestions
"AGENCY_SELECTED_OPT_OUT_UNSELECT_ALL_EMAIL_NOTIFICATIONS" -> Right AgencySelectedOptOutUnselectAllEmailNotifications
"AGENCY_LINKED_INDIVIDUAL_MCC" -> Right AgencyLinkedIndividualMcc
"AGENCY_SUGGESTED_TO_USER" -> Right AgencySuggestedToUser
"AGENCY_IGNORED_SUGGESTED_AGENCIES_AND_SEARCHED" -> Right AgencyIgnoredSuggestedAgenciesAndSearched
"AGENCY_PICKED_SUGGESTED_AGENCY" -> Right AgencyPickedSuggestedAgency
"AGENCY_SEARCHED_FOR_AGENCIES" -> Right AgencySearchedForAgencies
"AGENCY_PICKED_SEARCHED_AGENCY" -> Right AgencyPickedSearchedAgency
"AGENCY_DISMISSED_AFFILIATION_WIDGET" -> Right AgencyDismissedAffiliationWidget
"AGENCY_CLICKED_INSIGHTS_DOWNLOAD_CONTENT" -> Right AgencyClickedInsightsDownloadContent
"AGENCY_PROGRESS_INSIGHTS_VIEW_CONTENT" -> Right AgencyProgressInsightsViewContent
"AGENCY_CLICKED_CANCEL_ACCEPT_TOS_BUTTON" -> Right AgencyClickedCancelAcceptTosButton
"SMB_ENTERED_WEBSITE_IN_CONTACT_PARTNER_FORM" -> Right SmbEnteredWebsiteInContactPartnerForm
"AGENCY_SELECTED_OPT_IN_AFA_MIGRATION" -> Right AgencySelectedOptInAfaMigration
"AGENCY_SELECTED_OPT_OUT_AFA_MIGRATION" -> Right AgencySelectedOptOutAfaMigration
x -> Left ("Unable to parse LogUserEventRequestEventAction from: " <> x)
instance ToHttpApiData LogUserEventRequestEventAction where
toQueryParam = \case
EventActionUnspecified -> "EVENT_ACTION_UNSPECIFIED"
SmbClickedFindAPartnerButtonBottom -> "SMB_CLICKED_FIND_A_PARTNER_BUTTON_BOTTOM"
SmbClickedFindAPartnerButtonTop -> "SMB_CLICKED_FIND_A_PARTNER_BUTTON_TOP"
AgencyClickedJoinNowButtonBottom -> "AGENCY_CLICKED_JOIN_NOW_BUTTON_BOTTOM"
AgencyClickedJoinNowButtonTop -> "AGENCY_CLICKED_JOIN_NOW_BUTTON_TOP"
SmbCanceledPartnerContactForm -> "SMB_CANCELED_PARTNER_CONTACT_FORM"
SmbClickedContactAPartner -> "SMB_CLICKED_CONTACT_A_PARTNER"
SmbCompletedPartnerContactForm -> "SMB_COMPLETED_PARTNER_CONTACT_FORM"
SmbEnteredEmailInContactPartnerForm -> "SMB_ENTERED_EMAIL_IN_CONTACT_PARTNER_FORM"
SmbEnteredNameInContactPartnerForm -> "SMB_ENTERED_NAME_IN_CONTACT_PARTNER_FORM"
SmbEnteredPhoneInContactPartnerForm -> "SMB_ENTERED_PHONE_IN_CONTACT_PARTNER_FORM"
SmbFailedRecaptchaInContactPartnerForm -> "SMB_FAILED_RECAPTCHA_IN_CONTACT_PARTNER_FORM"
PartnerViewedBySmb -> "PARTNER_VIEWED_BY_SMB"
SmbCanceledPartnerContactFormOnGps -> "SMB_CANCELED_PARTNER_CONTACT_FORM_ON_GPS"
SmbChangedASearchParameterTop -> "SMB_CHANGED_A_SEARCH_PARAMETER_TOP"
SmbClickedContactAPartnerOnGps -> "SMB_CLICKED_CONTACT_A_PARTNER_ON_GPS"
SmbClickedShowMorePartnersButtonBottom -> "SMB_CLICKED_SHOW_MORE_PARTNERS_BUTTON_BOTTOM"
SmbCompletedPartnerContactFormOnGps -> "SMB_COMPLETED_PARTNER_CONTACT_FORM_ON_GPS"
SmbNoPartnersAvailableWithSearchCriteria -> "SMB_NO_PARTNERS_AVAILABLE_WITH_SEARCH_CRITERIA"
SmbPerformedSearchOnGps -> "SMB_PERFORMED_SEARCH_ON_GPS"
SmbViewedAPartnerOnGps -> "SMB_VIEWED_A_PARTNER_ON_GPS"
SmbCanceledPartnerContactFormOnProFilePage -> "SMB_CANCELED_PARTNER_CONTACT_FORM_ON_PROFILE_PAGE"
SmbClickedContactAPartnerOnProFilePage -> "SMB_CLICKED_CONTACT_A_PARTNER_ON_PROFILE_PAGE"
SmbClickedPartnerWebsite -> "SMB_CLICKED_PARTNER_WEBSITE"
SmbCompletedPartnerContactFormOnProFilePage -> "SMB_COMPLETED_PARTNER_CONTACT_FORM_ON_PROFILE_PAGE"
SmbViewedAPartnerProFile -> "SMB_VIEWED_A_PARTNER_PROFILE"
AgencyClickedAcceptTosButton -> "AGENCY_CLICKED_ACCEPT_TOS_BUTTON"
AgencyChangedTosCountry -> "AGENCY_CHANGED_TOS_COUNTRY"
AgencyAddedAddressInMyProFilePortal -> "AGENCY_ADDED_ADDRESS_IN_MY_PROFILE_PORTAL"
AgencyAddedPhoneNumberInMyProFilePortal -> "AGENCY_ADDED_PHONE_NUMBER_IN_MY_PROFILE_PORTAL"
AgencyChangedPrimaryAccountAssociation -> "AGENCY_CHANGED_PRIMARY_ACCOUNT_ASSOCIATION"
AgencyChangedPrimaryCountryAssociation -> "AGENCY_CHANGED_PRIMARY_COUNTRY_ASSOCIATION"
AgencyClickedAffiliateButtonInMyProFileInPortal -> "AGENCY_CLICKED_AFFILIATE_BUTTON_IN_MY_PROFILE_IN_PORTAL"
AgencyClickedGiveEditAccessInMyProFilePortal -> "AGENCY_CLICKED_GIVE_EDIT_ACCESS_IN_MY_PROFILE_PORTAL"
AgencyClickedLogOutInMyProFilePortal -> "AGENCY_CLICKED_LOG_OUT_IN_MY_PROFILE_PORTAL"
AgencyClickedMyProFileLeftNavInPortal -> "AGENCY_CLICKED_MY_PROFILE_LEFT_NAV_IN_PORTAL"
AgencyClickedSaveAndContinueAtBotOfCompleteProFile -> "AGENCY_CLICKED_SAVE_AND_CONTINUE_AT_BOT_OF_COMPLETE_PROFILE"
AgencyClickedUnaffiliateInMyProFilePortal -> "AGENCY_CLICKED_UNAFFILIATE_IN_MY_PROFILE_PORTAL"
AgencyFilledOutCompAffiliationInMyProFilePortal -> "AGENCY_FILLED_OUT_COMP_AFFILIATION_IN_MY_PROFILE_PORTAL"
AgencySuccessfullyConnectedWithCompanyInMyProFile -> "AGENCY_SUCCESSFULLY_CONNECTED_WITH_COMPANY_IN_MY_PROFILE"
AgencyClickedCreateMccInMyProFilePortal -> "AGENCY_CLICKED_CREATE_MCC_IN_MY_PROFILE_PORTAL"
AgencyDidntHaveAnMccAssociatedOnCompleteProFile -> "AGENCY_DIDNT_HAVE_AN_MCC_ASSOCIATED_ON_COMPLETE_PROFILE"
AgencyHadAnMccAssociatedOnCompleteProFile -> "AGENCY_HAD_AN_MCC_ASSOCIATED_ON_COMPLETE_PROFILE"
AgencyAddedJobFunctionInMyProFilePortal -> "AGENCY_ADDED_JOB_FUNCTION_IN_MY_PROFILE_PORTAL"
AgencyLookedAtJobFunctionDropDown -> "AGENCY_LOOKED_AT_JOB_FUNCTION_DROP_DOWN"
AgencySelectedAccountManagerAsJobFunction -> "AGENCY_SELECTED_ACCOUNT_MANAGER_AS_JOB_FUNCTION"
AgencySelectedAccountPlannerAsJobFunction -> "AGENCY_SELECTED_ACCOUNT_PLANNER_AS_JOB_FUNCTION"
AgencySelectedAnalyticsAsJobFunction -> "AGENCY_SELECTED_ANALYTICS_AS_JOB_FUNCTION"
AgencySelectedCreativeAsJobFunction -> "AGENCY_SELECTED_CREATIVE_AS_JOB_FUNCTION"
AgencySelectedMediaBuyerAsJobFunction -> "AGENCY_SELECTED_MEDIA_BUYER_AS_JOB_FUNCTION"
AgencySelectedMediaPlannerAsJobFunction -> "AGENCY_SELECTED_MEDIA_PLANNER_AS_JOB_FUNCTION"
AgencySelectedOtherAsJobFunction -> "AGENCY_SELECTED_OTHER_AS_JOB_FUNCTION"
AgencySelectedProductionAsJobFunction -> "AGENCY_SELECTED_PRODUCTION_AS_JOB_FUNCTION"
AgencySelectedSeoAsJobFunction -> "AGENCY_SELECTED_SEO_AS_JOB_FUNCTION"
AgencySelectedSalesRepAsJobFunction -> "AGENCY_SELECTED_SALES_REP_AS_JOB_FUNCTION"
AgencySelectedSearchSpeciaListAsJobFunction -> "AGENCY_SELECTED_SEARCH_SPECIALIST_AS_JOB_FUNCTION"
AgencyAddedChannelsInMyProFilePortal -> "AGENCY_ADDED_CHANNELS_IN_MY_PROFILE_PORTAL"
AgencyLookedAtAddChannelDropDown -> "AGENCY_LOOKED_AT_ADD_CHANNEL_DROP_DOWN"
AgencySelectedCrossChannelFromAddChannel -> "AGENCY_SELECTED_CROSS_CHANNEL_FROM_ADD_CHANNEL"
AgencySelectedDisplayFromAddChannel -> "AGENCY_SELECTED_DISPLAY_FROM_ADD_CHANNEL"
AgencySelectedMobileFromAddChannel -> "AGENCY_SELECTED_MOBILE_FROM_ADD_CHANNEL"
AgencySelectedSearchFromAddChannel -> "AGENCY_SELECTED_SEARCH_FROM_ADD_CHANNEL"
AgencySelectedSocialFromAddChannel -> "AGENCY_SELECTED_SOCIAL_FROM_ADD_CHANNEL"
AgencySelectedToolsFromAddChannel -> "AGENCY_SELECTED_TOOLS_FROM_ADD_CHANNEL"
AgencySelectedYouTubeFromAddChannel -> "AGENCY_SELECTED_YOUTUBE_FROM_ADD_CHANNEL"
AgencyAddedIndustriesInMyProFilePortal -> "AGENCY_ADDED_INDUSTRIES_IN_MY_PROFILE_PORTAL"
AgencyChangedAddIndustriesDropDown -> "AGENCY_CHANGED_ADD_INDUSTRIES_DROP_DOWN"
AgencyAddedMarketsInMyProFilePortal -> "AGENCY_ADDED_MARKETS_IN_MY_PROFILE_PORTAL"
AgencyChangedAddMarketsDropDown -> "AGENCY_CHANGED_ADD_MARKETS_DROP_DOWN"
AgencyCheckedRecieveMailPromotionsMyproFile -> "AGENCY_CHECKED_RECIEVE_MAIL_PROMOTIONS_MYPROFILE"
AgencyCheckedRecieveMailPromotionsSignup -> "AGENCY_CHECKED_RECIEVE_MAIL_PROMOTIONS_SIGNUP"
AgencySelectedOptInBetaTestsAndMktResearch -> "AGENCY_SELECTED_OPT_IN_BETA_TESTS_AND_MKT_RESEARCH"
AgencySelectedOptInBetaTestsInMyProFilePortal -> "AGENCY_SELECTED_OPT_IN_BETA_TESTS_IN_MY_PROFILE_PORTAL"
AgencySelectedOptInNewsInMyProFilePortal -> "AGENCY_SELECTED_OPT_IN_NEWS_IN_MY_PROFILE_PORTAL"
AgencySelectedOptInNewsInvitationsAndPromos -> "AGENCY_SELECTED_OPT_IN_NEWS_INVITATIONS_AND_PROMOS"
AgencySelectedOptInPerformanceSugInMyProFilePortal -> "AGENCY_SELECTED_OPT_IN_PERFORMANCE_SUG_IN_MY_PROFILE_PORTAL"
AgencySelectedOptInPerformanceSuggestions -> "AGENCY_SELECTED_OPT_IN_PERFORMANCE_SUGGESTIONS"
AgencySelectedOptInSelectAllEmailNotifications -> "AGENCY_SELECTED_OPT_IN_SELECT_ALL_EMAIL_NOTIFICATIONS"
AgencySelectedSelectAllOptInsInMyProFilePortal -> "AGENCY_SELECTED_SELECT_ALL_OPT_INS_IN_MY_PROFILE_PORTAL"
AgencyClickedBackButtonOnConnectWithCompany -> "AGENCY_CLICKED_BACK_BUTTON_ON_CONNECT_WITH_COMPANY"
AgencyClickedContinueToOverviewOnConnectWithCompany -> "AGENCY_CLICKED_CONTINUE_TO_OVERVIEW_ON_CONNECT_WITH_COMPANY"
AgecnyClickedCreateMccConnectWithCompanyNotFound -> "AGECNY_CLICKED_CREATE_MCC_CONNECT_WITH_COMPANY_NOT_FOUND"
AgecnyClickedGiveEditAccessConnectWithCompanyNotFound -> "AGECNY_CLICKED_GIVE_EDIT_ACCESS_CONNECT_WITH_COMPANY_NOT_FOUND"
AgecnyClickedLogOutConnectWithCompanyNotFound -> "AGECNY_CLICKED_LOG_OUT_CONNECT_WITH_COMPANY_NOT_FOUND"
AgencyClickedSkipForNowOnConnectWithCompanyPage -> "AGENCY_CLICKED_SKIP_FOR_NOW_ON_CONNECT_WITH_COMPANY_PAGE"
AgencyClosedConnectedToCompanyXButtonWrongCompany -> "AGENCY_CLOSED_CONNECTED_TO_COMPANY_X_BUTTON_WRONG_COMPANY"
AgencyCompletedFieldConnectWithCompany -> "AGENCY_COMPLETED_FIELD_CONNECT_WITH_COMPANY"
AgecnyFoundCompanyToConnectWith -> "AGECNY_FOUND_COMPANY_TO_CONNECT_WITH"
AgencySuccessfullyCreatedCompany -> "AGENCY_SUCCESSFULLY_CREATED_COMPANY"
AgencyAddedNewCompanyLocation -> "AGENCY_ADDED_NEW_COMPANY_LOCATION"
AgencyClickedCommUnityJoinNowLinkInPortalNotifications -> "AGENCY_CLICKED_COMMUNITY_JOIN_NOW_LINK_IN_PORTAL_NOTIFICATIONS"
AgencyClickedConnectToCompanyLinkInPortalNotifications -> "AGENCY_CLICKED_CONNECT_TO_COMPANY_LINK_IN_PORTAL_NOTIFICATIONS"
AgencyClickedGetCertifiedLinkInPortalNotifications -> "AGENCY_CLICKED_GET_CERTIFIED_LINK_IN_PORTAL_NOTIFICATIONS"
AgencyClickedGetVideoAdsCertifiedLinkInPortalNotifications -> "AGENCY_CLICKED_GET_VIDEO_ADS_CERTIFIED_LINK_IN_PORTAL_NOTIFICATIONS"
AgencyClickedLinkToMccLinkInPortalNotifications -> "AGENCY_CLICKED_LINK_TO_MCC_LINK_IN_PORTAL_NOTIFICATIONS"
AgencyClickedInsightContentInPortal -> "AGENCY_CLICKED_INSIGHT_CONTENT_IN_PORTAL"
AgencyClickedInsightsViewNowPitchDecksInPortal -> "AGENCY_CLICKED_INSIGHTS_VIEW_NOW_PITCH_DECKS_IN_PORTAL"
AgencyClickedInsightsLeftNavInPortal -> "AGENCY_CLICKED_INSIGHTS_LEFT_NAV_IN_PORTAL"
AgencyClickedInsightsUploadContent -> "AGENCY_CLICKED_INSIGHTS_UPLOAD_CONTENT"
AgencyClickedInsightsViewedDeprecated -> "AGENCY_CLICKED_INSIGHTS_VIEWED_DEPRECATED"
AgencyClickedCommUnityLeftNavInPortal -> "AGENCY_CLICKED_COMMUNITY_LEFT_NAV_IN_PORTAL"
AgencyClickedJoinCommUnityButtonCommUnityPortal -> "AGENCY_CLICKED_JOIN_COMMUNITY_BUTTON_COMMUNITY_PORTAL"
AgencyClickedCertificationsLeftNavInPortal -> "AGENCY_CLICKED_CERTIFICATIONS_LEFT_NAV_IN_PORTAL"
AgencyClickedCertificationsProductLeftNavInPortal -> "AGENCY_CLICKED_CERTIFICATIONS_PRODUCT_LEFT_NAV_IN_PORTAL"
AgencyClickedPartnerStatusLeftNavInPortal -> "AGENCY_CLICKED_PARTNER_STATUS_LEFT_NAV_IN_PORTAL"
AgencyClickedPartnerStatusProductLeftNavInPortal -> "AGENCY_CLICKED_PARTNER_STATUS_PRODUCT_LEFT_NAV_IN_PORTAL"
AgencyClickedOffersLeftNavInPortal -> "AGENCY_CLICKED_OFFERS_LEFT_NAV_IN_PORTAL"
AgencyClickedSendButtonOnOffersPage -> "AGENCY_CLICKED_SEND_BUTTON_ON_OFFERS_PAGE"
AgencyClickedExamDetailsOnCertAdwordsPage -> "AGENCY_CLICKED_EXAM_DETAILS_ON_CERT_ADWORDS_PAGE"
AgencyClickedSeeExamsCertificationMainPage -> "AGENCY_CLICKED_SEE_EXAMS_CERTIFICATION_MAIN_PAGE"
AgencyClickedTakeExamOnCertExamPage -> "AGENCY_CLICKED_TAKE_EXAM_ON_CERT_EXAM_PAGE"
AgencyOpenedLastAdminDialog -> "AGENCY_OPENED_LAST_ADMIN_DIALOG"
AgencyOpenedDialogWithNoUsers -> "AGENCY_OPENED_DIALOG_WITH_NO_USERS"
AgencyPromotedUserToAdmin -> "AGENCY_PROMOTED_USER_TO_ADMIN"
AgencyUnaffiliated -> "AGENCY_UNAFFILIATED"
AgencyChangedRoles -> "AGENCY_CHANGED_ROLES"
SmbClickedCompanyNameLinkToProFile -> "SMB_CLICKED_COMPANY_NAME_LINK_TO_PROFILE"
SmbViewedAdwordsCertificate -> "SMB_VIEWED_ADWORDS_CERTIFICATE"
SmbViewedAdwordsSearchCertificate -> "SMB_VIEWED_ADWORDS_SEARCH_CERTIFICATE"
SmbViewedAdwordsDisplayCertificate -> "SMB_VIEWED_ADWORDS_DISPLAY_CERTIFICATE"
SmbClickedAdwordsCertificateHelpIcon -> "SMB_CLICKED_ADWORDS_CERTIFICATE_HELP_ICON"
SmbViewedAnalyticsCertificate -> "SMB_VIEWED_ANALYTICS_CERTIFICATE"
SmbViewedDoubleClickCertificate -> "SMB_VIEWED_DOUBLECLICK_CERTIFICATE"
SmbViewedMobileSitesCertificate -> "SMB_VIEWED_MOBILE_SITES_CERTIFICATE"
SmbViewedVideoAdsCertificate -> "SMB_VIEWED_VIDEO_ADS_CERTIFICATE"
SmbViewedShoppingCertificate -> "SMB_VIEWED_SHOPPING_CERTIFICATE"
SmbClickedVideoAdsCertificateHelpIcon -> "SMB_CLICKED_VIDEO_ADS_CERTIFICATE_HELP_ICON"
SmbViewedDigitalSalesCertificate -> "SMB_VIEWED_DIGITAL_SALES_CERTIFICATE"
ClickedHelpAtBottom -> "CLICKED_HELP_AT_BOTTOM"
ClickedHelpAtTop -> "CLICKED_HELP_AT_TOP"
ClientError -> "CLIENT_ERROR"
AgencyClickedLeftNavStories -> "AGENCY_CLICKED_LEFT_NAV_STORIES"
Clicked -> "CLICKED"
SmbViewedMobileCertificate -> "SMB_VIEWED_MOBILE_CERTIFICATE"
AgencyFailedCompanyVerification -> "AGENCY_FAILED_COMPANY_VERIFICATION"
VisitedLanding -> "VISITED_LANDING"
VisitedGps -> "VISITED_GPS"
VisitedAgencyPortal -> "VISITED_AGENCY_PORTAL"
CancelledIndividualSignUp -> "CANCELLED_INDIVIDUAL_SIGN_UP"
CancelledCompanySignUp -> "CANCELLED_COMPANY_SIGN_UP"
AgencyClickedSignInButtonTop -> "AGENCY_CLICKED_SIGN_IN_BUTTON_TOP"
AgencyClickedSaveAndContinueAtBotOfIncompleteProFile -> "AGENCY_CLICKED_SAVE_AND_CONTINUE_AT_BOT_OF_INCOMPLETE_PROFILE"
AgencyUnselectedOptInNewsInvitationsAndPromos -> "AGENCY_UNSELECTED_OPT_IN_NEWS_INVITATIONS_AND_PROMOS"
AgencyUnselectedOptInBetaTestsAndMktResearch -> "AGENCY_UNSELECTED_OPT_IN_BETA_TESTS_AND_MKT_RESEARCH"
AgencyUnselectedOptInPerformanceSuggestions -> "AGENCY_UNSELECTED_OPT_IN_PERFORMANCE_SUGGESTIONS"
AgencySelectedOptOutUnselectAllEmailNotifications -> "AGENCY_SELECTED_OPT_OUT_UNSELECT_ALL_EMAIL_NOTIFICATIONS"
AgencyLinkedIndividualMcc -> "AGENCY_LINKED_INDIVIDUAL_MCC"
AgencySuggestedToUser -> "AGENCY_SUGGESTED_TO_USER"
AgencyIgnoredSuggestedAgenciesAndSearched -> "AGENCY_IGNORED_SUGGESTED_AGENCIES_AND_SEARCHED"
AgencyPickedSuggestedAgency -> "AGENCY_PICKED_SUGGESTED_AGENCY"
AgencySearchedForAgencies -> "AGENCY_SEARCHED_FOR_AGENCIES"
AgencyPickedSearchedAgency -> "AGENCY_PICKED_SEARCHED_AGENCY"
AgencyDismissedAffiliationWidget -> "AGENCY_DISMISSED_AFFILIATION_WIDGET"
AgencyClickedInsightsDownloadContent -> "AGENCY_CLICKED_INSIGHTS_DOWNLOAD_CONTENT"
AgencyProgressInsightsViewContent -> "AGENCY_PROGRESS_INSIGHTS_VIEW_CONTENT"
AgencyClickedCancelAcceptTosButton -> "AGENCY_CLICKED_CANCEL_ACCEPT_TOS_BUTTON"
SmbEnteredWebsiteInContactPartnerForm -> "SMB_ENTERED_WEBSITE_IN_CONTACT_PARTNER_FORM"
AgencySelectedOptInAfaMigration -> "AGENCY_SELECTED_OPT_IN_AFA_MIGRATION"
AgencySelectedOptOutAfaMigration -> "AGENCY_SELECTED_OPT_OUT_AFA_MIGRATION"
instance FromJSON LogUserEventRequestEventAction where
parseJSON = parseJSONText "LogUserEventRequestEventAction"
instance ToJSON LogUserEventRequestEventAction where
toJSON = toJSONText
-- | Status of the offer.
data HistoricalOfferStatus
= OfferStatusUnspecified
-- ^ @OFFER_STATUS_UNSPECIFIED@
-- Unset.
| OfferStatusDistributed
-- ^ @OFFER_STATUS_DISTRIBUTED@
-- Offer distributed.
| OfferStatusRedeemed
-- ^ @OFFER_STATUS_REDEEMED@
-- Offer redeemed.
| OfferStatusAwarded
-- ^ @OFFER_STATUS_AWARDED@
-- Offer awarded.
| OfferStatusExpired
-- ^ @OFFER_STATUS_EXPIRED@
-- Offer expired.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable HistoricalOfferStatus
instance FromHttpApiData HistoricalOfferStatus where
parseQueryParam = \case
"OFFER_STATUS_UNSPECIFIED" -> Right OfferStatusUnspecified
"OFFER_STATUS_DISTRIBUTED" -> Right OfferStatusDistributed
"OFFER_STATUS_REDEEMED" -> Right OfferStatusRedeemed
"OFFER_STATUS_AWARDED" -> Right OfferStatusAwarded
"OFFER_STATUS_EXPIRED" -> Right OfferStatusExpired
x -> Left ("Unable to parse HistoricalOfferStatus from: " <> x)
instance ToHttpApiData HistoricalOfferStatus where
toQueryParam = \case
OfferStatusUnspecified -> "OFFER_STATUS_UNSPECIFIED"
OfferStatusDistributed -> "OFFER_STATUS_DISTRIBUTED"
OfferStatusRedeemed -> "OFFER_STATUS_REDEEMED"
OfferStatusAwarded -> "OFFER_STATUS_AWARDED"
OfferStatusExpired -> "OFFER_STATUS_EXPIRED"
instance FromJSON HistoricalOfferStatus where
parseJSON = parseJSONText "HistoricalOfferStatus"
instance ToJSON HistoricalOfferStatus where
toJSON = toJSONText
-- | The public viewability status of the company\'s profile.
data CompanyProFileStatus
= CompanyProFileStatusUnspecified
-- ^ @COMPANY_PROFILE_STATUS_UNSPECIFIED@
-- Unchosen.
| Hidden
-- ^ @HIDDEN@
-- Company profile does not show up publicly.
| Published
-- ^ @PUBLISHED@
-- Company profile can only be viewed by the profile\'s URL and not by
-- Google Partner Search.
| Searchable
-- ^ @SEARCHABLE@
-- Company profile can be viewed by the profile\'s URL and by Google
-- Partner Search.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompanyProFileStatus
instance FromHttpApiData CompanyProFileStatus where
parseQueryParam = \case
"COMPANY_PROFILE_STATUS_UNSPECIFIED" -> Right CompanyProFileStatusUnspecified
"HIDDEN" -> Right Hidden
"PUBLISHED" -> Right Published
"SEARCHABLE" -> Right Searchable
x -> Left ("Unable to parse CompanyProFileStatus from: " <> x)
instance ToHttpApiData CompanyProFileStatus where
toQueryParam = \case
CompanyProFileStatusUnspecified -> "COMPANY_PROFILE_STATUS_UNSPECIFIED"
Hidden -> "HIDDEN"
Published -> "PUBLISHED"
Searchable -> "SEARCHABLE"
instance FromJSON CompanyProFileStatus where
parseJSON = parseJSONText "CompanyProFileStatus"
instance ToJSON CompanyProFileStatus where
toJSON = toJSONText
-- | Partner badge tier
data CompanyBadgeTier
= BadgeTierNone
-- ^ @BADGE_TIER_NONE@
-- Tier badge is not set.
| BadgeTierRegular
-- ^ @BADGE_TIER_REGULAR@
-- Agency has regular partner badge.
| BadgeTierPremier
-- ^ @BADGE_TIER_PREMIER@
-- Agency has premier badge.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompanyBadgeTier
instance FromHttpApiData CompanyBadgeTier where
parseQueryParam = \case
"BADGE_TIER_NONE" -> Right BadgeTierNone
"BADGE_TIER_REGULAR" -> Right BadgeTierRegular
"BADGE_TIER_PREMIER" -> Right BadgeTierPremier
x -> Left ("Unable to parse CompanyBadgeTier from: " <> x)
instance ToHttpApiData CompanyBadgeTier where
toQueryParam = \case
BadgeTierNone -> "BADGE_TIER_NONE"
BadgeTierRegular -> "BADGE_TIER_REGULAR"
BadgeTierPremier -> "BADGE_TIER_PREMIER"
instance FromJSON CompanyBadgeTier where
parseJSON = parseJSONText "CompanyBadgeTier"
instance ToJSON CompanyBadgeTier where
toJSON = toJSONText
-- | Whether the company is a Partner.
data CompanyRelationBadgeTier
= CRBTBadgeTierNone
-- ^ @BADGE_TIER_NONE@
-- Tier badge is not set.
| CRBTBadgeTierRegular
-- ^ @BADGE_TIER_REGULAR@
-- Agency has regular partner badge.
| CRBTBadgeTierPremier
-- ^ @BADGE_TIER_PREMIER@
-- Agency has premier badge.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompanyRelationBadgeTier
instance FromHttpApiData CompanyRelationBadgeTier where
parseQueryParam = \case
"BADGE_TIER_NONE" -> Right CRBTBadgeTierNone
"BADGE_TIER_REGULAR" -> Right CRBTBadgeTierRegular
"BADGE_TIER_PREMIER" -> Right CRBTBadgeTierPremier
x -> Left ("Unable to parse CompanyRelationBadgeTier from: " <> x)
instance ToHttpApiData CompanyRelationBadgeTier where
toQueryParam = \case
CRBTBadgeTierNone -> "BADGE_TIER_NONE"
CRBTBadgeTierRegular -> "BADGE_TIER_REGULAR"
CRBTBadgeTierPremier -> "BADGE_TIER_PREMIER"
instance FromJSON CompanyRelationBadgeTier where
parseJSON = parseJSONText "CompanyRelationBadgeTier"
instance ToJSON CompanyRelationBadgeTier where
toJSON = toJSONText
-- | The state of relationship, in terms of approvals.
data CompanyRelationState
= UserCompanyReationStateNoneSpecified
-- ^ @USER_COMPANY_REATION_STATE_NONE_SPECIFIED@
-- Default unspecified value.
| UserCompanyRelationStateAwaitEmail
-- ^ @USER_COMPANY_RELATION_STATE_AWAIT_EMAIL@
-- User has filled in a request to be associated with an company. Now
-- waiting email confirmation.
| UserCompanyRelationStateAwaitAdmin
-- ^ @USER_COMPANY_RELATION_STATE_AWAIT_ADMIN@
-- Pending approval from company. Email confirmation will not approve this
-- one.
| UserCompanyRelationStateApproved
-- ^ @USER_COMPANY_RELATION_STATE_APPROVED@
-- Approved by company.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CompanyRelationState
instance FromHttpApiData CompanyRelationState where
parseQueryParam = \case
"USER_COMPANY_REATION_STATE_NONE_SPECIFIED" -> Right UserCompanyReationStateNoneSpecified
"USER_COMPANY_RELATION_STATE_AWAIT_EMAIL" -> Right UserCompanyRelationStateAwaitEmail
"USER_COMPANY_RELATION_STATE_AWAIT_ADMIN" -> Right UserCompanyRelationStateAwaitAdmin
"USER_COMPANY_RELATION_STATE_APPROVED" -> Right UserCompanyRelationStateApproved
x -> Left ("Unable to parse CompanyRelationState from: " <> x)
instance ToHttpApiData CompanyRelationState where
toQueryParam = \case
UserCompanyReationStateNoneSpecified -> "USER_COMPANY_REATION_STATE_NONE_SPECIFIED"
UserCompanyRelationStateAwaitEmail -> "USER_COMPANY_RELATION_STATE_AWAIT_EMAIL"
UserCompanyRelationStateAwaitAdmin -> "USER_COMPANY_RELATION_STATE_AWAIT_ADMIN"
UserCompanyRelationStateApproved -> "USER_COMPANY_RELATION_STATE_APPROVED"
instance FromJSON CompanyRelationState where
parseJSON = parseJSONText "CompanyRelationState"
instance ToJSON CompanyRelationState where
toJSON = toJSONText
-- | Type of offer country is eligible for.
data CountryOfferInfoOfferType
= COIOTOfferTypeUnspecified
-- ^ @OFFER_TYPE_UNSPECIFIED@
-- Unset.
| COIOTOfferTypeSpendXGetY
-- ^ @OFFER_TYPE_SPEND_X_GET_Y@
-- AdWords spend X get Y.
| COIOTOfferTypeVideo
-- ^ @OFFER_TYPE_VIDEO@
-- Youtube video.
| COIOTOfferTypeSpendMatch
-- ^ @OFFER_TYPE_SPEND_MATCH@
-- Spend Match up to Y.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CountryOfferInfoOfferType
instance FromHttpApiData CountryOfferInfoOfferType where
parseQueryParam = \case
"OFFER_TYPE_UNSPECIFIED" -> Right COIOTOfferTypeUnspecified
"OFFER_TYPE_SPEND_X_GET_Y" -> Right COIOTOfferTypeSpendXGetY
"OFFER_TYPE_VIDEO" -> Right COIOTOfferTypeVideo
"OFFER_TYPE_SPEND_MATCH" -> Right COIOTOfferTypeSpendMatch
x -> Left ("Unable to parse CountryOfferInfoOfferType from: " <> x)
instance ToHttpApiData CountryOfferInfoOfferType where
toQueryParam = \case
COIOTOfferTypeUnspecified -> "OFFER_TYPE_UNSPECIFIED"
COIOTOfferTypeSpendXGetY -> "OFFER_TYPE_SPEND_X_GET_Y"
COIOTOfferTypeVideo -> "OFFER_TYPE_VIDEO"
COIOTOfferTypeSpendMatch -> "OFFER_TYPE_SPEND_MATCH"
instance FromJSON CountryOfferInfoOfferType where
parseJSON = parseJSONText "CountryOfferInfoOfferType"
instance ToJSON CountryOfferInfoOfferType where
toJSON = toJSONText
-- | The type of rank.
data RankType
= RankTypeUnspecified
-- ^ @RANK_TYPE_UNSPECIFIED@
-- Unchosen.
| RtFinalScore
-- ^ @RT_FINAL_SCORE@
-- Total final score.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RankType
instance FromHttpApiData RankType where
parseQueryParam = \case
"RANK_TYPE_UNSPECIFIED" -> Right RankTypeUnspecified
"RT_FINAL_SCORE" -> Right RtFinalScore
x -> Left ("Unable to parse RankType from: " <> x)
instance ToHttpApiData RankType where
toQueryParam = \case
RankTypeUnspecified -> "RANK_TYPE_UNSPECIFIED"
RtFinalScore -> "RT_FINAL_SCORE"
instance FromJSON RankType where
parseJSON = parseJSONText "RankType"
instance ToJSON RankType where
toJSON = toJSONText
-- | State of agency specialization.
data SpecializationStatusBadgeSpecializationState
= BadgeSpecializationStateUnknown
-- ^ @BADGE_SPECIALIZATION_STATE_UNKNOWN@
-- Unknown state
| BadgeSpecializationStatePassed
-- ^ @BADGE_SPECIALIZATION_STATE_PASSED@
-- Specialization passed
| BadgeSpecializationStateNotPassed
-- ^ @BADGE_SPECIALIZATION_STATE_NOT_PASSED@
-- Specialization not passed
| BadgeSpecializationStateInGrace
-- ^ @BADGE_SPECIALIZATION_STATE_IN_GRACE@
-- Specialization in grace
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpecializationStatusBadgeSpecializationState
instance FromHttpApiData SpecializationStatusBadgeSpecializationState where
parseQueryParam = \case
"BADGE_SPECIALIZATION_STATE_UNKNOWN" -> Right BadgeSpecializationStateUnknown
"BADGE_SPECIALIZATION_STATE_PASSED" -> Right BadgeSpecializationStatePassed
"BADGE_SPECIALIZATION_STATE_NOT_PASSED" -> Right BadgeSpecializationStateNotPassed
"BADGE_SPECIALIZATION_STATE_IN_GRACE" -> Right BadgeSpecializationStateInGrace
x -> Left ("Unable to parse SpecializationStatusBadgeSpecializationState from: " <> x)
instance ToHttpApiData SpecializationStatusBadgeSpecializationState where
toQueryParam = \case
BadgeSpecializationStateUnknown -> "BADGE_SPECIALIZATION_STATE_UNKNOWN"
BadgeSpecializationStatePassed -> "BADGE_SPECIALIZATION_STATE_PASSED"
BadgeSpecializationStateNotPassed -> "BADGE_SPECIALIZATION_STATE_NOT_PASSED"
BadgeSpecializationStateInGrace -> "BADGE_SPECIALIZATION_STATE_IN_GRACE"
instance FromJSON SpecializationStatusBadgeSpecializationState where
parseJSON = parseJSONText "SpecializationStatusBadgeSpecializationState"
instance ToJSON SpecializationStatusBadgeSpecializationState where
toJSON = toJSONText
-- | Type of offer.
data AvailableOfferOfferType
= AOOTOfferTypeUnspecified
-- ^ @OFFER_TYPE_UNSPECIFIED@
-- Unset.
| AOOTOfferTypeSpendXGetY
-- ^ @OFFER_TYPE_SPEND_X_GET_Y@
-- AdWords spend X get Y.
| AOOTOfferTypeVideo
-- ^ @OFFER_TYPE_VIDEO@
-- Youtube video.
| AOOTOfferTypeSpendMatch
-- ^ @OFFER_TYPE_SPEND_MATCH@
-- Spend Match up to Y.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AvailableOfferOfferType
instance FromHttpApiData AvailableOfferOfferType where
parseQueryParam = \case
"OFFER_TYPE_UNSPECIFIED" -> Right AOOTOfferTypeUnspecified
"OFFER_TYPE_SPEND_X_GET_Y" -> Right AOOTOfferTypeSpendXGetY
"OFFER_TYPE_VIDEO" -> Right AOOTOfferTypeVideo
"OFFER_TYPE_SPEND_MATCH" -> Right AOOTOfferTypeSpendMatch
x -> Left ("Unable to parse AvailableOfferOfferType from: " <> x)
instance ToHttpApiData AvailableOfferOfferType where
toQueryParam = \case
AOOTOfferTypeUnspecified -> "OFFER_TYPE_UNSPECIFIED"
AOOTOfferTypeSpendXGetY -> "OFFER_TYPE_SPEND_X_GET_Y"
AOOTOfferTypeVideo -> "OFFER_TYPE_VIDEO"
AOOTOfferTypeSpendMatch -> "OFFER_TYPE_SPEND_MATCH"
instance FromJSON AvailableOfferOfferType where
parseJSON = parseJSONText "AvailableOfferOfferType"
instance ToJSON AvailableOfferOfferType where
toJSON = toJSONText
-- | The specialization this status is for.
data SpecializationStatusBadgeSpecialization
= BadgeSpecializationUnknown
-- ^ @BADGE_SPECIALIZATION_UNKNOWN@
-- Unknown specialization
| BadgeSpecializationAdwordsSearch
-- ^ @BADGE_SPECIALIZATION_ADWORDS_SEARCH@
-- AdWords Search specialization
| BadgeSpecializationAdwordsDisplay
-- ^ @BADGE_SPECIALIZATION_ADWORDS_DISPLAY@
-- AdWords Display specialization
| BadgeSpecializationAdwordsMobile
-- ^ @BADGE_SPECIALIZATION_ADWORDS_MOBILE@
-- AdWords Mobile specialization
| BadgeSpecializationAdwordsVideo
-- ^ @BADGE_SPECIALIZATION_ADWORDS_VIDEO@
-- AdWords Video specialization
| BadgeSpecializationAdwordsShopping
-- ^ @BADGE_SPECIALIZATION_ADWORDS_SHOPPING@
-- AdWords Shopping specialization
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable SpecializationStatusBadgeSpecialization
instance FromHttpApiData SpecializationStatusBadgeSpecialization where
parseQueryParam = \case
"BADGE_SPECIALIZATION_UNKNOWN" -> Right BadgeSpecializationUnknown
"BADGE_SPECIALIZATION_ADWORDS_SEARCH" -> Right BadgeSpecializationAdwordsSearch
"BADGE_SPECIALIZATION_ADWORDS_DISPLAY" -> Right BadgeSpecializationAdwordsDisplay
"BADGE_SPECIALIZATION_ADWORDS_MOBILE" -> Right BadgeSpecializationAdwordsMobile
"BADGE_SPECIALIZATION_ADWORDS_VIDEO" -> Right BadgeSpecializationAdwordsVideo
"BADGE_SPECIALIZATION_ADWORDS_SHOPPING" -> Right BadgeSpecializationAdwordsShopping
x -> Left ("Unable to parse SpecializationStatusBadgeSpecialization from: " <> x)
instance ToHttpApiData SpecializationStatusBadgeSpecialization where
toQueryParam = \case
BadgeSpecializationUnknown -> "BADGE_SPECIALIZATION_UNKNOWN"
BadgeSpecializationAdwordsSearch -> "BADGE_SPECIALIZATION_ADWORDS_SEARCH"
BadgeSpecializationAdwordsDisplay -> "BADGE_SPECIALIZATION_ADWORDS_DISPLAY"
BadgeSpecializationAdwordsMobile -> "BADGE_SPECIALIZATION_ADWORDS_MOBILE"
BadgeSpecializationAdwordsVideo -> "BADGE_SPECIALIZATION_ADWORDS_VIDEO"
BadgeSpecializationAdwordsShopping -> "BADGE_SPECIALIZATION_ADWORDS_SHOPPING"
instance FromJSON SpecializationStatusBadgeSpecialization where
parseJSON = parseJSONText "SpecializationStatusBadgeSpecialization"
instance ToJSON SpecializationStatusBadgeSpecialization where
toJSON = toJSONText
-- | The category the action belongs to.
data LogUserEventRequestEventCategory
= EventCategoryUnspecified
-- ^ @EVENT_CATEGORY_UNSPECIFIED@
-- Unchosen.
| GooglePartnerSearch
-- ^ @GOOGLE_PARTNER_SEARCH@
-- Google Partner Search category.
| GooglePartnerSignupFlow
-- ^ @GOOGLE_PARTNER_SIGNUP_FLOW@
-- Google Partner sign-up flow category.
| GooglePartnerPortal
-- ^ @GOOGLE_PARTNER_PORTAL@
-- Google Partner portal category.
| GooglePartnerPortalMyProFile
-- ^ @GOOGLE_PARTNER_PORTAL_MY_PROFILE@
-- Google Partner portal my-profile category.
| GooglePartnerPortalCertifications
-- ^ @GOOGLE_PARTNER_PORTAL_CERTIFICATIONS@
-- Google Partner portal certifications category.
| GooglePartnerPortalCommUnity
-- ^ @GOOGLE_PARTNER_PORTAL_COMMUNITY@
-- Google Partner portal community category.
| GooglePartnerPortalInsights
-- ^ @GOOGLE_PARTNER_PORTAL_INSIGHTS@
-- Google Partner portal insights category.
| GooglePartnerPortalClients
-- ^ @GOOGLE_PARTNER_PORTAL_CLIENTS@
-- Google Partner portal clients category.
| GooglePartnerPublicUserProFile
-- ^ @GOOGLE_PARTNER_PUBLIC_USER_PROFILE@
-- Google Partner portal public user profile category.
| GooglePartnerPanel
-- ^ @GOOGLE_PARTNER_PANEL@
-- Google Partner panel category.
| GooglePartnerPortalLastAdminDialog
-- ^ @GOOGLE_PARTNER_PORTAL_LAST_ADMIN_DIALOG@
-- Google Partner portal last admin dialog category.
| GooglePartnerClient
-- ^ @GOOGLE_PARTNER_CLIENT@
-- Google Partner client category.
| GooglePartnerPortalCompanyProFile
-- ^ @GOOGLE_PARTNER_PORTAL_COMPANY_PROFILE@
-- Google Partner portal company profile category.
| ExternalLinks
-- ^ @EXTERNAL_LINKS@
-- External links category.
| GooglePartnerLanding
-- ^ @GOOGLE_PARTNER_LANDING@
-- Google Partner landing category.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LogUserEventRequestEventCategory
instance FromHttpApiData LogUserEventRequestEventCategory where
parseQueryParam = \case
"EVENT_CATEGORY_UNSPECIFIED" -> Right EventCategoryUnspecified
"GOOGLE_PARTNER_SEARCH" -> Right GooglePartnerSearch
"GOOGLE_PARTNER_SIGNUP_FLOW" -> Right GooglePartnerSignupFlow
"GOOGLE_PARTNER_PORTAL" -> Right GooglePartnerPortal
"GOOGLE_PARTNER_PORTAL_MY_PROFILE" -> Right GooglePartnerPortalMyProFile
"GOOGLE_PARTNER_PORTAL_CERTIFICATIONS" -> Right GooglePartnerPortalCertifications
"GOOGLE_PARTNER_PORTAL_COMMUNITY" -> Right GooglePartnerPortalCommUnity
"GOOGLE_PARTNER_PORTAL_INSIGHTS" -> Right GooglePartnerPortalInsights
"GOOGLE_PARTNER_PORTAL_CLIENTS" -> Right GooglePartnerPortalClients
"GOOGLE_PARTNER_PUBLIC_USER_PROFILE" -> Right GooglePartnerPublicUserProFile
"GOOGLE_PARTNER_PANEL" -> Right GooglePartnerPanel
"GOOGLE_PARTNER_PORTAL_LAST_ADMIN_DIALOG" -> Right GooglePartnerPortalLastAdminDialog
"GOOGLE_PARTNER_CLIENT" -> Right GooglePartnerClient
"GOOGLE_PARTNER_PORTAL_COMPANY_PROFILE" -> Right GooglePartnerPortalCompanyProFile
"EXTERNAL_LINKS" -> Right ExternalLinks
"GOOGLE_PARTNER_LANDING" -> Right GooglePartnerLanding
x -> Left ("Unable to parse LogUserEventRequestEventCategory from: " <> x)
instance ToHttpApiData LogUserEventRequestEventCategory where
toQueryParam = \case
EventCategoryUnspecified -> "EVENT_CATEGORY_UNSPECIFIED"
GooglePartnerSearch -> "GOOGLE_PARTNER_SEARCH"
GooglePartnerSignupFlow -> "GOOGLE_PARTNER_SIGNUP_FLOW"
GooglePartnerPortal -> "GOOGLE_PARTNER_PORTAL"
GooglePartnerPortalMyProFile -> "GOOGLE_PARTNER_PORTAL_MY_PROFILE"
GooglePartnerPortalCertifications -> "GOOGLE_PARTNER_PORTAL_CERTIFICATIONS"
GooglePartnerPortalCommUnity -> "GOOGLE_PARTNER_PORTAL_COMMUNITY"
GooglePartnerPortalInsights -> "GOOGLE_PARTNER_PORTAL_INSIGHTS"
GooglePartnerPortalClients -> "GOOGLE_PARTNER_PORTAL_CLIENTS"
GooglePartnerPublicUserProFile -> "GOOGLE_PARTNER_PUBLIC_USER_PROFILE"
GooglePartnerPanel -> "GOOGLE_PARTNER_PANEL"
GooglePartnerPortalLastAdminDialog -> "GOOGLE_PARTNER_PORTAL_LAST_ADMIN_DIALOG"
GooglePartnerClient -> "GOOGLE_PARTNER_CLIENT"
GooglePartnerPortalCompanyProFile -> "GOOGLE_PARTNER_PORTAL_COMPANY_PROFILE"
ExternalLinks -> "EXTERNAL_LINKS"
GooglePartnerLanding -> "GOOGLE_PARTNER_LANDING"
instance FromJSON LogUserEventRequestEventCategory where
parseJSON = parseJSONText "LogUserEventRequestEventCategory"
instance ToJSON LogUserEventRequestEventCategory where
toJSON = toJSONText
-- | Type of offer.
data HistoricalOfferOfferType
= HOOTOfferTypeUnspecified
-- ^ @OFFER_TYPE_UNSPECIFIED@
-- Unset.
| HOOTOfferTypeSpendXGetY
-- ^ @OFFER_TYPE_SPEND_X_GET_Y@
-- AdWords spend X get Y.
| HOOTOfferTypeVideo
-- ^ @OFFER_TYPE_VIDEO@
-- Youtube video.
| HOOTOfferTypeSpendMatch
-- ^ @OFFER_TYPE_SPEND_MATCH@
-- Spend Match up to Y.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable HistoricalOfferOfferType
instance FromHttpApiData HistoricalOfferOfferType where
parseQueryParam = \case
"OFFER_TYPE_UNSPECIFIED" -> Right HOOTOfferTypeUnspecified
"OFFER_TYPE_SPEND_X_GET_Y" -> Right HOOTOfferTypeSpendXGetY
"OFFER_TYPE_VIDEO" -> Right HOOTOfferTypeVideo
"OFFER_TYPE_SPEND_MATCH" -> Right HOOTOfferTypeSpendMatch
x -> Left ("Unable to parse HistoricalOfferOfferType from: " <> x)
instance ToHttpApiData HistoricalOfferOfferType where
toQueryParam = \case
HOOTOfferTypeUnspecified -> "OFFER_TYPE_UNSPECIFIED"
HOOTOfferTypeSpendXGetY -> "OFFER_TYPE_SPEND_X_GET_Y"
HOOTOfferTypeVideo -> "OFFER_TYPE_VIDEO"
HOOTOfferTypeSpendMatch -> "OFFER_TYPE_SPEND_MATCH"
instance FromJSON HistoricalOfferOfferType where
parseJSON = parseJSONText "HistoricalOfferOfferType"
instance ToJSON HistoricalOfferOfferType where
toJSON = toJSONText
-- | The type of the certification.
data CertificationStatusType
= CertificationTypeUnspecified
-- ^ @CERTIFICATION_TYPE_UNSPECIFIED@
-- Unchosen.
| CtAdwords
-- ^ @CT_ADWORDS@
-- AdWords certified.
| CtYouTube
-- ^ @CT_YOUTUBE@
-- YouTube certified.
| CtVideoads
-- ^ @CT_VIDEOADS@
-- VideoAds certified.
| CtAnalytics
-- ^ @CT_ANALYTICS@
-- Analytics certified.
| CtDoubleClick
-- ^ @CT_DOUBLECLICK@
-- DoubleClick certified.
| CtShopping
-- ^ @CT_SHOPPING@
-- Shopping certified.
| CtMobile
-- ^ @CT_MOBILE@
-- Mobile certified.
| CtDigitalSales
-- ^ @CT_DIGITAL_SALES@
-- Digital sales certified.
| CtAdwordsSearch
-- ^ @CT_ADWORDS_SEARCH@
-- AdWords Search certified.
| CtAdwordsDisplay
-- ^ @CT_ADWORDS_DISPLAY@
-- AdWords Display certified.
| CtMobileSites
-- ^ @CT_MOBILE_SITES@
-- Mobile Sites certified.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CertificationStatusType
instance FromHttpApiData CertificationStatusType where
parseQueryParam = \case
"CERTIFICATION_TYPE_UNSPECIFIED" -> Right CertificationTypeUnspecified
"CT_ADWORDS" -> Right CtAdwords
"CT_YOUTUBE" -> Right CtYouTube
"CT_VIDEOADS" -> Right CtVideoads
"CT_ANALYTICS" -> Right CtAnalytics
"CT_DOUBLECLICK" -> Right CtDoubleClick
"CT_SHOPPING" -> Right CtShopping
"CT_MOBILE" -> Right CtMobile
"CT_DIGITAL_SALES" -> Right CtDigitalSales
"CT_ADWORDS_SEARCH" -> Right CtAdwordsSearch
"CT_ADWORDS_DISPLAY" -> Right CtAdwordsDisplay
"CT_MOBILE_SITES" -> Right CtMobileSites
x -> Left ("Unable to parse CertificationStatusType from: " <> x)
instance ToHttpApiData CertificationStatusType where
toQueryParam = \case
CertificationTypeUnspecified -> "CERTIFICATION_TYPE_UNSPECIFIED"
CtAdwords -> "CT_ADWORDS"
CtYouTube -> "CT_YOUTUBE"
CtVideoads -> "CT_VIDEOADS"
CtAnalytics -> "CT_ANALYTICS"
CtDoubleClick -> "CT_DOUBLECLICK"
CtShopping -> "CT_SHOPPING"
CtMobile -> "CT_MOBILE"
CtDigitalSales -> "CT_DIGITAL_SALES"
CtAdwordsSearch -> "CT_ADWORDS_SEARCH"
CtAdwordsDisplay -> "CT_ADWORDS_DISPLAY"
CtMobileSites -> "CT_MOBILE_SITES"
instance FromJSON CertificationStatusType where
parseJSON = parseJSONText "CertificationStatusType"
instance ToJSON CertificationStatusType where
toJSON = toJSONText
-- | The outcome of <https://www.google.com/recaptcha/ reCaptcha> validation.
data CreateLeadResponseRecaptchaStatus
= RecaptchaStatusUnspecified
-- ^ @RECAPTCHA_STATUS_UNSPECIFIED@
-- Unchosen.
| RsNotNeeded
-- ^ @RS_NOT_NEEDED@
-- No reCaptcha validation needed.
| RsPassed
-- ^ @RS_PASSED@
-- reCaptcha challenge passed.
| RsFailed
-- ^ @RS_FAILED@
-- reCaptcha challenge failed.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CreateLeadResponseRecaptchaStatus
instance FromHttpApiData CreateLeadResponseRecaptchaStatus where
parseQueryParam = \case
"RECAPTCHA_STATUS_UNSPECIFIED" -> Right RecaptchaStatusUnspecified
"RS_NOT_NEEDED" -> Right RsNotNeeded
"RS_PASSED" -> Right RsPassed
"RS_FAILED" -> Right RsFailed
x -> Left ("Unable to parse CreateLeadResponseRecaptchaStatus from: " <> x)
instance ToHttpApiData CreateLeadResponseRecaptchaStatus where
toQueryParam = \case
RecaptchaStatusUnspecified -> "RECAPTCHA_STATUS_UNSPECIFIED"
RsNotNeeded -> "RS_NOT_NEEDED"
RsPassed -> "RS_PASSED"
RsFailed -> "RS_FAILED"
instance FromJSON CreateLeadResponseRecaptchaStatus where
parseJSON = parseJSONText "CreateLeadResponseRecaptchaStatus"
instance ToJSON CreateLeadResponseRecaptchaStatus where
toJSON = toJSONText
-- | The type of the exam.
data ExamStatusExamType
= CertificationExamTypeUnspecified
-- ^ @CERTIFICATION_EXAM_TYPE_UNSPECIFIED@
-- Unchosen.
| CetAdwordsFundamentals
-- ^ @CET_ADWORDS_FUNDAMENTALS@
-- Adwords Fundamentals exam.
| CetAdwordsAdvancedSearch
-- ^ @CET_ADWORDS_ADVANCED_SEARCH@
-- AdWords advanced search exam.
| CetAdwordsAdvancedDisplay
-- ^ @CET_ADWORDS_ADVANCED_DISPLAY@
-- AdWords advanced display exam.
| CetVideoAds
-- ^ @CET_VIDEO_ADS@
-- VideoAds exam.
| CetDoubleClick
-- ^ @CET_DOUBLECLICK@
-- DoubleClick exam.
| CetAnalytics
-- ^ @CET_ANALYTICS@
-- Analytics exam.
| CetShopping
-- ^ @CET_SHOPPING@
-- Shopping exam.
| CetMobile
-- ^ @CET_MOBILE@
-- Mobile exam.
| CetDigitalSales
-- ^ @CET_DIGITAL_SALES@
-- Digital Sales exam.
| CetMobileSites
-- ^ @CET_MOBILE_SITES@
-- Mobile Sites exam.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ExamStatusExamType
instance FromHttpApiData ExamStatusExamType where
parseQueryParam = \case
"CERTIFICATION_EXAM_TYPE_UNSPECIFIED" -> Right CertificationExamTypeUnspecified
"CET_ADWORDS_FUNDAMENTALS" -> Right CetAdwordsFundamentals
"CET_ADWORDS_ADVANCED_SEARCH" -> Right CetAdwordsAdvancedSearch
"CET_ADWORDS_ADVANCED_DISPLAY" -> Right CetAdwordsAdvancedDisplay
"CET_VIDEO_ADS" -> Right CetVideoAds
"CET_DOUBLECLICK" -> Right CetDoubleClick
"CET_ANALYTICS" -> Right CetAnalytics
"CET_SHOPPING" -> Right CetShopping
"CET_MOBILE" -> Right CetMobile
"CET_DIGITAL_SALES" -> Right CetDigitalSales
"CET_MOBILE_SITES" -> Right CetMobileSites
x -> Left ("Unable to parse ExamStatusExamType from: " <> x)
instance ToHttpApiData ExamStatusExamType where
toQueryParam = \case
CertificationExamTypeUnspecified -> "CERTIFICATION_EXAM_TYPE_UNSPECIFIED"
CetAdwordsFundamentals -> "CET_ADWORDS_FUNDAMENTALS"
CetAdwordsAdvancedSearch -> "CET_ADWORDS_ADVANCED_SEARCH"
CetAdwordsAdvancedDisplay -> "CET_ADWORDS_ADVANCED_DISPLAY"
CetVideoAds -> "CET_VIDEO_ADS"
CetDoubleClick -> "CET_DOUBLECLICK"
CetAnalytics -> "CET_ANALYTICS"
CetShopping -> "CET_SHOPPING"
CetMobile -> "CET_MOBILE"
CetDigitalSales -> "CET_DIGITAL_SALES"
CetMobileSites -> "CET_MOBILE_SITES"
instance FromJSON ExamStatusExamType where
parseJSON = parseJSONText "ExamStatusExamType"
instance ToJSON ExamStatusExamType where
toJSON = toJSONText
-- | Reason why no Offers are available.
data ListOffersResponseNoOfferReason
= NoOfferReasonUnspecified
-- ^ @NO_OFFER_REASON_UNSPECIFIED@
-- Unset.
| NoOfferReasonNoMcc
-- ^ @NO_OFFER_REASON_NO_MCC@
-- Not an MCC.
| NoOfferReasonLimitReached
-- ^ @NO_OFFER_REASON_LIMIT_REACHED@
-- Offer limit has been reached.
| NoOfferReasonIneligible
-- ^ @NO_OFFER_REASON_INELIGIBLE@
-- Ineligible for offers.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ListOffersResponseNoOfferReason
instance FromHttpApiData ListOffersResponseNoOfferReason where
parseQueryParam = \case
"NO_OFFER_REASON_UNSPECIFIED" -> Right NoOfferReasonUnspecified
"NO_OFFER_REASON_NO_MCC" -> Right NoOfferReasonNoMcc
"NO_OFFER_REASON_LIMIT_REACHED" -> Right NoOfferReasonLimitReached
"NO_OFFER_REASON_INELIGIBLE" -> Right NoOfferReasonIneligible
x -> Left ("Unable to parse ListOffersResponseNoOfferReason from: " <> x)
instance ToHttpApiData ListOffersResponseNoOfferReason where
toQueryParam = \case
NoOfferReasonUnspecified -> "NO_OFFER_REASON_UNSPECIFIED"
NoOfferReasonNoMcc -> "NO_OFFER_REASON_NO_MCC"
NoOfferReasonLimitReached -> "NO_OFFER_REASON_LIMIT_REACHED"
NoOfferReasonIneligible -> "NO_OFFER_REASON_INELIGIBLE"
instance FromJSON ListOffersResponseNoOfferReason where
parseJSON = parseJSONText "ListOffersResponseNoOfferReason"
instance ToJSON ListOffersResponseNoOfferReason 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
-- | The type of certification exam.
data CertificationExamStatusType
= CESTCertificationExamTypeUnspecified
-- ^ @CERTIFICATION_EXAM_TYPE_UNSPECIFIED@
-- Unchosen.
| CESTCetAdwordsFundamentals
-- ^ @CET_ADWORDS_FUNDAMENTALS@
-- Adwords Fundamentals exam.
| CESTCetAdwordsAdvancedSearch
-- ^ @CET_ADWORDS_ADVANCED_SEARCH@
-- AdWords advanced search exam.
| CESTCetAdwordsAdvancedDisplay
-- ^ @CET_ADWORDS_ADVANCED_DISPLAY@
-- AdWords advanced display exam.
| CESTCetVideoAds
-- ^ @CET_VIDEO_ADS@
-- VideoAds exam.
| CESTCetDoubleClick
-- ^ @CET_DOUBLECLICK@
-- DoubleClick exam.
| CESTCetAnalytics
-- ^ @CET_ANALYTICS@
-- Analytics exam.
| CESTCetShopping
-- ^ @CET_SHOPPING@
-- Shopping exam.
| CESTCetMobile
-- ^ @CET_MOBILE@
-- Mobile exam.
| CESTCetDigitalSales
-- ^ @CET_DIGITAL_SALES@
-- Digital Sales exam.
| CESTCetMobileSites
-- ^ @CET_MOBILE_SITES@
-- Mobile Sites exam.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CertificationExamStatusType
instance FromHttpApiData CertificationExamStatusType where
parseQueryParam = \case
"CERTIFICATION_EXAM_TYPE_UNSPECIFIED" -> Right CESTCertificationExamTypeUnspecified
"CET_ADWORDS_FUNDAMENTALS" -> Right CESTCetAdwordsFundamentals
"CET_ADWORDS_ADVANCED_SEARCH" -> Right CESTCetAdwordsAdvancedSearch
"CET_ADWORDS_ADVANCED_DISPLAY" -> Right CESTCetAdwordsAdvancedDisplay
"CET_VIDEO_ADS" -> Right CESTCetVideoAds
"CET_DOUBLECLICK" -> Right CESTCetDoubleClick
"CET_ANALYTICS" -> Right CESTCetAnalytics
"CET_SHOPPING" -> Right CESTCetShopping
"CET_MOBILE" -> Right CESTCetMobile
"CET_DIGITAL_SALES" -> Right CESTCetDigitalSales
"CET_MOBILE_SITES" -> Right CESTCetMobileSites
x -> Left ("Unable to parse CertificationExamStatusType from: " <> x)
instance ToHttpApiData CertificationExamStatusType where
toQueryParam = \case
CESTCertificationExamTypeUnspecified -> "CERTIFICATION_EXAM_TYPE_UNSPECIFIED"
CESTCetAdwordsFundamentals -> "CET_ADWORDS_FUNDAMENTALS"
CESTCetAdwordsAdvancedSearch -> "CET_ADWORDS_ADVANCED_SEARCH"
CESTCetAdwordsAdvancedDisplay -> "CET_ADWORDS_ADVANCED_DISPLAY"
CESTCetVideoAds -> "CET_VIDEO_ADS"
CESTCetDoubleClick -> "CET_DOUBLECLICK"
CESTCetAnalytics -> "CET_ANALYTICS"
CESTCetShopping -> "CET_SHOPPING"
CESTCetMobile -> "CET_MOBILE"
CESTCetDigitalSales -> "CET_DIGITAL_SALES"
CESTCetMobileSites -> "CET_MOBILE_SITES"
instance FromJSON CertificationExamStatusType where
parseJSON = parseJSONText "CertificationExamStatusType"
instance ToJSON CertificationExamStatusType where
toJSON = toJSONText
-- | Message level of client message.
data LogMessageRequestLevel
= MessageLevelUnspecified
-- ^ @MESSAGE_LEVEL_UNSPECIFIED@
-- Unchosen.
| MlFine
-- ^ @ML_FINE@
-- Message level for tracing information.
| MlInfo
-- ^ @ML_INFO@
-- Message level for informational messages.
| MlWarning
-- ^ @ML_WARNING@
-- Message level for potential problems.
| MlSevere
-- ^ @ML_SEVERE@
-- Message level for serious failures.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LogMessageRequestLevel
instance FromHttpApiData LogMessageRequestLevel where
parseQueryParam = \case
"MESSAGE_LEVEL_UNSPECIFIED" -> Right MessageLevelUnspecified
"ML_FINE" -> Right MlFine
"ML_INFO" -> Right MlInfo
"ML_WARNING" -> Right MlWarning
"ML_SEVERE" -> Right MlSevere
x -> Left ("Unable to parse LogMessageRequestLevel from: " <> x)
instance ToHttpApiData LogMessageRequestLevel where
toQueryParam = \case
MessageLevelUnspecified -> "MESSAGE_LEVEL_UNSPECIFIED"
MlFine -> "ML_FINE"
MlInfo -> "ML_INFO"
MlWarning -> "ML_WARNING"
MlSevere -> "ML_SEVERE"
instance FromJSON LogMessageRequestLevel where
parseJSON = parseJSONText "LogMessageRequestLevel"
instance ToJSON LogMessageRequestLevel where
toJSON = toJSONText
-- | The type of certification, the area of expertise.
data CertificationCertificationType
= CCTCertificationTypeUnspecified
-- ^ @CERTIFICATION_TYPE_UNSPECIFIED@
-- Unchosen.
| CCTCtAdwords
-- ^ @CT_ADWORDS@
-- AdWords certified.
| CCTCtYouTube
-- ^ @CT_YOUTUBE@
-- YouTube certified.
| CCTCtVideoads
-- ^ @CT_VIDEOADS@
-- VideoAds certified.
| CCTCtAnalytics
-- ^ @CT_ANALYTICS@
-- Analytics certified.
| CCTCtDoubleClick
-- ^ @CT_DOUBLECLICK@
-- DoubleClick certified.
| CCTCtShopping
-- ^ @CT_SHOPPING@
-- Shopping certified.
| CCTCtMobile
-- ^ @CT_MOBILE@
-- Mobile certified.
| CCTCtDigitalSales
-- ^ @CT_DIGITAL_SALES@
-- Digital sales certified.
| CCTCtAdwordsSearch
-- ^ @CT_ADWORDS_SEARCH@
-- AdWords Search certified.
| CCTCtAdwordsDisplay
-- ^ @CT_ADWORDS_DISPLAY@
-- AdWords Display certified.
| CCTCtMobileSites
-- ^ @CT_MOBILE_SITES@
-- Mobile Sites certified.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CertificationCertificationType
instance FromHttpApiData CertificationCertificationType where
parseQueryParam = \case
"CERTIFICATION_TYPE_UNSPECIFIED" -> Right CCTCertificationTypeUnspecified
"CT_ADWORDS" -> Right CCTCtAdwords
"CT_YOUTUBE" -> Right CCTCtYouTube
"CT_VIDEOADS" -> Right CCTCtVideoads
"CT_ANALYTICS" -> Right CCTCtAnalytics
"CT_DOUBLECLICK" -> Right CCTCtDoubleClick
"CT_SHOPPING" -> Right CCTCtShopping
"CT_MOBILE" -> Right CCTCtMobile
"CT_DIGITAL_SALES" -> Right CCTCtDigitalSales
"CT_ADWORDS_SEARCH" -> Right CCTCtAdwordsSearch
"CT_ADWORDS_DISPLAY" -> Right CCTCtAdwordsDisplay
"CT_MOBILE_SITES" -> Right CCTCtMobileSites
x -> Left ("Unable to parse CertificationCertificationType from: " <> x)
instance ToHttpApiData CertificationCertificationType where
toQueryParam = \case
CCTCertificationTypeUnspecified -> "CERTIFICATION_TYPE_UNSPECIFIED"
CCTCtAdwords -> "CT_ADWORDS"
CCTCtYouTube -> "CT_YOUTUBE"
CCTCtVideoads -> "CT_VIDEOADS"
CCTCtAnalytics -> "CT_ANALYTICS"
CCTCtDoubleClick -> "CT_DOUBLECLICK"
CCTCtShopping -> "CT_SHOPPING"
CCTCtMobile -> "CT_MOBILE"
CCTCtDigitalSales -> "CT_DIGITAL_SALES"
CCTCtAdwordsSearch -> "CT_ADWORDS_SEARCH"
CCTCtAdwordsDisplay -> "CT_ADWORDS_DISPLAY"
CCTCtMobileSites -> "CT_MOBILE_SITES"
instance FromJSON CertificationCertificationType where
parseJSON = parseJSONText "CertificationCertificationType"
instance ToJSON CertificationCertificationType where
toJSON = toJSONText
-- | Data type.
data EventDataKey
= EDKEventDataTypeUnspecified
-- ^ @EVENT_DATA_TYPE_UNSPECIFIED@
-- Unchosen.
| EDKAction
-- ^ @ACTION@
-- Action data.
| EDKAgencyId
-- ^ @AGENCY_ID@
-- Agency ID data.
| EDKAgencyName
-- ^ @AGENCY_NAME@
-- Agency name data.
| EDKAgencyPhoneNumber
-- ^ @AGENCY_PHONE_NUMBER@
-- Agency phone number data.
| EDKAgencyWebsite
-- ^ @AGENCY_WEBSITE@
-- Agency website data.
| EDKBudget
-- ^ @BUDGET@
-- Budget data.
| EDKCenterPoint
-- ^ @CENTER_POINT@
-- Center-point data.
| EDKCertification
-- ^ @CERTIFICATION@
-- Certification data.
| EDKComment
-- ^ @COMMENT@
-- Comment data.
| EDKCountry
-- ^ @COUNTRY@
-- Country data.
| EDKCurrency
-- ^ @CURRENCY@
-- Currency data.
| EDKCurrentlyViewedAgencyId
-- ^ @CURRENTLY_VIEWED_AGENCY_ID@
-- Currently viewed agency ID data.
| EDKDistance
-- ^ @DISTANCE@
-- Distance data.
| EDKDistanceType
-- ^ @DISTANCE_TYPE@
-- Distance type data.
| EDKExam
-- ^ @EXAM@
-- Exam data.
| EDKHistoryToken
-- ^ @HISTORY_TOKEN@
-- History token data.
| EDKID
-- ^ @ID@
-- Identifier data.
| EDKIndustry
-- ^ @INDUSTRY@
-- Industry data.
| EDKInsightTag
-- ^ @INSIGHT_TAG@
-- Insight tag data.
| EDKLanguage
-- ^ @LANGUAGE@
-- Language data.
| EDKLocation
-- ^ @LOCATION@
-- Location data.
| EDKMarketingOptIn
-- ^ @MARKETING_OPT_IN@
-- Marketing opt-in data.
| EDKQuery
-- ^ @QUERY@
-- Query data.
| EDKSearchStartIndex
-- ^ @SEARCH_START_INDEX@
-- Search start index data.
| EDKService
-- ^ @SERVICE@
-- Service data.
| EDKShowVow
-- ^ @SHOW_VOW@
-- Show vow data.
| EDKSolution
-- ^ @SOLUTION@
-- Solution data.
| EDKTrafficSourceId
-- ^ @TRAFFIC_SOURCE_ID@
-- Traffic source ID data.
| EDKTrafficSubId
-- ^ @TRAFFIC_SUB_ID@
-- Traffic sub ID data.
| EDKViewPort
-- ^ @VIEW_PORT@
-- Viewport data.
| EDKWebsite
-- ^ @WEBSITE@
-- Website data.
| EDKDetails
-- ^ @DETAILS@
-- Details data.
| EDKExperimentId
-- ^ @EXPERIMENT_ID@
-- Experiment ID data.
| EDKGpsMotivation
-- ^ @GPS_MOTIVATION@
-- Google Partner Search motivation data.
| EDKURL
-- ^ @URL@
-- URL data.
| EDKElementFocus
-- ^ @ELEMENT_FOCUS@
-- Element we wanted user to focus on.
| EDKProgress
-- ^ @PROGRESS@
-- Progress when viewing an item \\[0-100\\].
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable EventDataKey
instance FromHttpApiData EventDataKey where
parseQueryParam = \case
"EVENT_DATA_TYPE_UNSPECIFIED" -> Right EDKEventDataTypeUnspecified
"ACTION" -> Right EDKAction
"AGENCY_ID" -> Right EDKAgencyId
"AGENCY_NAME" -> Right EDKAgencyName
"AGENCY_PHONE_NUMBER" -> Right EDKAgencyPhoneNumber
"AGENCY_WEBSITE" -> Right EDKAgencyWebsite
"BUDGET" -> Right EDKBudget
"CENTER_POINT" -> Right EDKCenterPoint
"CERTIFICATION" -> Right EDKCertification
"COMMENT" -> Right EDKComment
"COUNTRY" -> Right EDKCountry
"CURRENCY" -> Right EDKCurrency
"CURRENTLY_VIEWED_AGENCY_ID" -> Right EDKCurrentlyViewedAgencyId
"DISTANCE" -> Right EDKDistance
"DISTANCE_TYPE" -> Right EDKDistanceType
"EXAM" -> Right EDKExam
"HISTORY_TOKEN" -> Right EDKHistoryToken
"ID" -> Right EDKID
"INDUSTRY" -> Right EDKIndustry
"INSIGHT_TAG" -> Right EDKInsightTag
"LANGUAGE" -> Right EDKLanguage
"LOCATION" -> Right EDKLocation
"MARKETING_OPT_IN" -> Right EDKMarketingOptIn
"QUERY" -> Right EDKQuery
"SEARCH_START_INDEX" -> Right EDKSearchStartIndex
"SERVICE" -> Right EDKService
"SHOW_VOW" -> Right EDKShowVow
"SOLUTION" -> Right EDKSolution
"TRAFFIC_SOURCE_ID" -> Right EDKTrafficSourceId
"TRAFFIC_SUB_ID" -> Right EDKTrafficSubId
"VIEW_PORT" -> Right EDKViewPort
"WEBSITE" -> Right EDKWebsite
"DETAILS" -> Right EDKDetails
"EXPERIMENT_ID" -> Right EDKExperimentId
"GPS_MOTIVATION" -> Right EDKGpsMotivation
"URL" -> Right EDKURL
"ELEMENT_FOCUS" -> Right EDKElementFocus
"PROGRESS" -> Right EDKProgress
x -> Left ("Unable to parse EventDataKey from: " <> x)
instance ToHttpApiData EventDataKey where
toQueryParam = \case
EDKEventDataTypeUnspecified -> "EVENT_DATA_TYPE_UNSPECIFIED"
EDKAction -> "ACTION"
EDKAgencyId -> "AGENCY_ID"
EDKAgencyName -> "AGENCY_NAME"
EDKAgencyPhoneNumber -> "AGENCY_PHONE_NUMBER"
EDKAgencyWebsite -> "AGENCY_WEBSITE"
EDKBudget -> "BUDGET"
EDKCenterPoint -> "CENTER_POINT"
EDKCertification -> "CERTIFICATION"
EDKComment -> "COMMENT"
EDKCountry -> "COUNTRY"
EDKCurrency -> "CURRENCY"
EDKCurrentlyViewedAgencyId -> "CURRENTLY_VIEWED_AGENCY_ID"
EDKDistance -> "DISTANCE"
EDKDistanceType -> "DISTANCE_TYPE"
EDKExam -> "EXAM"
EDKHistoryToken -> "HISTORY_TOKEN"
EDKID -> "ID"
EDKIndustry -> "INDUSTRY"
EDKInsightTag -> "INSIGHT_TAG"
EDKLanguage -> "LANGUAGE"
EDKLocation -> "LOCATION"
EDKMarketingOptIn -> "MARKETING_OPT_IN"
EDKQuery -> "QUERY"
EDKSearchStartIndex -> "SEARCH_START_INDEX"
EDKService -> "SERVICE"
EDKShowVow -> "SHOW_VOW"
EDKSolution -> "SOLUTION"
EDKTrafficSourceId -> "TRAFFIC_SOURCE_ID"
EDKTrafficSubId -> "TRAFFIC_SUB_ID"
EDKViewPort -> "VIEW_PORT"
EDKWebsite -> "WEBSITE"
EDKDetails -> "DETAILS"
EDKExperimentId -> "EXPERIMENT_ID"
EDKGpsMotivation -> "GPS_MOTIVATION"
EDKURL -> "URL"
EDKElementFocus -> "ELEMENT_FOCUS"
EDKProgress -> "PROGRESS"
instance FromJSON EventDataKey where
parseJSON = parseJSONText "EventDataKey"
instance ToJSON EventDataKey where
toJSON = toJSONText
-- | The lead\'s state in relation to the company.
data LeadState
= LSLeadStateUnspecified
-- ^ @LEAD_STATE_UNSPECIFIED@
-- Unchosen.
| LSLead
-- ^ @LEAD@
-- Lead not yet contacted.
| LSContacted
-- ^ @CONTACTED@
-- Lead has been contacted.
| LSClient
-- ^ @CLIENT@
-- Lead has become a client.
| LSOther
-- ^ @OTHER@
-- Lead in a state not covered by other options.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LeadState
instance FromHttpApiData LeadState where
parseQueryParam = \case
"LEAD_STATE_UNSPECIFIED" -> Right LSLeadStateUnspecified
"LEAD" -> Right LSLead
"CONTACTED" -> Right LSContacted
"CLIENT" -> Right LSClient
"OTHER" -> Right LSOther
x -> Left ("Unable to parse LeadState from: " <> x)
instance ToHttpApiData LeadState where
toQueryParam = \case
LSLeadStateUnspecified -> "LEAD_STATE_UNSPECIFIED"
LSLead -> "LEAD"
LSContacted -> "CONTACTED"
LSClient -> "CLIENT"
LSOther -> "OTHER"
instance FromJSON LeadState where
parseJSON = parseJSONText "LeadState"
instance ToJSON LeadState where
toJSON = toJSONText
-- | The scope of the event.
data LogUserEventRequestEventScope
= EventScopeUnspecified
-- ^ @EVENT_SCOPE_UNSPECIFIED@
-- Unchosen.
| Visitor
-- ^ @VISITOR@
-- Based on visitor.
| Session
-- ^ @SESSION@
-- Based on session.
| Page
-- ^ @PAGE@
-- Based on page visit.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable LogUserEventRequestEventScope
instance FromHttpApiData LogUserEventRequestEventScope where
parseQueryParam = \case
"EVENT_SCOPE_UNSPECIFIED" -> Right EventScopeUnspecified
"VISITOR" -> Right Visitor
"SESSION" -> Right Session
"PAGE" -> Right Page
x -> Left ("Unable to parse LogUserEventRequestEventScope from: " <> x)
instance ToHttpApiData LogUserEventRequestEventScope where
toQueryParam = \case
EventScopeUnspecified -> "EVENT_SCOPE_UNSPECIFIED"
Visitor -> "VISITOR"
Session -> "SESSION"
Page -> "PAGE"
instance FromJSON LogUserEventRequestEventScope where
parseJSON = parseJSONText "LogUserEventRequestEventScope"
instance ToJSON LogUserEventRequestEventScope where
toJSON = toJSONText
| brendanhay/gogol | gogol-partners/gen/Network/Google/Partners/Types/Sum.hs | mpl-2.0 | 106,864 | 0 | 11 | 19,730 | 10,134 | 5,475 | 4,659 | 1,352 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
func
:: forall m
. ColMap2
-> ColInfo
-> ColInfo
-> ColInfo
-> ColInfo
-> ColInfo
-> m ()
| lspitzner/brittany | data/Test33.hs | agpl-3.0 | 144 | 0 | 13 | 40 | 41 | 21 | 20 | 10 | 0 |
module HW08 where
import Data.Maybe
import Text.Read
import Data.List
import Data.Monoid
import Control.Monad.Random
import Control.Monad (replicateM)
-- | Exercise 1: detect wether a string as a certain format and return
-- true
-- >>> stringFitsFormat "3aaa2aa"
-- True
-- >>> stringFitsFormat "100a"
-- False
-- >>> stringFitsFormat "001a"
-- True
-- >>> stringFitsFormat "2bb2bb"
-- False
-- >>> stringFitsFormat "0"
-- True
-- >>> stringFitsFormat "1"
-- False
stringFitsFormat :: String -> Bool
stringFitsFormat = isJust . go
-- |
-- >>> go "3aaa"
-- Just ""
-- >>> go "100"
-- Nothing
-- >>> go "0"
-- Just ""
go :: String -> Maybe String
go "0" = Just ""
go [] = Just ""
go [_] = Nothing
go (x:xs) = do
n <- readMaybe [x] :: Maybe Int
rest <- stripPrefix (replicate n 'a') xs
go rest
-- | Exercise 2
-- list of all numbers between 1 and 100 that are divisible by 5 and 7
-- Note: the 35 and 70 is a bit of a cheat I agree
specialNumbers :: [Int]
specialNumbers = [ n | n <- [1..100], n `mod` 5 == 0 && n /= 35 && n /= 70]
-- | Risk
--
type StdRand = Rand StdGen
type Army = Int
data ArmyCounts = ArmyCounts { attackers :: Army, defenders :: Army }
deriving Show
type DieRoll = Int
-- | Exercise 3
-- simulates rolling a fair, 6-sided die
dieRoll :: StdRand DieRoll
dieRoll = getRandomR (1,6)
-- | Exercise 4
-- Monoid instance for ArmyCounts to make our life easier.
-- >>> let a = ArmyCounts {attackers = 0, defenders = -1}
-- >>> let b = ArmyCounts {attackers = -1, defenders = 0}
-- >>> a `mappend` b
-- ArmyCounts {attackers = -1, defenders = -1}
--
instance Monoid ArmyCounts where
mempty = ArmyCounts { attackers = 0, defenders = 0 }
mappend (ArmyCounts a b) (ArmyCounts x y) = ArmyCounts { attackers = a + x, defenders = b + y}
-- | Exercise 4
-- computes the change in the number of armies resulting from the rolls
-- >>> battleResults [3,6,4] [5,5]
-- ArmyCounts {attackers = -1, defenders = -1}
-- >>> battleResults [3,6,4] [5,6]
-- ArmyCounts {attackers = -2, defenders = 0}
-- >>> battleResults [4] [3,2]
-- ArmyCounts {attackers = 0, defenders = -1}
--
battleResults :: [DieRoll] -> [DieRoll] -> ArmyCounts
battleResults ab cd = roll sx sy
where sx = sortBy (flip compare) ab
sy = sortBy (flip compare) cd
roll :: [DieRoll] -> [DieRoll] -> ArmyCounts
roll (a:xs) (b:ys)
| a > b = ArmyCounts { attackers = 0, defenders = -1} `mappend` roll xs ys
| otherwise = ArmyCounts { attackers = -1, defenders = 0 } `mappend` roll xs ys
roll _ _ = ArmyCounts 0 0
-- | Exercise 5
-- simulates single battle
--
battle :: ArmyCounts -> StdRand ArmyCounts
battle (ArmyCounts a b) = do
let turns = minimum [a,b]
attackersRolls <- replicateM turns dieRoll
defendersRolls <- replicateM turns dieRoll
let r = battleResults attackersRolls defendersRolls
return r
| romanofski/codesnippets | haskellCIS194/homework8/HW08.hs | unlicense | 2,926 | 0 | 12 | 676 | 702 | 395 | 307 | 45 | 2 |
--(**) Flatten a nested list structure.
--
--Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).
--
--Example:
--
-- * (my-flatten '(a (b (c d) e)))
--(A B C D E)
--Example in Haskell:
--
--We have to define a new data type, because lists in Haskell are homogeneous.
--
-- data NestedList a = Elem a | List [NestedList a]
-- *Main> flatten (Elem 5)
-- [5]
-- *Main> flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])
-- [1,2,3,4,5]
-- *Main> flatten (List [])
-- []
--
data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten (Elem e) = [e]
flatten (List ls) = foldl (\acc x -> acc ++ flatten x) [] ls
| tiann/haskell-learning | haskell99/p07/main.hs | apache-2.0 | 730 | 0 | 9 | 143 | 114 | 69 | 45 | 4 | 1 |
module NLP.LTAG.Early3.Test1 where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (void)
import qualified Data.IntMap as I
import qualified Data.Set as S
import Data.List (sortBy)
import Data.Ord (comparing)
import NLP.LTAG.Tree (AuxTree(AuxTree), Tree(FNode, INode))
import NLP.LTAG.Early3
jean :: Tree String String
jean = INode "N" [FNode "jean"]
dort :: Tree String String
dort = INode "S"
[ INode "N" []
, INode "V"
[FNode "dort"] ]
aime :: Tree String String
aime = INode "S"
[ INode "N" []
, INode "V"
[FNode "aime"]
, INode "N" [] ]
souvent :: AuxTree String String
souvent = AuxTree (INode "V"
[ INode "V" []
, INode "Adv"
[FNode "souvent"] ]
) [0]
nePas :: AuxTree String String
nePas = AuxTree (INode "V"
[ FNode "ne"
, INode "V" []
, FNode "pas" ]
) [1]
treeRules' :: Tree String String -> IO ()
treeRules' = mapM_ print . snd . runRM . treeRules True
auxRules' :: AuxTree String String -> IO ()
auxRules' = mapM_ print . snd . runRM . auxRules True
testGram :: [String] -> IO ()
testGram sent = do
-- xs <- S.toList <$> earley gram sent
-- mapM_ print $ sortBy (comparing ((-) <$> end <*> beg)) xs
void $ earley gram sent
-- mapM_ print $ S.toList gram
where
gram = S.fromList $ snd $ runRM $ do
mapM_ (treeRules True) [jean, dort, aime]
mapM_ (auxRules True) [souvent, nePas]
| kawu/ltag | src/NLP/LTAG/Early3/Test2.hs | bsd-2-clause | 1,496 | 0 | 12 | 421 | 521 | 280 | 241 | 44 | 1 |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where
import Import
import Data.Time
import Handler.Quote
import Model.Quote
import Database.Persist.GenericSql.Raw
-- | form widget
quoteCreate :: GWidget App App () -> Enctype -> GWidget App App ()
quoteCreate formWidget enctype = $(widgetFile "quote-create")
-- | version list widget
versionCreate :: [Entity (TarballGeneric SqlPersist)] -> GWidget App App ()
versionCreate versions = $(widgetFile "quote-version")
getHomeR :: Handler RepHtml
getHomeR = do
-- get database info
(notApproved,versions) <- runDB $ do
a <- count [QuoteApproved ==. False]
b <- selectList [] [Desc TarballTimestamp]
return (a,b)
-- create form widet
time <- liftIO $ zonedTimeToUTC <$> getZonedTime
form <- quoteAForm
(formWidget,enctype) <- generateFormPost $ renderTable form
authors <- getAuthorsList
defaultLayout $ do
aDomId <- lift newIdent
setTitle "Welcome To Yesod!"
let pages = menuPages
in $(widgetFile "homepage")
| qnikst/ygruq | Handler/Home.hs | bsd-2-clause | 1,077 | 0 | 14 | 231 | 301 | 150 | 151 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
#if MIN_VERSION_base(4,7,0)
{-# LANGUAGE RoleAnnotations #-}
#endif
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE Trustworthy #-}
{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Lazy demand-driven promises.
--
-----------------------------------------------------------------------------
module Data.Promise
( Lazy
, runLazy
, runLazy_
, runLazyIO
, runLazyIO_
, Promise(..)
, promise, promise_
, (!=)
, demand
, BrokenPromise(..)
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Concurrent.MVar
import Control.Exception
import Control.Monad (ap)
import Control.Monad.Fix
import Control.Monad.Primitive
import Control.Monad.ST.Unsafe
import Data.Typeable
import System.IO.Unsafe
import Unsafe.Coerce
-- | Thrown when the answer for an unfulfillable promise is demanded.
data BrokenPromise = BrokenPromise deriving (Show, Typeable)
instance Exception BrokenPromise
--------------------------------------------------------------------------------
-- * Internals
--------------------------------------------------------------------------------
meq :: MVar a -> MVar b -> Bool
meq a b = a == unsafeCoerce b
data K s a where
Pure :: a -> K s a
Fulfilled :: MVar x -> IO (K s a) -> K s a
instance Functor (K s) where
fmap f (Pure a) = Pure (f a)
fmap f (Fulfilled m k) = Fulfilled m (fmap (fmap f) k)
pump :: a -> IO (K s x) -> MVar a -> IO (Maybe (IO (K s x)))
pump d m v = m >>= \case
Pure _ -> return Nothing
Fulfilled u n
| meq u v -> return (Just n)
| otherwise -> pump d n v
drive :: a -> MVar (Maybe (IO (K s x))) -> MVar a -> a
drive d mv v = unsafePerformIO $ tryTakeMVar v >>= \case
Just a -> return a -- if we're satisfied give the answer
Nothing -> takeMVar mv >>= \case -- grab the lock on this computation
Nothing -> do -- it has nothing left to do, so we fail to the default answer
putMVar mv Nothing
return d
Just k -> tryTakeMVar v >>= \case -- ok, check to make sure we haven't been satisfied in the meantime
Just a -> do
putMVar mv (Just k) -- if so, restore the continuation, and return the answer
return a
Nothing -> do
mk <- pump d k v
putMVar mv mk
case mk of
Nothing -> return d
Just _ -> takeMVar v
{-# NOINLINE drive #-}
--------------------------------------------------------------------------------
-- * Demand driven computations
--------------------------------------------------------------------------------
-- | A lazy, demand-driven calculation that can create and fulfill promises.
newtype Lazy s a = Lazy { getLazy :: forall x. MVar (Maybe (IO (K s x))) -> IO (K s a) }
deriving Typeable
#if MIN_VERSION_base(4,7,0)
type role Lazy nominal representational
#endif
instance Functor (Lazy s) where
fmap f (Lazy m) = Lazy $ \mv -> fmap go (m mv) where
go (Pure a) = Pure (f a)
go (Fulfilled v k) = Fulfilled v (fmap (fmap f) k)
instance Applicative (Lazy s) where
pure = return
(<*>) = ap
instance Monad (Lazy s) where
return a = Lazy $ \_ -> return $ Pure a
m >>= f = Lazy $ \mv -> let
go (Pure a) = getLazy (f a) mv
go (Fulfilled v k) = return $ Fulfilled v (k >>= go)
in getLazy m mv >>= go
instance PrimMonad (Lazy s) where
type PrimState (Lazy s) = s
primitive m = Lazy $ \_ -> Pure <$> unsafeSTToIO (primitive m)
instance MonadFix (Lazy s) where
mfix f = do
a <- promise_
r <- f (demand a)
a != r
return r
--------------------------------------------------------------------------------
-- * Promises, Promises
--------------------------------------------------------------------------------
-- | A lazy I-Var.
data Promise s a where
Promise :: MVar a -> a -> Promise s a
deriving Typeable
-- | Demand the result of a promise.
demand :: Promise s a -> a
demand (Promise _ a) = a
-- | Promise that by the end of the computation we'll provide a "real" answer, or we'll fall back and give you this answer
promise :: a -> Lazy s (Promise s a)
promise d = Lazy $ \mv -> do
v <- newEmptyMVar
return $ Pure $ Promise v (drive d mv v)
-- | Create an empty promise. If you observe the demanded answer of this promise then either by the end of the current lazy
-- computation we'll provide a "real" answer, or you'll get an error.
--
-- @
-- 'promise_' ≡ 'promise' ('throw' 'BrokenPromise')
-- @
promise_ :: Lazy s (Promise s a)
promise_ = promise $ throw BrokenPromise
infixl 0 !=
-- | Fulfill a promise. Each promise should only be fulfilled once.
--
-- >>> runLazy_ $ \p -> p != "good"
-- "good"
--
-- >>> runLazy_ $ \p -> do q <- promise_; p != "yay! " ++ demand q; q != "it works."
-- "yay! it works."
--
-- >>> runLazy_ $ \p -> return ()
-- *** Exception: BrokenPromise
--
-- >>> runLazy (\p -> return ()) "default"
-- "default"
--
(!=) :: Promise s a -> a -> Lazy s ()
Promise v _ != a = Lazy $ \ _ -> do
putMVar v a
return $ Fulfilled v $ return (Pure ())
--------------------------------------------------------------------------------
-- * Running It All
--------------------------------------------------------------------------------
runLazyIO :: (forall s. Promise s a -> Lazy s b) -> a -> IO a
runLazyIO f d = do
mv <- newEmptyMVar
v <- newEmptyMVar
let iv = Promise v (drive d mv v)
putMVar mv (Just (getLazy (f iv) mv))
return $ demand iv
runLazyIO_ :: (forall s. Promise s a -> Lazy s b) -> IO a
runLazyIO_ k = runLazyIO k $ throw BrokenPromise
-- | Run a lazy computation. The final answer is given in the form of a promise to be fulfilled.
-- If the promises is unfulfilled then an user supplied default value will be returned.
runLazy :: (forall s. Promise s a -> Lazy s b) -> a -> a
runLazy f d = unsafePerformIO (runLazyIO f d)
{-# NOINLINE runLazy #-}
-- | Run a lazy computation. The final answer is given in the form of a promise to be fulfilled.
-- If the promises is unfulfilled then an 'BrokenPromise' will be thrown.
--
-- @
-- 'runLazy_' k ≡ 'runLazy' k ('throw' 'BrokenPromise')
-- @
runLazy_ :: (forall s. Promise s a -> Lazy s b) -> a
runLazy_ k = runLazy k $ throw BrokenPromise
| Gabriel439/promises | src/Data/Promise.hs | bsd-2-clause | 6,566 | 0 | 22 | 1,366 | 1,713 | 890 | 823 | 117 | 5 |
--- Copyright (C) 2007 Bart Massey
--- ALL RIGHTS RESERVED
--- Please see the end of this file for license information.
module DelayArgs
where
import System.Console.ParseArgs
data Options =
OptionDelay |
OptionAmplitude |
OptionForward |
OptionInputFile |
OptionOutputFile
deriving (Ord, Eq, Show)
argd :: [ Arg Options ]
argd = [ Arg { argIndex = OptionDelay,
argName = Just "delay",
argAbbr = Just 'd',
argData = argDataDefaulted "msecs" ArgtypeInt 0,
argDesc = "Delay time" },
Arg { argIndex = OptionAmplitude,
argName = Just "amplitude",
argAbbr = Just 'a',
argData = argDataDefaulted "percent" ArgtypeDouble 100,
argDesc = "Relative amplitude of delayed signal" },
Arg { argIndex = OptionForward,
argName = Just "forward",
argAbbr = Just 'f',
argData = Nothing,
argDesc = "Signal is not circulated" },
Arg { argIndex = OptionInputFile,
argName = Nothing,
argAbbr = Nothing,
argData = argDataOptional "input" ArgtypeString,
argDesc = "Input file" },
Arg { argIndex = OptionOutputFile,
argName = Nothing,
argAbbr = Nothing,
argData = argDataOptional "output" ArgtypeString,
argDesc = "Output file" }]
--- Redistribution and use in source and binary forms, with or
--- without modification, are permitted provided that the
--- following conditions are met:
--- * Redistributions of source code must retain the above
--- copyright notice, this list of conditions and the following
--- disclaimer.
--- * Redistributions in binary form must reproduce the
--- above copyright notice, this list of conditions and the
--- following disclaimer in the documentation and/or other
--- materials provided with the distribution.
--- * Neither the name of Bart Massey, nor the names
--- of other affiliated organizations, nor the names
--- of other contributors may be used to endorse or promote
--- products derived from this software without specific prior
--- written permission.
---
--- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
--- CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
--- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
--- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
--- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
--- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
--- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
--- NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
--- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
--- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
--- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
--- OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
--- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| BartMassey/sounddelay | DelayArgs.hs | bsd-3-clause | 3,115 | 0 | 8 | 850 | 309 | 199 | 110 | 35 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, RankNTypes, ConstraintKinds #-}
module Test where
-- TODO: use "Scrap your typeclasses" examples
import Classes ((<$>), (<*>))
import qualified Classes as D
import Prelude (Eq, Read, Show, (+), (-), zipWith, repeat, ($), const, id)
import Templates
import Language.Haskell.InstanceTemplates
data Maybe a = Just a | Nothing
deriving (Eq, Read, Show)
$(instantiate
[template Monad_T [t| Monad Maybe |] [d|
-- instance Monad where
Just x >>= k = k x
Nothing >>= _ = Nothing
Just _ >> k = k
Nothing >> _ = Nothing
return x = Just x
fail _ = Nothing
|]
])
testMaybe = (-) <$> Just 49 <*> Just 7
newtype ZipList a = ZipList [a]
deriving (Eq, Read, Show)
$(instantiate
[template Applicative_T [t| Applicative ZipList |]
[d|
-- instance Applicative ZipList where
(ZipList fs) <*> (ZipList xs) = ZipList (zipWith ($) fs xs)
pure x = ZipList (repeat x)
(*>) :: D.Applicative f => f a -> f b -> f b
(*>) = D.liftA2 (const id)
(<*) :: D.Applicative f => f a -> f b -> f a
(<*) = D.liftA2 const
|]
])
testZipList = (+) <$> ZipList [1,2,3] <*> ZipList [6,5,4] | mgsloan/instance-templates | tests/monads/Test.hs | bsd-3-clause | 1,218 | 0 | 9 | 317 | 248 | 156 | 92 | 30 | 1 |
{-------------------------------------------------------------------------------
DSem.Vector
Vector interface
(c) 2013 Jan Snajder <[email protected]>
-------------------------------------------------------------------------------}
module DSem.Vector
( Vector (..)
, Weight
, norm1
, norm2
, scale
, normalize
, sum
, linComb
, VectorSim
, cosine
, centroid
, dimShared
, entropy
, klDivergence
, jsDivergence
, jaccardIndex
, toDistribution
, nonzeroDims ) where
import Data.List hiding (insert,sum,zipWith,map)
import Prelude hiding (zipWith,sum,map)
import qualified Data.List as L (sum,map)
import Data.Word (Word64)
------------------------------------------------------------------------------
type Weight = Double
type Dim = Word64
class Vector v where
empty :: v
-- number of stored weights
size :: v -> Dim
-- combines vectors along common dimensions
zipWith :: (Weight -> Weight -> Weight) -> v -> v -> v
-- maps function over weights ---> TODO: ill-defined: behaves differently for sparse and non sparse!
map :: (Weight -> Weight) -> v -> v
-- vector addition
add :: v -> v -> v
-- piecewise (componentwise) multiplication
pmul :: v -> v -> v
-- dot product
dot :: v -> v -> Weight
-- number of non-zero dimensions
nonzeroes :: v -> Dim
-- nonzero wieghts
nonzeroWeights :: v -> [Weight]
-- from/to list conversions
fromList :: [Weight] -> v
toList :: v -> [Weight]
toAssocList :: v -> [(Dim,Weight)]
fromAssocList :: [(Dim,Weight)] -> v
-- default implementations:
add = zipWith (+)
pmul = zipWith (*)
dot v1 v2 = listSum . nonzeroWeights $ pmul v1 v2
nonzeroWeights = filter (/=0) . toList
nonzeroes = fromIntegral . length . nonzeroWeights
nonzeroDims :: Vector v => v -> [Dim]
nonzeroDims = L.map fst . filter ((/=0) . snd) . toAssocList
-- L1-norm
norm1 :: Vector v => v -> Weight
norm1 = listSum . L.map abs . nonzeroWeights
-- L2-norm
norm2 :: Vector v => v -> Weight
norm2 v = sqrt $ v `dot` v
scale :: Vector v => Weight -> v -> v
scale w v = map (*w) v
normalize :: Vector v => v -> v
normalize v = scale (1 / norm2 v) v
sum :: Vector v => [v] -> v
sum [] = empty
sum vs = foldl1' add vs
linComb :: Vector v => [(Weight,v)] -> v
linComb = sum . L.map (uncurry scale)
type VectorSim v = v -> v -> Double
cosine :: Vector v => VectorSim v
cosine v1 v2
| n1==0 || n2==0 = 0
| otherwise = v1 `dot` v2 / (n1 * n2)
where n1 = norm2 v1
n2 = norm2 v2
centroid :: Vector v => [v] -> v
centroid vs = scale (1 / (realToFrac $ length vs)) $ sum vs
dimShared :: Vector v => v -> v -> Dim
dimShared v = nonzeroes . pmul v
entropy :: Vector v => v -> Double
entropy =
negate. listSum . nonzeroWeights .
map (\p -> if p==0 then 0 else p * log p) . toDistribution
-- Negative weights are converted to positive...
-- there's no real justification for doing so
toDistribution :: Vector v => v -> v
toDistribution v = map (\w -> w / n) v'
where n = listSum $ nonzeroWeights v'
v' = map abs v
-- TODO: Move to VectorSpace.Similarity
klDivergence :: Vector v => v -> v -> Double
klDivergence v1 v2 = klDivergence' (toDistribution v1) (toDistribution v2)
-- Assumes vectors are distributions.
klDivergence' :: Vector v => v -> v -> Double
klDivergence' v1 v2 =
listSum . nonzeroWeights $
zipWith (\p q -> if p==0 then 0 else p * log (p / q)) v1 v2
jsDivergence :: Vector v => v -> v -> Double
jsDivergence v1 v2 = (klDivergence' p m + klDivergence' q m) / 2
where p = toDistribution v1
q = toDistribution v2
m = scale (1/2) $ p `add` q
jaccardIndex :: Vector v => v -> v -> Double
jaccardIndex v1 v2 = m / n
where m = listSum . nonzeroWeights $ zipWith min v1 v2
n = listSum . nonzeroWeights $ zipWith max v1 v2
listSum = foldl' (+) 0
| jsnajder/dsem | src/DSem/Vector.hs | bsd-3-clause | 3,965 | 0 | 13 | 1,001 | 1,337 | 724 | 613 | 94 | 2 |
module Words where
import Prelude hiding (readFile)
import System.IO.UTF8(readFile)
import NLP.Tokenize(tokenize)
import Text.Regex.TDFA((=~))
import Data.Char(toLower)
import Data.List(sortBy, intersperse)
import Data.Ord(comparing)
import Data.HashMap.Strict(empty,
insertWith,
HashMap,
toList,
size,
elems)
import Control.Monad(foldM)
import Huffman
data Dictionary = Dict {
dictionary :: HashMap String Coding,
dictionaryLength :: Int,
encodingLength :: Int } deriving (Eq)
instance Show Dictionary where
show (Dict dict size len) = concat $ intersperse "," [show $ toList dict, show size, show len]
emptyDictionary :: Dictionary
emptyDictionary = Dict empty 0 0
-- | Return a list of all words in dictionary in ascending order of their index.
--
-- >>> orderedWords (encodeWords $ indexString empty "some words for testing words")
-- ["words","some","for","testing"]
orderedWords :: Dictionary -> [ String ]
orderedWords (Dict d _ _) = map fst $ sortBy (comparing (index.snd)) (toList d)
-- |Index a list of words into a frequency map
indexWord :: HashMap String Int -> String -> HashMap String Int
indexWord m w = insertWith (+) w 1 m
-- |Tokenize and normalize a string
tokenizeString :: String -> [ String ]
tokenizeString = map (map toLower).filter (=~ "^[a-zA-Z-]+$").tokenize
-- |Update a frequency map with tokens from given string.
indexString :: HashMap String Int -> String -> HashMap String Int
indexString dict = foldl indexWord dict . tokenizeString
encodeWords :: HashMap String Int -> Dictionary
encodeWords dictionary = let encoding = huffmanEncode $ dictionary
encodingLength = maximum (map (length . huffman) $ elems encoding)
in Dict encoding (size encoding) encodingLength
-- |Encode the words of several files into a dictionary
tokenizeFiles :: [String] -- file paths
-> IO Dictionary
tokenizeFiles files = do
dictionary <- foldM (\ dict f -> putStrLn ("Tokenizing " ++ f) >> readFile f >>= return.indexString dict) empty files
putStrLn $ "Encoding dictionary: " ++ (show $ size dictionary)
return $ encodeWords dictionary
| RayRacine/hs-word2vec | Words.hs | bsd-3-clause | 2,289 | 0 | 15 | 541 | 602 | 324 | 278 | 42 | 1 |
import System.Environment
import Control.Applicative
import Text.HTML.TagSoup
import qualified Data.ByteString.Char8 as S
main :: IO ()
main = do
[filename] <- getArgs
renderTags . parseTags <$> S.readFile filename >>= S.putStrLn
| yihuang/tag-stream | TestTagSoup.hs | bsd-3-clause | 239 | 0 | 10 | 38 | 73 | 40 | 33 | 8 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Data.Folds.Accumulator (
-- * Monoid accumulators
Accumulator(..)
-- ** Data types
, Count(..)
, Max(..)
, Min(..)
) where
import Data.Monoid
----------------------------------------------------------------
-- Monoidal accumulator
----------------------------------------------------------------
-- | Type class for monoidal accumulators
class Monoid m => Accumulator m a where
-- | Convert value to 1-element accumulator
unit :: a -> m
unit a = cons a mempty
-- | Prepend value to accumulator
cons :: a -> m -> m
cons a m = unit a <> m
-- | Append value to accumulator
snoc :: m -> a -> m
snoc m a = m <> unit a
newtype Count a = Count { getCount :: Int }
instance Monoid (Count a) where
mempty = Count 0
mappend (Count a) (Count b) = Count (a + b)
instance Accumulator (Count a) a where
unit _ = Count 1
newtype Max a = Max { getMax :: Maybe a }
instance Ord a => Monoid (Max a) where
mempty = Max Nothing
mappend (Max Nothing) m = m
mappend m (Max Nothing) = m
mappend (Max (Just a)) (Max (Just b)) = Max (Just $! max a b)
instance Ord a => Accumulator (Max a) a where
snoc (Max (Just a)) b = Max $ Just $! max a b
snoc (Max Nothing) b = Max $ Just b
cons = flip snoc
unit = Max . Just
newtype Min a = Min { getMin :: Maybe a }
instance Ord a => Monoid (Min a) where
mempty = Min Nothing
mappend (Min Nothing) m = m
mappend m (Min Nothing) = m
mappend (Min (Just a)) (Min (Just b)) = Min (Just $! min a b)
instance Ord a => Accumulator (Min a) a where
snoc (Min (Just a)) b = Min $ Just $! min a b
snoc (Min Nothing) b = Min $ Just b
cons = flip snoc
unit = Min . Just
instance Accumulator () a where
unit _ = ()
instance Num a => Accumulator (Sum a) a where
unit = Sum
instance Num a => Accumulator (Product a) a where
unit = Product
instance Accumulator Any Bool where
unit = Any
instance Accumulator All Bool where
unit = All
instance Accumulator (Endo a) (a -> a) where
unit = Endo
-- -- | Convert monoidal accumulator to left fold
-- fromAcc :: Accumulator m a => Fold a m
-- fromAcc = Fold snoc mempty id
| Shimuuar/data-folds | Data/Folds/Accumulator.hs | bsd-3-clause | 2,214 | 0 | 10 | 533 | 837 | 438 | 399 | 55 | 0 |
module Main where
import Control.Monad
import qualified Toc1
import qualified Toc2
import qualified Toc4a
import qualified Toc4b
import qualified Toc4c
import Test.HUnit
main :: IO ()
main = void $ runTestTT tests
where
tests = TestList
[ Toc1.tests
, Toc2.tests
, Toc4a.tests
, Toc4b.tests
, Toc4c.tests
]
| hjwylde/haskell-type-classes-workshop | test/Main.hs | bsd-3-clause | 395 | 0 | 9 | 135 | 91 | 55 | 36 | 16 | 1 |
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
module Value.Integer (
IntegerValue,
fromInt,
getAll,
) where
import SudokuAbstract
import GHC.Generics (Generic)
import Control.DeepSeq
newtype IntegerValue = IntegerValue Integer
deriving (Show, Eq, Generic, NFData)
instance SudokuValue IntegerValue where
fromInt 1 = IntegerValue 1
fromInt 2 = IntegerValue 2
fromInt 3 = IntegerValue 3
fromInt 4 = IntegerValue 4
fromInt 5 = IntegerValue 5
fromInt 6 = IntegerValue 6
fromInt 7 = IntegerValue 7
fromInt 8 = IntegerValue 8
fromInt 9 = IntegerValue 9
getAll = map IntegerValue [1..9]
| Solpatium/Haskell-Sudoku | src/Value/Integer.hs | bsd-3-clause | 634 | 0 | 7 | 137 | 186 | 96 | 90 | 21 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Views.AddClient (toClient, newClientAddDialog) where
import Graphics.Vty.Widgets.All (Widget, Edit,
editWidget,getEditText,
plainText,
centered,
(<-->),(<++>),
hFill,hLimit,
boxFixed,
withPadding,padRight,
newFocusGroup,addToFocusGroup,mergeFocusGroups)
import Graphics.Vty.Widgets.Dialog
import qualified Data.Text as T
import Control.Applicative ((<$>),(<*>))
import Control.Monad (liftM)
import Models.Client (Client, mkClient, mkAddress)
data AddClientUI =
AddClientUI { no :: Widget Edit
, name :: Widget Edit
, street :: Widget Edit
, zipcode :: Widget Edit
, city :: Widget Edit
, state :: Widget Edit
, country :: Widget Edit
, vat :: Widget Edit }
mkAddClientUI = do
no <- editWidget
name <- editWidget
street <- editWidget
zipcode <- editWidget
city <- editWidget
state <- editWidget
country <- editWidget
vat <- editWidget
return $ AddClientUI no name street zipcode city state country vat
toClient st = do
no' <- get $ no st
name' <- get $ name st
street' <- get $ street st
zipcode' <- get $ zipcode st
city' <- get $ city st
state' <- get $ state st
country' <- get $ country st
vat' <- get $ vat st
let address = mkAddress street' zipcode' city' (Just state') country'
return $ mkClient 0 (read no') name' address (Just vat')
where get = liftM T.unpack . getEditText
clientAddUI st = do
fg <- newFocusGroup
mapM_ (addToFocusGroup fg) $ [no', name', vat', street', zipcode', city', state', country']
ui <- (plainText "ID:") <--> (boxFixed 5 1 no') <-->
(plainText "Name:") <--> (boxFixed 40 1 name') <-->
(plainText "VAT ID:") <--> (boxFixed 40 1 vat') <-->
(plainText "Street:") <--> (boxFixed 40 1 street') <-->
(plainText "Zipcode, City:") <-->
(((boxFixed 10 1 zipcode') >>= withPadding (padRight 2)) <++> (boxFixed 28 1 city')) <-->
(plainText "State, Country:") <-->
(((boxFixed 10 1 state') >>= withPadding (padRight 2)) <++> (boxFixed 28 1 country'))
return (ui, fg)
where AddClientUI no' name' street' zipcode' city' state' country' vat' = st
newClientAddDialog onAccept onCancel = do
header <- plainText "Add Client" <++> hFill ' ' 1 <++> plainText "HInvoice"
footer <- plainText "Clients | Products | Invoices" <++> hFill ' ' 1 <++> plainText "v0.1"
st <- mkAddClientUI
(ui, fg) <- clientAddUI st
(dlg, dfg) <- newDialog ui "New Client"
mfg <- mergeFocusGroups fg dfg
mui <- (return header) <--> (centered =<< hLimit 55 =<< (return (dialogWidget dlg))) <--> (return footer)
dlg `onDialogAccept` onAccept st
dlg `onDialogCancel` onCancel st
return (mui, mfg)
| angerman/HInvoice | Views/AddClient.hs | bsd-3-clause | 3,080 | 0 | 20 | 941 | 1,001 | 511 | 490 | 71 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.Compatibility43
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.Compatibility43 (
-- * Types
GLDEBUGPROC,
GLDEBUGPROCFunc,
GLbitfield,
GLboolean,
GLbyte,
GLchar,
GLclampd,
GLclampf,
GLdouble,
GLenum,
GLfloat,
GLhalf,
GLint,
GLint64,
GLintptr,
GLshort,
GLsizei,
GLsizeiptr,
GLsync,
GLubyte,
GLuint,
GLuint64,
GLushort,
GLvoid,
makeGLDEBUGPROC,
-- * Enums
pattern GL_2D,
pattern GL_2_BYTES,
pattern GL_3D,
pattern GL_3D_COLOR,
pattern GL_3D_COLOR_TEXTURE,
pattern GL_3_BYTES,
pattern GL_4D_COLOR_TEXTURE,
pattern GL_4_BYTES,
pattern GL_ACCUM,
pattern GL_ACCUM_ALPHA_BITS,
pattern GL_ACCUM_BLUE_BITS,
pattern GL_ACCUM_BUFFER_BIT,
pattern GL_ACCUM_CLEAR_VALUE,
pattern GL_ACCUM_GREEN_BITS,
pattern GL_ACCUM_RED_BITS,
pattern GL_ACTIVE_ATOMIC_COUNTER_BUFFERS,
pattern GL_ACTIVE_ATTRIBUTES,
pattern GL_ACTIVE_ATTRIBUTE_MAX_LENGTH,
pattern GL_ACTIVE_PROGRAM,
pattern GL_ACTIVE_RESOURCES,
pattern GL_ACTIVE_SUBROUTINES,
pattern GL_ACTIVE_SUBROUTINE_MAX_LENGTH,
pattern GL_ACTIVE_SUBROUTINE_UNIFORMS,
pattern GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS,
pattern GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH,
pattern GL_ACTIVE_TEXTURE,
pattern GL_ACTIVE_UNIFORMS,
pattern GL_ACTIVE_UNIFORM_BLOCKS,
pattern GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH,
pattern GL_ACTIVE_UNIFORM_MAX_LENGTH,
pattern GL_ACTIVE_VARIABLES,
pattern GL_ADD,
pattern GL_ADD_SIGNED,
pattern GL_ALIASED_LINE_WIDTH_RANGE,
pattern GL_ALIASED_POINT_SIZE_RANGE,
pattern GL_ALL_ATTRIB_BITS,
pattern GL_ALL_BARRIER_BITS,
pattern GL_ALL_SHADER_BITS,
pattern GL_ALPHA,
pattern GL_ALPHA12,
pattern GL_ALPHA16,
pattern GL_ALPHA4,
pattern GL_ALPHA8,
pattern GL_ALPHA_BIAS,
pattern GL_ALPHA_BITS,
pattern GL_ALPHA_INTEGER,
pattern GL_ALPHA_SCALE,
pattern GL_ALPHA_TEST,
pattern GL_ALPHA_TEST_FUNC,
pattern GL_ALPHA_TEST_REF,
pattern GL_ALREADY_SIGNALED,
pattern GL_ALWAYS,
pattern GL_AMBIENT,
pattern GL_AMBIENT_AND_DIFFUSE,
pattern GL_AND,
pattern GL_AND_INVERTED,
pattern GL_AND_REVERSE,
pattern GL_ANY_SAMPLES_PASSED,
pattern GL_ANY_SAMPLES_PASSED_CONSERVATIVE,
pattern GL_ARRAY_BUFFER,
pattern GL_ARRAY_BUFFER_BINDING,
pattern GL_ARRAY_SIZE,
pattern GL_ARRAY_STRIDE,
pattern GL_ATOMIC_COUNTER_BARRIER_BIT,
pattern GL_ATOMIC_COUNTER_BUFFER,
pattern GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS,
pattern GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES,
pattern GL_ATOMIC_COUNTER_BUFFER_BINDING,
pattern GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE,
pattern GL_ATOMIC_COUNTER_BUFFER_INDEX,
pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER,
pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER,
pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER,
pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER,
pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER,
pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER,
pattern GL_ATOMIC_COUNTER_BUFFER_SIZE,
pattern GL_ATOMIC_COUNTER_BUFFER_START,
pattern GL_ATTACHED_SHADERS,
pattern GL_ATTRIB_STACK_DEPTH,
pattern GL_AUTO_GENERATE_MIPMAP,
pattern GL_AUTO_NORMAL,
pattern GL_AUX0,
pattern GL_AUX1,
pattern GL_AUX2,
pattern GL_AUX3,
pattern GL_AUX_BUFFERS,
pattern GL_BACK,
pattern GL_BACK_LEFT,
pattern GL_BACK_RIGHT,
pattern GL_BGR,
pattern GL_BGRA,
pattern GL_BGRA_INTEGER,
pattern GL_BGR_INTEGER,
pattern GL_BITMAP,
pattern GL_BITMAP_TOKEN,
pattern GL_BLEND,
pattern GL_BLEND_COLOR,
pattern GL_BLEND_DST,
pattern GL_BLEND_DST_ALPHA,
pattern GL_BLEND_DST_RGB,
pattern GL_BLEND_EQUATION,
pattern GL_BLEND_EQUATION_ALPHA,
pattern GL_BLEND_EQUATION_RGB,
pattern GL_BLEND_SRC,
pattern GL_BLEND_SRC_ALPHA,
pattern GL_BLEND_SRC_RGB,
pattern GL_BLOCK_INDEX,
pattern GL_BLUE,
pattern GL_BLUE_BIAS,
pattern GL_BLUE_BITS,
pattern GL_BLUE_INTEGER,
pattern GL_BLUE_SCALE,
pattern GL_BOOL,
pattern GL_BOOL_VEC2,
pattern GL_BOOL_VEC3,
pattern GL_BOOL_VEC4,
pattern GL_BUFFER,
pattern GL_BUFFER_ACCESS,
pattern GL_BUFFER_ACCESS_FLAGS,
pattern GL_BUFFER_BINDING,
pattern GL_BUFFER_DATA_SIZE,
pattern GL_BUFFER_MAPPED,
pattern GL_BUFFER_MAP_LENGTH,
pattern GL_BUFFER_MAP_OFFSET,
pattern GL_BUFFER_MAP_POINTER,
pattern GL_BUFFER_SIZE,
pattern GL_BUFFER_UPDATE_BARRIER_BIT,
pattern GL_BUFFER_USAGE,
pattern GL_BUFFER_VARIABLE,
pattern GL_BYTE,
pattern GL_C3F_V3F,
pattern GL_C4F_N3F_V3F,
pattern GL_C4UB_V2F,
pattern GL_C4UB_V3F,
pattern GL_CAVEAT_SUPPORT,
pattern GL_CCW,
pattern GL_CLAMP,
pattern GL_CLAMP_FRAGMENT_COLOR,
pattern GL_CLAMP_READ_COLOR,
pattern GL_CLAMP_TO_BORDER,
pattern GL_CLAMP_TO_EDGE,
pattern GL_CLAMP_VERTEX_COLOR,
pattern GL_CLEAR,
pattern GL_CLEAR_BUFFER,
pattern GL_CLIENT_ACTIVE_TEXTURE,
pattern GL_CLIENT_ALL_ATTRIB_BITS,
pattern GL_CLIENT_ATTRIB_STACK_DEPTH,
pattern GL_CLIENT_PIXEL_STORE_BIT,
pattern GL_CLIENT_VERTEX_ARRAY_BIT,
pattern GL_CLIP_DISTANCE0,
pattern GL_CLIP_DISTANCE1,
pattern GL_CLIP_DISTANCE2,
pattern GL_CLIP_DISTANCE3,
pattern GL_CLIP_DISTANCE4,
pattern GL_CLIP_DISTANCE5,
pattern GL_CLIP_DISTANCE6,
pattern GL_CLIP_DISTANCE7,
pattern GL_CLIP_PLANE0,
pattern GL_CLIP_PLANE1,
pattern GL_CLIP_PLANE2,
pattern GL_CLIP_PLANE3,
pattern GL_CLIP_PLANE4,
pattern GL_CLIP_PLANE5,
pattern GL_COEFF,
pattern GL_COLOR,
pattern GL_COLOR_ARRAY,
pattern GL_COLOR_ARRAY_BUFFER_BINDING,
pattern GL_COLOR_ARRAY_POINTER,
pattern GL_COLOR_ARRAY_SIZE,
pattern GL_COLOR_ARRAY_STRIDE,
pattern GL_COLOR_ARRAY_TYPE,
pattern GL_COLOR_ATTACHMENT0,
pattern GL_COLOR_ATTACHMENT1,
pattern GL_COLOR_ATTACHMENT10,
pattern GL_COLOR_ATTACHMENT11,
pattern GL_COLOR_ATTACHMENT12,
pattern GL_COLOR_ATTACHMENT13,
pattern GL_COLOR_ATTACHMENT14,
pattern GL_COLOR_ATTACHMENT15,
pattern GL_COLOR_ATTACHMENT16,
pattern GL_COLOR_ATTACHMENT17,
pattern GL_COLOR_ATTACHMENT18,
pattern GL_COLOR_ATTACHMENT19,
pattern GL_COLOR_ATTACHMENT2,
pattern GL_COLOR_ATTACHMENT20,
pattern GL_COLOR_ATTACHMENT21,
pattern GL_COLOR_ATTACHMENT22,
pattern GL_COLOR_ATTACHMENT23,
pattern GL_COLOR_ATTACHMENT24,
pattern GL_COLOR_ATTACHMENT25,
pattern GL_COLOR_ATTACHMENT26,
pattern GL_COLOR_ATTACHMENT27,
pattern GL_COLOR_ATTACHMENT28,
pattern GL_COLOR_ATTACHMENT29,
pattern GL_COLOR_ATTACHMENT3,
pattern GL_COLOR_ATTACHMENT30,
pattern GL_COLOR_ATTACHMENT31,
pattern GL_COLOR_ATTACHMENT4,
pattern GL_COLOR_ATTACHMENT5,
pattern GL_COLOR_ATTACHMENT6,
pattern GL_COLOR_ATTACHMENT7,
pattern GL_COLOR_ATTACHMENT8,
pattern GL_COLOR_ATTACHMENT9,
pattern GL_COLOR_BUFFER_BIT,
pattern GL_COLOR_CLEAR_VALUE,
pattern GL_COLOR_COMPONENTS,
pattern GL_COLOR_ENCODING,
pattern GL_COLOR_INDEX,
pattern GL_COLOR_INDEXES,
pattern GL_COLOR_LOGIC_OP,
pattern GL_COLOR_MATERIAL,
pattern GL_COLOR_MATERIAL_FACE,
pattern GL_COLOR_MATERIAL_PARAMETER,
pattern GL_COLOR_RENDERABLE,
pattern GL_COLOR_SUM,
pattern GL_COLOR_WRITEMASK,
pattern GL_COMBINE,
pattern GL_COMBINE_ALPHA,
pattern GL_COMBINE_RGB,
pattern GL_COMMAND_BARRIER_BIT,
pattern GL_COMPARE_REF_TO_TEXTURE,
pattern GL_COMPARE_R_TO_TEXTURE,
pattern GL_COMPATIBLE_SUBROUTINES,
pattern GL_COMPILE,
pattern GL_COMPILE_AND_EXECUTE,
pattern GL_COMPILE_STATUS,
pattern GL_COMPRESSED_ALPHA,
pattern GL_COMPRESSED_INTENSITY,
pattern GL_COMPRESSED_LUMINANCE,
pattern GL_COMPRESSED_LUMINANCE_ALPHA,
pattern GL_COMPRESSED_R11_EAC,
pattern GL_COMPRESSED_RED,
pattern GL_COMPRESSED_RED_RGTC1,
pattern GL_COMPRESSED_RG,
pattern GL_COMPRESSED_RG11_EAC,
pattern GL_COMPRESSED_RGB,
pattern GL_COMPRESSED_RGB8_ETC2,
pattern GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,
pattern GL_COMPRESSED_RGBA,
pattern GL_COMPRESSED_RGBA8_ETC2_EAC,
pattern GL_COMPRESSED_RGBA_BPTC_UNORM,
pattern GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT,
pattern GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT,
pattern GL_COMPRESSED_RG_RGTC2,
pattern GL_COMPRESSED_SIGNED_R11_EAC,
pattern GL_COMPRESSED_SIGNED_RED_RGTC1,
pattern GL_COMPRESSED_SIGNED_RG11_EAC,
pattern GL_COMPRESSED_SIGNED_RG_RGTC2,
pattern GL_COMPRESSED_SLUMINANCE,
pattern GL_COMPRESSED_SLUMINANCE_ALPHA,
pattern GL_COMPRESSED_SRGB,
pattern GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,
pattern GL_COMPRESSED_SRGB8_ETC2,
pattern GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,
pattern GL_COMPRESSED_SRGB_ALPHA,
pattern GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM,
pattern GL_COMPRESSED_TEXTURE_FORMATS,
pattern GL_COMPUTE_SHADER,
pattern GL_COMPUTE_SHADER_BIT,
pattern GL_COMPUTE_SUBROUTINE,
pattern GL_COMPUTE_SUBROUTINE_UNIFORM,
pattern GL_COMPUTE_TEXTURE,
pattern GL_COMPUTE_WORK_GROUP_SIZE,
pattern GL_CONDITION_SATISFIED,
pattern GL_CONSTANT,
pattern GL_CONSTANT_ALPHA,
pattern GL_CONSTANT_ATTENUATION,
pattern GL_CONSTANT_COLOR,
pattern GL_CONTEXT_COMPATIBILITY_PROFILE_BIT,
pattern GL_CONTEXT_CORE_PROFILE_BIT,
pattern GL_CONTEXT_FLAGS,
pattern GL_CONTEXT_FLAG_DEBUG_BIT,
pattern GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT,
pattern GL_CONTEXT_PROFILE_MASK,
pattern GL_COORD_REPLACE,
pattern GL_COPY,
pattern GL_COPY_INVERTED,
pattern GL_COPY_PIXEL_TOKEN,
pattern GL_COPY_READ_BUFFER,
pattern GL_COPY_READ_BUFFER_BINDING,
pattern GL_COPY_WRITE_BUFFER,
pattern GL_COPY_WRITE_BUFFER_BINDING,
pattern GL_CULL_FACE,
pattern GL_CULL_FACE_MODE,
pattern GL_CURRENT_BIT,
pattern GL_CURRENT_COLOR,
pattern GL_CURRENT_FOG_COORD,
pattern GL_CURRENT_FOG_COORDINATE,
pattern GL_CURRENT_INDEX,
pattern GL_CURRENT_NORMAL,
pattern GL_CURRENT_PROGRAM,
pattern GL_CURRENT_QUERY,
pattern GL_CURRENT_RASTER_COLOR,
pattern GL_CURRENT_RASTER_DISTANCE,
pattern GL_CURRENT_RASTER_INDEX,
pattern GL_CURRENT_RASTER_POSITION,
pattern GL_CURRENT_RASTER_POSITION_VALID,
pattern GL_CURRENT_RASTER_SECONDARY_COLOR,
pattern GL_CURRENT_RASTER_TEXTURE_COORDS,
pattern GL_CURRENT_SECONDARY_COLOR,
pattern GL_CURRENT_TEXTURE_COORDS,
pattern GL_CURRENT_VERTEX_ATTRIB,
pattern GL_CW,
pattern GL_DEBUG_CALLBACK_FUNCTION,
pattern GL_DEBUG_CALLBACK_USER_PARAM,
pattern GL_DEBUG_GROUP_STACK_DEPTH,
pattern GL_DEBUG_LOGGED_MESSAGES,
pattern GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH,
pattern GL_DEBUG_OUTPUT,
pattern GL_DEBUG_OUTPUT_SYNCHRONOUS,
pattern GL_DEBUG_SEVERITY_HIGH,
pattern GL_DEBUG_SEVERITY_LOW,
pattern GL_DEBUG_SEVERITY_MEDIUM,
pattern GL_DEBUG_SEVERITY_NOTIFICATION,
pattern GL_DEBUG_SOURCE_API,
pattern GL_DEBUG_SOURCE_APPLICATION,
pattern GL_DEBUG_SOURCE_OTHER,
pattern GL_DEBUG_SOURCE_SHADER_COMPILER,
pattern GL_DEBUG_SOURCE_THIRD_PARTY,
pattern GL_DEBUG_SOURCE_WINDOW_SYSTEM,
pattern GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
pattern GL_DEBUG_TYPE_ERROR,
pattern GL_DEBUG_TYPE_MARKER,
pattern GL_DEBUG_TYPE_OTHER,
pattern GL_DEBUG_TYPE_PERFORMANCE,
pattern GL_DEBUG_TYPE_POP_GROUP,
pattern GL_DEBUG_TYPE_PORTABILITY,
pattern GL_DEBUG_TYPE_PUSH_GROUP,
pattern GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
pattern GL_DECAL,
pattern GL_DECR,
pattern GL_DECR_WRAP,
pattern GL_DELETE_STATUS,
pattern GL_DEPTH,
pattern GL_DEPTH24_STENCIL8,
pattern GL_DEPTH32F_STENCIL8,
pattern GL_DEPTH_ATTACHMENT,
pattern GL_DEPTH_BIAS,
pattern GL_DEPTH_BITS,
pattern GL_DEPTH_BUFFER_BIT,
pattern GL_DEPTH_CLAMP,
pattern GL_DEPTH_CLEAR_VALUE,
pattern GL_DEPTH_COMPONENT,
pattern GL_DEPTH_COMPONENT16,
pattern GL_DEPTH_COMPONENT24,
pattern GL_DEPTH_COMPONENT32,
pattern GL_DEPTH_COMPONENT32F,
pattern GL_DEPTH_COMPONENTS,
pattern GL_DEPTH_FUNC,
pattern GL_DEPTH_RANGE,
pattern GL_DEPTH_RENDERABLE,
pattern GL_DEPTH_SCALE,
pattern GL_DEPTH_STENCIL,
pattern GL_DEPTH_STENCIL_ATTACHMENT,
pattern GL_DEPTH_STENCIL_TEXTURE_MODE,
pattern GL_DEPTH_TEST,
pattern GL_DEPTH_TEXTURE_MODE,
pattern GL_DEPTH_WRITEMASK,
pattern GL_DIFFUSE,
pattern GL_DISPATCH_INDIRECT_BUFFER,
pattern GL_DISPATCH_INDIRECT_BUFFER_BINDING,
pattern GL_DISPLAY_LIST,
pattern GL_DITHER,
pattern GL_DOMAIN,
pattern GL_DONT_CARE,
pattern GL_DOT3_RGB,
pattern GL_DOT3_RGBA,
pattern GL_DOUBLE,
pattern GL_DOUBLEBUFFER,
pattern GL_DOUBLE_MAT2,
pattern GL_DOUBLE_MAT2x3,
pattern GL_DOUBLE_MAT2x4,
pattern GL_DOUBLE_MAT3,
pattern GL_DOUBLE_MAT3x2,
pattern GL_DOUBLE_MAT3x4,
pattern GL_DOUBLE_MAT4,
pattern GL_DOUBLE_MAT4x2,
pattern GL_DOUBLE_MAT4x3,
pattern GL_DOUBLE_VEC2,
pattern GL_DOUBLE_VEC3,
pattern GL_DOUBLE_VEC4,
pattern GL_DRAW_BUFFER,
pattern GL_DRAW_BUFFER0,
pattern GL_DRAW_BUFFER1,
pattern GL_DRAW_BUFFER10,
pattern GL_DRAW_BUFFER11,
pattern GL_DRAW_BUFFER12,
pattern GL_DRAW_BUFFER13,
pattern GL_DRAW_BUFFER14,
pattern GL_DRAW_BUFFER15,
pattern GL_DRAW_BUFFER2,
pattern GL_DRAW_BUFFER3,
pattern GL_DRAW_BUFFER4,
pattern GL_DRAW_BUFFER5,
pattern GL_DRAW_BUFFER6,
pattern GL_DRAW_BUFFER7,
pattern GL_DRAW_BUFFER8,
pattern GL_DRAW_BUFFER9,
pattern GL_DRAW_FRAMEBUFFER,
pattern GL_DRAW_FRAMEBUFFER_BINDING,
pattern GL_DRAW_INDIRECT_BUFFER,
pattern GL_DRAW_INDIRECT_BUFFER_BINDING,
pattern GL_DRAW_PIXEL_TOKEN,
pattern GL_DST_ALPHA,
pattern GL_DST_COLOR,
pattern GL_DYNAMIC_COPY,
pattern GL_DYNAMIC_DRAW,
pattern GL_DYNAMIC_READ,
pattern GL_EDGE_FLAG,
pattern GL_EDGE_FLAG_ARRAY,
pattern GL_EDGE_FLAG_ARRAY_BUFFER_BINDING,
pattern GL_EDGE_FLAG_ARRAY_POINTER,
pattern GL_EDGE_FLAG_ARRAY_STRIDE,
pattern GL_ELEMENT_ARRAY_BARRIER_BIT,
pattern GL_ELEMENT_ARRAY_BUFFER,
pattern GL_ELEMENT_ARRAY_BUFFER_BINDING,
pattern GL_EMISSION,
pattern GL_ENABLE_BIT,
pattern GL_EQUAL,
pattern GL_EQUIV,
pattern GL_EVAL_BIT,
pattern GL_EXP,
pattern GL_EXP2,
pattern GL_EXTENSIONS,
pattern GL_EYE_LINEAR,
pattern GL_EYE_PLANE,
pattern GL_FALSE,
pattern GL_FASTEST,
pattern GL_FEEDBACK,
pattern GL_FEEDBACK_BUFFER_POINTER,
pattern GL_FEEDBACK_BUFFER_SIZE,
pattern GL_FEEDBACK_BUFFER_TYPE,
pattern GL_FILL,
pattern GL_FILTER,
pattern GL_FIRST_VERTEX_CONVENTION,
pattern GL_FIXED,
pattern GL_FIXED_ONLY,
pattern GL_FLAT,
pattern GL_FLOAT,
pattern GL_FLOAT_32_UNSIGNED_INT_24_8_REV,
pattern GL_FLOAT_MAT2,
pattern GL_FLOAT_MAT2x3,
pattern GL_FLOAT_MAT2x4,
pattern GL_FLOAT_MAT3,
pattern GL_FLOAT_MAT3x2,
pattern GL_FLOAT_MAT3x4,
pattern GL_FLOAT_MAT4,
pattern GL_FLOAT_MAT4x2,
pattern GL_FLOAT_MAT4x3,
pattern GL_FLOAT_VEC2,
pattern GL_FLOAT_VEC3,
pattern GL_FLOAT_VEC4,
pattern GL_FOG,
pattern GL_FOG_BIT,
pattern GL_FOG_COLOR,
pattern GL_FOG_COORD,
pattern GL_FOG_COORDINATE,
pattern GL_FOG_COORDINATE_ARRAY,
pattern GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING,
pattern GL_FOG_COORDINATE_ARRAY_POINTER,
pattern GL_FOG_COORDINATE_ARRAY_STRIDE,
pattern GL_FOG_COORDINATE_ARRAY_TYPE,
pattern GL_FOG_COORDINATE_SOURCE,
pattern GL_FOG_COORD_ARRAY,
pattern GL_FOG_COORD_ARRAY_BUFFER_BINDING,
pattern GL_FOG_COORD_ARRAY_POINTER,
pattern GL_FOG_COORD_ARRAY_STRIDE,
pattern GL_FOG_COORD_ARRAY_TYPE,
pattern GL_FOG_COORD_SRC,
pattern GL_FOG_DENSITY,
pattern GL_FOG_END,
pattern GL_FOG_HINT,
pattern GL_FOG_INDEX,
pattern GL_FOG_MODE,
pattern GL_FOG_START,
pattern GL_FRACTIONAL_EVEN,
pattern GL_FRACTIONAL_ODD,
pattern GL_FRAGMENT_DEPTH,
pattern GL_FRAGMENT_INTERPOLATION_OFFSET_BITS,
pattern GL_FRAGMENT_SHADER,
pattern GL_FRAGMENT_SHADER_BIT,
pattern GL_FRAGMENT_SHADER_DERIVATIVE_HINT,
pattern GL_FRAGMENT_SUBROUTINE,
pattern GL_FRAGMENT_SUBROUTINE_UNIFORM,
pattern GL_FRAGMENT_TEXTURE,
pattern GL_FRAMEBUFFER,
pattern GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
pattern GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE,
pattern GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING,
pattern GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE,
pattern GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE,
pattern GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE,
pattern GL_FRAMEBUFFER_ATTACHMENT_LAYERED,
pattern GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
pattern GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
pattern GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE,
pattern GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE,
pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER,
pattern GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
pattern GL_FRAMEBUFFER_BARRIER_BIT,
pattern GL_FRAMEBUFFER_BINDING,
pattern GL_FRAMEBUFFER_BLEND,
pattern GL_FRAMEBUFFER_COMPLETE,
pattern GL_FRAMEBUFFER_DEFAULT,
pattern GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS,
pattern GL_FRAMEBUFFER_DEFAULT_HEIGHT,
pattern GL_FRAMEBUFFER_DEFAULT_LAYERS,
pattern GL_FRAMEBUFFER_DEFAULT_SAMPLES,
pattern GL_FRAMEBUFFER_DEFAULT_WIDTH,
pattern GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT,
pattern GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER,
pattern GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS,
pattern GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT,
pattern GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE,
pattern GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER,
pattern GL_FRAMEBUFFER_RENDERABLE,
pattern GL_FRAMEBUFFER_RENDERABLE_LAYERED,
pattern GL_FRAMEBUFFER_SRGB,
pattern GL_FRAMEBUFFER_UNDEFINED,
pattern GL_FRAMEBUFFER_UNSUPPORTED,
pattern GL_FRONT,
pattern GL_FRONT_AND_BACK,
pattern GL_FRONT_FACE,
pattern GL_FRONT_LEFT,
pattern GL_FRONT_RIGHT,
pattern GL_FULL_SUPPORT,
pattern GL_FUNC_ADD,
pattern GL_FUNC_REVERSE_SUBTRACT,
pattern GL_FUNC_SUBTRACT,
pattern GL_GENERATE_MIPMAP,
pattern GL_GENERATE_MIPMAP_HINT,
pattern GL_GEOMETRY_INPUT_TYPE,
pattern GL_GEOMETRY_OUTPUT_TYPE,
pattern GL_GEOMETRY_SHADER,
pattern GL_GEOMETRY_SHADER_BIT,
pattern GL_GEOMETRY_SHADER_INVOCATIONS,
pattern GL_GEOMETRY_SUBROUTINE,
pattern GL_GEOMETRY_SUBROUTINE_UNIFORM,
pattern GL_GEOMETRY_TEXTURE,
pattern GL_GEOMETRY_VERTICES_OUT,
pattern GL_GEQUAL,
pattern GL_GET_TEXTURE_IMAGE_FORMAT,
pattern GL_GET_TEXTURE_IMAGE_TYPE,
pattern GL_GREATER,
pattern GL_GREEN,
pattern GL_GREEN_BIAS,
pattern GL_GREEN_BITS,
pattern GL_GREEN_INTEGER,
pattern GL_GREEN_SCALE,
pattern GL_HALF_FLOAT,
pattern GL_HIGH_FLOAT,
pattern GL_HIGH_INT,
pattern GL_HINT_BIT,
pattern GL_IMAGE_1D,
pattern GL_IMAGE_1D_ARRAY,
pattern GL_IMAGE_2D,
pattern GL_IMAGE_2D_ARRAY,
pattern GL_IMAGE_2D_MULTISAMPLE,
pattern GL_IMAGE_2D_MULTISAMPLE_ARRAY,
pattern GL_IMAGE_2D_RECT,
pattern GL_IMAGE_3D,
pattern GL_IMAGE_BINDING_ACCESS,
pattern GL_IMAGE_BINDING_FORMAT,
pattern GL_IMAGE_BINDING_LAYER,
pattern GL_IMAGE_BINDING_LAYERED,
pattern GL_IMAGE_BINDING_LEVEL,
pattern GL_IMAGE_BINDING_NAME,
pattern GL_IMAGE_BUFFER,
pattern GL_IMAGE_CLASS_10_10_10_2,
pattern GL_IMAGE_CLASS_11_11_10,
pattern GL_IMAGE_CLASS_1_X_16,
pattern GL_IMAGE_CLASS_1_X_32,
pattern GL_IMAGE_CLASS_1_X_8,
pattern GL_IMAGE_CLASS_2_X_16,
pattern GL_IMAGE_CLASS_2_X_32,
pattern GL_IMAGE_CLASS_2_X_8,
pattern GL_IMAGE_CLASS_4_X_16,
pattern GL_IMAGE_CLASS_4_X_32,
pattern GL_IMAGE_CLASS_4_X_8,
pattern GL_IMAGE_COMPATIBILITY_CLASS,
pattern GL_IMAGE_CUBE,
pattern GL_IMAGE_CUBE_MAP_ARRAY,
pattern GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS,
pattern GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE,
pattern GL_IMAGE_FORMAT_COMPATIBILITY_TYPE,
pattern GL_IMAGE_PIXEL_FORMAT,
pattern GL_IMAGE_PIXEL_TYPE,
pattern GL_IMAGE_TEXEL_SIZE,
pattern GL_IMPLEMENTATION_COLOR_READ_FORMAT,
pattern GL_IMPLEMENTATION_COLOR_READ_TYPE,
pattern GL_INCR,
pattern GL_INCR_WRAP,
pattern GL_INDEX,
pattern GL_INDEX_ARRAY,
pattern GL_INDEX_ARRAY_BUFFER_BINDING,
pattern GL_INDEX_ARRAY_POINTER,
pattern GL_INDEX_ARRAY_STRIDE,
pattern GL_INDEX_ARRAY_TYPE,
pattern GL_INDEX_BITS,
pattern GL_INDEX_CLEAR_VALUE,
pattern GL_INDEX_LOGIC_OP,
pattern GL_INDEX_MODE,
pattern GL_INDEX_OFFSET,
pattern GL_INDEX_SHIFT,
pattern GL_INDEX_WRITEMASK,
pattern GL_INFO_LOG_LENGTH,
pattern GL_INT,
pattern GL_INTENSITY,
pattern GL_INTENSITY12,
pattern GL_INTENSITY16,
pattern GL_INTENSITY4,
pattern GL_INTENSITY8,
pattern GL_INTERLEAVED_ATTRIBS,
pattern GL_INTERNALFORMAT_ALPHA_SIZE,
pattern GL_INTERNALFORMAT_ALPHA_TYPE,
pattern GL_INTERNALFORMAT_BLUE_SIZE,
pattern GL_INTERNALFORMAT_BLUE_TYPE,
pattern GL_INTERNALFORMAT_DEPTH_SIZE,
pattern GL_INTERNALFORMAT_DEPTH_TYPE,
pattern GL_INTERNALFORMAT_GREEN_SIZE,
pattern GL_INTERNALFORMAT_GREEN_TYPE,
pattern GL_INTERNALFORMAT_PREFERRED,
pattern GL_INTERNALFORMAT_RED_SIZE,
pattern GL_INTERNALFORMAT_RED_TYPE,
pattern GL_INTERNALFORMAT_SHARED_SIZE,
pattern GL_INTERNALFORMAT_STENCIL_SIZE,
pattern GL_INTERNALFORMAT_STENCIL_TYPE,
pattern GL_INTERNALFORMAT_SUPPORTED,
pattern GL_INTERPOLATE,
pattern GL_INT_2_10_10_10_REV,
pattern GL_INT_IMAGE_1D,
pattern GL_INT_IMAGE_1D_ARRAY,
pattern GL_INT_IMAGE_2D,
pattern GL_INT_IMAGE_2D_ARRAY,
pattern GL_INT_IMAGE_2D_MULTISAMPLE,
pattern GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY,
pattern GL_INT_IMAGE_2D_RECT,
pattern GL_INT_IMAGE_3D,
pattern GL_INT_IMAGE_BUFFER,
pattern GL_INT_IMAGE_CUBE,
pattern GL_INT_IMAGE_CUBE_MAP_ARRAY,
pattern GL_INT_SAMPLER_1D,
pattern GL_INT_SAMPLER_1D_ARRAY,
pattern GL_INT_SAMPLER_2D,
pattern GL_INT_SAMPLER_2D_ARRAY,
pattern GL_INT_SAMPLER_2D_MULTISAMPLE,
pattern GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY,
pattern GL_INT_SAMPLER_2D_RECT,
pattern GL_INT_SAMPLER_3D,
pattern GL_INT_SAMPLER_BUFFER,
pattern GL_INT_SAMPLER_CUBE,
pattern GL_INT_SAMPLER_CUBE_MAP_ARRAY,
pattern GL_INT_VEC2,
pattern GL_INT_VEC3,
pattern GL_INT_VEC4,
pattern GL_INVALID_ENUM,
pattern GL_INVALID_FRAMEBUFFER_OPERATION,
pattern GL_INVALID_INDEX,
pattern GL_INVALID_OPERATION,
pattern GL_INVALID_VALUE,
pattern GL_INVERT,
pattern GL_ISOLINES,
pattern GL_IS_PER_PATCH,
pattern GL_IS_ROW_MAJOR,
pattern GL_KEEP,
pattern GL_LAST_VERTEX_CONVENTION,
pattern GL_LAYER_PROVOKING_VERTEX,
pattern GL_LEFT,
pattern GL_LEQUAL,
pattern GL_LESS,
pattern GL_LIGHT0,
pattern GL_LIGHT1,
pattern GL_LIGHT2,
pattern GL_LIGHT3,
pattern GL_LIGHT4,
pattern GL_LIGHT5,
pattern GL_LIGHT6,
pattern GL_LIGHT7,
pattern GL_LIGHTING,
pattern GL_LIGHTING_BIT,
pattern GL_LIGHT_MODEL_AMBIENT,
pattern GL_LIGHT_MODEL_COLOR_CONTROL,
pattern GL_LIGHT_MODEL_LOCAL_VIEWER,
pattern GL_LIGHT_MODEL_TWO_SIDE,
pattern GL_LINE,
pattern GL_LINEAR,
pattern GL_LINEAR_ATTENUATION,
pattern GL_LINEAR_MIPMAP_LINEAR,
pattern GL_LINEAR_MIPMAP_NEAREST,
pattern GL_LINES,
pattern GL_LINES_ADJACENCY,
pattern GL_LINE_BIT,
pattern GL_LINE_LOOP,
pattern GL_LINE_RESET_TOKEN,
pattern GL_LINE_SMOOTH,
pattern GL_LINE_SMOOTH_HINT,
pattern GL_LINE_STIPPLE,
pattern GL_LINE_STIPPLE_PATTERN,
pattern GL_LINE_STIPPLE_REPEAT,
pattern GL_LINE_STRIP,
pattern GL_LINE_STRIP_ADJACENCY,
pattern GL_LINE_TOKEN,
pattern GL_LINE_WIDTH,
pattern GL_LINE_WIDTH_GRANULARITY,
pattern GL_LINE_WIDTH_RANGE,
pattern GL_LINK_STATUS,
pattern GL_LIST_BASE,
pattern GL_LIST_BIT,
pattern GL_LIST_INDEX,
pattern GL_LIST_MODE,
pattern GL_LOAD,
pattern GL_LOCATION,
pattern GL_LOCATION_INDEX,
pattern GL_LOGIC_OP,
pattern GL_LOGIC_OP_MODE,
pattern GL_LOWER_LEFT,
pattern GL_LOW_FLOAT,
pattern GL_LOW_INT,
pattern GL_LUMINANCE,
pattern GL_LUMINANCE12,
pattern GL_LUMINANCE12_ALPHA12,
pattern GL_LUMINANCE12_ALPHA4,
pattern GL_LUMINANCE16,
pattern GL_LUMINANCE16_ALPHA16,
pattern GL_LUMINANCE4,
pattern GL_LUMINANCE4_ALPHA4,
pattern GL_LUMINANCE6_ALPHA2,
pattern GL_LUMINANCE8,
pattern GL_LUMINANCE8_ALPHA8,
pattern GL_LUMINANCE_ALPHA,
pattern GL_MAJOR_VERSION,
pattern GL_MANUAL_GENERATE_MIPMAP,
pattern GL_MAP1_COLOR_4,
pattern GL_MAP1_GRID_DOMAIN,
pattern GL_MAP1_GRID_SEGMENTS,
pattern GL_MAP1_INDEX,
pattern GL_MAP1_NORMAL,
pattern GL_MAP1_TEXTURE_COORD_1,
pattern GL_MAP1_TEXTURE_COORD_2,
pattern GL_MAP1_TEXTURE_COORD_3,
pattern GL_MAP1_TEXTURE_COORD_4,
pattern GL_MAP1_VERTEX_3,
pattern GL_MAP1_VERTEX_4,
pattern GL_MAP2_COLOR_4,
pattern GL_MAP2_GRID_DOMAIN,
pattern GL_MAP2_GRID_SEGMENTS,
pattern GL_MAP2_INDEX,
pattern GL_MAP2_NORMAL,
pattern GL_MAP2_TEXTURE_COORD_1,
pattern GL_MAP2_TEXTURE_COORD_2,
pattern GL_MAP2_TEXTURE_COORD_3,
pattern GL_MAP2_TEXTURE_COORD_4,
pattern GL_MAP2_VERTEX_3,
pattern GL_MAP2_VERTEX_4,
pattern GL_MAP_COLOR,
pattern GL_MAP_FLUSH_EXPLICIT_BIT,
pattern GL_MAP_INVALIDATE_BUFFER_BIT,
pattern GL_MAP_INVALIDATE_RANGE_BIT,
pattern GL_MAP_READ_BIT,
pattern GL_MAP_STENCIL,
pattern GL_MAP_UNSYNCHRONIZED_BIT,
pattern GL_MAP_WRITE_BIT,
pattern GL_MATRIX_MODE,
pattern GL_MATRIX_STRIDE,
pattern GL_MAX,
pattern GL_MAX_3D_TEXTURE_SIZE,
pattern GL_MAX_ARRAY_TEXTURE_LAYERS,
pattern GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS,
pattern GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE,
pattern GL_MAX_ATTRIB_STACK_DEPTH,
pattern GL_MAX_CLIENT_ATTRIB_STACK_DEPTH,
pattern GL_MAX_CLIP_DISTANCES,
pattern GL_MAX_CLIP_PLANES,
pattern GL_MAX_COLOR_ATTACHMENTS,
pattern GL_MAX_COLOR_TEXTURE_SAMPLES,
pattern GL_MAX_COMBINED_ATOMIC_COUNTERS,
pattern GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS,
pattern GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS,
pattern GL_MAX_COMBINED_DIMENSIONS,
pattern GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS,
pattern GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS,
pattern GL_MAX_COMBINED_IMAGE_UNIFORMS,
pattern GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS,
pattern GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES,
pattern GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS,
pattern GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS,
pattern GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS,
pattern GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS,
pattern GL_MAX_COMBINED_UNIFORM_BLOCKS,
pattern GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS,
pattern GL_MAX_COMPUTE_ATOMIC_COUNTERS,
pattern GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS,
pattern GL_MAX_COMPUTE_IMAGE_UNIFORMS,
pattern GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS,
pattern GL_MAX_COMPUTE_SHARED_MEMORY_SIZE,
pattern GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS,
pattern GL_MAX_COMPUTE_UNIFORM_BLOCKS,
pattern GL_MAX_COMPUTE_UNIFORM_COMPONENTS,
pattern GL_MAX_COMPUTE_WORK_GROUP_COUNT,
pattern GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS,
pattern GL_MAX_COMPUTE_WORK_GROUP_SIZE,
pattern GL_MAX_CUBE_MAP_TEXTURE_SIZE,
pattern GL_MAX_DEBUG_GROUP_STACK_DEPTH,
pattern GL_MAX_DEBUG_LOGGED_MESSAGES,
pattern GL_MAX_DEBUG_MESSAGE_LENGTH,
pattern GL_MAX_DEPTH,
pattern GL_MAX_DEPTH_TEXTURE_SAMPLES,
pattern GL_MAX_DRAW_BUFFERS,
pattern GL_MAX_DUAL_SOURCE_DRAW_BUFFERS,
pattern GL_MAX_ELEMENTS_INDICES,
pattern GL_MAX_ELEMENTS_VERTICES,
pattern GL_MAX_ELEMENT_INDEX,
pattern GL_MAX_EVAL_ORDER,
pattern GL_MAX_FRAGMENT_ATOMIC_COUNTERS,
pattern GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS,
pattern GL_MAX_FRAGMENT_IMAGE_UNIFORMS,
pattern GL_MAX_FRAGMENT_INPUT_COMPONENTS,
pattern GL_MAX_FRAGMENT_INTERPOLATION_OFFSET,
pattern GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS,
pattern GL_MAX_FRAGMENT_UNIFORM_BLOCKS,
pattern GL_MAX_FRAGMENT_UNIFORM_COMPONENTS,
pattern GL_MAX_FRAGMENT_UNIFORM_VECTORS,
pattern GL_MAX_FRAMEBUFFER_HEIGHT,
pattern GL_MAX_FRAMEBUFFER_LAYERS,
pattern GL_MAX_FRAMEBUFFER_SAMPLES,
pattern GL_MAX_FRAMEBUFFER_WIDTH,
pattern GL_MAX_GEOMETRY_ATOMIC_COUNTERS,
pattern GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS,
pattern GL_MAX_GEOMETRY_IMAGE_UNIFORMS,
pattern GL_MAX_GEOMETRY_INPUT_COMPONENTS,
pattern GL_MAX_GEOMETRY_OUTPUT_COMPONENTS,
pattern GL_MAX_GEOMETRY_OUTPUT_VERTICES,
pattern GL_MAX_GEOMETRY_SHADER_INVOCATIONS,
pattern GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS,
pattern GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS,
pattern GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS,
pattern GL_MAX_GEOMETRY_UNIFORM_BLOCKS,
pattern GL_MAX_GEOMETRY_UNIFORM_COMPONENTS,
pattern GL_MAX_HEIGHT,
pattern GL_MAX_IMAGE_SAMPLES,
pattern GL_MAX_IMAGE_UNITS,
pattern GL_MAX_INTEGER_SAMPLES,
pattern GL_MAX_LABEL_LENGTH,
pattern GL_MAX_LAYERS,
pattern GL_MAX_LIGHTS,
pattern GL_MAX_LIST_NESTING,
pattern GL_MAX_MODELVIEW_STACK_DEPTH,
pattern GL_MAX_NAME_LENGTH,
pattern GL_MAX_NAME_STACK_DEPTH,
pattern GL_MAX_NUM_ACTIVE_VARIABLES,
pattern GL_MAX_NUM_COMPATIBLE_SUBROUTINES,
pattern GL_MAX_PATCH_VERTICES,
pattern GL_MAX_PIXEL_MAP_TABLE,
pattern GL_MAX_PROGRAM_TEXEL_OFFSET,
pattern GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET,
pattern GL_MAX_PROJECTION_STACK_DEPTH,
pattern GL_MAX_RECTANGLE_TEXTURE_SIZE,
pattern GL_MAX_RENDERBUFFER_SIZE,
pattern GL_MAX_SAMPLES,
pattern GL_MAX_SAMPLE_MASK_WORDS,
pattern GL_MAX_SERVER_WAIT_TIMEOUT,
pattern GL_MAX_SHADER_STORAGE_BLOCK_SIZE,
pattern GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS,
pattern GL_MAX_SUBROUTINES,
pattern GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS,
pattern GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS,
pattern GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS,
pattern GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS,
pattern GL_MAX_TESS_CONTROL_INPUT_COMPONENTS,
pattern GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS,
pattern GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS,
pattern GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS,
pattern GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS,
pattern GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS,
pattern GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS,
pattern GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS,
pattern GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS,
pattern GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS,
pattern GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS,
pattern GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS,
pattern GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS,
pattern GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS,
pattern GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS,
pattern GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS,
pattern GL_MAX_TESS_GEN_LEVEL,
pattern GL_MAX_TESS_PATCH_COMPONENTS,
pattern GL_MAX_TEXTURE_BUFFER_SIZE,
pattern GL_MAX_TEXTURE_COORDS,
pattern GL_MAX_TEXTURE_IMAGE_UNITS,
pattern GL_MAX_TEXTURE_LOD_BIAS,
pattern GL_MAX_TEXTURE_SIZE,
pattern GL_MAX_TEXTURE_STACK_DEPTH,
pattern GL_MAX_TEXTURE_UNITS,
pattern GL_MAX_TRANSFORM_FEEDBACK_BUFFERS,
pattern GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS,
pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS,
pattern GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS,
pattern GL_MAX_UNIFORM_BLOCK_SIZE,
pattern GL_MAX_UNIFORM_BUFFER_BINDINGS,
pattern GL_MAX_UNIFORM_LOCATIONS,
pattern GL_MAX_VARYING_COMPONENTS,
pattern GL_MAX_VARYING_FLOATS,
pattern GL_MAX_VARYING_VECTORS,
pattern GL_MAX_VERTEX_ATOMIC_COUNTERS,
pattern GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS,
pattern GL_MAX_VERTEX_ATTRIBS,
pattern GL_MAX_VERTEX_ATTRIB_BINDINGS,
pattern GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET,
pattern GL_MAX_VERTEX_IMAGE_UNIFORMS,
pattern GL_MAX_VERTEX_OUTPUT_COMPONENTS,
pattern GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS,
pattern GL_MAX_VERTEX_STREAMS,
pattern GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
pattern GL_MAX_VERTEX_UNIFORM_BLOCKS,
pattern GL_MAX_VERTEX_UNIFORM_COMPONENTS,
pattern GL_MAX_VERTEX_UNIFORM_VECTORS,
pattern GL_MAX_VIEWPORTS,
pattern GL_MAX_VIEWPORT_DIMS,
pattern GL_MAX_WIDTH,
pattern GL_MEDIUM_FLOAT,
pattern GL_MEDIUM_INT,
pattern GL_MIN,
pattern GL_MINOR_VERSION,
pattern GL_MIN_FRAGMENT_INTERPOLATION_OFFSET,
pattern GL_MIN_MAP_BUFFER_ALIGNMENT,
pattern GL_MIN_PROGRAM_TEXEL_OFFSET,
pattern GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET,
pattern GL_MIN_SAMPLE_SHADING_VALUE,
pattern GL_MIPMAP,
pattern GL_MIRRORED_REPEAT,
pattern GL_MODELVIEW,
pattern GL_MODELVIEW_MATRIX,
pattern GL_MODELVIEW_STACK_DEPTH,
pattern GL_MODULATE,
pattern GL_MULT,
pattern GL_MULTISAMPLE,
pattern GL_MULTISAMPLE_BIT,
pattern GL_N3F_V3F,
pattern GL_NAME_LENGTH,
pattern GL_NAME_STACK_DEPTH,
pattern GL_NAND,
pattern GL_NEAREST,
pattern GL_NEAREST_MIPMAP_LINEAR,
pattern GL_NEAREST_MIPMAP_NEAREST,
pattern GL_NEVER,
pattern GL_NICEST,
pattern GL_NONE,
pattern GL_NOOP,
pattern GL_NOR,
pattern GL_NORMALIZE,
pattern GL_NORMAL_ARRAY,
pattern GL_NORMAL_ARRAY_BUFFER_BINDING,
pattern GL_NORMAL_ARRAY_POINTER,
pattern GL_NORMAL_ARRAY_STRIDE,
pattern GL_NORMAL_ARRAY_TYPE,
pattern GL_NORMAL_MAP,
pattern GL_NOTEQUAL,
pattern GL_NO_ERROR,
pattern GL_NUM_ACTIVE_VARIABLES,
pattern GL_NUM_COMPATIBLE_SUBROUTINES,
pattern GL_NUM_COMPRESSED_TEXTURE_FORMATS,
pattern GL_NUM_EXTENSIONS,
pattern GL_NUM_PROGRAM_BINARY_FORMATS,
pattern GL_NUM_SAMPLE_COUNTS,
pattern GL_NUM_SHADER_BINARY_FORMATS,
pattern GL_NUM_SHADING_LANGUAGE_VERSIONS,
pattern GL_OBJECT_LINEAR,
pattern GL_OBJECT_PLANE,
pattern GL_OBJECT_TYPE,
pattern GL_OFFSET,
pattern GL_ONE,
pattern GL_ONE_MINUS_CONSTANT_ALPHA,
pattern GL_ONE_MINUS_CONSTANT_COLOR,
pattern GL_ONE_MINUS_DST_ALPHA,
pattern GL_ONE_MINUS_DST_COLOR,
pattern GL_ONE_MINUS_SRC1_ALPHA,
pattern GL_ONE_MINUS_SRC1_COLOR,
pattern GL_ONE_MINUS_SRC_ALPHA,
pattern GL_ONE_MINUS_SRC_COLOR,
pattern GL_OPERAND0_ALPHA,
pattern GL_OPERAND0_RGB,
pattern GL_OPERAND1_ALPHA,
pattern GL_OPERAND1_RGB,
pattern GL_OPERAND2_ALPHA,
pattern GL_OPERAND2_RGB,
pattern GL_OR,
pattern GL_ORDER,
pattern GL_OR_INVERTED,
pattern GL_OR_REVERSE,
pattern GL_OUT_OF_MEMORY,
pattern GL_PACK_ALIGNMENT,
pattern GL_PACK_COMPRESSED_BLOCK_DEPTH,
pattern GL_PACK_COMPRESSED_BLOCK_HEIGHT,
pattern GL_PACK_COMPRESSED_BLOCK_SIZE,
pattern GL_PACK_COMPRESSED_BLOCK_WIDTH,
pattern GL_PACK_IMAGE_HEIGHT,
pattern GL_PACK_LSB_FIRST,
pattern GL_PACK_ROW_LENGTH,
pattern GL_PACK_SKIP_IMAGES,
pattern GL_PACK_SKIP_PIXELS,
pattern GL_PACK_SKIP_ROWS,
pattern GL_PACK_SWAP_BYTES,
pattern GL_PASS_THROUGH_TOKEN,
pattern GL_PATCHES,
pattern GL_PATCH_DEFAULT_INNER_LEVEL,
pattern GL_PATCH_DEFAULT_OUTER_LEVEL,
pattern GL_PATCH_VERTICES,
pattern GL_PERSPECTIVE_CORRECTION_HINT,
pattern GL_PIXEL_BUFFER_BARRIER_BIT,
pattern GL_PIXEL_MAP_A_TO_A,
pattern GL_PIXEL_MAP_A_TO_A_SIZE,
pattern GL_PIXEL_MAP_B_TO_B,
pattern GL_PIXEL_MAP_B_TO_B_SIZE,
pattern GL_PIXEL_MAP_G_TO_G,
pattern GL_PIXEL_MAP_G_TO_G_SIZE,
pattern GL_PIXEL_MAP_I_TO_A,
pattern GL_PIXEL_MAP_I_TO_A_SIZE,
pattern GL_PIXEL_MAP_I_TO_B,
pattern GL_PIXEL_MAP_I_TO_B_SIZE,
pattern GL_PIXEL_MAP_I_TO_G,
pattern GL_PIXEL_MAP_I_TO_G_SIZE,
pattern GL_PIXEL_MAP_I_TO_I,
pattern GL_PIXEL_MAP_I_TO_I_SIZE,
pattern GL_PIXEL_MAP_I_TO_R,
pattern GL_PIXEL_MAP_I_TO_R_SIZE,
pattern GL_PIXEL_MAP_R_TO_R,
pattern GL_PIXEL_MAP_R_TO_R_SIZE,
pattern GL_PIXEL_MAP_S_TO_S,
pattern GL_PIXEL_MAP_S_TO_S_SIZE,
pattern GL_PIXEL_MODE_BIT,
pattern GL_PIXEL_PACK_BUFFER,
pattern GL_PIXEL_PACK_BUFFER_BINDING,
pattern GL_PIXEL_UNPACK_BUFFER,
pattern GL_PIXEL_UNPACK_BUFFER_BINDING,
pattern GL_POINT,
pattern GL_POINTS,
pattern GL_POINT_BIT,
pattern GL_POINT_DISTANCE_ATTENUATION,
pattern GL_POINT_FADE_THRESHOLD_SIZE,
pattern GL_POINT_SIZE,
pattern GL_POINT_SIZE_GRANULARITY,
pattern GL_POINT_SIZE_MAX,
pattern GL_POINT_SIZE_MIN,
pattern GL_POINT_SIZE_RANGE,
pattern GL_POINT_SMOOTH,
pattern GL_POINT_SMOOTH_HINT,
pattern GL_POINT_SPRITE,
pattern GL_POINT_SPRITE_COORD_ORIGIN,
pattern GL_POINT_TOKEN,
pattern GL_POLYGON,
pattern GL_POLYGON_BIT,
pattern GL_POLYGON_MODE,
pattern GL_POLYGON_OFFSET_FACTOR,
pattern GL_POLYGON_OFFSET_FILL,
pattern GL_POLYGON_OFFSET_LINE,
pattern GL_POLYGON_OFFSET_POINT,
pattern GL_POLYGON_OFFSET_UNITS,
pattern GL_POLYGON_SMOOTH,
pattern GL_POLYGON_SMOOTH_HINT,
pattern GL_POLYGON_STIPPLE,
pattern GL_POLYGON_STIPPLE_BIT,
pattern GL_POLYGON_TOKEN,
pattern GL_POSITION,
pattern GL_PREVIOUS,
pattern GL_PRIMARY_COLOR,
pattern GL_PRIMITIVES_GENERATED,
pattern GL_PRIMITIVE_RESTART,
pattern GL_PRIMITIVE_RESTART_FIXED_INDEX,
pattern GL_PRIMITIVE_RESTART_INDEX,
pattern GL_PROGRAM,
pattern GL_PROGRAM_BINARY_FORMATS,
pattern GL_PROGRAM_BINARY_LENGTH,
pattern GL_PROGRAM_BINARY_RETRIEVABLE_HINT,
pattern GL_PROGRAM_INPUT,
pattern GL_PROGRAM_OUTPUT,
pattern GL_PROGRAM_PIPELINE,
pattern GL_PROGRAM_PIPELINE_BINDING,
pattern GL_PROGRAM_POINT_SIZE,
pattern GL_PROGRAM_SEPARABLE,
pattern GL_PROJECTION,
pattern GL_PROJECTION_MATRIX,
pattern GL_PROJECTION_STACK_DEPTH,
pattern GL_PROVOKING_VERTEX,
pattern GL_PROXY_TEXTURE_1D,
pattern GL_PROXY_TEXTURE_1D_ARRAY,
pattern GL_PROXY_TEXTURE_2D,
pattern GL_PROXY_TEXTURE_2D_ARRAY,
pattern GL_PROXY_TEXTURE_2D_MULTISAMPLE,
pattern GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY,
pattern GL_PROXY_TEXTURE_3D,
pattern GL_PROXY_TEXTURE_CUBE_MAP,
pattern GL_PROXY_TEXTURE_CUBE_MAP_ARRAY,
pattern GL_PROXY_TEXTURE_RECTANGLE,
pattern GL_Q,
pattern GL_QUADRATIC_ATTENUATION,
pattern GL_QUADS,
pattern GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION,
pattern GL_QUAD_STRIP,
pattern GL_QUERY,
pattern GL_QUERY_BY_REGION_NO_WAIT,
pattern GL_QUERY_BY_REGION_WAIT,
pattern GL_QUERY_COUNTER_BITS,
pattern GL_QUERY_NO_WAIT,
pattern GL_QUERY_RESULT,
pattern GL_QUERY_RESULT_AVAILABLE,
pattern GL_QUERY_WAIT,
pattern GL_R,
pattern GL_R11F_G11F_B10F,
pattern GL_R16,
pattern GL_R16F,
pattern GL_R16I,
pattern GL_R16UI,
pattern GL_R16_SNORM,
pattern GL_R32F,
pattern GL_R32I,
pattern GL_R32UI,
pattern GL_R3_G3_B2,
pattern GL_R8,
pattern GL_R8I,
pattern GL_R8UI,
pattern GL_R8_SNORM,
pattern GL_RASTERIZER_DISCARD,
pattern GL_READ_BUFFER,
pattern GL_READ_FRAMEBUFFER,
pattern GL_READ_FRAMEBUFFER_BINDING,
pattern GL_READ_ONLY,
pattern GL_READ_PIXELS,
pattern GL_READ_PIXELS_FORMAT,
pattern GL_READ_PIXELS_TYPE,
pattern GL_READ_WRITE,
pattern GL_RED,
pattern GL_RED_BIAS,
pattern GL_RED_BITS,
pattern GL_RED_INTEGER,
pattern GL_RED_SCALE,
pattern GL_REFERENCED_BY_COMPUTE_SHADER,
pattern GL_REFERENCED_BY_FRAGMENT_SHADER,
pattern GL_REFERENCED_BY_GEOMETRY_SHADER,
pattern GL_REFERENCED_BY_TESS_CONTROL_SHADER,
pattern GL_REFERENCED_BY_TESS_EVALUATION_SHADER,
pattern GL_REFERENCED_BY_VERTEX_SHADER,
pattern GL_REFLECTION_MAP,
pattern GL_RENDER,
pattern GL_RENDERBUFFER,
pattern GL_RENDERBUFFER_ALPHA_SIZE,
pattern GL_RENDERBUFFER_BINDING,
pattern GL_RENDERBUFFER_BLUE_SIZE,
pattern GL_RENDERBUFFER_DEPTH_SIZE,
pattern GL_RENDERBUFFER_GREEN_SIZE,
pattern GL_RENDERBUFFER_HEIGHT,
pattern GL_RENDERBUFFER_INTERNAL_FORMAT,
pattern GL_RENDERBUFFER_RED_SIZE,
pattern GL_RENDERBUFFER_SAMPLES,
pattern GL_RENDERBUFFER_STENCIL_SIZE,
pattern GL_RENDERBUFFER_WIDTH,
pattern GL_RENDERER,
pattern GL_RENDER_MODE,
pattern GL_REPEAT,
pattern GL_REPLACE,
pattern GL_RESCALE_NORMAL,
pattern GL_RETURN,
pattern GL_RG,
pattern GL_RG16,
pattern GL_RG16F,
pattern GL_RG16I,
pattern GL_RG16UI,
pattern GL_RG16_SNORM,
pattern GL_RG32F,
pattern GL_RG32I,
pattern GL_RG32UI,
pattern GL_RG8,
pattern GL_RG8I,
pattern GL_RG8UI,
pattern GL_RG8_SNORM,
pattern GL_RGB,
pattern GL_RGB10,
pattern GL_RGB10_A2,
pattern GL_RGB10_A2UI,
pattern GL_RGB12,
pattern GL_RGB16,
pattern GL_RGB16F,
pattern GL_RGB16I,
pattern GL_RGB16UI,
pattern GL_RGB16_SNORM,
pattern GL_RGB32F,
pattern GL_RGB32I,
pattern GL_RGB32UI,
pattern GL_RGB4,
pattern GL_RGB5,
pattern GL_RGB565,
pattern GL_RGB5_A1,
pattern GL_RGB8,
pattern GL_RGB8I,
pattern GL_RGB8UI,
pattern GL_RGB8_SNORM,
pattern GL_RGB9_E5,
pattern GL_RGBA,
pattern GL_RGBA12,
pattern GL_RGBA16,
pattern GL_RGBA16F,
pattern GL_RGBA16I,
pattern GL_RGBA16UI,
pattern GL_RGBA16_SNORM,
pattern GL_RGBA2,
pattern GL_RGBA32F,
pattern GL_RGBA32I,
pattern GL_RGBA32UI,
pattern GL_RGBA4,
pattern GL_RGBA8,
pattern GL_RGBA8I,
pattern GL_RGBA8UI,
pattern GL_RGBA8_SNORM,
pattern GL_RGBA_INTEGER,
pattern GL_RGBA_MODE,
pattern GL_RGB_INTEGER,
pattern GL_RGB_SCALE,
pattern GL_RG_INTEGER,
pattern GL_RIGHT,
pattern GL_S,
pattern GL_SAMPLER,
pattern GL_SAMPLER_1D,
pattern GL_SAMPLER_1D_ARRAY,
pattern GL_SAMPLER_1D_ARRAY_SHADOW,
pattern GL_SAMPLER_1D_SHADOW,
pattern GL_SAMPLER_2D,
pattern GL_SAMPLER_2D_ARRAY,
pattern GL_SAMPLER_2D_ARRAY_SHADOW,
pattern GL_SAMPLER_2D_MULTISAMPLE,
pattern GL_SAMPLER_2D_MULTISAMPLE_ARRAY,
pattern GL_SAMPLER_2D_RECT,
pattern GL_SAMPLER_2D_RECT_SHADOW,
pattern GL_SAMPLER_2D_SHADOW,
pattern GL_SAMPLER_3D,
pattern GL_SAMPLER_BINDING,
pattern GL_SAMPLER_BUFFER,
pattern GL_SAMPLER_CUBE,
pattern GL_SAMPLER_CUBE_MAP_ARRAY,
pattern GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW,
pattern GL_SAMPLER_CUBE_SHADOW,
pattern GL_SAMPLES,
pattern GL_SAMPLES_PASSED,
pattern GL_SAMPLE_ALPHA_TO_COVERAGE,
pattern GL_SAMPLE_ALPHA_TO_ONE,
pattern GL_SAMPLE_BUFFERS,
pattern GL_SAMPLE_COVERAGE,
pattern GL_SAMPLE_COVERAGE_INVERT,
pattern GL_SAMPLE_COVERAGE_VALUE,
pattern GL_SAMPLE_MASK,
pattern GL_SAMPLE_MASK_VALUE,
pattern GL_SAMPLE_POSITION,
pattern GL_SAMPLE_SHADING,
pattern GL_SCISSOR_BIT,
pattern GL_SCISSOR_BOX,
pattern GL_SCISSOR_TEST,
pattern GL_SECONDARY_COLOR_ARRAY,
pattern GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING,
pattern GL_SECONDARY_COLOR_ARRAY_POINTER,
pattern GL_SECONDARY_COLOR_ARRAY_SIZE,
pattern GL_SECONDARY_COLOR_ARRAY_STRIDE,
pattern GL_SECONDARY_COLOR_ARRAY_TYPE,
pattern GL_SELECT,
pattern GL_SELECTION_BUFFER_POINTER,
pattern GL_SELECTION_BUFFER_SIZE,
pattern GL_SEPARATE_ATTRIBS,
pattern GL_SEPARATE_SPECULAR_COLOR,
pattern GL_SET,
pattern GL_SHADER,
pattern GL_SHADER_BINARY_FORMATS,
pattern GL_SHADER_COMPILER,
pattern GL_SHADER_IMAGE_ACCESS_BARRIER_BIT,
pattern GL_SHADER_IMAGE_ATOMIC,
pattern GL_SHADER_IMAGE_LOAD,
pattern GL_SHADER_IMAGE_STORE,
pattern GL_SHADER_SOURCE_LENGTH,
pattern GL_SHADER_STORAGE_BARRIER_BIT,
pattern GL_SHADER_STORAGE_BLOCK,
pattern GL_SHADER_STORAGE_BUFFER,
pattern GL_SHADER_STORAGE_BUFFER_BINDING,
pattern GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT,
pattern GL_SHADER_STORAGE_BUFFER_SIZE,
pattern GL_SHADER_STORAGE_BUFFER_START,
pattern GL_SHADER_TYPE,
pattern GL_SHADE_MODEL,
pattern GL_SHADING_LANGUAGE_VERSION,
pattern GL_SHININESS,
pattern GL_SHORT,
pattern GL_SIGNALED,
pattern GL_SIGNED_NORMALIZED,
pattern GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST,
pattern GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE,
pattern GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST,
pattern GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE,
pattern GL_SINGLE_COLOR,
pattern GL_SLUMINANCE,
pattern GL_SLUMINANCE8,
pattern GL_SLUMINANCE8_ALPHA8,
pattern GL_SLUMINANCE_ALPHA,
pattern GL_SMOOTH,
pattern GL_SMOOTH_LINE_WIDTH_GRANULARITY,
pattern GL_SMOOTH_LINE_WIDTH_RANGE,
pattern GL_SMOOTH_POINT_SIZE_GRANULARITY,
pattern GL_SMOOTH_POINT_SIZE_RANGE,
pattern GL_SOURCE0_ALPHA,
pattern GL_SOURCE0_RGB,
pattern GL_SOURCE1_ALPHA,
pattern GL_SOURCE1_RGB,
pattern GL_SOURCE2_ALPHA,
pattern GL_SOURCE2_RGB,
pattern GL_SPECULAR,
pattern GL_SPHERE_MAP,
pattern GL_SPOT_CUTOFF,
pattern GL_SPOT_DIRECTION,
pattern GL_SPOT_EXPONENT,
pattern GL_SRC0_ALPHA,
pattern GL_SRC0_RGB,
pattern GL_SRC1_ALPHA,
pattern GL_SRC1_COLOR,
pattern GL_SRC1_RGB,
pattern GL_SRC2_ALPHA,
pattern GL_SRC2_RGB,
pattern GL_SRC_ALPHA,
pattern GL_SRC_ALPHA_SATURATE,
pattern GL_SRC_COLOR,
pattern GL_SRGB,
pattern GL_SRGB8,
pattern GL_SRGB8_ALPHA8,
pattern GL_SRGB_ALPHA,
pattern GL_SRGB_READ,
pattern GL_SRGB_WRITE,
pattern GL_STACK_OVERFLOW,
pattern GL_STACK_UNDERFLOW,
pattern GL_STATIC_COPY,
pattern GL_STATIC_DRAW,
pattern GL_STATIC_READ,
pattern GL_STENCIL,
pattern GL_STENCIL_ATTACHMENT,
pattern GL_STENCIL_BACK_FAIL,
pattern GL_STENCIL_BACK_FUNC,
pattern GL_STENCIL_BACK_PASS_DEPTH_FAIL,
pattern GL_STENCIL_BACK_PASS_DEPTH_PASS,
pattern GL_STENCIL_BACK_REF,
pattern GL_STENCIL_BACK_VALUE_MASK,
pattern GL_STENCIL_BACK_WRITEMASK,
pattern GL_STENCIL_BITS,
pattern GL_STENCIL_BUFFER_BIT,
pattern GL_STENCIL_CLEAR_VALUE,
pattern GL_STENCIL_COMPONENTS,
pattern GL_STENCIL_FAIL,
pattern GL_STENCIL_FUNC,
pattern GL_STENCIL_INDEX,
pattern GL_STENCIL_INDEX1,
pattern GL_STENCIL_INDEX16,
pattern GL_STENCIL_INDEX4,
pattern GL_STENCIL_INDEX8,
pattern GL_STENCIL_PASS_DEPTH_FAIL,
pattern GL_STENCIL_PASS_DEPTH_PASS,
pattern GL_STENCIL_REF,
pattern GL_STENCIL_RENDERABLE,
pattern GL_STENCIL_TEST,
pattern GL_STENCIL_VALUE_MASK,
pattern GL_STENCIL_WRITEMASK,
pattern GL_STEREO,
pattern GL_STREAM_COPY,
pattern GL_STREAM_DRAW,
pattern GL_STREAM_READ,
pattern GL_SUBPIXEL_BITS,
pattern GL_SUBTRACT,
pattern GL_SYNC_CONDITION,
pattern GL_SYNC_FENCE,
pattern GL_SYNC_FLAGS,
pattern GL_SYNC_FLUSH_COMMANDS_BIT,
pattern GL_SYNC_GPU_COMMANDS_COMPLETE,
pattern GL_SYNC_STATUS,
pattern GL_T,
pattern GL_T2F_C3F_V3F,
pattern GL_T2F_C4F_N3F_V3F,
pattern GL_T2F_C4UB_V3F,
pattern GL_T2F_N3F_V3F,
pattern GL_T2F_V3F,
pattern GL_T4F_C4F_N3F_V4F,
pattern GL_T4F_V4F,
pattern GL_TESS_CONTROL_OUTPUT_VERTICES,
pattern GL_TESS_CONTROL_SHADER,
pattern GL_TESS_CONTROL_SHADER_BIT,
pattern GL_TESS_CONTROL_SUBROUTINE,
pattern GL_TESS_CONTROL_SUBROUTINE_UNIFORM,
pattern GL_TESS_CONTROL_TEXTURE,
pattern GL_TESS_EVALUATION_SHADER,
pattern GL_TESS_EVALUATION_SHADER_BIT,
pattern GL_TESS_EVALUATION_SUBROUTINE,
pattern GL_TESS_EVALUATION_SUBROUTINE_UNIFORM,
pattern GL_TESS_EVALUATION_TEXTURE,
pattern GL_TESS_GEN_MODE,
pattern GL_TESS_GEN_POINT_MODE,
pattern GL_TESS_GEN_SPACING,
pattern GL_TESS_GEN_VERTEX_ORDER,
pattern GL_TEXTURE,
pattern GL_TEXTURE0,
pattern GL_TEXTURE1,
pattern GL_TEXTURE10,
pattern GL_TEXTURE11,
pattern GL_TEXTURE12,
pattern GL_TEXTURE13,
pattern GL_TEXTURE14,
pattern GL_TEXTURE15,
pattern GL_TEXTURE16,
pattern GL_TEXTURE17,
pattern GL_TEXTURE18,
pattern GL_TEXTURE19,
pattern GL_TEXTURE2,
pattern GL_TEXTURE20,
pattern GL_TEXTURE21,
pattern GL_TEXTURE22,
pattern GL_TEXTURE23,
pattern GL_TEXTURE24,
pattern GL_TEXTURE25,
pattern GL_TEXTURE26,
pattern GL_TEXTURE27,
pattern GL_TEXTURE28,
pattern GL_TEXTURE29,
pattern GL_TEXTURE3,
pattern GL_TEXTURE30,
pattern GL_TEXTURE31,
pattern GL_TEXTURE4,
pattern GL_TEXTURE5,
pattern GL_TEXTURE6,
pattern GL_TEXTURE7,
pattern GL_TEXTURE8,
pattern GL_TEXTURE9,
pattern GL_TEXTURE_1D,
pattern GL_TEXTURE_1D_ARRAY,
pattern GL_TEXTURE_2D,
pattern GL_TEXTURE_2D_ARRAY,
pattern GL_TEXTURE_2D_MULTISAMPLE,
pattern GL_TEXTURE_2D_MULTISAMPLE_ARRAY,
pattern GL_TEXTURE_3D,
pattern GL_TEXTURE_ALPHA_SIZE,
pattern GL_TEXTURE_ALPHA_TYPE,
pattern GL_TEXTURE_BASE_LEVEL,
pattern GL_TEXTURE_BINDING_1D,
pattern GL_TEXTURE_BINDING_1D_ARRAY,
pattern GL_TEXTURE_BINDING_2D,
pattern GL_TEXTURE_BINDING_2D_ARRAY,
pattern GL_TEXTURE_BINDING_2D_MULTISAMPLE,
pattern GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY,
pattern GL_TEXTURE_BINDING_3D,
pattern GL_TEXTURE_BINDING_BUFFER,
pattern GL_TEXTURE_BINDING_CUBE_MAP,
pattern GL_TEXTURE_BINDING_CUBE_MAP_ARRAY,
pattern GL_TEXTURE_BINDING_RECTANGLE,
pattern GL_TEXTURE_BIT,
pattern GL_TEXTURE_BLUE_SIZE,
pattern GL_TEXTURE_BLUE_TYPE,
pattern GL_TEXTURE_BORDER,
pattern GL_TEXTURE_BORDER_COLOR,
pattern GL_TEXTURE_BUFFER,
pattern GL_TEXTURE_BUFFER_DATA_STORE_BINDING,
pattern GL_TEXTURE_BUFFER_OFFSET,
pattern GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT,
pattern GL_TEXTURE_BUFFER_SIZE,
pattern GL_TEXTURE_COMPARE_FUNC,
pattern GL_TEXTURE_COMPARE_MODE,
pattern GL_TEXTURE_COMPONENTS,
pattern GL_TEXTURE_COMPRESSED,
pattern GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT,
pattern GL_TEXTURE_COMPRESSED_BLOCK_SIZE,
pattern GL_TEXTURE_COMPRESSED_BLOCK_WIDTH,
pattern GL_TEXTURE_COMPRESSED_IMAGE_SIZE,
pattern GL_TEXTURE_COMPRESSION_HINT,
pattern GL_TEXTURE_COORD_ARRAY,
pattern GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING,
pattern GL_TEXTURE_COORD_ARRAY_POINTER,
pattern GL_TEXTURE_COORD_ARRAY_SIZE,
pattern GL_TEXTURE_COORD_ARRAY_STRIDE,
pattern GL_TEXTURE_COORD_ARRAY_TYPE,
pattern GL_TEXTURE_CUBE_MAP,
pattern GL_TEXTURE_CUBE_MAP_ARRAY,
pattern GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
pattern GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
pattern GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
pattern GL_TEXTURE_CUBE_MAP_POSITIVE_X,
pattern GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
pattern GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
pattern GL_TEXTURE_CUBE_MAP_SEAMLESS,
pattern GL_TEXTURE_DEPTH,
pattern GL_TEXTURE_DEPTH_SIZE,
pattern GL_TEXTURE_DEPTH_TYPE,
pattern GL_TEXTURE_ENV,
pattern GL_TEXTURE_ENV_COLOR,
pattern GL_TEXTURE_ENV_MODE,
pattern GL_TEXTURE_FETCH_BARRIER_BIT,
pattern GL_TEXTURE_FILTER_CONTROL,
pattern GL_TEXTURE_FIXED_SAMPLE_LOCATIONS,
pattern GL_TEXTURE_GATHER,
pattern GL_TEXTURE_GATHER_SHADOW,
pattern GL_TEXTURE_GEN_MODE,
pattern GL_TEXTURE_GEN_Q,
pattern GL_TEXTURE_GEN_R,
pattern GL_TEXTURE_GEN_S,
pattern GL_TEXTURE_GEN_T,
pattern GL_TEXTURE_GREEN_SIZE,
pattern GL_TEXTURE_GREEN_TYPE,
pattern GL_TEXTURE_HEIGHT,
pattern GL_TEXTURE_IMAGE_FORMAT,
pattern GL_TEXTURE_IMAGE_TYPE,
pattern GL_TEXTURE_IMMUTABLE_FORMAT,
pattern GL_TEXTURE_IMMUTABLE_LEVELS,
pattern GL_TEXTURE_INTENSITY_SIZE,
pattern GL_TEXTURE_INTENSITY_TYPE,
pattern GL_TEXTURE_INTERNAL_FORMAT,
pattern GL_TEXTURE_LOD_BIAS,
pattern GL_TEXTURE_LUMINANCE_SIZE,
pattern GL_TEXTURE_LUMINANCE_TYPE,
pattern GL_TEXTURE_MAG_FILTER,
pattern GL_TEXTURE_MATRIX,
pattern GL_TEXTURE_MAX_LEVEL,
pattern GL_TEXTURE_MAX_LOD,
pattern GL_TEXTURE_MIN_FILTER,
pattern GL_TEXTURE_MIN_LOD,
pattern GL_TEXTURE_PRIORITY,
pattern GL_TEXTURE_RECTANGLE,
pattern GL_TEXTURE_RED_SIZE,
pattern GL_TEXTURE_RED_TYPE,
pattern GL_TEXTURE_RESIDENT,
pattern GL_TEXTURE_SAMPLES,
pattern GL_TEXTURE_SHADOW,
pattern GL_TEXTURE_SHARED_SIZE,
pattern GL_TEXTURE_STACK_DEPTH,
pattern GL_TEXTURE_STENCIL_SIZE,
pattern GL_TEXTURE_SWIZZLE_A,
pattern GL_TEXTURE_SWIZZLE_B,
pattern GL_TEXTURE_SWIZZLE_G,
pattern GL_TEXTURE_SWIZZLE_R,
pattern GL_TEXTURE_SWIZZLE_RGBA,
pattern GL_TEXTURE_UPDATE_BARRIER_BIT,
pattern GL_TEXTURE_VIEW,
pattern GL_TEXTURE_VIEW_MIN_LAYER,
pattern GL_TEXTURE_VIEW_MIN_LEVEL,
pattern GL_TEXTURE_VIEW_NUM_LAYERS,
pattern GL_TEXTURE_VIEW_NUM_LEVELS,
pattern GL_TEXTURE_WIDTH,
pattern GL_TEXTURE_WRAP_R,
pattern GL_TEXTURE_WRAP_S,
pattern GL_TEXTURE_WRAP_T,
pattern GL_TIMEOUT_EXPIRED,
pattern GL_TIMEOUT_IGNORED,
pattern GL_TIMESTAMP,
pattern GL_TIME_ELAPSED,
pattern GL_TOP_LEVEL_ARRAY_SIZE,
pattern GL_TOP_LEVEL_ARRAY_STRIDE,
pattern GL_TRANSFORM_BIT,
pattern GL_TRANSFORM_FEEDBACK,
pattern GL_TRANSFORM_FEEDBACK_ACTIVE,
pattern GL_TRANSFORM_FEEDBACK_BARRIER_BIT,
pattern GL_TRANSFORM_FEEDBACK_BINDING,
pattern GL_TRANSFORM_FEEDBACK_BUFFER,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_BINDING,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_MODE,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_SIZE,
pattern GL_TRANSFORM_FEEDBACK_BUFFER_START,
pattern GL_TRANSFORM_FEEDBACK_PAUSED,
pattern GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN,
pattern GL_TRANSFORM_FEEDBACK_VARYING,
pattern GL_TRANSFORM_FEEDBACK_VARYINGS,
pattern GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH,
pattern GL_TRANSPOSE_COLOR_MATRIX,
pattern GL_TRANSPOSE_MODELVIEW_MATRIX,
pattern GL_TRANSPOSE_PROJECTION_MATRIX,
pattern GL_TRANSPOSE_TEXTURE_MATRIX,
pattern GL_TRIANGLES,
pattern GL_TRIANGLES_ADJACENCY,
pattern GL_TRIANGLE_FAN,
pattern GL_TRIANGLE_STRIP,
pattern GL_TRIANGLE_STRIP_ADJACENCY,
pattern GL_TRUE,
pattern GL_TYPE,
pattern GL_UNDEFINED_VERTEX,
pattern GL_UNIFORM,
pattern GL_UNIFORM_ARRAY_STRIDE,
pattern GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX,
pattern GL_UNIFORM_BARRIER_BIT,
pattern GL_UNIFORM_BLOCK,
pattern GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS,
pattern GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES,
pattern GL_UNIFORM_BLOCK_BINDING,
pattern GL_UNIFORM_BLOCK_DATA_SIZE,
pattern GL_UNIFORM_BLOCK_INDEX,
pattern GL_UNIFORM_BLOCK_NAME_LENGTH,
pattern GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER,
pattern GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER,
pattern GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER,
pattern GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER,
pattern GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER,
pattern GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER,
pattern GL_UNIFORM_BUFFER,
pattern GL_UNIFORM_BUFFER_BINDING,
pattern GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT,
pattern GL_UNIFORM_BUFFER_SIZE,
pattern GL_UNIFORM_BUFFER_START,
pattern GL_UNIFORM_IS_ROW_MAJOR,
pattern GL_UNIFORM_MATRIX_STRIDE,
pattern GL_UNIFORM_NAME_LENGTH,
pattern GL_UNIFORM_OFFSET,
pattern GL_UNIFORM_SIZE,
pattern GL_UNIFORM_TYPE,
pattern GL_UNPACK_ALIGNMENT,
pattern GL_UNPACK_COMPRESSED_BLOCK_DEPTH,
pattern GL_UNPACK_COMPRESSED_BLOCK_HEIGHT,
pattern GL_UNPACK_COMPRESSED_BLOCK_SIZE,
pattern GL_UNPACK_COMPRESSED_BLOCK_WIDTH,
pattern GL_UNPACK_IMAGE_HEIGHT,
pattern GL_UNPACK_LSB_FIRST,
pattern GL_UNPACK_ROW_LENGTH,
pattern GL_UNPACK_SKIP_IMAGES,
pattern GL_UNPACK_SKIP_PIXELS,
pattern GL_UNPACK_SKIP_ROWS,
pattern GL_UNPACK_SWAP_BYTES,
pattern GL_UNSIGNALED,
pattern GL_UNSIGNED_BYTE,
pattern GL_UNSIGNED_BYTE_2_3_3_REV,
pattern GL_UNSIGNED_BYTE_3_3_2,
pattern GL_UNSIGNED_INT,
pattern GL_UNSIGNED_INT_10F_11F_11F_REV,
pattern GL_UNSIGNED_INT_10_10_10_2,
pattern GL_UNSIGNED_INT_24_8,
pattern GL_UNSIGNED_INT_2_10_10_10_REV,
pattern GL_UNSIGNED_INT_5_9_9_9_REV,
pattern GL_UNSIGNED_INT_8_8_8_8,
pattern GL_UNSIGNED_INT_8_8_8_8_REV,
pattern GL_UNSIGNED_INT_ATOMIC_COUNTER,
pattern GL_UNSIGNED_INT_IMAGE_1D,
pattern GL_UNSIGNED_INT_IMAGE_1D_ARRAY,
pattern GL_UNSIGNED_INT_IMAGE_2D,
pattern GL_UNSIGNED_INT_IMAGE_2D_ARRAY,
pattern GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE,
pattern GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY,
pattern GL_UNSIGNED_INT_IMAGE_2D_RECT,
pattern GL_UNSIGNED_INT_IMAGE_3D,
pattern GL_UNSIGNED_INT_IMAGE_BUFFER,
pattern GL_UNSIGNED_INT_IMAGE_CUBE,
pattern GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY,
pattern GL_UNSIGNED_INT_SAMPLER_1D,
pattern GL_UNSIGNED_INT_SAMPLER_1D_ARRAY,
pattern GL_UNSIGNED_INT_SAMPLER_2D,
pattern GL_UNSIGNED_INT_SAMPLER_2D_ARRAY,
pattern GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE,
pattern GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY,
pattern GL_UNSIGNED_INT_SAMPLER_2D_RECT,
pattern GL_UNSIGNED_INT_SAMPLER_3D,
pattern GL_UNSIGNED_INT_SAMPLER_BUFFER,
pattern GL_UNSIGNED_INT_SAMPLER_CUBE,
pattern GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY,
pattern GL_UNSIGNED_INT_VEC2,
pattern GL_UNSIGNED_INT_VEC3,
pattern GL_UNSIGNED_INT_VEC4,
pattern GL_UNSIGNED_NORMALIZED,
pattern GL_UNSIGNED_SHORT,
pattern GL_UNSIGNED_SHORT_1_5_5_5_REV,
pattern GL_UNSIGNED_SHORT_4_4_4_4,
pattern GL_UNSIGNED_SHORT_4_4_4_4_REV,
pattern GL_UNSIGNED_SHORT_5_5_5_1,
pattern GL_UNSIGNED_SHORT_5_6_5,
pattern GL_UNSIGNED_SHORT_5_6_5_REV,
pattern GL_UPPER_LEFT,
pattern GL_V2F,
pattern GL_V3F,
pattern GL_VALIDATE_STATUS,
pattern GL_VENDOR,
pattern GL_VERSION,
pattern GL_VERTEX_ARRAY,
pattern GL_VERTEX_ARRAY_BINDING,
pattern GL_VERTEX_ARRAY_BUFFER_BINDING,
pattern GL_VERTEX_ARRAY_POINTER,
pattern GL_VERTEX_ARRAY_SIZE,
pattern GL_VERTEX_ARRAY_STRIDE,
pattern GL_VERTEX_ARRAY_TYPE,
pattern GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT,
pattern GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING,
pattern GL_VERTEX_ATTRIB_ARRAY_DIVISOR,
pattern GL_VERTEX_ATTRIB_ARRAY_ENABLED,
pattern GL_VERTEX_ATTRIB_ARRAY_INTEGER,
pattern GL_VERTEX_ATTRIB_ARRAY_LONG,
pattern GL_VERTEX_ATTRIB_ARRAY_NORMALIZED,
pattern GL_VERTEX_ATTRIB_ARRAY_POINTER,
pattern GL_VERTEX_ATTRIB_ARRAY_SIZE,
pattern GL_VERTEX_ATTRIB_ARRAY_STRIDE,
pattern GL_VERTEX_ATTRIB_ARRAY_TYPE,
pattern GL_VERTEX_ATTRIB_BINDING,
pattern GL_VERTEX_ATTRIB_RELATIVE_OFFSET,
pattern GL_VERTEX_BINDING_BUFFER,
pattern GL_VERTEX_BINDING_DIVISOR,
pattern GL_VERTEX_BINDING_OFFSET,
pattern GL_VERTEX_BINDING_STRIDE,
pattern GL_VERTEX_PROGRAM_POINT_SIZE,
pattern GL_VERTEX_PROGRAM_TWO_SIDE,
pattern GL_VERTEX_SHADER,
pattern GL_VERTEX_SHADER_BIT,
pattern GL_VERTEX_SUBROUTINE,
pattern GL_VERTEX_SUBROUTINE_UNIFORM,
pattern GL_VERTEX_TEXTURE,
pattern GL_VIEWPORT,
pattern GL_VIEWPORT_BIT,
pattern GL_VIEWPORT_BOUNDS_RANGE,
pattern GL_VIEWPORT_INDEX_PROVOKING_VERTEX,
pattern GL_VIEWPORT_SUBPIXEL_BITS,
pattern GL_VIEW_CLASS_128_BITS,
pattern GL_VIEW_CLASS_16_BITS,
pattern GL_VIEW_CLASS_24_BITS,
pattern GL_VIEW_CLASS_32_BITS,
pattern GL_VIEW_CLASS_48_BITS,
pattern GL_VIEW_CLASS_64_BITS,
pattern GL_VIEW_CLASS_8_BITS,
pattern GL_VIEW_CLASS_96_BITS,
pattern GL_VIEW_CLASS_BPTC_FLOAT,
pattern GL_VIEW_CLASS_BPTC_UNORM,
pattern GL_VIEW_CLASS_RGTC1_RED,
pattern GL_VIEW_CLASS_RGTC2_RG,
pattern GL_VIEW_CLASS_S3TC_DXT1_RGB,
pattern GL_VIEW_CLASS_S3TC_DXT1_RGBA,
pattern GL_VIEW_CLASS_S3TC_DXT3_RGBA,
pattern GL_VIEW_CLASS_S3TC_DXT5_RGBA,
pattern GL_VIEW_COMPATIBILITY_CLASS,
pattern GL_WAIT_FAILED,
pattern GL_WEIGHT_ARRAY_BUFFER_BINDING,
pattern GL_WRITE_ONLY,
pattern GL_XOR,
pattern GL_ZERO,
pattern GL_ZOOM_X,
pattern GL_ZOOM_Y,
-- * Functions
glAccum,
glActiveShaderProgram,
glActiveTexture,
glAlphaFunc,
glAreTexturesResident,
glArrayElement,
glAttachShader,
glBegin,
glBeginConditionalRender,
glBeginQuery,
glBeginQueryIndexed,
glBeginTransformFeedback,
glBindAttribLocation,
glBindBuffer,
glBindBufferBase,
glBindBufferRange,
glBindFragDataLocation,
glBindFragDataLocationIndexed,
glBindFramebuffer,
glBindImageTexture,
glBindProgramPipeline,
glBindRenderbuffer,
glBindSampler,
glBindTexture,
glBindTransformFeedback,
glBindVertexArray,
glBindVertexBuffer,
glBitmap,
glBlendColor,
glBlendEquation,
glBlendEquationSeparate,
glBlendEquationSeparatei,
glBlendEquationi,
glBlendFunc,
glBlendFuncSeparate,
glBlendFuncSeparatei,
glBlendFunci,
glBlitFramebuffer,
glBufferData,
glBufferSubData,
glCallList,
glCallLists,
glCheckFramebufferStatus,
glClampColor,
glClear,
glClearAccum,
glClearBufferData,
glClearBufferSubData,
glClearBufferfi,
glClearBufferfv,
glClearBufferiv,
glClearBufferuiv,
glClearColor,
glClearDepth,
glClearDepthf,
glClearIndex,
glClearStencil,
glClientActiveTexture,
glClientWaitSync,
glClipPlane,
glColor3b,
glColor3bv,
glColor3d,
glColor3dv,
glColor3f,
glColor3fv,
glColor3i,
glColor3iv,
glColor3s,
glColor3sv,
glColor3ub,
glColor3ubv,
glColor3ui,
glColor3uiv,
glColor3us,
glColor3usv,
glColor4b,
glColor4bv,
glColor4d,
glColor4dv,
glColor4f,
glColor4fv,
glColor4i,
glColor4iv,
glColor4s,
glColor4sv,
glColor4ub,
glColor4ubv,
glColor4ui,
glColor4uiv,
glColor4us,
glColor4usv,
glColorMask,
glColorMaski,
glColorMaterial,
glColorP3ui,
glColorP3uiv,
glColorP4ui,
glColorP4uiv,
glColorPointer,
glCompileShader,
glCompressedTexImage1D,
glCompressedTexImage2D,
glCompressedTexImage3D,
glCompressedTexSubImage1D,
glCompressedTexSubImage2D,
glCompressedTexSubImage3D,
glCopyBufferSubData,
glCopyImageSubData,
glCopyPixels,
glCopyTexImage1D,
glCopyTexImage2D,
glCopyTexSubImage1D,
glCopyTexSubImage2D,
glCopyTexSubImage3D,
glCreateProgram,
glCreateShader,
glCreateShaderProgramv,
glCullFace,
glDebugMessageCallback,
glDebugMessageControl,
glDebugMessageInsert,
glDeleteBuffers,
glDeleteFramebuffers,
glDeleteLists,
glDeleteProgram,
glDeleteProgramPipelines,
glDeleteQueries,
glDeleteRenderbuffers,
glDeleteSamplers,
glDeleteShader,
glDeleteSync,
glDeleteTextures,
glDeleteTransformFeedbacks,
glDeleteVertexArrays,
glDepthFunc,
glDepthMask,
glDepthRange,
glDepthRangeArrayv,
glDepthRangeIndexed,
glDepthRangef,
glDetachShader,
glDisable,
glDisableClientState,
glDisableVertexAttribArray,
glDisablei,
glDispatchCompute,
glDispatchComputeIndirect,
glDrawArrays,
glDrawArraysIndirect,
glDrawArraysInstanced,
glDrawArraysInstancedBaseInstance,
glDrawBuffer,
glDrawBuffers,
glDrawElements,
glDrawElementsBaseVertex,
glDrawElementsIndirect,
glDrawElementsInstanced,
glDrawElementsInstancedBaseInstance,
glDrawElementsInstancedBaseVertex,
glDrawElementsInstancedBaseVertexBaseInstance,
glDrawPixels,
glDrawRangeElements,
glDrawRangeElementsBaseVertex,
glDrawTransformFeedback,
glDrawTransformFeedbackInstanced,
glDrawTransformFeedbackStream,
glDrawTransformFeedbackStreamInstanced,
glEdgeFlag,
glEdgeFlagPointer,
glEdgeFlagv,
glEnable,
glEnableClientState,
glEnableVertexAttribArray,
glEnablei,
glEnd,
glEndConditionalRender,
glEndList,
glEndQuery,
glEndQueryIndexed,
glEndTransformFeedback,
glEvalCoord1d,
glEvalCoord1dv,
glEvalCoord1f,
glEvalCoord1fv,
glEvalCoord2d,
glEvalCoord2dv,
glEvalCoord2f,
glEvalCoord2fv,
glEvalMesh1,
glEvalMesh2,
glEvalPoint1,
glEvalPoint2,
glFeedbackBuffer,
glFenceSync,
glFinish,
glFlush,
glFlushMappedBufferRange,
glFogCoordPointer,
glFogCoordd,
glFogCoorddv,
glFogCoordf,
glFogCoordfv,
glFogf,
glFogfv,
glFogi,
glFogiv,
glFramebufferParameteri,
glFramebufferRenderbuffer,
glFramebufferTexture,
glFramebufferTexture1D,
glFramebufferTexture2D,
glFramebufferTexture3D,
glFramebufferTextureLayer,
glFrontFace,
glFrustum,
glGenBuffers,
glGenFramebuffers,
glGenLists,
glGenProgramPipelines,
glGenQueries,
glGenRenderbuffers,
glGenSamplers,
glGenTextures,
glGenTransformFeedbacks,
glGenVertexArrays,
glGenerateMipmap,
glGetActiveAtomicCounterBufferiv,
glGetActiveAttrib,
glGetActiveSubroutineName,
glGetActiveSubroutineUniformName,
glGetActiveSubroutineUniformiv,
glGetActiveUniform,
glGetActiveUniformBlockName,
glGetActiveUniformBlockiv,
glGetActiveUniformName,
glGetActiveUniformsiv,
glGetAttachedShaders,
glGetAttribLocation,
glGetBooleani_v,
glGetBooleanv,
glGetBufferParameteri64v,
glGetBufferParameteriv,
glGetBufferPointerv,
glGetBufferSubData,
glGetClipPlane,
glGetCompressedTexImage,
glGetDebugMessageLog,
glGetDoublei_v,
glGetDoublev,
glGetError,
glGetFloati_v,
glGetFloatv,
glGetFragDataIndex,
glGetFragDataLocation,
glGetFramebufferAttachmentParameteriv,
glGetFramebufferParameteriv,
glGetInteger64i_v,
glGetInteger64v,
glGetIntegeri_v,
glGetIntegerv,
glGetInternalformati64v,
glGetInternalformativ,
glGetLightfv,
glGetLightiv,
glGetMapdv,
glGetMapfv,
glGetMapiv,
glGetMaterialfv,
glGetMaterialiv,
glGetMultisamplefv,
glGetObjectLabel,
glGetObjectPtrLabel,
glGetPixelMapfv,
glGetPixelMapuiv,
glGetPixelMapusv,
glGetPointerv,
glGetPolygonStipple,
glGetProgramBinary,
glGetProgramInfoLog,
glGetProgramInterfaceiv,
glGetProgramPipelineInfoLog,
glGetProgramPipelineiv,
glGetProgramResourceIndex,
glGetProgramResourceLocation,
glGetProgramResourceLocationIndex,
glGetProgramResourceName,
glGetProgramResourceiv,
glGetProgramStageiv,
glGetProgramiv,
glGetQueryIndexediv,
glGetQueryObjecti64v,
glGetQueryObjectiv,
glGetQueryObjectui64v,
glGetQueryObjectuiv,
glGetQueryiv,
glGetRenderbufferParameteriv,
glGetSamplerParameterIiv,
glGetSamplerParameterIuiv,
glGetSamplerParameterfv,
glGetSamplerParameteriv,
glGetShaderInfoLog,
glGetShaderPrecisionFormat,
glGetShaderSource,
glGetShaderiv,
glGetString,
glGetStringi,
glGetSubroutineIndex,
glGetSubroutineUniformLocation,
glGetSynciv,
glGetTexEnvfv,
glGetTexEnviv,
glGetTexGendv,
glGetTexGenfv,
glGetTexGeniv,
glGetTexImage,
glGetTexLevelParameterfv,
glGetTexLevelParameteriv,
glGetTexParameterIiv,
glGetTexParameterIuiv,
glGetTexParameterfv,
glGetTexParameteriv,
glGetTransformFeedbackVarying,
glGetUniformBlockIndex,
glGetUniformIndices,
glGetUniformLocation,
glGetUniformSubroutineuiv,
glGetUniformdv,
glGetUniformfv,
glGetUniformiv,
glGetUniformuiv,
glGetVertexAttribIiv,
glGetVertexAttribIuiv,
glGetVertexAttribLdv,
glGetVertexAttribPointerv,
glGetVertexAttribdv,
glGetVertexAttribfv,
glGetVertexAttribiv,
glHint,
glIndexMask,
glIndexPointer,
glIndexd,
glIndexdv,
glIndexf,
glIndexfv,
glIndexi,
glIndexiv,
glIndexs,
glIndexsv,
glIndexub,
glIndexubv,
glInitNames,
glInterleavedArrays,
glInvalidateBufferData,
glInvalidateBufferSubData,
glInvalidateFramebuffer,
glInvalidateSubFramebuffer,
glInvalidateTexImage,
glInvalidateTexSubImage,
glIsBuffer,
glIsEnabled,
glIsEnabledi,
glIsFramebuffer,
glIsList,
glIsProgram,
glIsProgramPipeline,
glIsQuery,
glIsRenderbuffer,
glIsSampler,
glIsShader,
glIsSync,
glIsTexture,
glIsTransformFeedback,
glIsVertexArray,
glLightModelf,
glLightModelfv,
glLightModeli,
glLightModeliv,
glLightf,
glLightfv,
glLighti,
glLightiv,
glLineStipple,
glLineWidth,
glLinkProgram,
glListBase,
glLoadIdentity,
glLoadMatrixd,
glLoadMatrixf,
glLoadName,
glLoadTransposeMatrixd,
glLoadTransposeMatrixf,
glLogicOp,
glMap1d,
glMap1f,
glMap2d,
glMap2f,
glMapBuffer,
glMapBufferRange,
glMapGrid1d,
glMapGrid1f,
glMapGrid2d,
glMapGrid2f,
glMaterialf,
glMaterialfv,
glMateriali,
glMaterialiv,
glMatrixMode,
glMemoryBarrier,
glMinSampleShading,
glMultMatrixd,
glMultMatrixf,
glMultTransposeMatrixd,
glMultTransposeMatrixf,
glMultiDrawArrays,
glMultiDrawArraysIndirect,
glMultiDrawElements,
glMultiDrawElementsBaseVertex,
glMultiDrawElementsIndirect,
glMultiTexCoord1d,
glMultiTexCoord1dv,
glMultiTexCoord1f,
glMultiTexCoord1fv,
glMultiTexCoord1i,
glMultiTexCoord1iv,
glMultiTexCoord1s,
glMultiTexCoord1sv,
glMultiTexCoord2d,
glMultiTexCoord2dv,
glMultiTexCoord2f,
glMultiTexCoord2fv,
glMultiTexCoord2i,
glMultiTexCoord2iv,
glMultiTexCoord2s,
glMultiTexCoord2sv,
glMultiTexCoord3d,
glMultiTexCoord3dv,
glMultiTexCoord3f,
glMultiTexCoord3fv,
glMultiTexCoord3i,
glMultiTexCoord3iv,
glMultiTexCoord3s,
glMultiTexCoord3sv,
glMultiTexCoord4d,
glMultiTexCoord4dv,
glMultiTexCoord4f,
glMultiTexCoord4fv,
glMultiTexCoord4i,
glMultiTexCoord4iv,
glMultiTexCoord4s,
glMultiTexCoord4sv,
glMultiTexCoordP1ui,
glMultiTexCoordP1uiv,
glMultiTexCoordP2ui,
glMultiTexCoordP2uiv,
glMultiTexCoordP3ui,
glMultiTexCoordP3uiv,
glMultiTexCoordP4ui,
glMultiTexCoordP4uiv,
glNewList,
glNormal3b,
glNormal3bv,
glNormal3d,
glNormal3dv,
glNormal3f,
glNormal3fv,
glNormal3i,
glNormal3iv,
glNormal3s,
glNormal3sv,
glNormalP3ui,
glNormalP3uiv,
glNormalPointer,
glObjectLabel,
glObjectPtrLabel,
glOrtho,
glPassThrough,
glPatchParameterfv,
glPatchParameteri,
glPauseTransformFeedback,
glPixelMapfv,
glPixelMapuiv,
glPixelMapusv,
glPixelStoref,
glPixelStorei,
glPixelTransferf,
glPixelTransferi,
glPixelZoom,
glPointParameterf,
glPointParameterfv,
glPointParameteri,
glPointParameteriv,
glPointSize,
glPolygonMode,
glPolygonOffset,
glPolygonStipple,
glPopAttrib,
glPopClientAttrib,
glPopDebugGroup,
glPopMatrix,
glPopName,
glPrimitiveRestartIndex,
glPrioritizeTextures,
glProgramBinary,
glProgramParameteri,
glProgramUniform1d,
glProgramUniform1dv,
glProgramUniform1f,
glProgramUniform1fv,
glProgramUniform1i,
glProgramUniform1iv,
glProgramUniform1ui,
glProgramUniform1uiv,
glProgramUniform2d,
glProgramUniform2dv,
glProgramUniform2f,
glProgramUniform2fv,
glProgramUniform2i,
glProgramUniform2iv,
glProgramUniform2ui,
glProgramUniform2uiv,
glProgramUniform3d,
glProgramUniform3dv,
glProgramUniform3f,
glProgramUniform3fv,
glProgramUniform3i,
glProgramUniform3iv,
glProgramUniform3ui,
glProgramUniform3uiv,
glProgramUniform4d,
glProgramUniform4dv,
glProgramUniform4f,
glProgramUniform4fv,
glProgramUniform4i,
glProgramUniform4iv,
glProgramUniform4ui,
glProgramUniform4uiv,
glProgramUniformMatrix2dv,
glProgramUniformMatrix2fv,
glProgramUniformMatrix2x3dv,
glProgramUniformMatrix2x3fv,
glProgramUniformMatrix2x4dv,
glProgramUniformMatrix2x4fv,
glProgramUniformMatrix3dv,
glProgramUniformMatrix3fv,
glProgramUniformMatrix3x2dv,
glProgramUniformMatrix3x2fv,
glProgramUniformMatrix3x4dv,
glProgramUniformMatrix3x4fv,
glProgramUniformMatrix4dv,
glProgramUniformMatrix4fv,
glProgramUniformMatrix4x2dv,
glProgramUniformMatrix4x2fv,
glProgramUniformMatrix4x3dv,
glProgramUniformMatrix4x3fv,
glProvokingVertex,
glPushAttrib,
glPushClientAttrib,
glPushDebugGroup,
glPushMatrix,
glPushName,
glQueryCounter,
glRasterPos2d,
glRasterPos2dv,
glRasterPos2f,
glRasterPos2fv,
glRasterPos2i,
glRasterPos2iv,
glRasterPos2s,
glRasterPos2sv,
glRasterPos3d,
glRasterPos3dv,
glRasterPos3f,
glRasterPos3fv,
glRasterPos3i,
glRasterPos3iv,
glRasterPos3s,
glRasterPos3sv,
glRasterPos4d,
glRasterPos4dv,
glRasterPos4f,
glRasterPos4fv,
glRasterPos4i,
glRasterPos4iv,
glRasterPos4s,
glRasterPos4sv,
glReadBuffer,
glReadPixels,
glRectd,
glRectdv,
glRectf,
glRectfv,
glRecti,
glRectiv,
glRects,
glRectsv,
glReleaseShaderCompiler,
glRenderMode,
glRenderbufferStorage,
glRenderbufferStorageMultisample,
glResumeTransformFeedback,
glRotated,
glRotatef,
glSampleCoverage,
glSampleMaski,
glSamplerParameterIiv,
glSamplerParameterIuiv,
glSamplerParameterf,
glSamplerParameterfv,
glSamplerParameteri,
glSamplerParameteriv,
glScaled,
glScalef,
glScissor,
glScissorArrayv,
glScissorIndexed,
glScissorIndexedv,
glSecondaryColor3b,
glSecondaryColor3bv,
glSecondaryColor3d,
glSecondaryColor3dv,
glSecondaryColor3f,
glSecondaryColor3fv,
glSecondaryColor3i,
glSecondaryColor3iv,
glSecondaryColor3s,
glSecondaryColor3sv,
glSecondaryColor3ub,
glSecondaryColor3ubv,
glSecondaryColor3ui,
glSecondaryColor3uiv,
glSecondaryColor3us,
glSecondaryColor3usv,
glSecondaryColorP3ui,
glSecondaryColorP3uiv,
glSecondaryColorPointer,
glSelectBuffer,
glShadeModel,
glShaderBinary,
glShaderSource,
glShaderStorageBlockBinding,
glStencilFunc,
glStencilFuncSeparate,
glStencilMask,
glStencilMaskSeparate,
glStencilOp,
glStencilOpSeparate,
glTexBuffer,
glTexBufferRange,
glTexCoord1d,
glTexCoord1dv,
glTexCoord1f,
glTexCoord1fv,
glTexCoord1i,
glTexCoord1iv,
glTexCoord1s,
glTexCoord1sv,
glTexCoord2d,
glTexCoord2dv,
glTexCoord2f,
glTexCoord2fv,
glTexCoord2i,
glTexCoord2iv,
glTexCoord2s,
glTexCoord2sv,
glTexCoord3d,
glTexCoord3dv,
glTexCoord3f,
glTexCoord3fv,
glTexCoord3i,
glTexCoord3iv,
glTexCoord3s,
glTexCoord3sv,
glTexCoord4d,
glTexCoord4dv,
glTexCoord4f,
glTexCoord4fv,
glTexCoord4i,
glTexCoord4iv,
glTexCoord4s,
glTexCoord4sv,
glTexCoordP1ui,
glTexCoordP1uiv,
glTexCoordP2ui,
glTexCoordP2uiv,
glTexCoordP3ui,
glTexCoordP3uiv,
glTexCoordP4ui,
glTexCoordP4uiv,
glTexCoordPointer,
glTexEnvf,
glTexEnvfv,
glTexEnvi,
glTexEnviv,
glTexGend,
glTexGendv,
glTexGenf,
glTexGenfv,
glTexGeni,
glTexGeniv,
glTexImage1D,
glTexImage2D,
glTexImage2DMultisample,
glTexImage3D,
glTexImage3DMultisample,
glTexParameterIiv,
glTexParameterIuiv,
glTexParameterf,
glTexParameterfv,
glTexParameteri,
glTexParameteriv,
glTexStorage1D,
glTexStorage2D,
glTexStorage2DMultisample,
glTexStorage3D,
glTexStorage3DMultisample,
glTexSubImage1D,
glTexSubImage2D,
glTexSubImage3D,
glTextureView,
glTransformFeedbackVaryings,
glTranslated,
glTranslatef,
glUniform1d,
glUniform1dv,
glUniform1f,
glUniform1fv,
glUniform1i,
glUniform1iv,
glUniform1ui,
glUniform1uiv,
glUniform2d,
glUniform2dv,
glUniform2f,
glUniform2fv,
glUniform2i,
glUniform2iv,
glUniform2ui,
glUniform2uiv,
glUniform3d,
glUniform3dv,
glUniform3f,
glUniform3fv,
glUniform3i,
glUniform3iv,
glUniform3ui,
glUniform3uiv,
glUniform4d,
glUniform4dv,
glUniform4f,
glUniform4fv,
glUniform4i,
glUniform4iv,
glUniform4ui,
glUniform4uiv,
glUniformBlockBinding,
glUniformMatrix2dv,
glUniformMatrix2fv,
glUniformMatrix2x3dv,
glUniformMatrix2x3fv,
glUniformMatrix2x4dv,
glUniformMatrix2x4fv,
glUniformMatrix3dv,
glUniformMatrix3fv,
glUniformMatrix3x2dv,
glUniformMatrix3x2fv,
glUniformMatrix3x4dv,
glUniformMatrix3x4fv,
glUniformMatrix4dv,
glUniformMatrix4fv,
glUniformMatrix4x2dv,
glUniformMatrix4x2fv,
glUniformMatrix4x3dv,
glUniformMatrix4x3fv,
glUniformSubroutinesuiv,
glUnmapBuffer,
glUseProgram,
glUseProgramStages,
glValidateProgram,
glValidateProgramPipeline,
glVertex2d,
glVertex2dv,
glVertex2f,
glVertex2fv,
glVertex2i,
glVertex2iv,
glVertex2s,
glVertex2sv,
glVertex3d,
glVertex3dv,
glVertex3f,
glVertex3fv,
glVertex3i,
glVertex3iv,
glVertex3s,
glVertex3sv,
glVertex4d,
glVertex4dv,
glVertex4f,
glVertex4fv,
glVertex4i,
glVertex4iv,
glVertex4s,
glVertex4sv,
glVertexAttrib1d,
glVertexAttrib1dv,
glVertexAttrib1f,
glVertexAttrib1fv,
glVertexAttrib1s,
glVertexAttrib1sv,
glVertexAttrib2d,
glVertexAttrib2dv,
glVertexAttrib2f,
glVertexAttrib2fv,
glVertexAttrib2s,
glVertexAttrib2sv,
glVertexAttrib3d,
glVertexAttrib3dv,
glVertexAttrib3f,
glVertexAttrib3fv,
glVertexAttrib3s,
glVertexAttrib3sv,
glVertexAttrib4Nbv,
glVertexAttrib4Niv,
glVertexAttrib4Nsv,
glVertexAttrib4Nub,
glVertexAttrib4Nubv,
glVertexAttrib4Nuiv,
glVertexAttrib4Nusv,
glVertexAttrib4bv,
glVertexAttrib4d,
glVertexAttrib4dv,
glVertexAttrib4f,
glVertexAttrib4fv,
glVertexAttrib4iv,
glVertexAttrib4s,
glVertexAttrib4sv,
glVertexAttrib4ubv,
glVertexAttrib4uiv,
glVertexAttrib4usv,
glVertexAttribBinding,
glVertexAttribDivisor,
glVertexAttribFormat,
glVertexAttribI1i,
glVertexAttribI1iv,
glVertexAttribI1ui,
glVertexAttribI1uiv,
glVertexAttribI2i,
glVertexAttribI2iv,
glVertexAttribI2ui,
glVertexAttribI2uiv,
glVertexAttribI3i,
glVertexAttribI3iv,
glVertexAttribI3ui,
glVertexAttribI3uiv,
glVertexAttribI4bv,
glVertexAttribI4i,
glVertexAttribI4iv,
glVertexAttribI4sv,
glVertexAttribI4ubv,
glVertexAttribI4ui,
glVertexAttribI4uiv,
glVertexAttribI4usv,
glVertexAttribIFormat,
glVertexAttribIPointer,
glVertexAttribL1d,
glVertexAttribL1dv,
glVertexAttribL2d,
glVertexAttribL2dv,
glVertexAttribL3d,
glVertexAttribL3dv,
glVertexAttribL4d,
glVertexAttribL4dv,
glVertexAttribLFormat,
glVertexAttribLPointer,
glVertexAttribP1ui,
glVertexAttribP1uiv,
glVertexAttribP2ui,
glVertexAttribP2uiv,
glVertexAttribP3ui,
glVertexAttribP3uiv,
glVertexAttribP4ui,
glVertexAttribP4uiv,
glVertexAttribPointer,
glVertexBindingDivisor,
glVertexP2ui,
glVertexP2uiv,
glVertexP3ui,
glVertexP3uiv,
glVertexP4ui,
glVertexP4uiv,
glVertexPointer,
glViewport,
glViewportArrayv,
glViewportIndexedf,
glViewportIndexedfv,
glWaitSync,
glWindowPos2d,
glWindowPos2dv,
glWindowPos2f,
glWindowPos2fv,
glWindowPos2i,
glWindowPos2iv,
glWindowPos2s,
glWindowPos2sv,
glWindowPos3d,
glWindowPos3dv,
glWindowPos3f,
glWindowPos3fv,
glWindowPos3i,
glWindowPos3iv,
glWindowPos3s,
glWindowPos3sv
) where
import Graphics.GL.Types
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/Compatibility43.hs | bsd-3-clause | 75,901 | 0 | 5 | 9,833 | 11,521 | 7,108 | 4,413 | 2,676 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module Mapnik.Bindings.Render where
import Mapnik (Proj4, AspectFixMode(..), Color(RGBA))
import Mapnik.Lens
import Mapnik.Bindings.Types
import Mapnik.Bindings.Variant
import Mapnik.Bindings.Datasource -- For field class defs
import Mapnik.Bindings.Raster -- For field class defs
import Mapnik.Bindings.Orphans()
import qualified Mapnik.Bindings.Cpp as C
import qualified Mapnik.Bindings.Image as Image
import qualified Mapnik.Bindings.Map as Map
import Control.Exception (bracket)
import Control.Monad (forM_, forM)
import Control.Lens
import Data.Monoid (mempty)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import qualified Data.HashMap.Strict as M
import Foreign.Marshal.Utils (with)
C.context mapnikCtx
C.include "<string>"
C.include "<mapnik/attribute.hpp>"
C.include "<mapnik/agg_renderer.hpp>"
C.include "<mapnik/map.hpp>"
C.using "namespace mapnik"
C.using "bbox = box2d<double>"
data RenderSettings = RenderSettings
{ _renderSettingsWidth :: !Int
, _renderSettingsHeight :: !Int
, _renderSettingsExtent :: !Box
, _renderSettingsVariables :: !Attributes
, _renderSettingsScaleFactor :: !Double
, _renderSettingsSrs :: !(Maybe Proj4)
, _renderSettingsAspectFixMode :: !AspectFixMode
, _renderSettingsBackgroundColor :: !(Maybe Color)
, _renderSettingsLayers :: !(Maybe [Text])
} deriving (Eq, Show)
makeFields ''RenderSettings
renderSettings :: Int -> Int -> Box -> RenderSettings
renderSettings w h e =
RenderSettings w h e mempty 1 Nothing Respect Nothing Nothing
-- | It is not safe to call this function on the same 'Map' from different
-- threads. It is the responsability of the caller to implement locking, a
-- reosurce pool...
render :: Map -> RenderSettings-> IO Image
render m cfg = Image.unsafeNew $ \ptr ->
withAttributes $ \vars ->
with (cfg^.extent) $ \ext ->
bracket setRenderOverrides id $ \ _ -> do
forM_ (cfg^.variables.to M.toList) $ \(encodeUtf8 -> k, val) -> withV val $ \v ->
[C.block|void {
std::string k($bs-ptr:k, $bs-len:k);
attributes &m = *$(attributes *vars);
m[k] = *$(value *v);
}|]
[C.catchBlock|
mapnik::Map &m = *$fptr-ptr:(Map *m);
m.resize($(int w), $(int h)); //FIXME MAPNIK: The query resolution comes out wrong if we dont' do this
m.zoom_to_box(*$(bbox *ext)); //FIXME MAPNIK: the extent we pass in the request seems to be ignored
mapnik::request req($(int w), $(int h), *$(bbox *ext));
mapnik::image_rgba8 *im = new mapnik::image_rgba8($(int w), $(int h));
std::string oldSrs;
try {
mapnik::agg_renderer<mapnik::image_rgba8> ren(m, req, *$(attributes *vars), *im, $(double scale));
ren.apply();
*$(image_rgba8** ptr) = im;
} catch (...) {
delete im;
throw;
}
|]
where
w = cfg^?!width.to fromIntegral
h = cfg^?!height.to fromIntegral
scale = cfg^.scaleFactor.to realToFrac
withAttributes = bracket alloc dealloc where
alloc = [C.exp|attributes * { new attributes }|]
dealloc p = [C.exp|void { delete $(attributes *p) }|]
setRenderOverrides = do
rollbackSrs <- overrideWith Map.getSrs Map.setSrs (cfg^.srs)
rollbackBg <- overrideWith (fmap (fromMaybe (RGBA 0 0 0 0)) . Map.getBackground)
Map.setBackground (cfg^.backgroundColor)
rollbackLayers <- fromMaybe (return ()) <$> forM (cfg^.layers) (\ ls -> do
Map.setActiveLayers m (Just ls)
return (Map.setActiveLayers m Nothing)
)
return (sequence_ [rollbackSrs, rollbackBg, rollbackLayers])
overrideWith :: (Map -> IO a) -> (Map -> a -> IO ()) -> Maybe a -> IO (IO ())
overrideWith get_ set_ = fmap (fromMaybe (return ())) . mapM (\ x -> do
old <- get_ m
set_ m x
return (set_ m old))
| albertov/hs-mapnik | bindings/src/Mapnik/Bindings/Render.hs | bsd-3-clause | 4,379 | 0 | 20 | 1,009 | 949 | 515 | 434 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Common
import Database.PostgreSQL.Simple.FromField (FromField)
import Database.PostgreSQL.Simple.Types(Query(..),Values(..))
import Database.PostgreSQL.Simple.HStore
import Database.PostgreSQL.Simple.Copy
import qualified Database.PostgreSQL.Simple.Transaction as ST
import Control.Applicative
import Control.Exception as E
import Control.Monad
import Data.ByteString (ByteString)
import Data.IORef
import Data.Typeable
import qualified Data.ByteString as B
import Data.Map (Map)
import Data.List (sort)
import qualified Data.Map as Map
import Data.Text(Text)
import qualified Data.Text.Encoding as T
import System.Exit (exitFailure)
import System.IO
import qualified Data.Vector as V
import Data.Aeson
import Notify
import Serializable
import Time
tests :: [TestEnv -> Test]
tests =
[ TestLabel "Bytea" . testBytea
, TestLabel "ExecuteMany" . testExecuteMany
, TestLabel "Fold" . testFold
, TestLabel "Notify" . testNotify
, TestLabel "Serializable" . testSerializable
, TestLabel "Time" . testTime
, TestLabel "Array" . testArray
, TestLabel "HStore" . testHStore
, TestLabel "JSON" . testJSON
, TestLabel "Savepoint" . testSavepoint
, TestLabel "Unicode" . testUnicode
, TestLabel "Values" . testValues
, TestLabel "Copy" . testCopy
, TestLabel "Double" . testDouble
]
testBytea :: TestEnv -> Test
testBytea TestEnv{..} = TestList
[ testStr "empty" []
, testStr "\"hello\"" $ map (fromIntegral . fromEnum) ("hello" :: String)
, testStr "ascending" [0..255]
, testStr "descending" [255,254..0]
, testStr "ascending, doubled up" $ doubleUp [0..255]
, testStr "descending, doubled up" $ doubleUp [255,254..0]
]
where
testStr label bytes = TestLabel label $ TestCase $ do
let bs = B.pack bytes
[Only h] <- query conn "SELECT md5(?::bytea)" [Binary bs]
assertBool "Haskell -> SQL conversion altered the string" $ md5 bs == h
[Only (Binary r)] <- query conn "SELECT ?::bytea" [Binary bs]
assertBool "SQL -> Haskell conversion altered the string" $ bs == r
doubleUp = concatMap (\x -> [x, x])
testExecuteMany :: TestEnv -> Test
testExecuteMany TestEnv{..} = TestCase $ do
execute_ conn "CREATE TEMPORARY TABLE tmp_executeMany (i INT, t TEXT, b BYTEA)"
let rows :: [(Int, String, Binary ByteString)]
rows = [ (1, "hello", Binary "bye")
, (2, "world", Binary "\0\r\t\n")
, (3, "?", Binary "")
]
count <- executeMany conn "INSERT INTO tmp_executeMany VALUES (?, ?, ?)" rows
count @?= fromIntegral (length rows)
rows' <- query_ conn "SELECT * FROM tmp_executeMany"
rows' @?= rows
return ()
testFold :: TestEnv -> Test
testFold TestEnv{..} = TestCase $ do
xs <- fold_ conn "SELECT generate_series(1,10000)"
[] $ \xs (Only x) -> return (x:xs)
reverse xs @?= ([1..10000] :: [Int])
ref <- newIORef []
forEach conn "SELECT * FROM generate_series(1,?) a, generate_series(1,?) b"
(100 :: Int, 50 :: Int) $ \(a :: Int, b :: Int) -> do
xs <- readIORef ref
writeIORef ref $! (a,b):xs
xs <- readIORef ref
reverse xs @?= [(a,b) | a <- [1..100], b <- [1..50]]
-- Make sure fold propagates our exception.
ref <- newIORef []
True <- expectError (== TestException) $
forEach_ conn "SELECT generate_series(1,10)" $ \(Only a) ->
if a == 5 then do
-- Cause a SQL error to trip up CLOSE.
True <- expectError isSyntaxError $
execute_ conn "asdf"
True <- expectError ST.isFailedTransactionError $
(query_ conn "SELECT 1" :: IO [(Only Int)])
throwIO TestException
else do
xs <- readIORef ref
writeIORef ref $! (a :: Int) : xs
xs <- readIORef ref
reverse xs @?= [1..4]
withTransaction conn $ replicateM_ 2 $ do
xs <- fold_ conn "VALUES (1), (2), (3), (4), (5)"
[] $ \xs (Only x) -> return (x:xs)
reverse xs @?= ([1..5] :: [Int])
ref <- newIORef []
forEach_ conn "SELECT generate_series(1,101)" $ \(Only a) ->
forEach_ conn "SELECT generate_series(1,55)" $ \(Only b) -> do
xs <- readIORef ref
writeIORef ref $! (a :: Int, b :: Int) : xs
xs <- readIORef ref
reverse xs @?= [(a,b) | a <- [1..101], b <- [1..55]]
xs <- fold_ conn "SELECT 1 WHERE FALSE"
[] $ \xs (Only x) -> return (x:xs)
xs @?= ([] :: [Int])
-- TODO: add more complete tests, e.g.:
--
-- * Fold in a transaction
--
-- * Fold in a transaction after a previous fold has been performed
--
-- * Nested fold
return ()
queryFailure :: forall a. (FromField a, Typeable a, Show a)
=> Connection -> Query -> a -> Assertion
queryFailure conn q resultType = do
x :: Either SomeException [Only a] <- E.try $ query_ conn q
case x of
Left _ -> return ()
Right val -> assertFailure ("Did not fail as expected: "
++ show q
++ " :: "
++ show (typeOf resultType)
++ " -> " ++ show val)
testArray :: TestEnv -> Test
testArray TestEnv{..} = TestCase $ do
xs <- query_ conn "SELECT '{1,2,3,4}'::_int4"
xs @?= [Only (V.fromList [1,2,3,4 :: Int])]
xs <- query_ conn "SELECT '{{1,2},{3,4}}'::_int4"
xs @?= [Only (V.fromList [V.fromList [1,2],
V.fromList [3,4 :: Int]])]
queryFailure conn "SELECT '{1,2,3,4}'::_int4" (undefined :: V.Vector Bool)
queryFailure conn "SELECT '{{1,2},{3,4}}'::_int4" (undefined :: V.Vector Int)
testHStore :: TestEnv -> Test
testHStore TestEnv{..} = TestCase $ do
execute_ conn "CREATE EXTENSION IF NOT EXISTS hstore"
roundTrip []
roundTrip [("foo","bar"),("bar","baz"),("baz","hello")]
roundTrip [("fo\"o","bar"),("b\\ar","baz"),("baz","\"value\\with\"escapes")]
where
roundTrip :: [(Text,Text)] -> Assertion
roundTrip xs = do
let m = Only (HStoreMap (Map.fromList xs))
m' <- query conn "SELECT ?::hstore" m
[m] @?= m'
testJSON :: TestEnv -> Test
testJSON TestEnv{..} = TestCase $ do
roundTrip (Map.fromList [] :: Map Text Text)
roundTrip (Map.fromList [("foo","bar"),("bar","baz"),("baz","hello")] :: Map Text Text)
roundTrip (Map.fromList [("fo\"o","bar"),("b\\ar","baz"),("baz","\"value\\with\"escapes")] :: Map Text Text)
roundTrip (V.fromList [1,2,3,4,5::Int])
where
roundTrip :: ToJSON a => a -> Assertion
roundTrip a = do
let js = Only (toJSON a)
js' <- query conn "SELECT ?::json" js
[js] @?= js'
testSavepoint :: TestEnv -> Test
testSavepoint TestEnv{..} = TestCase $ do
True <- expectError ST.isNoActiveTransactionError $
withSavepoint conn $ return ()
let getRows :: IO [Int]
getRows = map fromOnly <$> query_ conn "SELECT a FROM tmp_savepoint ORDER BY a"
withTransaction conn $ do
execute_ conn "CREATE TEMPORARY TABLE tmp_savepoint (a INT UNIQUE)"
execute_ conn "INSERT INTO tmp_savepoint VALUES (1)"
[1] <- getRows
withSavepoint conn $ do
execute_ conn "INSERT INTO tmp_savepoint VALUES (2)"
[1,2] <- getRows
return ()
[1,2] <- getRows
withSavepoint conn $ do
execute_ conn "INSERT INTO tmp_savepoint VALUES (3)"
[1,2,3] <- getRows
True <- expectError isUniqueViolation $
execute_ conn "INSERT INTO tmp_savepoint VALUES (2)"
True <- expectError ST.isFailedTransactionError getRows
-- Body returning successfully after handling error,
-- but 'withSavepoint' will roll back without complaining.
return ()
-- Rolling back clears the error condition.
[1,2] <- getRows
-- 'withSavepoint' will roll back after an exception, even if the
-- exception wasn't SQL-related.
True <- expectError (== TestException) $
withSavepoint conn $ do
execute_ conn "INSERT INTO tmp_savepoint VALUES (3)"
[1,2,3] <- getRows
throwIO TestException
[1,2] <- getRows
-- Nested savepoint can be rolled back while the
-- outer effects are retained.
withSavepoint conn $ do
execute_ conn "INSERT INTO tmp_savepoint VALUES (3)"
True <- expectError isUniqueViolation $
withSavepoint conn $ do
execute_ conn "INSERT INTO tmp_savepoint VALUES (4)"
[1,2,3,4] <- getRows
execute_ conn "INSERT INTO tmp_savepoint VALUES (4)"
[1,2,3] <- getRows
return ()
[1,2,3] <- getRows
return ()
-- Transaction committed successfully, even though there were errors
-- (but we rolled them back).
[1,2,3] <- getRows
return ()
testUnicode :: TestEnv -> Test
testUnicode TestEnv{..} = TestCase $ do
let q = Query . T.encodeUtf8 -- Handle encoding ourselves to ensure
-- the table gets created correctly.
let messages = map Only ["привет","мир"] :: [Only Text]
execute_ conn (q "CREATE TEMPORARY TABLE ру́сский (сообщение TEXT)")
executeMany conn "INSERT INTO ру́сский (сообщение) VALUES (?)" messages
messages' <- query_ conn "SELECT сообщение FROM ру́сский"
sort messages @?= sort messages'
testValues :: TestEnv -> Test
testValues TestEnv{..} = TestCase $ do
execute_ conn "CREATE TEMPORARY TABLE values_test (x int, y text)"
test (Values ["int4","text"] [])
test (Values ["int4","text"] [(1,"hello")])
test (Values ["int4","text"] [(1,"hello"),(2,"world")])
test (Values ["int4","text"] [(1,"hello"),(2,"world"),(3,"goodbye")])
test (Values [] [(1,"hello")])
test (Values [] [(1,"hello"),(2,"world")])
test (Values [] [(1,"hello"),(2,"world"),(3,"goodbye")])
where
test :: Values (Int, Text) -> Assertion
test table@(Values _ vals) = do
execute conn "INSERT INTO values_test ?" (Only table)
vals' <- query_ conn "DELETE FROM values_test RETURNING *"
sort vals @?= sort vals'
testCopy :: TestEnv -> Test
testCopy TestEnv{..} = TestCase $ do
execute_ conn "CREATE TEMPORARY TABLE copy_test (x int, y text)"
copy_ conn "COPY copy_test FROM STDIN (FORMAT CSV)"
mapM_ (putCopyData conn) copyRows
putCopyEnd conn
copy_ conn "COPY copy_test FROM STDIN (FORMAT CSV)"
mapM_ (putCopyData conn) abortRows
putCopyError conn "aborted"
-- Hmm, does postgres always produce \n as an end-of-line here, or
-- are there cases where it will use a \r\n as well?
copy_ conn "COPY copy_test TO STDOUT (FORMAT CSV)"
rows <- loop []
sort rows @?= sort copyRows
-- Now, let's just verify that the connection state is back to ready,
-- so that we can issue more queries:
[Only (x::Int)] <- query_ conn "SELECT 2 + 2"
x @?= 4
where
copyRows = ["1,foo\n"
,"2,bar\n"]
abortRows = ["3,baz\n"]
loop rows = do
mrow <- getCopyData conn
case mrow of
CopyOutDone _ -> return rows
CopyOutRow row -> loop (row:rows)
testDouble :: TestEnv -> Test
testDouble TestEnv{..} = TestCase $ do
[Only (x :: Double)] <- query_ conn "SELECT 'NaN'::float8"
assertBool "expected NaN" (isNaN x)
[Only (x :: Double)] <- query_ conn "SELECT 'Infinity'::float8"
x @?= (1 / 0)
[Only (x :: Double)] <- query_ conn "SELECT '-Infinity'::float8"
x @?= (-1 / 0)
data TestException
= TestException
deriving (Eq, Show, Typeable)
instance Exception TestException
expectError :: Exception e => (e -> Bool) -> IO a -> IO Bool
expectError p io =
(io >> return False) `E.catch` \ex ->
if p ex then return True else throwIO ex
isUniqueViolation :: SqlError -> Bool
isUniqueViolation SqlError{..} = sqlState == "23505"
isSyntaxError :: SqlError -> Bool
isSyntaxError SqlError{..} = sqlState == "42601"
------------------------------------------------------------------------
-- | Action for connecting to the database that will be used for testing.
--
-- Note that some tests, such as Notify, use multiple connections, and assume
-- that 'testConnect' connects to the same database every time it is called.
testConnect :: IO Connection
testConnect = connectPostgreSQL ""
withTestEnv :: (TestEnv -> IO a) -> IO a
withTestEnv cb =
withConn $ \conn ->
cb TestEnv
{ conn = conn
, withConn = withConn
}
where
withConn = bracket testConnect close
main :: IO ()
main = do
mapM_ (`hSetBuffering` LineBuffering) [stdout, stderr]
Counts{cases, tried, errors, failures} <-
withTestEnv $ \env -> runTestTT $ TestList $ map ($ env) tests
when (cases /= tried || errors /= 0 || failures /= 0) $ exitFailure
| avieth/postgresql-simple | test/Main.hs | bsd-3-clause | 13,354 | 0 | 20 | 3,679 | 4,016 | 2,048 | 1,968 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Orbits.Simulation.TensorFlow (createSimulation) where
import Control.Lens hiding (_1, _2)
import Data.Int (Int32, Int64)
import Data.Vector (Vector)
import qualified Data.ByteString as BS
import qualified Data.Vector as V
import qualified Numeric.Units.Dimensional as D
import qualified TensorFlow.Core as TF
import qualified TensorFlow.Ops as TF
( scalar, vector, placeholder, initializedVariable, constant )
import qualified TensorFlow.GenOps.Core as TF
( sum, mul, sub, squeeze, matrixSetDiag, neg, square, expandDims, assign, add
, zerosLike, realDiv, concat, sqrt, slice, transpose, print' )
import qualified TensorFlow.Types as TF (ListOf((:/), Nil))
import TensorFlow.Operators
import Orbits.Simulation
import Orbits.System
import Orbits.Units
data State a = State
{ _positions :: TF.Tensor TF.Value a -- ^ Positions. Shape: [3, n]
, _velocities :: TF.Tensor TF.Value a -- ^ Velocities. Shape: [3, n]
, _masses :: TF.Tensor TF.Value a -- ^ Masses. Shape: [n]
}
makeLenses ''State
-- | Build a TensorFlow graph to compute the new velocities.
buildNewPositions :: TF.Tensor v'0 Double -- ^ Length of time step. Scalar.
-> State Double -- ^ current state of the system
-> TF.Build (TF.Tensor TF.Value Double) -- ^ new velocities. Shape: [3, n].
buildNewPositions timeDelta state =
TF.render $ state^.positions ^+ timeDelta ^* state^.velocities
-- | Build a TensorFlow graph to compute the new velocities.
buildNewVelocities :: TF.Tensor v'0 Double -- ^ Length of time step. Scalar.
-> State Double
-> TF.Build (TF.Tensor TF.Value Double) -- ^ new velocities. Shape: [3, n].
buildNewVelocities timeDelta state = do
-- distance[i,j] = distance from body i to body j
-- distance2[i,j] = squared distance from body i to body j
-- positionDiffs[*,i,j] = vector from body j to body i
(distance, distance2, positionDiffs) <- buildDistance state
-- unitDiffs[*,i,j] = unit vector pointing from body j toward body i
let unitDiffs = positionDiffs ^/ distance
-- masses, expanded to shape [n,1], to line up with the shape of distance2
masses' = TF.expandDims (state^.masses) _1
-- accelerations'[*,i,j] = acceleration on body i due to the gravitational attraction of body j
-- accelerations'[*,i,i] = NaN
accelerations' =
unitDiffs ^*
TF.scalar simGravitationalConstant ^*
masses' ^/
distance2
-- accelerations[*,i,j] = acceleration on body i due to the gravitational attraction of body j
-- accelerations'[*,i,i] = (0,0,0)
accelerations = TF.matrixSetDiag accelerations' (TF.zerosLike (state^.positions))
-- totalAcceleration[*,i] = total acceleration on body i due to the gravitational attraction to all other bodies
totalAcceleration = TF.sum accelerations _1
TF.render $ state^.velocities ^+ timeDelta ^* totalAcceleration
-- | Build a TensorFlow graph to compute the energy of the system
buildEnergy :: State Double
-> TF.Build (TF.Tensor TF.Value Double)
buildEnergy state = do
-- distance[i,j] = distance from body i to body j
(distance, _, _) <- buildDistance state
-- kineticEnergy = total kinetic energy in the system
let kineticEnergy =
TF.scalar 0.5 ^* TF.sum kineticEnergies _0
-- kineticEnergies[i] = 2 * (kinetic energy of body i)
kineticEnergies =
state^.masses ^* TF.sum (TF.square (state^.velocities)) _0
-- gravitationalPotential = total gravitational potential of the system
gravitationalPotential =
TF.scalar 0.5 ^* TF.sum gravitationalPotentials (int32Vector [0, 1])
-- gravitationalPotentials[i,j] = gravitational potential between bodies i and j
-- gravitationalPotentials[i,i] = 0
gravitationalPotentials =
TF.matrixSetDiag gravitationalPotentials' (TF.zerosLike kineticEnergies)
-- gravitationalPotentials'[i,j] = gravitational potential between bodies i and j
-- gravitationalPotentials'[i,i] = NaN
gravitationalPotentials' =
TF.scalar simGravitationalConstant ^* massProd ^/ distance
-- massProd[i,j] = (mass of body i) * (mass of body j)
massProd =
TF.expandDims (state^.masses) _0 ^* -- masses, in shape [1,n]
TF.expandDims (state^.masses) _1 -- masses, in shape [n,1]
TF.render $ kineticEnergy - gravitationalPotential
-- | Build TensorFlow graph to compute the distance between the bodies, and related tensors.
buildDistance :: State Double
-> TF.Build ( TF.Tensor TF.Value Double
, TF.Tensor TF.Value Double
, TF.Tensor TF.Value Double )
-- ^ returns (distance, distance^2, positionDiffs),
-- where distance[i,j] is the distance between body i and body j
-- and positionDiffs[*,i,j] is the vector from body j to body i
buildDistance state = do
-- positionDiffs[*,i,j] = 3d vector from body j to body i (first axis is x/y/z)
positionDiffs <- TF.render (TF.expandDims (state^.positions) _2 ^- -- positions, in shape [*,n,1]
TF.expandDims (state^.positions) _1) -- positions, in shape [*,1,n]
-- distance2[i,j] = squared distance between body i and body j
distance2 <- TF.render $ TF.sum (TF.square positionDiffs) _0
-- distance[i,j] = distance between body i and body j
distance <- TF.render $ TF.sqrt distance2
return (distance, distance2, positionDiffs)
-- | Build the TensorFlow graph, and return the simulation object to control it
createSimulation :: Vector (Body Double)
-> TF.Build (Simulation TF.Session Double)
createSimulation initialBodies = do
let numBodies = V.length initialBodies
-- initialPositions[i,*] = initial position of body i. Note that the last dimension is the x/y/z channel.
initialPositions = TF.constant [fromIntegral numBodies, 3]
(initialBodies & toListOf (traverse.position.traverse.inUnit simLength))
-- initialVelocities[i,*] = initial velocity of body i.
initialVelocities = TF.constant [fromIntegral numBodies, 3]
(initialBodies & toListOf (traverse.velocity.traverse.inUnit simVelocity))
-- masses[i] = mass of body i.
masses <- TF.render $ TF.constant [fromIntegral numBodies]
(initialBodies & toListOf (traverse.mass.inUnit simMass))
-- positionsVar[*,i] = current position of body i (mutable variable).
-- Note that the first dimension is the x/y/z channel.
positionsVar <- TF.initializedVariable (TF.transpose initialPositions (int32Vector [1, 0]))
-- velocitiesVar[*,i] = current velocity of body i (mutable variable).
velocitiesVar <- TF.initializedVariable (TF.transpose initialVelocities (int32Vector [1, 0]))
-- positionsOutput[i,*] = current positions of the body i.
-- Note that the last dimension is the x/y/z channel.
positionsOutput <- TF.render $ TF.transpose positionsVar (int32Vector [1, 0])
-- velocitiesOutput[i,*] = current velocity of body i.
velocitiesOutput <- TF.render $ TF.transpose velocitiesVar (int32Vector [1, 0])
-- Time step size. Must be fed in when doing the step
timeDelta <- TF.placeholder []
let state = State
{ _positions = TF.value positionsVar
, _velocities = TF.value velocitiesVar
, _masses = masses
}
-- new positions, obtained by moving each body at the current velocity for 'timeDelta' amount of time
newPositions <- buildNewPositions timeDelta state
-- new velocities, computed *at the new positions* by adding the gravitational forces from all other bodies
newVelocities <- buildNewVelocities timeDelta (state & positions .~ newPositions)
-- current energy of the system
energy <- buildEnergy state
-- Operation which stores the new position in the position variable
updatePositionsOp <- TF.assign positionsVar newPositions
-- Operation which stores the new velocity in the velocity variable
updateVelocitiesOp <- TF.assign velocitiesVar newVelocities
-- Operation which performs one simulation step
stepOp <- TF.group (updatePositionsOp, updateVelocitiesOp)
-- Feed a 'Quantity' of time into the timeDelta placeholder
let feedTimeDelta dt = TF.feed timeDelta $ TF.encodeTensorData [] (V.singleton (dt^.inUnit simTime))
-- get the positions, velocities and masses of the bodies as flat 'Vector Double's,
-- and convert these into a 'Vector (Body Double)'
getBodies = bodiesFromVecs <$>
TF.run (positionsOutput, velocitiesOutput, masses)
-- get the energy, and convert it into a 'Quantity'
getEnergy = view (from $ inUnit simEnergy) .
TF.unScalar <$>
TF.run energy
-- advance the simulation by 1 time step
step dt = TF.runWithFeeds_ [feedTimeDelta dt] stepOp
return $ Simulation getBodies getEnergy step
-- | Helper for creating a constant Int32 scalar.
int32Scalar :: Int32 -> TF.Tensor TF.Build Int32
int32Scalar = TF.scalar
-- | Helper for creating a constant Int32 rank-1 tensor.
int32Vector :: [Int32] -> TF.Tensor TF.Build Int32
int32Vector = TF.vector
-- | Convenient shorthand for 'int32Scalar 0'
_0 :: TF.Tensor TF.Build Int32
_0 = TF.scalar 0
-- | Convenient shorthand for 'int32Scalar 1'
_1 :: TF.Tensor TF.Build Int32
_1 = TF.scalar 1
-- | Convenient shorthand for 'int32Scalar 2'
_2 :: TF.Tensor TF.Build Int32
_2 = TF.scalar 2
| bjoeris/orbits-haskell-tensorflow | src/Orbits/Simulation/TensorFlow.hs | bsd-3-clause | 9,620 | 0 | 18 | 2,061 | 1,733 | 931 | 802 | 118 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module GeoLabel.Real (R) where
import System.Random (Random)
import Data.Fixed (Fixed, HasResolution, resolution)
newtype R = R (Double) deriving (Eq, Ord, Fractional, Floating, RealFloat, Num, Real, Random, RealFrac, Show)
--instance Floating R where
data E30
instance HasResolution E30 where
resolution _ = 10^30 | wyager/GeoLabel | src/GeoLabel/Real.hs | bsd-3-clause | 372 | 0 | 6 | 59 | 116 | 66 | 50 | -1 | -1 |
import Fakemain
main :: IO ()
main = main'
| Frefreak/hnem | app/Main.hs | bsd-3-clause | 44 | 0 | 6 | 10 | 19 | 10 | 9 | 3 | 1 |
module Main where
import Data.HashSet (singleton)
import Language.Haskell.TH
import TH
x = 321
main :: IO ()
main = do
let i = $(hinsert)
let ii = $(hinserte)
print $ i 2 (singleton (1 :: Int))
print $ ii 2 (singleton (1 :: Int))
| s9gf4ult/letqq | src/Main.hs | bsd-3-clause | 257 | 0 | 11 | 71 | 117 | 62 | 55 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
module SlitherBot.Prelude
( module All
, MonadSlither
) where
import ClassyPrelude as All hiding (mapM_, toList)
import Prelude as All (mapM_, iterate)
import Data.Foldable as All (toList)
import Control.Monad.Logger as All
import Control.Concurrent.Async.Lifted.Safe as Async
import Control.Monad.Trans.Unlift (MonadBaseUnlift)
type MonadSlither m =
(MonadIO m, MonadCatch m, MonadMask m, MonadLogger m, MonadBaseUnlift IO m, Async.Forall (Async.Pure m))
| chpatrick/slither-bot | src/SlitherBot/Prelude.hs | bsd-3-clause | 596 | 0 | 9 | 82 | 143 | 92 | 51 | 15 | 0 |
module Folly.Lexer(
Token, name, isVar, isPred, pos,
testOp, testVar, testQuant,
testPred, testSep,
lexer) where
import Text.Parsec.Pos
import Text.ParserCombinators.Parsec
import Folly.Utils
data Token =
Var String SourcePos |
Pred String SourcePos |
Sep String SourcePos |
Op String SourcePos |
Quant String SourcePos |
Res String SourcePos
instance Show Token where
show = showTok
instance Eq Token where
(==) = tokEqual
isVar (Var _ _) = True
isVar _ = False
isPred (Pred _ _) = True
isPred _ = False
name (Var n _) = n
name (Pred n _) = n
name (Sep n _) = n
name (Op n _) = n
name (Res n _) = n
name (Quant n _) = n
pos (Var _ p) = p
pos (Pred _ p) = p
pos (Sep _ p) = p
pos (Op _ p) = p
pos (Res _ p) = p
pos (Quant _ p) = p
testVar s = Var s (newPos "DUMMY" 0 0)
testPred s = Pred s (newPos "DUMMY" 0 0)
testSep s = Sep s (newPos "DUMMY" 0 0)
testOp s = Sep s (newPos "DUMMY" 0 0)
testRes s = Res s (newPos "DUMMY" 0 0)
testQuant s = Quant s (newPos "DUMMY" 0 0)
showTok :: Token -> String
showTok t = name t
tokEqual :: Token -> Token -> Bool
tokEqual t1 t2 = name t1 == name t2
lexer :: String -> Error [Token]
lexer str = case parse parseToks "LEXER" str of
Left err -> Left $ show err
Right toks -> Right toks
parseToks = endBy parseTok spaces
parseTok = try atomicLit
<|> try reservedWord
<|> try predicate
<|> try separator
<|> try quantifier
<|> operator
predicate = do
pos <- getPosition
firstChar <- upper <|> specialChar
case firstChar of
'E' -> eOrQPred 'E' pos
'Q' -> eOrQPred 'Q' pos
_ -> nonEQPred firstChar pos
eOrQPred firstChar pos = do
rest <- many1 bodyChar
return $ Pred (firstChar:rest) pos
nonEQPred firstChar pos = do
rest <- many bodyChar
return $ Pred (firstChar:rest) pos
atomicLit = do
pos <- getPosition
firstChar <- lower
rest <- many bodyChar
return $ Var (firstChar:rest) pos
reservedWord = do
pos <- getPosition
name <- try (string "HYPOTHESIS:") <|> (string "CONCLUSION:")
return $ Res name pos
separator = do
pos <- getPosition
name <- choice $ map string ["(", ")", "]", "[", ",", "."]
return $ Sep name pos
operator = do
pos <- getPosition
name <- choice $ map string ["~", "|", "&", "<->", "->"]
return $ Op name pos
quantifier = do
pos <- getPosition
name <- choice $ map string ["E", "Q"]
return $ Quant name pos
bodyChar = alphaNum <|> specialChar
specialChar = oneOf "!@#$%*<>?+=-_"
| dillonhuff/Folly | src/Folly/Lexer.hs | bsd-3-clause | 2,523 | 0 | 11 | 641 | 1,090 | 543 | 547 | 92 | 3 |
module Metropolis (metroStep) where
import Control.Monad.Random
metroStep :: (RandomGen g) => (Double -> Double) -> Double -> Double -> Rand g Double
metroStep p delta x = do
dx <- getRandomR (-delta, delta)
let
newx = x + dx
p0 = p x
p1 = p newx
weightselect = do
let odds = exp (p1 - p0)
select <- getRandom
return (if select < odds then newx else x)
if p1 > p0
then return newx
else weightselect
| mstksg/pi-monte-carlo | src/pimc/Metropolis.hs | bsd-3-clause | 450 | 0 | 17 | 129 | 182 | 94 | 88 | 16 | 3 |
module Data.OrgMode.OrgDocView (
OrgDocView(..), generateDocView, getRawElements,
updateDoc, NodeUpdate(..)
) where
import Data.OrgMode.Doc
import Data.OrgMode.Text
import Data.Set (Set(..), member, lookupLE)
import Data.Maybe (mapMaybe, fromJust, catMaybes)
data OrgDocView a = OrgDocView
{ ovElements :: [(a, Node)]
, ovDocument :: OrgDoc
}
-- | Generic visitor for updating a Node's values. Intentionally, we
-- don't allow node deletion, just update. Preferably, if you want to
-- delete a Node, you should control the parent. We also have
-- findItemInNode which will construct an 'a' from the Node, which we
-- may then update against a list.
class (Eq a) => NodeUpdate a where
findItemInNode :: Node -> Maybe a
updateNodeLine :: a -> Node -> Maybe Node
-- Doesn't assume that xs or ys are individually sorted, which works
-- well for TextLines with no line number mid-stream.
mergeSorted :: (Ord a) => [a] -> [a] -> [a]
mergeSorted [] [] = []
mergeSorted xs [] = xs
mergeSorted [] ys = ys
mergeSorted xl@(x:xs) yl@(y:ys) =
case compare x y of
EQ -> x:(mergeSorted xs yl)
LT -> x:(mergeSorted xs yl)
GT -> y:(mergeSorted xl ys)
instance TextLineSource OrgDoc where
getTextLines doc =
let docLines = concatMap getTextLines $ odNodes doc
propLines = concatMap getTextLines $ odProperties doc
in mergeSorted docLines propLines
instance TextLineSource (OrgDocView a) where
getTextLines = getTextLines . ovDocument
-- * Constructors
generateDocView :: (NodeUpdate a) => OrgDoc -> OrgDocView a
generateDocView doc =
let childNode (ChildNode n) = Just n
childNode _ = Nothing
childNodes n = mapMaybe childNode $ nChildren n
scanNode :: (Node -> Maybe a) -> Node -> [(a, Node)]
scanNode fn n = let hd = fn n
entry = maybe [] (\a -> [(a,n)]) hd
rest = (concatMap (scanNode fn) $ childNodes n)
in (entry++rest)
scanOrgForest :: (NodeUpdate a) => [Node] -> [(a, Node)]
scanOrgForest forest =
concatMap (scanNode findItemInNode) forest
forest = odNodes doc
elements = scanOrgForest forest
in OrgDocView elements doc
getRawElements :: OrgDocView a -> [a]
getRawElements docview =
map fst $ ovElements docview
-- * Update an OrgMode doc
-- Algorithm: sort the issues by textline line #. Then, get the
-- textlines of the entire tree, which shall be in ascending order.
-- Replace them as we match the node.
updateElementList :: (NodeUpdate a) => [Node] -> [(a, Node)]
updateElementList nodes =
let nodeChildScan (ChildNode nd) = nodeScan nd
nodeChildScan _ = []
nodeScan nd =
let children = concatMap nodeChildScan (nChildren nd)
in case findItemInNode nd of
Just item -> (item, nd):children
Nothing -> children
in concatMap nodeScan nodes
updateDoc :: (Ord a, NodeUpdate a) => Set a -> OrgDocView a -> OrgDocView a
updateDoc new_items doc =
let nodeUpdater node =
case findItemInNode node of
Just item ->
if member item new_items
then let new_item = fromJust $ lookupLE item new_items
in updateNodeLine new_item node
else Nothing
Nothing -> Nothing
new_nodes =
map (updateNode nodeUpdater) $ odNodes $ ovDocument doc
new_doc = (ovDocument doc) { odNodes = new_nodes }
in doc { ovDocument = new_doc }
| lally/orgmode | src/Data/OrgMode/OrgDocView.hs | bsd-3-clause | 3,510 | 0 | 18 | 917 | 1,023 | 539 | 484 | 72 | 3 |
module Lib.Revisit
( M, avoid, run
) where
import Control.Monad.Trans.State (StateT, evalStateT)
import Data.Set (Set)
import qualified Control.Monad.Trans.State as State
import qualified Data.Set as Set
import Prelude.Compat
-- Visited:
type M e m = StateT (Set e) m
avoid :: (Monad m, Ord e) => e -> M e m a -> M e m (Maybe a)
avoid rep act = do
visited <- State.get
if rep `Set.member` visited
then pure Nothing
else do
State.modify $ Set.insert rep
Just <$> act
run :: Monad m => M e m a -> m a
run = flip evalStateT Set.empty
| buildsome/buildsome | src/Lib/Revisit.hs | gpl-2.0 | 594 | 0 | 12 | 161 | 233 | 128 | 105 | 18 | 2 |
{- |
Module : ./CSL/SimpleExtendedParameter.hs
Description : Handling of simple extended parameters
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
This module contains a simple extended parameter representation
Extended parameters may be based on one of the following
relations:
> =, <=, >=, !=, <, >, -|
We reduce the relations to one of the Data items in 'NormEP'. We
handle @-|@ as @*@ for comparison and range computations, i.e.,
we remove it, and @< n@ is turned into @<= n-1@
(or @'LeftOf' n-1@) and accordingly for @>@.
We could work more generally (and we do it) as in
CSL.GeneralExtendedParameter .
-}
module CSL.SimpleExtendedParameter where
import CSL.BoolBasic
import CSL.TreePO
import CSL.AS_BASIC_CSL
import Common.Id (tokStr)
import Common.Doc
import Common.DocUtils
{- ----------------------------------------------------------------------
Datatypes for efficient Extended Parameter comparison
---------------------------------------------------------------------- -}
-- | Normalized representation of an extended param relation
data NormEP = LeftOf | RightOf | Equal | Except deriving (Eq, Ord)
instance Show NormEP where
show LeftOf = "<="
show RightOf = ">="
show Equal = "="
show Except = "/="
instance Pretty NormEP where
pretty x = text $ show x
type EPExp = (NormEP, APInt)
cmpOp :: NormEP -> APInt -> APInt -> Bool
cmpOp LeftOf = (<=)
cmpOp RightOf = (>=)
cmpOp Equal = (==)
cmpOp Except = (/=)
evalEP :: Int -> EPExp -> Bool
evalEP i (n, j) = cmpOp n (toInteger i) j
showEP :: (String, EPExp) -> String
showEP (s, (n, i)) = s ++ show n ++ show i
-- | Conversion function into the more efficient representation.
toEPExp :: EXTPARAM -> Maybe (String, EPExp)
toEPExp (EP t r i) =
case r of
"<=" -> Just (tokStr t, (LeftOf, i))
"<" -> Just (tokStr t, (LeftOf, i - 1))
">=" -> Just (tokStr t, (RightOf, i))
">" -> Just (tokStr t, (RightOf, i + 1))
"=" -> Just (tokStr t, (Equal, i))
"!=" -> Just (tokStr t, (Except, i))
"-|" -> Nothing
_ -> error $ "toEPExp: unsupported relation: " ++ r
toBoolRep :: String -> EPExp -> BoolRep
toBoolRep s (x, i) = Pred (show x) [s, show i]
complementEP :: EPExp -> EPExp
complementEP (x, i) = case x of
LeftOf -> (RightOf, i + 1)
RightOf -> (LeftOf, i - 1)
Equal -> (Except, i)
Except -> (Equal, i)
{- ----------------------------------------------------------------------
Extended Parameter comparison
---------------------------------------------------------------------- -}
-- | Compares two 'EPExp': They are uncompareable if they overlap or are disjoint.
compareEP :: EPExp -> EPExp -> SetOrdering
compareEP ep1@(r1, n1) ep2@(r2, n2)
| r1 == r2 = compareSameRel r1 n1 n2
| otherwise =
case (r1, r2) of
(Equal, Except) | n1 == n2 -> Incomparable Disjoint
| otherwise -> Comparable LT
(Equal, LeftOf) | n1 > n2 -> Incomparable Disjoint
| otherwise -> Comparable LT
(Equal, RightOf) | n1 < n2 -> Incomparable Disjoint
| otherwise -> Comparable LT
(Except, LeftOf) | n1 > n2 -> Comparable GT
| otherwise -> Incomparable Overlap
(Except, RightOf) | n1 < n2 -> Comparable GT
| otherwise -> Incomparable Overlap
(LeftOf, RightOf) | n1 < n2 -> Incomparable Disjoint
| otherwise -> Incomparable Overlap
_ -> swapCmp $ compareEP ep2 ep1
compareSameRel :: NormEP -> APInt -> APInt -> SetOrdering
compareSameRel r n1 n2
| n1 == n2 = Comparable EQ
| otherwise =
case r of
LeftOf -> Comparable (compare n1 n2)
RightOf -> Comparable (compare n2 n1)
Equal -> Incomparable Disjoint
Except -> Incomparable Overlap
| spechub/Hets | CSL/SimpleExtendedParameter.hs | gpl-2.0 | 4,144 | 0 | 12 | 1,141 | 1,062 | 554 | 508 | 71 | 8 |
#!/usr/bin/env runhaskell
{-
generatetimeclock.hs NUMENTRIES
Outputs a dummy timeclock log with the specified number of clock-in/clock-out entries,
one per day.
-}
module Main
where
import System.Environment
import Data.Time.LocalTime
import Data.Time.Calendar
import Text.Printf
main = do
args <- getArgs
let [numentries] = map read args :: [Integer]
today <- getCurrentDay
let startdate = addDays (-numentries) today
mapM_ (putStr . showentry) [startdate..today]
showentry d =
printf "i %s 09:00:00 dummy\no %s 17:00:00\n" (show d) (show d)
getCurrentDay = localDay . zonedTimeToLocalTime <$> getZonedTime
| simonmichael/hledger | tools/generatetimeclock.hs | gpl-3.0 | 626 | 0 | 12 | 99 | 150 | 79 | 71 | 14 | 1 |
{-
Copyright 2010-2012 Cognimeta Inc.
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 TemplateHaskell, FlexibleContexts, TypeFamilies, TupleSections, ScopedTypeVariables, FlexibleInstances #-}
module Database.Perdure.WValidator (
W32Validator,
W64Validator,
module Database.Perdure.Validator
) where
import Prelude ()
import Cgm.Prelude
import Data.Word
import Database.Perdure.Digest
import Database.Perdure.Validator
import Cgm.Data.Maybe
import Cgm.Data.Structured
data W32Validator = W32Validator {-# UNPACK #-} !MD5Digest deriving (Eq, Show)
data W64Validator = W64Validator {-# UNPACK #-} !(Skein512Digest Word128) deriving (Eq, Show)
instance Validator W32Validator where
type ValidatedElem W32Validator = Word32
mkValidationInput b = (W32Validator $ digest b, pure b)
validate (W32Validator h) b = b `justIf` True -- (digest b == h)
instance Validator W64Validator where
type ValidatedElem W64Validator = Word64
mkValidationInput b = (W64Validator $ digest b, pure b)
validate (W64Validator h) b = b `justIf` True -- (digest b == h)
deriveStructured ''W32Validator
deriveStructured ''W64Validator
| bitemyapp/perdure | src/Database/Perdure/WValidator.hs | apache-2.0 | 1,670 | 6 | 10 | 285 | 208 | 127 | 81 | 24 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- | View library.
module HL.View
(module HL.View
,module V)
where
import HL.Foundation as V (Route(..),App,Human(..),Slug(..))
import HL.Static as V
import Control.Monad as V
import Data.Text as V (Text)
import Lucid as V
import Lucid.Bootstrap as V
import Yesod.Lucid as V
todo :: Term a r => a -> r
todo = termWith "div" [class_ "muted"]
| gbaz/hl | src/HL/View.hs | bsd-3-clause | 387 | 0 | 7 | 71 | 132 | 86 | 46 | 13 | 1 |
module Main (main) where
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription
import Distribution.PackageDescription.Check hiding (doesFileExist)
import Distribution.PackageDescription.Configuration
import Distribution.PackageDescription.Parse
import Distribution.System
import Distribution.Simple
import Distribution.Simple.Configure
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.GHC
import Distribution.Simple.Program
import Distribution.Simple.Program.HcPkg
import Distribution.Simple.Setup (ConfigFlags(configStripLibs), fromFlag, toFlag)
import Distribution.Simple.Utils (defaultPackageDesc, writeFileAtomic, toUTF8)
import Distribution.Simple.Build (writeAutogenFiles)
import Distribution.Simple.Register
import Distribution.Text
import Distribution.Verbosity
import qualified Distribution.InstalledPackageInfo as Installed
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Control.Exception (bracket)
import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.List
import Data.Maybe
import System.IO
import System.Directory
import System.Environment
import System.Exit (exitWith, ExitCode(..))
import System.FilePath
main :: IO ()
main = do hSetBuffering stdout LineBuffering
args <- getArgs
case args of
"hscolour" : dir : distDir : args' ->
runHsColour dir distDir args'
"check" : dir : [] ->
doCheck dir
"copy" : dir : distDir
: strip : myDestDir : myPrefix : myLibdir : myDocdir
: ghcLibWays : args' ->
doCopy dir distDir
strip myDestDir myPrefix myLibdir myDocdir
("dyn" `elem` words ghcLibWays)
args'
"register" : dir : distDir : ghc : ghcpkg : topdir
: myDestDir : myPrefix : myLibdir : myDocdir
: relocatableBuild : args' ->
doRegister dir distDir ghc ghcpkg topdir
myDestDir myPrefix myLibdir myDocdir
relocatableBuild args'
"configure" : dir : distDir : dll0Modules : config_args ->
generate dir distDir dll0Modules config_args
"sdist" : dir : distDir : [] ->
doSdist dir distDir
["--version"] ->
defaultMainArgs ["--version"]
_ -> die syntax_error
syntax_error :: [String]
syntax_error =
["syntax: ghc-cabal configure <configure-args> -- <distdir> <directory>...",
" ghc-cabal install <ghc-pkg> <directory> <distdir> <destdir> <prefix> <args>...",
" ghc-cabal hscolour <distdir> <directory> <args>..."]
die :: [String] -> IO a
die errs = do mapM_ (hPutStrLn stderr) errs
exitWith (ExitFailure 1)
withCurrentDirectory :: FilePath -> IO a -> IO a
withCurrentDirectory directory io
= bracket (getCurrentDirectory) (setCurrentDirectory)
(const (setCurrentDirectory directory >> io))
-- We need to use the autoconfUserHooks, as the packages that use
-- configure can create a .buildinfo file, and we need any info that
-- ends up in it.
userHooks :: UserHooks
userHooks = autoconfUserHooks
runDefaultMain :: IO ()
runDefaultMain
= do let verbosity = normal
gpdFile <- defaultPackageDesc verbosity
gpd <- readPackageDescription verbosity gpdFile
case buildType (flattenPackageDescription gpd) of
Just Configure -> defaultMainWithHooks autoconfUserHooks
-- time has a "Custom" Setup.hs, but it's actually Configure
-- plus a "./Setup test" hook. However, Cabal is also
-- "Custom", but doesn't have a configure script.
Just Custom ->
do configureExists <- doesFileExist "configure"
if configureExists
then defaultMainWithHooks autoconfUserHooks
else defaultMain
-- not quite right, but good enough for us:
_ -> defaultMain
doSdist :: FilePath -> FilePath -> IO ()
doSdist directory distDir
= withCurrentDirectory directory
$ withArgs (["sdist", "--builddir", distDir])
runDefaultMain
doCheck :: FilePath -> IO ()
doCheck directory
= withCurrentDirectory directory
$ do let verbosity = normal
gpdFile <- defaultPackageDesc verbosity
gpd <- readPackageDescription verbosity gpdFile
case partition isFailure $ checkPackage gpd Nothing of
([], []) -> return ()
([], warnings) -> mapM_ print warnings
(errs, _) -> do mapM_ print errs
exitWith (ExitFailure 1)
where isFailure (PackageDistSuspicious {}) = False
isFailure _ = True
runHsColour :: FilePath -> FilePath -> [String] -> IO ()
runHsColour directory distdir args
= withCurrentDirectory directory
$ defaultMainArgs ("hscolour" : "--builddir" : distdir : args)
doCopy :: FilePath -> FilePath
-> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> Bool
-> [String]
-> IO ()
doCopy directory distDir
strip myDestDir myPrefix myLibdir myDocdir withSharedLibs
args
= withCurrentDirectory directory $ do
let copyArgs = ["copy", "--builddir", distDir]
++ (if null myDestDir
then []
else ["--destdir", myDestDir])
++ args
copyHooks = userHooks {
copyHook = noGhcPrimHook
$ modHook False
$ copyHook userHooks
}
defaultMainWithHooksArgs copyHooks copyArgs
where
noGhcPrimHook f pd lbi us flags
= let pd'
| packageName pd == PackageName "ghc-prim" =
case library pd of
Just lib ->
let ghcPrim = fromJust (simpleParse "GHC.Prim")
ems = filter (ghcPrim /=) (exposedModules lib)
lib' = lib { exposedModules = ems }
in pd { library = Just lib' }
Nothing ->
error "Expected a library, but none found"
| otherwise = pd
in f pd' lbi us flags
modHook relocatableBuild f pd lbi us flags
= do let verbosity = normal
idts = updateInstallDirTemplates relocatableBuild
myPrefix myLibdir myDocdir
(installDirTemplates lbi)
progs = withPrograms lbi
stripProgram' = stripProgram {
programFindLocation = \_ _ -> return (Just strip) }
progs' <- configureProgram verbosity stripProgram' progs
let lbi' = lbi {
withPrograms = progs',
installDirTemplates = idts,
configFlags = cfg,
stripLibs = fromFlag (configStripLibs cfg),
withSharedLib = withSharedLibs
}
-- This hack allows to interpret the "strip"
-- command-line argument being set to ':' to signify
-- disabled library stripping
cfg | strip == ":" = (configFlags lbi) { configStripLibs = toFlag False }
| otherwise = configFlags lbi
f pd lbi' us flags
doRegister :: FilePath -> FilePath -> FilePath -> FilePath
-> FilePath -> FilePath -> FilePath -> FilePath -> FilePath
-> String -> [String]
-> IO ()
doRegister directory distDir ghc ghcpkg topdir
myDestDir myPrefix myLibdir myDocdir
relocatableBuildStr args
= withCurrentDirectory directory $ do
relocatableBuild <- case relocatableBuildStr of
"YES" -> return True
"NO" -> return False
_ -> die ["Bad relocatableBuildStr: " ++
show relocatableBuildStr]
let regArgs = "register" : "--builddir" : distDir : args
regHooks = userHooks {
regHook = modHook relocatableBuild
$ regHook userHooks
}
defaultMainWithHooksArgs regHooks regArgs
where
modHook relocatableBuild f pd lbi us flags
= do let verbosity = normal
idts = updateInstallDirTemplates relocatableBuild
myPrefix myLibdir myDocdir
(installDirTemplates lbi)
progs = withPrograms lbi
ghcpkgconf = topdir </> "package.conf.d"
ghcProgram' = ghcProgram {
programPostConf = \_ cp -> return cp { programDefaultArgs = ["-B" ++ topdir] },
programFindLocation = \_ _ -> return (Just ghc) }
ghcPkgProgram' = ghcPkgProgram {
programPostConf = \_ cp -> return cp { programDefaultArgs =
["--global-package-db", ghcpkgconf]
++ ["--force" | not (null myDestDir) ] },
programFindLocation = \_ _ -> return (Just ghcpkg) }
configurePrograms ps conf = foldM (flip (configureProgram verbosity)) conf ps
progs' <- configurePrograms [ghcProgram', ghcPkgProgram'] progs
instInfos <- dump (hcPkgInfo progs') verbosity GlobalPackageDB
let installedPkgs' = PackageIndex.fromList instInfos
let updateComponentConfig (cn, clbi, deps)
= (cn, updateComponentLocalBuildInfo clbi, deps)
updateComponentLocalBuildInfo clbi
= clbi {
componentPackageDeps =
[ (fixupPackageId instInfos ipid, pid)
| (ipid,pid) <- componentPackageDeps clbi ]
}
ccs' = map updateComponentConfig (componentsConfigs lbi)
lbi' = lbi {
componentsConfigs = ccs',
installedPkgs = installedPkgs',
installDirTemplates = idts,
withPrograms = progs'
}
f pd lbi' us flags
updateInstallDirTemplates :: Bool -> FilePath -> FilePath -> FilePath
-> InstallDirTemplates
-> InstallDirTemplates
updateInstallDirTemplates relocatableBuild myPrefix myLibdir myDocdir idts
= idts {
prefix = toPathTemplate $
if relocatableBuild
then "$topdir"
else myPrefix,
libdir = toPathTemplate $
if relocatableBuild
then "$topdir"
else myLibdir,
libsubdir = toPathTemplate "$pkgkey",
docdir = toPathTemplate $
if relocatableBuild
then "$topdir/../doc/html/libraries/$pkgid"
else (myDocdir </> "$pkgid"),
htmldir = toPathTemplate "$docdir"
}
-- The packages are built with the package ID ending in "-inplace", but
-- when they're installed they get the package hash appended. We need to
-- fix up the package deps so that they use the hash package IDs, not
-- the inplace package IDs.
fixupPackageId :: [Installed.InstalledPackageInfo]
-> InstalledPackageId
-> InstalledPackageId
fixupPackageId _ x@(InstalledPackageId ipi)
| "builtin_" `isPrefixOf` ipi = x
fixupPackageId ipinfos (InstalledPackageId ipi)
= case stripPrefix (reverse "-inplace") $ reverse ipi of
Nothing ->
error ("Installed package ID doesn't end in -inplace: " ++ show ipi)
Just x ->
let ipi' = reverse ('-' : x)
f (ipinfo : ipinfos') = case Installed.installedPackageId ipinfo of
y@(InstalledPackageId ipinfoid)
| ipi' `isPrefixOf` ipinfoid ->
y
_ ->
f ipinfos'
f [] = error ("Installed package ID not registered: " ++ show ipi)
in f ipinfos
-- On Windows we need to split the ghc package into 2 pieces, or the
-- DLL that it makes contains too many symbols (#5987). There are
-- therefore 2 libraries, not just the 1 that Cabal assumes.
mangleLbi :: FilePath -> FilePath -> LocalBuildInfo -> LocalBuildInfo
mangleLbi "compiler" "stage2" lbi
| isWindows =
let ccs' = [ (cn, updateComponentLocalBuildInfo clbi, cns)
| (cn, clbi, cns) <- componentsConfigs lbi ]
updateComponentLocalBuildInfo clbi@(LibComponentLocalBuildInfo {})
= let cls' = concat [ [ LibraryName n, LibraryName (n ++ "-0") ]
| LibraryName n <- componentLibraries clbi ]
in clbi { componentLibraries = cls' }
updateComponentLocalBuildInfo clbi = clbi
in lbi { componentsConfigs = ccs' }
where isWindows = case hostPlatform lbi of
Platform _ Windows -> True
_ -> False
mangleLbi _ _ lbi = lbi
generate :: FilePath -> FilePath -> String -> [String] -> IO ()
generate directory distdir dll0Modules config_args
= withCurrentDirectory directory
$ do let verbosity = normal
-- XXX We shouldn't just configure with the default flags
-- XXX And this, and thus the "getPersistBuildConfig distdir" below,
-- aren't going to work when the deps aren't built yet
withArgs (["configure", "--distdir", distdir] ++ config_args)
runDefaultMain
lbi0 <- getPersistBuildConfig distdir
let lbi = mangleLbi directory distdir lbi0
pd0 = localPkgDescr lbi
writePersistBuildConfig distdir lbi
hooked_bi <-
if (buildType pd0 == Just Configure) || (buildType pd0 == Just Custom)
then do
maybe_infoFile <- defaultHookedPackageDesc
case maybe_infoFile of
Nothing -> return emptyHookedBuildInfo
Just infoFile -> readHookedBuildInfo verbosity infoFile
else
return emptyHookedBuildInfo
let pd = updatePackageDescription hooked_bi pd0
-- generate Paths_<pkg>.hs and cabal-macros.h
writeAutogenFiles verbosity pd lbi
-- generate inplace-pkg-config
withLibLBI pd lbi $ \lib clbi ->
do cwd <- getCurrentDirectory
let ipid = InstalledPackageId (display (packageId pd) ++ "-inplace")
let installedPkgInfo = inplaceInstalledPackageInfo cwd distdir
pd ipid lib lbi clbi
final_ipi = installedPkgInfo {
Installed.installedPackageId = ipid,
Installed.haddockHTMLs = []
}
content = Installed.showInstalledPackageInfo final_ipi ++ "\n"
writeFileAtomic (distdir </> "inplace-pkg-config") (BS.pack $ toUTF8 content)
let
comp = compiler lbi
libBiModules lib = (libBuildInfo lib, libModules lib)
exeBiModules exe = (buildInfo exe, ModuleName.main : exeModules exe)
biModuless = (maybeToList $ fmap libBiModules $ library pd)
++ (map exeBiModules $ executables pd)
buildableBiModuless = filter isBuildable biModuless
where isBuildable (bi', _) = buildable bi'
(bi, modules) = case buildableBiModuless of
[] -> error "No buildable component found"
[biModules] -> biModules
_ -> error ("XXX ghc-cabal can't handle " ++
"more than one buildinfo yet")
-- XXX Another Just...
Just ghcProg = lookupProgram ghcProgram (withPrograms lbi)
dep_pkgs = PackageIndex.topologicalOrder (packageHacks (installedPkgs lbi))
forDeps f = concatMap f dep_pkgs
-- copied from Distribution.Simple.PreProcess.ppHsc2Hs
packageHacks = case compilerFlavor (compiler lbi) of
GHC -> hackRtsPackage
_ -> id
-- We don't link in the actual Haskell libraries of our
-- dependencies, so the -u flags in the ldOptions of the rts
-- package mean linking fails on OS X (it's ld is a tad
-- stricter than gnu ld). Thus we remove the ldOptions for
-- GHC's rts package:
hackRtsPackage index =
case PackageIndex.lookupPackageName index (PackageName "rts") of
[(_,[rts])] ->
PackageIndex.insert rts{
Installed.ldOptions = [],
Installed.libraryDirs = filter (not . ("gcc-lib" `isSuffixOf`)) (Installed.libraryDirs rts)} index
-- GHC <= 6.12 had $topdir/gcc-lib in their
-- library-dirs for the rts package, which causes
-- problems when we try to use the in-tree mingw,
-- due to accidentally picking up the incompatible
-- libraries there. So we filter out gcc-lib from
-- the RTS's library-dirs here.
_ -> error "No (or multiple) ghc rts package is registered!!"
dep_ids = map snd (externalPackageDeps lbi)
deps = map display dep_ids
dep_keys
| packageKeySupported comp
= map (display
. Installed.packageKey
. fromMaybe (error "ghc-cabal: dep_keys failed")
. PackageIndex.lookupInstalledPackageId
(installedPkgs lbi)
. fst)
. externalPackageDeps
$ lbi
| otherwise = deps
depNames = map (display . packageName) dep_ids
transitive_dep_ids = map Installed.sourcePackageId dep_pkgs
transitiveDeps = map display transitive_dep_ids
transitiveDepKeys
| packageKeySupported comp
= map (display . Installed.packageKey) dep_pkgs
| otherwise = transitiveDeps
transitiveDepNames = map (display . packageName) transitive_dep_ids
libraryDirs = forDeps Installed.libraryDirs
-- temporary hack to support two in-tree versions of `integer-gmp`
isIntegerGmp2 = any ("integer-gmp2" `isInfixOf`) libraryDirs
-- The mkLibraryRelDir function is a bit of a hack.
-- Ideally it should be handled in the makefiles instead.
mkLibraryRelDir "rts" = "rts/dist/build"
mkLibraryRelDir "ghc" = "compiler/stage2/build"
mkLibraryRelDir "Cabal" = "libraries/Cabal/Cabal/dist-install/build"
mkLibraryRelDir "integer-gmp"
| isIntegerGmp2 = mkLibraryRelDir "integer-gmp2"
mkLibraryRelDir l = "libraries/" ++ l ++ "/dist-install/build"
libraryRelDirs = map mkLibraryRelDir transitiveDepNames
wrappedIncludeDirs <- wrap $ forDeps Installed.includeDirs
wrappedLibraryDirs <- wrap libraryDirs
let variablePrefix = directory ++ '_':distdir
mods = map display modules
otherMods = map display (otherModules bi)
allMods = mods ++ otherMods
let xs = [variablePrefix ++ "_VERSION = " ++ display (pkgVersion (package pd)),
variablePrefix ++ "_PACKAGE_KEY = " ++ display (pkgKey lbi),
variablePrefix ++ "_MODULES = " ++ unwords mods,
variablePrefix ++ "_HIDDEN_MODULES = " ++ unwords otherMods,
variablePrefix ++ "_SYNOPSIS =" ++ synopsis pd,
variablePrefix ++ "_HS_SRC_DIRS = " ++ unwords (hsSourceDirs bi),
variablePrefix ++ "_DEPS = " ++ unwords deps,
variablePrefix ++ "_DEP_KEYS = " ++ unwords dep_keys,
variablePrefix ++ "_DEP_NAMES = " ++ unwords depNames,
variablePrefix ++ "_TRANSITIVE_DEPS = " ++ unwords transitiveDeps,
variablePrefix ++ "_TRANSITIVE_DEP_KEYS = " ++ unwords transitiveDepKeys,
variablePrefix ++ "_TRANSITIVE_DEP_NAMES = " ++ unwords transitiveDepNames,
variablePrefix ++ "_INCLUDE_DIRS = " ++ unwords (includeDirs bi),
variablePrefix ++ "_INCLUDES = " ++ unwords (includes bi),
variablePrefix ++ "_INSTALL_INCLUDES = " ++ unwords (installIncludes bi),
variablePrefix ++ "_EXTRA_LIBRARIES = " ++ unwords (extraLibs bi),
variablePrefix ++ "_EXTRA_LIBDIRS = " ++ unwords (extraLibDirs bi),
variablePrefix ++ "_C_SRCS = " ++ unwords (cSources bi),
variablePrefix ++ "_CMM_SRCS := $(addprefix cbits/,$(notdir $(wildcard " ++ directory ++ "/cbits/*.cmm)))",
variablePrefix ++ "_DATA_FILES = " ++ unwords (dataFiles pd),
-- XXX This includes things it shouldn't, like:
-- -odir dist-bootstrapping/build
variablePrefix ++ "_HC_OPTS = " ++ escape (unwords
( programDefaultArgs ghcProg
++ hcOptions GHC bi
++ languageToFlags (compiler lbi) (defaultLanguage bi)
++ extensionsToFlags (compiler lbi) (usedExtensions bi)
++ programOverrideArgs ghcProg)),
variablePrefix ++ "_CC_OPTS = " ++ unwords (ccOptions bi),
variablePrefix ++ "_CPP_OPTS = " ++ unwords (cppOptions bi),
variablePrefix ++ "_LD_OPTS = " ++ unwords (ldOptions bi),
variablePrefix ++ "_DEP_INCLUDE_DIRS_SINGLE_QUOTED = " ++ unwords wrappedIncludeDirs,
variablePrefix ++ "_DEP_CC_OPTS = " ++ unwords (forDeps Installed.ccOptions),
variablePrefix ++ "_DEP_LIB_DIRS_SINGLE_QUOTED = " ++ unwords wrappedLibraryDirs,
variablePrefix ++ "_DEP_LIB_DIRS_SEARCHPATH = " ++ mkSearchPath libraryDirs,
variablePrefix ++ "_DEP_LIB_REL_DIRS = " ++ unwords libraryRelDirs,
variablePrefix ++ "_DEP_LIB_REL_DIRS_SEARCHPATH = " ++ mkSearchPath libraryRelDirs,
variablePrefix ++ "_DEP_EXTRA_LIBS = " ++ unwords (forDeps Installed.extraLibraries),
variablePrefix ++ "_DEP_LD_OPTS = " ++ unwords (forDeps Installed.ldOptions),
variablePrefix ++ "_BUILD_GHCI_LIB = " ++ boolToYesNo (withGHCiLib lbi),
"",
-- Sometimes we need to modify the automatically-generated package-data.mk
-- bindings in a special way for the GHC build system, so allow that here:
"$(eval $(" ++ directory ++ "_PACKAGE_MAGIC))"
]
writeFile (distdir ++ "/package-data.mk") $ unlines xs
writeFileUtf8 (distdir ++ "/haddock-prologue.txt") $
if null (description pd) then synopsis pd
else description pd
unless (null dll0Modules) $
do let dll0Mods = words dll0Modules
dllMods = allMods \\ dll0Mods
dllModSets = map unwords [dll0Mods, dllMods]
writeFile (distdir ++ "/dll-split") $ unlines dllModSets
where
escape = foldr (\c xs -> if c == '#' then '\\':'#':xs else c:xs) []
wrap = mapM wrap1
wrap1 s
| null s = die ["Wrapping empty value"]
| '\'' `elem` s = die ["Single quote in value to be wrapped:", s]
-- We want to be able to assume things like <space><quote> is the
-- start of a value, so check there are no spaces in confusing
-- positions
| head s == ' ' = die ["Leading space in value to be wrapped:", s]
| last s == ' ' = die ["Trailing space in value to be wrapped:", s]
| otherwise = return ("\'" ++ s ++ "\'")
mkSearchPath = intercalate [searchPathSeparator]
boolToYesNo True = "YES"
boolToYesNo False = "NO"
-- | Version of 'writeFile' that always uses UTF8 encoding
writeFileUtf8 f txt = withFile f WriteMode $ \hdl -> do
hSetEncoding hdl utf8
hPutStr hdl txt
| green-haskell/ghc | utils/ghc-cabal/Main.hs | bsd-3-clause | 25,173 | 53 | 27 | 9,107 | 4,782 | 2,489 | 2,293 | 416 | 14 |
import Diagrams.AST
main = outputImage "recursion.png" 300 300 pilla
pilla = Images $ Atop face body
face = Modifier (Scale 0.3 0.3) $ Images $ Horizontal [pcirc, pcirc]
pcirc = Modifier (Foreground black) $ Shape Circle
body = circles !! 50
circles = iterate (Images . Atop circle . modifier) Blank
circle = Modifier (Foreground green) $ Shape Circle
modifier = Modifier $ Changes [Scale 0.9 0.9, Rotate (Fraction 0.1), Translate 0 (-2)]
green = RGBA 0.1 0.9 0.1 1
black = RGBA 0 0 0 1
| sordina/Diagrams-AST | test/recursion.hs | bsd-3-clause | 515 | 6 | 10 | 115 | 234 | 108 | 126 | 11 | 1 |
module System.Console.Haskeline.RunCommand (runCommandLoop) where
import System.Console.Haskeline.Command
import System.Console.Haskeline.Term
import System.Console.Haskeline.LineState
import System.Console.Haskeline.Monads
import System.Console.Haskeline.Prefs
import System.Console.Haskeline.Key
import Control.Exception (SomeException)
import Control.Monad
import Control.Monad.Catch (handle, throwM)
runCommandLoop :: (CommandMonad m, MonadState Layout m, LineState s)
=> TermOps -> Prefix -> KeyCommand m s a -> s -> m a
runCommandLoop tops@TermOps{evalTerm = e} prefix cmds initState
= case e of -- NB: Need to separate this case out from the above pattern
-- in order to build on ghc-6.12.3
EvalTerm eval liftE
-> eval $ withGetEvent tops
$ runCommandLoop' liftE tops prefix initState
cmds
runCommandLoop' :: forall m n s a . (Term n, CommandMonad n,
MonadState Layout m, LineState s)
=> (forall b . m b -> n b) -> TermOps -> Prefix -> s -> KeyCommand m s a -> n Event
-> n a
runCommandLoop' liftE tops prefix initState cmds getEvent = do
let s = lineChars prefix initState
drawLine s
readMoreKeys s (fmap (liftM (\x -> (x,[])) . ($ initState)) cmds)
where
readMoreKeys :: LineChars -> KeyMap (CmdM m (a,[Key])) -> n a
readMoreKeys s next = do
event <- handle (\(e::SomeException) -> moveToNextLine s >> throwM e)
getEvent
case event of
ErrorEvent e -> moveToNextLine s >> throwM e
WindowResize -> do
drawReposition liftE tops s
readMoreKeys s next
KeyInput ks -> do
bound_ks <- mapM (asks . lookupKeyBinding) ks
loopCmd s $ applyKeysToMap (concat bound_ks) next
ExternalPrint str -> do
printPreservingLineChars s str
readMoreKeys s next
loopCmd :: LineChars -> CmdM m (a,[Key]) -> n a
loopCmd s (GetKey next) = readMoreKeys s next
-- If there are multiple consecutive LineChanges, only render the diff
-- to the last one, and skip the rest. This greatly improves speed when
-- a large amount of text is pasted in at once.
loopCmd s (DoEffect (LineChange _)
e@(DoEffect (LineChange _) _)) = loopCmd s e
loopCmd s (DoEffect e next) = do
t <- drawEffect prefix s e
loopCmd t next
loopCmd s (CmdM next) = liftE next >>= loopCmd s
loopCmd s (Result (x,ks)) = do
liftIO (saveUnusedKeys tops ks)
moveToNextLine s
return x
printPreservingLineChars :: Term m => LineChars -> String -> m ()
printPreservingLineChars s str = do
clearLine s
printLines . lines $ str
drawLine s
drawReposition :: (Term n, MonadState Layout m)
=> (forall a . m a -> n a) -> TermOps -> LineChars -> n ()
drawReposition liftE tops s = do
oldLayout <- liftE get
newLayout <- liftIO (getLayout tops)
liftE (put newLayout)
when (oldLayout /= newLayout) $ reposition oldLayout s
drawEffect :: (Term m, MonadReader Prefs m)
=> Prefix -> LineChars -> Effect -> m LineChars
drawEffect prefix s (LineChange ch) = do
let t = ch prefix
drawLineDiff s t
return t
drawEffect _ s ClearScreen = do
clearLayout
drawLine s
return s
drawEffect _ s (PrintLines ls) = do
when (s /= ([],[])) $ moveToNextLine s
printLines ls
drawLine s
return s
drawEffect _ s RingBell = actBell >> return s
actBell :: (Term m, MonadReader Prefs m) => m ()
actBell = do
style <- asks bellStyle
case style of
NoBell -> return ()
VisualBell -> ringBell False
AudibleBell -> ringBell True
---------------
-- Traverse through the tree of keybindings, using the given keys.
-- Remove as many GetKeys as possible.
-- Returns any unused keys (so that they can be applied at the next getInputLine).
applyKeysToMap :: Monad m => [Key] -> KeyMap (CmdM m (a,[Key]))
-> CmdM m (a,[Key])
applyKeysToMap [] next = GetKey next
applyKeysToMap (k:ks) next = case lookupKM next k of
Nothing -> DoEffect RingBell $ GetKey next
Just (Consumed cmd) -> applyKeysToCmd ks cmd
Just (NotConsumed cmd) -> applyKeysToCmd (k:ks) cmd
applyKeysToCmd :: Monad m => [Key] -> CmdM m (a,[Key])
-> CmdM m (a,[Key])
applyKeysToCmd ks (GetKey next) = applyKeysToMap ks next
applyKeysToCmd ks (DoEffect e next) = DoEffect e (applyKeysToCmd ks next)
applyKeysToCmd ks (CmdM next) = CmdM $ liftM (applyKeysToCmd ks) next
applyKeysToCmd ks (Result (x,ys)) = Result (x,ys++ks) -- use in the next input line
| judah/haskeline | System/Console/Haskeline/RunCommand.hs | bsd-3-clause | 4,919 | 0 | 17 | 1,486 | 1,600 | 793 | 807 | -1 | -1 |
{-# LANGUAGE MagicHash, NoImplicitPrelude, TypeFamilies, UnboxedTuples,
RoleAnnotations #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Types
-- Copyright : (c) The University of Glasgow 2009
-- License : see libraries/ghc-prim/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- GHC type definitions.
-- Use GHC.Exts from the base package instead of importing this
-- module directly.
--
-----------------------------------------------------------------------------
module GHC.Types (
Bool(..), Char(..), Int(..), Word(..),
Float(..), Double(..),
Ordering(..), IO(..),
Java(..), Object(..), JString(..),
CharSequence(..),
Comparable(..),
Object#,
isTrue#,
SPEC(..),
Coercible,
) where
import GHC.Prim
infixr 5 :
data [] a = [] | a : [a]
data {-# CTYPE "HsBool" #-} Bool = False | True
{- | The character type 'Char' is an enumeration whose values represent
Unicode (or equivalently ISO\/IEC 10646) characters (see
<http://www.unicode.org/> for details). This set extends the ISO 8859-1
(Latin-1) character set (the first 256 characters), which is itself an extension
of the ASCII character set (the first 128 characters). A character literal in
Haskell has type 'Char'.
To convert a 'Char' to or from the corresponding 'Int' value defined
by Unicode, use 'Prelude.toEnum' and 'Prelude.fromEnum' from the
'Prelude.Enum' class respectively (or equivalently 'ord' and 'chr').
-}
data {-# CTYPE "HsChar" #-} Char = C# Char#
-- | A fixed-precision integer type with at least the range @[-2^29 .. 2^29-1]@.
-- The exact range for a given implementation can be determined by using
-- 'Prelude.minBound' and 'Prelude.maxBound' from the 'Prelude.Bounded' class.
data {-# CTYPE "HsInt" #-} Int = I# Int#
-- |A 'Word' is an unsigned integral type, with the same size as 'Int'.
data {-# CTYPE "HsWord" #-} Word = W# Word#
-- | Single-precision floating point numbers.
-- It is desirable that this type be at least equal in range and precision
-- to the IEEE single-precision type.
data {-# CTYPE "HsFloat" #-} Float = F# Float#
-- | Double-precision floating point numbers.
-- It is desirable that this type be at least equal in range and precision
-- to the IEEE double-precision type.
data {-# CTYPE "HsDouble" #-} Double = D# Double#
data Ordering = LT | EQ | GT
{- |
A value of type @'IO' a@ is a computation which, when performed,
does some I\/O before returning a value of type @a@.
There is really only one way to \"perform\" an I\/O action: bind it to
@Main.main@ in your program. When your program is run, the I\/O will
be performed. It isn't possible to perform I\/O from an arbitrary
function, unless that function is itself in the 'IO' monad and called
at some point, directly or indirectly, from @Main.main@.
'IO' is a monad, so 'IO' actions can be combined using either the do-notation
or the '>>' and '>>=' operations from the 'Monad' class.
-}
newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
type role IO representational
{-
The above role annotation is redundant but is included because this role
is significant in the normalisation of FFI types. Specifically, if this
role were to become nominal (which would be very strange, indeed!), changes
elsewhere in GHC would be necessary. See [FFI type roles] in TcForeign.
-}
{-
Note [Kind-changing of (~) and Coercible]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(~) and Coercible are tricky to define. To the user, they must appear as
constraints, but we cannot define them as such in Haskell. But we also cannot
just define them only in GHC.Prim (like (->)), because we need a real module
for them, e.g. to compile the constructor's info table.
Furthermore the type of MkCoercible cannot be written in Haskell
(no syntax for ~#R).
So we define them as regular data types in GHC.Types, and do magic in TysWiredIn,
inside GHC, to change the kind and type.
-}
-- | A data constructor used to box up all unlifted equalities
--
-- The type constructor is special in that GHC pretends that it
-- has kind (? -> ? -> Fact) rather than (* -> * -> *)
data (~) a b = Eq# ((~#) a b)
-- | This two-parameter class has instances for types @a@ and @b@ if
-- the compiler can infer that they have the same representation. This class
-- does not have regular instances; instead they are created on-the-fly during
-- type-checking. Trying to manually declare an instance of @Coercible@
-- is an error.
--
-- Nevertheless one can pretend that the following three kinds of instances
-- exist. First, as a trivial base-case:
--
-- @instance a a@
--
-- Furthermore, for every type constructor there is
-- an instance that allows to coerce under the type constructor. For
-- example, let @D@ be a prototypical type constructor (@data@ or
-- @newtype@) with three type arguments, which have roles @nominal@,
-- @representational@ resp. @phantom@. Then there is an instance of
-- the form
--
-- @instance Coercible b b\' => Coercible (D a b c) (D a b\' c\')@
--
-- Note that the @nominal@ type arguments are equal, the
-- @representational@ type arguments can differ, but need to have a
-- @Coercible@ instance themself, and the @phantom@ type arguments can be
-- changed arbitrarily.
--
-- The third kind of instance exists for every @newtype NT = MkNT T@ and
-- comes in two variants, namely
--
-- @instance Coercible a T => Coercible a NT@
--
-- @instance Coercible T b => Coercible NT b@
--
-- This instance is only usable if the constructor @MkNT@ is in scope.
--
-- If, as a library author of a type constructor like @Set a@, you
-- want to prevent a user of your module to write
-- @coerce :: Set T -> Set NT@,
-- you need to set the role of @Set@\'s type parameter to @nominal@,
-- by writing
--
-- @type role Set nominal@
--
-- For more details about this feature, please refer to
-- <http://www.cis.upenn.edu/~eir/papers/2014/coercible/coercible.pdf Safe Coercions>
-- by Joachim Breitner, Richard A. Eisenberg, Simon Peyton Jones and Stephanie Weirich.
--
-- @since 4.7.0.0
data Coercible a b = MkCoercible ((~#) a b)
-- It's really ~R# (representational equality), not ~#,
-- but * we don't yet have syntax for ~R#,
-- * the compiled code is the same either way
-- * TysWiredIn has the truthful types
-- Also see Note [Kind-changing of (~) and Coercible]
-- | Alias for 'tagToEnum#'. Returns True if its parameter is 1# and False
-- if it is 0#.
{-# INLINE isTrue# #-}
isTrue# :: Int# -> Bool -- See Note [Optimizing isTrue#]
isTrue# x = tagToEnum# x
-- Note [Optimizing isTrue#]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Current definition of isTrue# is a temporary workaround. We would like to
-- have functions isTrue# and isFalse# defined like this:
--
-- isTrue# :: Int# -> Bool
-- isTrue# 1# = True
-- isTrue# _ = False
--
-- isFalse# :: Int# -> Bool
-- isFalse# 0# = True
-- isFalse# _ = False
--
-- These functions would allow us to safely check if a tag can represent True
-- or False. Using isTrue# and isFalse# as defined above will not introduce
-- additional case into the code. When we scrutinize return value of isTrue#
-- or isFalse#, either explicitly in a case expression or implicitly in a guard,
-- the result will always be a single case expression (given that optimizations
-- are turned on). This results from case-of-case transformation. Consider this
-- code (this is both valid Haskell and Core):
--
-- case isTrue# (a ># b) of
-- True -> e1
-- False -> e2
--
-- Inlining isTrue# gives:
--
-- case (case (a ># b) of { 1# -> True; _ -> False } ) of
-- True -> e1
-- False -> e2
--
-- Case-of-case transforms that to:
--
-- case (a ># b) of
-- 1# -> case True of
-- True -> e1
-- False -> e2
-- _ -> case False of
-- True -> e1
-- False -> e2
--
-- Which is then simplified by case-of-known-constructor:
--
-- case (a ># b) of
-- 1# -> e1
-- _ -> e2
--
-- While we get good Core here, the code generator will generate very bad Cmm
-- if e1 or e2 do allocation. It will push heap checks into case alternatives
-- which results in about 2.5% increase in code size. Until this is improved we
-- just make isTrue# an alias to tagToEnum#. This is a temporary solution (if
-- you're reading this in 2023 then things went wrong). See #8326.
--
-- | 'SPEC' is used by GHC in the @SpecConstr@ pass in order to inform
-- the compiler when to be particularly aggressive. In particular, it
-- tells GHC to specialize regardless of size or the number of
-- specializations. However, not all loops fall into this category.
--
-- Libraries can specify this by using 'SPEC' data type to inform which
-- loops should be aggressively specialized.
data SPEC = SPEC | SPEC2
-- The Java Monad
newtype Java c a = Java (Object# c -> (# Object# c, a #))
type role Java nominal representational
data {-# CLASS "java.lang.Object" #-} Object = O# (Object# Object)
data {-# CLASS "java.lang.String" #-} JString = JS# (Object# JString)
data {-# CLASS "java.lang.CharSequence" #-} CharSequence = CS# (Object# CharSequence)
data {-# CLASS "java.lang.Comparable" #-} Comparable t = CT# (Object# (Comparable t))
| pparkkin/eta | libraries/ghc-prim/GHC/Types.hs | bsd-3-clause | 9,522 | 4 | 10 | 1,993 | 596 | 421 | 175 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Stack.Init
( initProject
, InitOpts (..)
) where
import Control.Exception (assert)
import Control.Exception.Safe (catchAny)
import Control.Monad
import Control.Monad.Catch (throwM)
import Control.Monad.IO.Class
import Control.Monad.Logger
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as L
import qualified Data.Foldable as F
import Data.Function (on)
import qualified Data.HashMap.Strict as HM
import qualified Data.IntMap as IntMap
import Data.List (intercalate, intersect,
maximumBy)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Yaml as Yaml
import qualified Distribution.PackageDescription as C
import qualified Distribution.Text as C
import qualified Distribution.Version as C
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import qualified Paths_stack as Meta
import Stack.BuildPlan
import Stack.Config (getSnapshots,
makeConcreteResolver)
import Stack.Constants
import Stack.Solver
import Stack.Types.Build
import Stack.Types.BuildPlan
import Stack.Types.Config
import Stack.Types.FlagName
import Stack.Types.PackageName
import Stack.Types.Resolver
import Stack.Types.StackT (StackM)
import Stack.Types.Version
import qualified System.FilePath as FP
-- | Generate stack.yaml
initProject
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs Dir
-> InitOpts
-> Maybe AbstractResolver
-> m ()
initProject whichCmd currDir initOpts mresolver = do
let dest = currDir </> stackDotYaml
reldest <- toFilePath `liftM` makeRelativeToCurrentDir dest
exists <- doesFileExist dest
when (not (forceOverwrite initOpts) && exists) $ do
error ("Stack configuration file " <> reldest <>
" exists, use 'stack solver' to fix the existing config file or \
\'--force' to overwrite it.")
dirs <- mapM (resolveDir' . T.unpack) (searchDirs initOpts)
let noPkgMsg = "In order to init, you should have an existing .cabal \
\file. Please try \"stack new\" instead."
find = findCabalFiles (includeSubDirs initOpts)
dirs' = if null dirs then [currDir] else dirs
$logInfo "Looking for .cabal or package.yaml files to use to init the project."
cabalfps <- liftM concat $ mapM find dirs'
(bundle, dupPkgs) <- cabalPackagesCheck cabalfps noPkgMsg Nothing
(r, flags, extraDeps, rbundle) <- getDefaultResolver whichCmd dest initOpts
mresolver bundle
let ignored = Map.difference bundle rbundle
dupPkgMsg
| dupPkgs /= [] =
"Warning (added by new or init): Some packages were found to \
\have names conflicting with others and have been commented \
\out in the packages section.\n"
| otherwise = ""
missingPkgMsg
| Map.size ignored > 0 =
"Warning (added by new or init): Some packages were found to \
\be incompatible with the resolver and have been left commented \
\out in the packages section.\n"
| otherwise = ""
extraDepMsg
| Map.size extraDeps > 0 =
"Warning (added by new or init): Specified resolver could not \
\satisfy all dependencies. Some external packages have been \
\added as dependencies.\n"
| otherwise = ""
makeUserMsg msgs =
let msg = concat msgs
in if msg /= "" then
msg <> "You can suppress this message by removing it from \
\stack.yaml\n"
else ""
userMsg = makeUserMsg [dupPkgMsg, missingPkgMsg, extraDepMsg]
gpds = Map.elems $ fmap snd rbundle
p = Project
{ projectUserMsg = if userMsg == "" then Nothing else Just userMsg
, projectPackages = pkgs
, projectExtraDeps = extraDeps
, projectFlags = PackageFlags (removeSrcPkgDefaultFlags gpds flags)
, projectResolver = r
, projectCompiler = Nothing
, projectExtraPackageDBs = []
}
makeRelDir dir =
case stripDir currDir dir of
Nothing
| currDir == dir -> "."
| otherwise -> assert False $ toFilePathNoTrailingSep dir
Just rel -> toFilePathNoTrailingSep rel
makeRel = fmap toFilePath . makeRelativeToCurrentDir
pkgs = map toPkg $ Map.elems (fmap (parent . fst) rbundle)
toPkg dir = PackageEntry
{ peExtraDepMaybe = Nothing
, peLocation = PLFilePath $ makeRelDir dir
, peSubdirs = []
}
indent t = T.unlines $ fmap (" " <>) (T.lines t)
$logInfo $ "Initialising configuration using resolver: " <> resolverName r
$logInfo $ "Total number of user packages considered: "
<> T.pack (show (Map.size bundle + length dupPkgs))
when (dupPkgs /= []) $ do
$logWarn $ "Warning! Ignoring "
<> T.pack (show $ length dupPkgs)
<> " duplicate packages:"
rels <- mapM makeRel dupPkgs
$logWarn $ indent $ showItems rels
when (Map.size ignored > 0) $ do
$logWarn $ "Warning! Ignoring "
<> T.pack (show $ Map.size ignored)
<> " packages due to dependency conflicts:"
rels <- mapM makeRel (Map.elems (fmap fst ignored))
$logWarn $ indent $ showItems rels
when (Map.size extraDeps > 0) $ do
$logWarn $ "Warning! " <> T.pack (show $ Map.size extraDeps)
<> " external dependencies were added."
$logInfo $
(if exists then "Overwriting existing configuration file: "
else "Writing configuration to file: ")
<> T.pack reldest
liftIO $ L.writeFile (toFilePath dest)
$ B.toLazyByteString
$ renderStackYaml p
(Map.elems $ fmap (makeRelDir . parent . fst) ignored)
(map (makeRelDir . parent) dupPkgs)
$logInfo "All done."
-- | Render a stack.yaml file with comments, see:
-- https://github.com/commercialhaskell/stack/issues/226
renderStackYaml :: Project -> [FilePath] -> [FilePath] -> B.Builder
renderStackYaml p ignoredPackages dupPackages =
case Yaml.toJSON p of
Yaml.Object o -> renderObject o
_ -> assert False $ B.byteString $ Yaml.encode p
where
renderObject o =
B.byteString headerHelp
<> B.byteString "\n\n"
<> F.foldMap (goComment o) comments
<> goOthers (o `HM.difference` HM.fromList comments)
<> B.byteString footerHelp
goComment o (name, comment) =
case HM.lookup name o of
Nothing -> assert (name == "user-message") mempty
Just v ->
B.byteString comment <>
B.byteString "\n" <>
B.byteString (Yaml.encode $ Yaml.object [(name, v)]) <>
if name == "packages" then commentedPackages else "" <>
B.byteString "\n"
commentLine l | null l = "#"
| otherwise = "# " ++ l
commentHelp = BC.pack . intercalate "\n" . map commentLine
commentedPackages =
let ignoredComment = commentHelp
[ "The following packages have been ignored due to incompatibility with the"
, "resolver compiler, dependency conflicts with other packages"
, "or unsatisfied dependencies."
]
dupComment = commentHelp
[ "The following packages have been ignored due to package name conflict "
, "with other packages."
]
in commentPackages ignoredComment ignoredPackages
<> commentPackages dupComment dupPackages
commentPackages comment pkgs
| pkgs /= [] =
B.byteString comment
<> B.byteString "\n"
<> B.byteString (BC.pack $ concat
$ map (\x -> "#- " ++ x ++ "\n") pkgs ++ ["\n"])
| otherwise = ""
goOthers o
| HM.null o = mempty
| otherwise = assert False $ B.byteString $ Yaml.encode o
-- Per Section Help
comments =
[ ("user-message" , userMsgHelp)
, ("resolver" , resolverHelp)
, ("packages" , packageHelp)
, ("extra-deps" , "# Dependency packages to be pulled from upstream that are not in the resolver\n# (e.g., acme-missiles-0.3)")
, ("flags" , "# Override default flag values for local packages and extra-deps")
, ("extra-package-dbs", "# Extra package databases containing global packages")
]
-- Help strings
headerHelp = commentHelp
[ "This file was automatically generated by 'stack init'"
, ""
, "Some commonly used options have been documented as comments in this file."
, "For advanced use and comprehensive documentation of the format, please see:"
, "http://docs.haskellstack.org/en/stable/yaml_configuration/"
]
resolverHelp = commentHelp
[ "Resolver to choose a 'specific' stackage snapshot or a compiler version."
, "A snapshot resolver dictates the compiler version and the set of packages"
, "to be used for project dependencies. For example:"
, ""
, "resolver: lts-3.5"
, "resolver: nightly-2015-09-21"
, "resolver: ghc-7.10.2"
, "resolver: ghcjs-0.1.0_ghc-7.10.2"
, "resolver:"
, " name: custom-snapshot"
, " location: \"./custom-snapshot.yaml\""
]
userMsgHelp = commentHelp
[ "A warning or info to be displayed to the user on config load." ]
packageHelp = commentHelp
[ "User packages to be built."
, "Various formats can be used as shown in the example below."
, ""
, "packages:"
, "- some-directory"
, "- https://example.com/foo/bar/baz-0.0.2.tar.gz"
, "- location:"
, " git: https://github.com/commercialhaskell/stack.git"
, " commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a"
, "- location: https://github.com/commercialhaskell/stack/commit/e7b331f14bcffb8367cd58fbfc8b40ec7642100a"
, " extra-dep: true"
, " subdirs:"
, " - auto-update"
, " - wai"
, ""
, "A package marked 'extra-dep: true' will only be built if demanded by a"
, "non-dependency (i.e. a user package), and its test suites and benchmarks"
, "will not be run. This is useful for tweaking upstream packages."
]
footerHelp =
let major = toCabalVersion
$ toMajorVersion $ fromCabalVersion Meta.version
in commentHelp
[ "Control whether we use the GHC we find on the path"
, "system-ghc: true"
, ""
, "Require a specific version of stack, using version ranges"
, "require-stack-version: -any # Default"
, "require-stack-version: \""
++ C.display (C.orLaterVersion major) ++ "\""
, ""
, "Override the architecture used by stack, especially useful on Windows"
, "arch: i386"
, "arch: x86_64"
, ""
, "Extra directories used by stack for building"
, "extra-include-dirs: [/path/to/dir]"
, "extra-lib-dirs: [/path/to/dir]"
, ""
, "Allow a newer minor version of GHC than the snapshot specifies"
, "compiler-check: newer-minor"
]
getSnapshots' :: (StackM env m, HasConfig env)
=> m Snapshots
getSnapshots' =
getSnapshots `catchAny` \e -> do
$logError $
"Unable to download snapshot list, and therefore could " <>
"not generate a stack.yaml file automatically"
$logError $
"This sometimes happens due to missing Certificate Authorities " <>
"on your system. For more information, see:"
$logError ""
$logError " https://github.com/commercialhaskell/stack/issues/234"
$logError ""
$logError "You can try again, or create your stack.yaml file by hand. See:"
$logError ""
$logError " http://docs.haskellstack.org/en/stable/yaml_configuration/"
$logError ""
$logError $ "Exception was: " <> T.pack (show e)
error ""
-- | Get the default resolver value
getDefaultResolver
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs File -- ^ stack.yaml
-> InitOpts
-> Maybe AbstractResolver
-> Map PackageName (Path Abs File, C.GenericPackageDescription)
-- ^ Src package name: cabal dir, cabal package description
-> m ( Resolver
, Map PackageName (Map FlagName Bool)
, Map PackageName Version
, Map PackageName (Path Abs File, C.GenericPackageDescription))
-- ^ ( Resolver
-- , Flags for src packages and extra deps
-- , Extra dependencies
-- , Src packages actually considered)
getDefaultResolver whichCmd stackYaml initOpts mresolver bundle =
maybe selectSnapResolver makeConcreteResolver mresolver
>>= getWorkingResolverPlan whichCmd stackYaml initOpts bundle
where
-- TODO support selecting best across regular and custom snapshots
selectSnapResolver = do
let gpds = Map.elems (fmap snd bundle)
snaps <- fmap getRecommendedSnapshots getSnapshots'
(s, r) <- selectBestSnapshot gpds snaps
case r of
BuildPlanCheckFail {} | not (omitPackages initOpts)
-> throwM (NoMatchingSnapshot whichCmd snaps)
_ -> return $ ResolverSnapshot s
getWorkingResolverPlan
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs File -- ^ stack.yaml
-> InitOpts
-> Map PackageName (Path Abs File, C.GenericPackageDescription)
-- ^ Src package name: cabal dir, cabal package description
-> Resolver
-> m ( Resolver
, Map PackageName (Map FlagName Bool)
, Map PackageName Version
, Map PackageName (Path Abs File, C.GenericPackageDescription))
-- ^ ( Resolver
-- , Flags for src packages and extra deps
-- , Extra dependencies
-- , Src packages actually considered)
getWorkingResolverPlan whichCmd stackYaml initOpts bundle resolver = do
$logInfo $ "Selected resolver: " <> resolverName resolver
go bundle
where
go info = do
eres <- checkBundleResolver whichCmd stackYaml initOpts info resolver
-- if some packages failed try again using the rest
case eres of
Right (f, edeps)-> return (resolver, f, edeps, info)
Left ignored
| Map.null available -> do
$logWarn "*** Could not find a working plan for any of \
\the user packages.\nProceeding to create a \
\config anyway."
return (resolver, Map.empty, Map.empty, Map.empty)
| otherwise -> do
when (Map.size available == Map.size info) $
error "Bug: No packages to ignore"
if length ignored > 1 then do
$logWarn "*** Ignoring packages:"
$logWarn $ indent $ showItems ignored
else
$logWarn $ "*** Ignoring package: "
<> T.pack (packageNameString (head ignored))
go available
where
indent t = T.unlines $ fmap (" " <>) (T.lines t)
isAvailable k _ = k `notElem` ignored
available = Map.filterWithKey isAvailable info
checkBundleResolver
:: (StackM env m, HasConfig env, HasGHCVariant env)
=> WhichSolverCmd
-> Path Abs File -- ^ stack.yaml
-> InitOpts
-> Map PackageName (Path Abs File, C.GenericPackageDescription)
-- ^ Src package name: cabal dir, cabal package description
-> Resolver
-> m (Either [PackageName] ( Map PackageName (Map FlagName Bool)
, Map PackageName Version))
checkBundleResolver whichCmd stackYaml initOpts bundle resolver = do
result <- checkResolverSpec gpds Nothing resolver
case result of
BuildPlanCheckOk f -> return $ Right (f, Map.empty)
BuildPlanCheckPartial f e
| needSolver resolver initOpts -> do
warnPartial result
solve f
| omitPackages initOpts -> do
warnPartial result
$logWarn "*** Omitting packages with unsatisfied dependencies"
return $ Left $ failedUserPkgs e
| otherwise -> throwM $ ResolverPartial whichCmd resolver (show result)
BuildPlanCheckFail _ e _
| omitPackages initOpts -> do
$logWarn $ "*** Resolver compiler mismatch: "
<> resolverName resolver
$logWarn $ indent $ T.pack $ show result
return $ Left $ failedUserPkgs e
| otherwise -> throwM $ ResolverMismatch whichCmd resolver (show result)
where
indent t = T.unlines $ fmap (" " <>) (T.lines t)
warnPartial res = do
$logWarn $ "*** Resolver " <> resolverName resolver
<> " will need external packages: "
$logWarn $ indent $ T.pack $ show res
failedUserPkgs e = Map.keys $ Map.unions (Map.elems (fmap deNeededBy e))
gpds = Map.elems (fmap snd bundle)
solve flags = do
let cabalDirs = map parent (Map.elems (fmap fst bundle))
srcConstraints = mergeConstraints (gpdPackages gpds) flags
eresult <- solveResolverSpec stackYaml cabalDirs
(resolver, srcConstraints, Map.empty)
case eresult of
Right (src, ext) ->
return $ Right (fmap snd (Map.union src ext), fmap fst ext)
Left packages
| omitPackages initOpts, srcpkgs /= []-> do
pkg <- findOneIndependent srcpkgs flags
return $ Left [pkg]
| otherwise -> throwM (SolverGiveUp giveUpMsg)
where srcpkgs = Map.keys bundle `intersect` packages
-- among a list of packages find one on which none among the rest of the
-- packages depend. This package is a good candidate to be removed from
-- the list of packages when there is conflict in dependencies among this
-- set of packages.
findOneIndependent packages flags = do
platform <- view platformL
(compiler, _) <- getResolverConstraints stackYaml resolver
let getGpd pkg = snd (fromJust (Map.lookup pkg bundle))
getFlags pkg = fromJust (Map.lookup pkg flags)
deps pkg = gpdPackageDeps (getGpd pkg) compiler platform
(getFlags pkg)
allDeps = concatMap (Map.keys . deps) packages
isIndependent pkg = pkg `notElem` allDeps
-- prefer to reject packages in deeper directories
path pkg = fst (fromJust (Map.lookup pkg bundle))
pathlen = length . FP.splitPath . toFilePath . path
maxPathlen = maximumBy (compare `on` pathlen)
return $ maxPathlen (filter isIndependent packages)
giveUpMsg = concat
[ " - Use '--omit-packages to exclude conflicting package(s).\n"
, " - Tweak the generated "
, toFilePath stackDotYaml <> " and then run 'stack solver':\n"
, " - Add any missing remote packages.\n"
, " - Add extra dependencies to guide solver.\n"
, " - Update external packages with 'stack update' and try again.\n"
]
needSolver _ InitOpts {useSolver = True} = True
needSolver (ResolverCompiler _) _ = True
needSolver _ _ = False
getRecommendedSnapshots :: Snapshots -> NonEmpty SnapName
getRecommendedSnapshots snapshots =
-- in order - Latest LTS, Latest Nightly, all LTS most recent first
case NonEmpty.nonEmpty ltss of
Just (mostRecent :| older)
-> mostRecent :| (nightly : older)
Nothing
-> nightly :| []
where
ltss = map (uncurry LTS) (IntMap.toDescList $ snapshotsLts snapshots)
nightly = Nightly (snapshotsNightly snapshots)
data InitOpts = InitOpts
{ searchDirs :: ![T.Text]
-- ^ List of sub directories to search for .cabal files
, useSolver :: Bool
-- ^ Use solver to determine required external dependencies
, omitPackages :: Bool
-- ^ Exclude conflicting or incompatible user packages
, forceOverwrite :: Bool
-- ^ Overwrite existing stack.yaml
, includeSubDirs :: Bool
-- ^ If True, include all .cabal files found in any sub directories
}
| deech/stack | src/Stack/Init.hs | bsd-3-clause | 22,455 | 0 | 21 | 7,722 | 4,392 | 2,240 | 2,152 | 420 | 6 |
{-# LANGUAGE TemplateHaskell #-}
module LibC
( someFuncC
) where
import THInSubdir
import Language.Haskell.TH
someFuncC :: IO ()
someFuncC = print $(thFuncC)
| mrkkrp/stack | test/integration/tests/717-sdist-test/files/subdirs/failing-in-subdir/src/LibC.hs | bsd-3-clause | 168 | 0 | 7 | 32 | 41 | 24 | 17 | 7 | 1 |
module A where
import D
import C
import B
main :: Tree Int ->Bool
main t = isSame (sumSquares (fringe t))
(sumSquares (B.myFringe t)+sumSquares (C.myFringe t))
| SAdams601/HaRe | old/testing/moveDefBtwMods/A_TokOut.hs | bsd-3-clause | 189 | 0 | 11 | 55 | 79 | 41 | 38 | 7 | 1 |
-- | A histogram with a uniform reservoir produces quantiles which are valid for the entirely of the histogram’s lifetime.
-- It will return a median value, for example, which is the median of all the values the histogram has ever been updated with.
-- It does this by using an algorithm called Vitter’s R), which randomly selects values for the reservoir with linearly-decreasing probability.
--
-- Use a uniform histogram when you’re interested in long-term measurements.
-- Don’t use one where you’d want to know if the distribution of the underlying data stream has changed recently.
module Data.Metrics.Reservoir.Uniform (
UniformReservoir,
reservoir,
unsafeReservoir,
clear,
unsafeClear,
size,
snapshot,
update,
unsafeUpdate
) where
import Control.Monad.ST
import Data.Metrics.Internal
import Data.Time.Clock
import qualified Data.Metrics.Reservoir as R
import qualified Data.Metrics.Snapshot as S
import Data.Primitive.MutVar
import System.Random.MWC
import qualified Data.Vector.Unboxed as I
import qualified Data.Vector.Unboxed.Mutable as V
-- | Make a safe uniform reservoir. This variant provides safe access at the expense of updates costing O(n)
reservoir :: Seed
-> Int -- ^ maximum reservoir size
-> R.Reservoir
reservoir g r = R.Reservoir
{ R._reservoirClear = clear
, R._reservoirSize = size
, R._reservoirSnapshot = snapshot
, R._reservoirUpdate = update
, R._reservoirState = UniformReservoir 0 (I.replicate r 0) g
}
-- | Using this variant requires that you ensure that there is no sharing of the reservoir itself.
--
-- In other words, there must only be a single point of access (an IORef, etc. that accepts some sort of modification function).
--
-- In return, updating the reservoir becomes an O(1) operation and clearing the reservoir avoids extra allocations.
unsafeReservoir :: Seed -> Int -> R.Reservoir
unsafeReservoir g r = R.Reservoir
{ R._reservoirClear = unsafeClear
, R._reservoirSize = size
, R._reservoirSnapshot = snapshot
, R._reservoirUpdate = unsafeUpdate
, R._reservoirState = UniformReservoir 0 (I.replicate r 0) g
}
-- | A reservoir in which all samples are equally likely to be evicted when the reservoir is at full capacity.
--
-- This is conceptually simpler than the "ExponentiallyDecayingReservoir", but at the expense of providing a less accurate sample.
data UniformReservoir = UniformReservoir
{ _urCount :: !Int
, _urReservoir :: !(I.Vector Double)
, _urSeed :: !Seed
}
-- | Reset the reservoir to empty.
clear :: NominalDiffTime -> UniformReservoir -> UniformReservoir
clear = go
where
go _ c = c { _urCount = 0, _urReservoir = newRes $ _urReservoir c }
newRes v = runST $ do
v' <- I.thaw v
V.set v' 0
I.unsafeFreeze v'
-- | Reset the reservoir to empty by performing an in-place modification of the reservoir.
unsafeClear :: NominalDiffTime -> UniformReservoir -> UniformReservoir
unsafeClear = go
where
go _ c = c { _urCount = 0, _urReservoir = newRes $ _urReservoir c }
newRes v = runST $ do
v' <- I.unsafeThaw v
V.set v' 0
I.unsafeFreeze v'
-- | Get the current size of the reservoir
size :: UniformReservoir -> Int
size = go
where
go c = min (_urCount c) (I.length $ _urReservoir c)
-- | Take a snapshot of the reservoir by doing an in-place unfreeze.
--
-- This should be safe as long as unsafe operations are performed appropriately.
snapshot :: UniformReservoir -> S.Snapshot
snapshot = go
where
go c = runST $ do
v' <- I.unsafeThaw $ _urReservoir c
S.takeSnapshot $ V.slice 0 (size c) v'
-- | Perform an update of the reservoir by copying the internal vector. O(n)
update :: Double -> NominalDiffTime -> UniformReservoir -> UniformReservoir
update = go
where
go x _ c = c { _urCount = newCount, _urReservoir = newRes, _urSeed = newSeed }
where
newCount = succ $ _urCount c
(newSeed, newRes) = runST $ do
v' <- I.thaw $ _urReservoir c
g <- restore (_urSeed c)
if newCount <= V.length v'
then V.unsafeWrite v' (_urCount c) x
else do
i <- uniformR (0, newCount) g
if i < V.length v'
then V.unsafeWrite v' i x
else return ()
v'' <- I.unsafeFreeze v'
s <- save g
return (s, v'')
-- | Perform an in-place update of the reservoir. O(1)
unsafeUpdate :: Double -> NominalDiffTime -> UniformReservoir -> UniformReservoir
unsafeUpdate = go
where
go x _ c = c { _urCount = newCount, _urReservoir = newRes, _urSeed = newSeed }
where
newCount = succ $ _urCount c
(newSeed, newRes) = runST $ do
v' <- I.unsafeThaw $ _urReservoir c
g <- restore (_urSeed c)
if newCount <= V.length v'
then V.unsafeWrite v' (_urCount c) x
else do
i <- uniformR (0, newCount) g
if i < V.length v'
then V.unsafeWrite v' i x
else return ()
v'' <- I.unsafeFreeze v'
s <- save g
return (s, v'')
| graydon/metrics | src/Data/Metrics/Reservoir/Uniform.hs | mit | 5,115 | 0 | 18 | 1,253 | 1,119 | 603 | 516 | 101 | 3 |
module Maior
( exec
, maior
) where
maior [] = error "maximum of empty list"
maior [x] = x
maior (x:xs)
| x > aux = x
| otherwise = aux
where aux = maior xs
-- fiz uma classe em python, para gerar uma lista
-- so precisa retirar a ultima virgula
exec = do
print (maior [415, 753, 480, 367, 492, 326, 603])
print (maior [ 827, 657, 727, 702, 388, 984, 904])
| tonussi/freezing-dubstep | pratica-04/Maior.hs | mit | 370 | 0 | 10 | 89 | 153 | 84 | 69 | 12 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
module Data.FreeAgent.Generate where
import Control.Arrow (second, (***))
import Control.Monad (forM)
import Control.Monad.Trans.State
import Data.Aeson hiding (fromJSON)
import Data.Char (toUpper)
import Data.Data
import Data.Function (on)
import qualified Data.HashMap.Strict as HMS
import Data.List (intersperse, nubBy)
import Data.List.Split
import Data.Maybe (catMaybes)
import Data.Monoid
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Vector as V
import System.FilePath
type Key = T.Text
type FieldRep = T.Text
type ModuleName = String
data DataDecl val = DD {
dataName :: T.Text
, fields :: [(Key, val)]
}
| Col {
colName :: T.Text
, colType :: val
}
deriving (Eq, Data, Typeable)
type FieldLookup a = HMS.HashMap [Key] (DataDecl a)
data ApiParseState a = APS {
resolved :: [DataDecl a]
, subObjects :: FieldLookup a
}
data ModuleCtx = ModuleCtx {
modName :: ModuleName
, declNames :: [String]
, dataDecls :: [String]
, fromJSONs :: [String]
} deriving (Data, Typeable)
type ApiState = StateT (ApiParseState Value) IO
type ResolvedState = StateT (ApiParseState T.Text) IO
initParseState :: ApiParseState a
initParseState = APS [] HMS.empty
dataDeclToText :: DataDecl T.Text -> T.Text
dataDeclToText (DD name fields) = T.unlines $ [nameLine, fieldLines, derivingLine]
where
nameLine = T.unwords ["data", name, "=", name, "{"]
fields' = map ((T.cons '_') *** id) fields
maxLen = maximum . map T.length
fMax = 1 + maxLen [f | (f, _) <- fields]
fieldLines = T.unlines . map fieldToLine $ zip [(0 :: Int)..] fields'
fieldToLine (0, (fname, ftype)) = T.unwords [" ", T.justifyLeft fMax ' ' fname, "::", ftype]
fieldToLine (_, (fname, ftype)) = T.unwords [" ,", T.justifyLeft fMax ' ' fname, "::", ftype]
derivingLine = "} deriving (Show, Data, Typeable)"
dataDeclToText (Col name val) = T.unwords ["type", name, "=", val]
dataDeclDeriveToJSON :: DataDecl T.Text -> T.Text
dataDeclDeriveToJSON (DD name fields) = T.unlines $ [
instanceLine
, parseJSONObj
, ddFields
, parseJSON_
]
where
instanceLine = T.unwords ["instance FromJSON", name, "where"]
parseJSONObj = T.unwords [" parseJSON (Object v) =", name, "<$>"]
fields' = reverse [fname | (fname, _) <- fields]
fieldWhiteSpace = T.length " parseJSON (Object v) = "
ddFields = T.unlines . map fieldToLine . reverse $ zip [(0 :: Int)..] fields'
fieldToLine (0, fname) = T.unwords [T.justifyRight fieldWhiteSpace ' ' "v .:", quotedField fname]
fieldToLine (_, fname) = T.unwords [T.justifyRight fieldWhiteSpace ' ' "v .:", quotedField fname, "<*>"]
quotedField fname = "\"" <> fname <> "\""
parseJSON_ = " parseJSON _ = empty"
dataDeclDeriveToJSON _ = T.empty
instance Show (DataDecl T.Text) where
show = T.unpack . dataDeclToText
instance Show (DataDecl Value) where
show (DD name fields) = unwords ["DD :", T.unpack name, (show $ map fst fields)]
show (Col name _) = "Col : " ++ T.unpack name
-- | Make a @DataDecl from a name and an Aeson @Value@
parseData :: Key -> Value -> ApiState ()
parseData name (Object o) = do
(APS resolved subs) <- get
let dd = DD name fields
put $ APS (dd `cons` resolved) (HMS.insert fieldNames dd subs)
_ <- HMS.traverseWithKey extract o
return ()
where
fields = HMS.toList o
fieldNames = HMS.keys o
extract k v = parseData (toCamelCase k) v
parseData name arr@(Array a) = do
_ <- V.forM a $ \obj ->
parseData (toCamelCase $ unpluralize name) obj
(APS resolved subs) <- get
let col = Col name arr
put $ APS (col `cons` resolved) subs
return ()
where unpluralize txt = if T.last txt == 's'
then T.init txt
else txt
parseData _ _ = return ()
-- | Extract from a top level @Object@
-- For each key in the @Object@ call @parseData@
parseTopLevel :: Value -> ApiState () -- (HMS.HashMap T.Text (Maybe (DataDecl Value)))
parseTopLevel (Object o) = do
_ <- HMS.traverseWithKey extract o
return ()
where
extract k v = parseData (toCamelCase k) v
parseTopLevel _ = return ()
-- | Get the @T.Text@ name for a field's type.
--
-- Resolves the name from the state built up by @parseData@ and @parseTopLevel@
resolveField :: FieldLookup Value -> Value -> FieldRep
resolveField _ (String s) = T.unwords ["BS.ByteString", "--", s]
resolveField subs (Array arr) =
case catMaybes $ V.toList possibles of
(DD name _):_ -> T.unwords ["[", name, "]"]
_ -> "[UNKNOWN]"
where
possibles = V.map (lookup subs) arr
lookup hm (Object o) = HMS.lookup (HMS.keys o) hm
lookup _ _ = Nothing
resolveField subs (Object obj) =
case HMS.lookup (HMS.keys obj) subs of
Just (DD name _) -> name
_ -> "UNKNOWN"
resolveField _ (Number _) = "Double"
resolveField _ (Bool _) = "Bool"
resolveField _ Null = "Maybe a"
-- | Convert an @ApiParseState@ of @Value@s to a list of printable @DataDecl@s
resolveDependencies :: Monad m => ApiParseState Value -> m [DataDecl FieldRep]
resolveDependencies (APS valDecls subs) = do
forM (nubBy nameEq valDecls) $ \dataDecl ->
return $ convertFieldType subs dataDecl
where nameEq = (==) `on` getName
convertFieldType :: FieldLookup Value -> DataDecl Value -> DataDecl FieldRep
convertFieldType subs (DD name fields) = DD name strFields
where
strFields = map (second $ resolveField subs) fields
convertFieldType subs (Col name val) = Col name $ resolveField subs val
-- UTILS
getName :: DataDecl t -> T.Text
getName (DD name _) = name
getName (Col name _) = name
toCamelCase :: T.Text -> T.Text
toCamelCase = T.concat . map capFirst . T.splitOn "_"
where capFirst word = (toUpper $ T.head word) `T.cons` T.tail word
toKeySet :: [(Key, FieldRep)] -> [Key]
toKeySet fields = S.toList . S.fromList $ map fst fields
cons :: (Eq a) => a -> [a] -> [a]
cons a as = case a `elem` as of
True -> as
False -> a:as
join :: [a] -> [[a]] -> [a]
join delim l = concat (intersperse delim l)
sepModule :: ModuleName -> [String]
sepModule = splitOneOf "."
splitUrl :: FilePath -> [FilePath]
splitUrl = splitDirectories
addHs :: FilePath -> FilePath
addHs = flip replaceExtension $ "hs"
docLinkToModuleName :: FilePath -> FilePath -> ModuleName
docLinkToModuleName prefix link = join "." $ prefix:linkElems
where camelize = T.unpack . toCamelCase . T.pack
linkElems = drop 1 . map camelize $ splitUrl link
moduleToFileName :: ModuleName -> FilePath
moduleToFileName = addHs . joinPath . sepModule
dataDeclsToContext :: ModuleName -> [DataDecl T.Text] -> ModuleCtx
dataDeclsToContext modName decls = ModuleCtx {
modName = modName
, declNames = (map (T.unpack . getName) . filter isData $ decls)
, dataDecls = (map (T.unpack . dataDeclToText) decls)
, fromJSONs = (map (T.unpack . dataDeclDeriveToJSON) decls)
}
where isData (DD _ _) = True
isData (Col _ _) = False
| perurbis/hfreeagent | fa-gen-types/Data/FreeAgent/Generate.hs | mit | 8,214 | 0 | 13 | 2,586 | 2,546 | 1,355 | 1,191 | 163 | 4 |
{-# htermination negate :: (Ratio Int) -> (Ratio Int) #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_negate_4.hs | mit | 58 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Initialisation where
import CountedQueue (CountedQueue, writeQueue)
import Crawl
import Directions
import Shared
import Types
import Urls
import Control.Concurrent.STM (atomically, writeTVar)
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.List (groupBy, partition, union)
import Data.List.Split (splitOn)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import Network.URI (unEscapeString)
import Safe
import qualified StmContainers.Set as S
import Text.Read (readMaybe)
newtype OptionFlag = OptionFlag String deriving (Show, Eq, Ord)
newtype OptionMap = OptionMap (M.Map OptionFlag [String]) deriving Show
optionMapFromArgs :: [String] -> OptionMap
optionMapFromArgs = OptionMap
<$> M.unionsWith union
. mapMaybe (\gr -> M.singleton <$> (OptionFlag <$> headMay gr) <*> tailMay gr)
. filter (maybe False isFlag . headMay)
. groupBy (\a b -> isFlag a /= isFlag b)
where
isFlag x = length x > 1 && head x == '-'
initialiseSettings :: CountedQueue bq => Crawler bq -> [String] -> (Loggable -> IO ()) -> IO ()
initialiseSettings crawler args logFunc = do
let optionMap = optionMapFromArgs args
initialiseStorage (getCrawlerSettings crawler) optionMap
initialiseFormInstructions (getCrawlerSettings crawler) optionMap
initialiseHrefDirections (getCrawlerSettings crawler) optionMap
initialiseProxy (getCrawlerSettings crawler) optionMap
initialiseCrawlLimit (getCrawlerSettings crawler) optionMap
initialiseIncludes optionMap
initialiseStartUrls optionMap
where
initialiseStorage :: CrawlerSettings -> OptionMap -> IO ()
initialiseStorage crawlerSettings (OptionMap optionMap) =
case M.lookup (OptionFlag "-wf") optionMap of
Nothing -> return ()
Just [warcFile] -> do
atomically $ writeTVar (getCrawlOutputType crawlerSettings) (Just (WarcFile warcFile))
logFunc . GeneralMessage . C8.pack . concat $ ["Writing output to: ", warcFile, "\n"]
initialiseCrawlLimit crawlerSettings (OptionMap optionMap) =
atomically . writeTVar (getCrawlLimit crawlerSettings) $
M.lookup (OptionFlag "-l") optionMap >>= headMay >>= readMay
initialiseIncludes :: OptionMap -> IO ()
initialiseIncludes (OptionMap optionMap) = do
case M.lookup (OptionFlag "-i") optionMap of
Nothing -> return ()
Just strIncludePatterns -> do
let includes = concatMap (splitOn ",") strIncludePatterns
insertIncludes (getUrlIncludePatterns crawler) (map C8.pack includes)
case M.lookup (OptionFlag "-if") optionMap of
Nothing -> return ()
Just includeFiles -> do
files <- mapM C8.readFile includeFiles
insertIncludes (getUrlIncludePatterns crawler) . map trim . filter (not . C8.null) . concatMap C8.lines $ files
case M.lookup (OptionFlag "-d") optionMap of
Nothing -> return ()
Just strDomainIncludePatterns -> do
let domainIncludes = concatMap (splitOn ",") strDomainIncludePatterns
insertIncludes (getDomainIncludePatterns crawler) (map C8.pack domainIncludes)
where
insertIncludes patterns =
mapM_ (\i -> do
atomically $ S.insert i patterns
logFunc . GeneralMessage $ C8.concat ["Added pattern: ", i])
initialiseStartUrls :: OptionMap -> IO ()
initialiseStartUrls (OptionMap optionMap) = do
case M.lookup (OptionFlag "-u") optionMap of
Nothing -> return ()
Just startUrls -> insertStartUrls (mapMaybe canonicaliseString startUrls)
case M.lookup (OptionFlag "-uf") optionMap of
Nothing -> return ()
Just urlFiles -> do
files <- mapM C8.readFile urlFiles
insertStartUrls . mapMaybe (canonicaliseByteString . trim)
. filter (not . C8.null)
. concatMap C8.lines
$ files
where
insertStartUrls =
mapM_ (\cu@(CanonicalUrl u)-> do
result <- processNextUrl crawler cu
case result of
Right () -> logFunc . GeneralMessage . C8.concat $ ["Added Url: ", u]
Left reason -> atomically $ writeQueue (getLogQueue crawler) (GeneralError (C8.concat ["Could not add Url: ", u, "\n", "Reason: ", reason])))
initialiseProxy :: CrawlerSettings -> OptionMap -> IO ()
initialiseProxy crawlerSettings (OptionMap optionMap) =
case parseProxy of
Just proxySettings -> atomically $ writeTVar (getProxySettings crawlerSettings) (Just proxySettings)
Nothing -> return ()
where
parseProxy :: Maybe ProxySettings
parseProxy = do
proxy <- headMay =<< M.lookup (OptionFlag "-p") optionMap
case splitOn ":" proxy of
[address,strPort] -> do
port <- readMaybe strPort
return $ ProxySettings (C8.pack address) port
_ -> Nothing
initialiseFormInstructions :: CrawlerSettings -> OptionMap -> IO ()
initialiseFormInstructions crawlerSettings (OptionMap optionMap) =
case M.lookup (OptionFlag "-ff") optionMap of
Nothing -> return ()
Just formFiles -> do
formFileContents <- mapM readFile formFiles
let processed = map processFormInstructions formFileContents
formInstructions = SuppliedFormActions $ M.unions processed
atomically $ writeTVar (getFormInstructions crawlerSettings) formInstructions
logFunc . GeneralMessage . C8.pack $ "Inserted Form instructions: \n" ++ show formInstructions
where
processFormInstructions :: String -> M.Map Label (UrlRegex, FormActionRegex, FormParameters)
processFormInstructions formFile = do
let ls = filter (not . null) . splitOn [""] . lines $ formFile
instructions = mapMaybe chunkToInstruction ls
M.fromList instructions
where
chunkToInstruction :: [String] -> Maybe (Label, (UrlRegex, FormActionRegex, FormParameters))
chunkToInstruction chunk = do
let keysAndVals = map (splitOn "=") chunk
tuples = map (\[a,b] -> (a,b))
. filter (\x -> length x == 2) $ keysAndVals
(required, paramStrings) =
partition (\x -> fst x `elem` ["Label", "UrlRegex", "FormActionRegex"]) tuples
label <- getVal "Label" required
urlRegex <- getVal "UrlRegex" required
formActionRegex <- getVal "FormActionRegex" required
let params = map (both (C8.pack . unEscapeString)) paramStrings
return (Label label, (UrlRegex urlRegex, FormActionRegex formActionRegex, FormParameters params))
where
getVal :: String -> [(String, String)] -> Maybe C8.ByteString
getVal key = headMay . map (C8.pack . snd) . filter (\x -> fst x == key)
initialiseHrefDirections :: CrawlerSettings -> OptionMap -> IO ()
initialiseHrefDirections crawlerSettings (OptionMap optionMap) =
case M.lookup (OptionFlag "-df") optionMap of
Nothing -> return ()
Just [hrefFile] -> do
hrefFileContents <- L8.readFile hrefFile
let hrefDirections = parseHrefDirections hrefFileContents
atomically $ writeTVar (getHrefDirections crawlerSettings) hrefDirections
logFunc . GeneralMessage . C8.pack $ "Inserted Href Directions: \n" ++ show hrefDirections
| jahaynes/crawler | src/Initialisation.hs | mit | 8,263 | 0 | 23 | 2,626 | 2,223 | 1,101 | 1,122 | 139 | 12 |
module Spear.Math.Segment
(
Segment(..)
, seglr
)
where
import Spear.Math.Utils
import Spear.Math.Vector
-- | A line segment in 2D space.
data Segment = Segment {-# UNPACK #-} !Vector2 {-# UNPACK #-} !Vector2
-- | Classify the given point's position with respect to the given segment.
seglr :: Segment -> Vector2 -> Side
seglr (Segment p0 p1) p
| orientation2d p0 p1 p < 0 = R
| otherwise = L
| jeannekamikaze/Spear | Spear/Math/Segment.hs | mit | 434 | 0 | 9 | 111 | 105 | 58 | 47 | 11 | 1 |
-- Distributed streaming using Transient
-- See the article: https://www.fpcomplete.com/user/agocorona/streaming-transient-effects-vi
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable, MonadComprehensions #-}
module MainCountinuous where
import Transient.Base
import Transient.Move
import Transient.Indeterminism
import Transient.Logged
import Transient.Stream.Resource
import Control.Applicative
import Data.Char
import Control.Monad
import Control.Monad.IO.Class
import System.Random
import Data.IORef
import System.IO
import GHC.Conc
import System.Environment
-- continuos streaming version
-- Perform the same calculation but it does not stop, and the results are accumulated in in a mutable reference within the calling node,
-- so the precision in the value of pi is printed with more and more precision. every 1000 calculations.
-- Here instead of `collect` that finish the calculation when the number of samples has been reached, i use `group` which simply
-- group the number of results in a list and then sum of the list is returned to the calling node.
-- Since `group` do not finish the calculation, new sums are streamed from the nodes again and again.
main= do
let numNodes= 5
numCalcsNode= 100
ports= [2000.. 2000+ numNodes -1]
createLocalNode p= createNode "localhost" p
nodes= map createLocalNode ports
rresults <- newIORef (0,0)
keep $ freeThreads $ threads 10 $ runCloud $ do
--setBufSize 1024
local $ addNodes nodes
foldl (<|>) empty (map listen nodes) <|> return()
r <- clustered $ do
--Connection (Just (_,h,_,_)) _ <- getSData <|> error "no connection"
--liftIO $ hSetBuffering h $ BlockBuffering Nothing
r <- local $ group numCalcsNode $ do
n <- liftIO getNumCapabilities
threads n .
spawn $ do
x <- randomIO :: IO Double
y <- randomIO
return $ if x * x + y * y < 1 then 1 else (0 :: Int)
return $ sum r
(n,c) <- local $ liftIO $ atomicModifyIORef' rresults $ \(num, count) ->
let num' = num + r
count'= count + numCalcsNode
in ((num', count'),(num',count'))
when ( c `rem` 1000 ==0) $ local $ liftIO $ do
th <- myThreadId
putStrLn $ "Samples: "++ show c ++ " -> " ++
show( 4.0 * fromIntegral n / fromIntegral c)++ "\t" ++ show th
-- really distributed version
-- generate an executable with this main and invoke it as such:
--
-- program myport remotehost remoteport
--
-- where remotehost remoteport are from a previously initialized node
-- The first node initialize it with:
--
-- program myport localhost myport
mainDistributed= do
args <- getArgs
let localPort = read (args !! 0)
seedHost = read (args !! 1)
seedPort = read (args !! 2)
mynode = createNode "localhost" localPort
seedNode = createNode seedHost seedPort
numCalcsNode= 100
rresults <- liftIO $ newIORef (0,0)
runCloudIO $ do
connect mynode seedNode
local $ option "start" "start the calculation once all the nodes have been started" :: Cloud String
r <- clustered $ do
--Connection (Just (_,h,_,_)) _ <- getSData <|> error "no connection"
--liftIO $ hSetBuffering h $ BlockBuffering Nothing
r <- local $ group numCalcsNode $ do
n <- liftIO getNumCapabilities
threads n .
spawn $ do
x <- randomIO :: IO Double
y <- randomIO
return $ if x * x + y * y < 1 then 1 else (0 :: Int)
return $ sum r
(n,c) <- local $ liftIO $ atomicModifyIORef' rresults $ \(num, count) ->
let num' = num + r
count'= count + numCalcsNode
in ((num', count'),(num',count'))
when ( c `rem` 1000 ==0) $ local $ liftIO $ do
th <- myThreadId
putStrLn $ "Samples: "++ show c ++ " -> " ++
show( 4.0 * fromIntegral n / fromIntegral c)++ "\t" ++ show th
| geraldus/transient-universe | examples/PiDistribCountinuous.hs | mit | 4,435 | 0 | 26 | 1,504 | 960 | 494 | 466 | 72 | 2 |
module Commons.Import
( module Commons.NoReflexDom.Import
-- * Re-exported from reflex-dom
, Widget, Element
, DomBuilder, DomBuilderSpace
, AnimationTime (..), AnimationHandler
, PointerEvent, AEventType (..), PEventType (..), PointerEventType (..)
, WheelEvent (..), ModKey (..)
, (=:)
) where
import Commons.NoReflexDom.Import
import Reflex.Dom
import Reflex.Dom.Widget.Animation
| achirkin/qua-view | src/Commons/Import.hs | mit | 422 | 0 | 5 | 82 | 99 | 69 | 30 | 11 | 0 |
module FiniteField.GF256
( GF256Elm(..)
, (/)
) where
import Data.Bits ((.&.), xor, shift, testBit)
import Data.Vector as V
import Prelude hiding ((/))
-- | A Galois Field element. Possible value of 0..255 (inclusive)
newtype GF256Elm = GF256Elm {getInt :: Int}
deriving (Eq, Ord, Read, Show)
type VectInt = V.Vector Int
instance Num GF256Elm where
GF256Elm a + GF256Elm b = GF256Elm (a `xor` b)
GF256Elm a - GF256Elm b = GF256Elm (a `xor` b)
-- Conversion from Integer to GF256Elm, allows any positive or negative integer
fromInteger a = GF256Elm $ ((fromInteger a `mod` 256) + 256) `mod` 256
GF256Elm a * GF256Elm b
| (a == 0 || b == 0) = GF256Elm 0
| otherwise = GF256Elm $ gf256ExpTable ! (((gf256LogTable ! a + gf256LogTable ! b) `mod` 255))
-- unused. Needed to complete the instance declaration
signum _ = 1
-- unused. Needed to complete the instance declaration
abs a = a
(/) :: GF256Elm -> GF256Elm -> GF256Elm
GF256Elm a / GF256Elm b
| a == 0 = GF256Elm 0
| b == 0 = error "Divison by Zero"
| otherwise =
let temp = (gf256LogTable ! a - gf256LogTable ! b)
in GF256Elm (gf256ExpTable ! ((temp `mod` 255) + 255 `mod` 255)) -- take care of negatives
-- | Function used to calculate the exp and log table of
-- GF256Elm, which is used for multiplication and division
gf256Init :: Int -> Int -> (VectInt, VectInt) -> (VectInt, VectInt)
gf256Init 255 _ (expTable, logTable) =
let expTableNew = expTable // [(255, 0)]
logTableNew = logTable // [(0, 0)]
in (expTableNew, logTableNew)
gf256Init i exp (expTable, logTable) =
let e = exp .&. 0xff
expTableNew = expTable // [(i, e)]
d = testBit e 7 -- check if it's going to be 'over' the max value once multiplied
e2 = shift e 1 --shifts left, i.e. (x^7, x^6, .., x^0) * (1 0)
e3 = if (d == True)
then e2 `xor` 0x1b
else e2
e4 = e3 `xor` (expTableNew ! i) -- adding the shifted to its unshifted version.
-- i.e. completing the 3 multiplication
-- since now we have (x^7, x^6 .. x^0) * (1 1)
logTableNew = logTable // [((expTableNew ! i), i)]
in gf256Init (i+1) e4 (expTableNew, logTableNew)
-- | Generate the exp and log table using gf256Init
generateTables :: (VectInt, VectInt)
generateTables = gf256Init 0 1 ((V.replicate 256 0), (V.replicate 256 0))
-- | GF256Elm log table used for multiplication and division
gf256LogTable :: VectInt
gf256LogTable = snd generateTables
-- | GF256Elm exp table used for multiplication and division
gf256ExpTable :: VectInt
gf256ExpTable = fst generateTables
| jtcwang/HaskSplit | src/lib/FiniteField/GF256.hs | mit | 2,836 | 0 | 15 | 826 | 779 | 435 | 344 | 47 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-addattributes.html
module Stratosphere.ResourceProperties.IoTAnalyticsPipelineAddAttributes where
import Stratosphere.ResourceImports
-- | Full data type definition for IoTAnalyticsPipelineAddAttributes. See
-- 'ioTAnalyticsPipelineAddAttributes' for a more convenient constructor.
data IoTAnalyticsPipelineAddAttributes =
IoTAnalyticsPipelineAddAttributes
{ _ioTAnalyticsPipelineAddAttributesAttributes :: Maybe Object
, _ioTAnalyticsPipelineAddAttributesName :: Maybe (Val Text)
, _ioTAnalyticsPipelineAddAttributesNext :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON IoTAnalyticsPipelineAddAttributes where
toJSON IoTAnalyticsPipelineAddAttributes{..} =
object $
catMaybes
[ fmap (("Attributes",) . toJSON) _ioTAnalyticsPipelineAddAttributesAttributes
, fmap (("Name",) . toJSON) _ioTAnalyticsPipelineAddAttributesName
, fmap (("Next",) . toJSON) _ioTAnalyticsPipelineAddAttributesNext
]
-- | Constructor for 'IoTAnalyticsPipelineAddAttributes' containing required
-- fields as arguments.
ioTAnalyticsPipelineAddAttributes
:: IoTAnalyticsPipelineAddAttributes
ioTAnalyticsPipelineAddAttributes =
IoTAnalyticsPipelineAddAttributes
{ _ioTAnalyticsPipelineAddAttributesAttributes = Nothing
, _ioTAnalyticsPipelineAddAttributesName = Nothing
, _ioTAnalyticsPipelineAddAttributesNext = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-addattributes.html#cfn-iotanalytics-pipeline-addattributes-attributes
itapaaAttributes :: Lens' IoTAnalyticsPipelineAddAttributes (Maybe Object)
itapaaAttributes = lens _ioTAnalyticsPipelineAddAttributesAttributes (\s a -> s { _ioTAnalyticsPipelineAddAttributesAttributes = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-addattributes.html#cfn-iotanalytics-pipeline-addattributes-name
itapaaName :: Lens' IoTAnalyticsPipelineAddAttributes (Maybe (Val Text))
itapaaName = lens _ioTAnalyticsPipelineAddAttributesName (\s a -> s { _ioTAnalyticsPipelineAddAttributesName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-addattributes.html#cfn-iotanalytics-pipeline-addattributes-next
itapaaNext :: Lens' IoTAnalyticsPipelineAddAttributes (Maybe (Val Text))
itapaaNext = lens _ioTAnalyticsPipelineAddAttributesNext (\s a -> s { _ioTAnalyticsPipelineAddAttributesNext = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/IoTAnalyticsPipelineAddAttributes.hs | mit | 2,691 | 0 | 12 | 251 | 343 | 196 | 147 | 32 | 1 |
-- file: ch04/SplitLines.hs
-- From chapter 4, http://book.realworldhaskell.org/read/functional-programming.html
splitLines :: String -> [String]
splitLines [] = []
splitLines cs =
let (pre, suf) = break isLineTerminator cs
in pre : case suf of
('\r':'\n':rest) -> splitLines rest
('\r':rest) -> splitLines rest
('\n':rest) -> splitLines rest
_ -> []
isLineTerminator c = c == '\r' || c == '\n'
| Sgoettschkes/learning | haskell/RealWorldHaskell/ch04/SplitLines.hs | mit | 486 | 0 | 12 | 149 | 142 | 72 | 70 | 10 | 4 |
import Utils.Fibonacci
main = putStrLn $ show getProblem2Value
getProblem2Value :: Integer
getProblem2Value = sum $ filter even $ takeWhile (<4000000) fibSequence
| jchitel/ProjectEuler.hs | Problems/Problem0002.hs | mit | 165 | 0 | 7 | 23 | 48 | 25 | 23 | 4 | 1 |
-- Copyright 2015 Mitchell Kember. Subject to the MIT License.
-- Project Euler: Problem 40
-- Champernowne's constant
module Problem40 where
import Common (digits, numDigits, takeDigits)
champDigit :: Int -> Int
champDigit = go 1
where
go n i
| i <= d = takeDigits i n `mod` 10
| otherwise = go (n + 1) (i - d)
where
d = numDigits n
solve :: Int
solve = product . map champDigit . takeWhile (<= 1000000) . iterate (* 10) $ 1
| mk12/euler | haskell/Problem40.hs | mit | 466 | 0 | 10 | 123 | 152 | 82 | 70 | 10 | 1 |
module Bindings.Stemmer.Simple
( Stemmer(..)
, Language(..)
, Encoding(..)
, init_stemmer
, simple_stem ) where
import Bindings.Stemmer (StemConfig(..), Stemmer(..),
Language(..), Encoding(..),
init_stemmer, new_stemmer,
delete_stemmer, stemword)
import Control.Monad.Trans.Resource (allocate, runResourceT, release)
import Control.Monad.Trans.Class (lift)
-- | stem word with 'ResourceT'.
--
-- new & delete 'Stemmer' a.k.a (Ptr C'sb_stemmer) automatically.
simple_stem :: StemConfig -> String -> IO String
simple_stem StemConfig{..} word = runResourceT $ do
(key, stemmer) <- allocate (new_stemmer StemConfig{..}) delete_stemmer
str <- lift $ stemword stemmer word
lift $ release key
return str
| cosmo0920/bindings-libstemmer | Bindings/Stemmer/Simple.hs | mit | 818 | 0 | 12 | 204 | 213 | 126 | 87 | -1 | -1 |
module LexML.Linker.HtmlCleaner ( cleanEmptyAnchors ) where
import Data.Maybe
import Network.URI
import Text.HTML.TagSoup
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Char
cleanEmptyAnchors :: [Tag String] -> [Tag String]
cleanEmptyAnchors [] = []
cleanEmptyAnchors ((TagOpen "a" _):(TagClose "a"):r) = cleanEmptyAnchors r
cleanEmptyAnchors ((TagOpen "a" _):(TagText tx):(TagClose "a"):r) | onlySpace tx = cleanEmptyAnchors r
where onlySpace = and . map isSpace
cleanEmptyAnchors (t:r) = t : cleanEmptyAnchors r
| lexml/lexml-linker | src/main/haskell/LexML/Linker/HtmlCleaner.hs | gpl-2.0 | 563 | 0 | 11 | 76 | 214 | 115 | 99 | 14 | 1 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Baum.Order where
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data Order = Pre | In | Post | Level
deriving ( Eq, Ord, Typeable )
$(derives [makeReader, makeToDoc] [''Order])
| Erdwolf/autotool-bonn | src/Baum/Order.hs | gpl-2.0 | 291 | 0 | 9 | 51 | 77 | 45 | 32 | 8 | 0 |
import Graphics.Gloss
main :: IO ()
main = display (InWindow "Dibujo" (300,300) (20,20)) white coronaCircular
coronaCircular :: Picture
coronaCircular = thickCircle 100 30
| jaalonso/I1M-Cod-Temas | src/Tema_25/corona_circular.hs | gpl-2.0 | 174 | 0 | 8 | 25 | 65 | 35 | 30 | 5 | 1 |
module Process (runProgram) where
import Types
import LibPico
import Helpers
import Data.Char (chr, intToDigit)
import Numeric (showHex, showIntAtBase)
import Data.List.Utils (startswith)
import Errors
-- Core Functions --
runProgram :: Program -> Tape -> Int -> String
runProgram _ _ 0 = showError "Maxium number of cycles used!\nSuggestion: Increase maximum cycles"
runProgram _ (TapeError msg) _ = showError msg
runProgram (ProgramError msg) _ _ = showError msg
runProgram (Program c p Running f) (Tape b cur) (-1) = ( printIns (c!!p) (Program c p Running f) (Tape b cur) ) ++
( runProgram
(programIns (c!!p) (Program c p Running f) (Tape b cur))
(tapeIns (c!!p) (Program c p Running f) (Tape b cur))
(-1)
)
runProgram (Program c p Running f) (Tape b cur) i = ( printIns (c!!p) (Program c p Running f) (Tape b cur) ) ++
( runProgram
(programIns (c!!p) (Program c p Running f) (Tape b cur))
(tapeIns (c!!p) (Program c p Running f) (Tape b cur))
(i-1)
)
runProgram (Program _ _ Halted _) _ _ = ""
-- Function Processing --
getTapeAfter :: String -> [Function] -> Tape -> Tape
getTapeAfter arg f t = runProgramTape (Program ((function ((filter (\x -> (identifier x) == arg) f)!!0))++["HALT"]) 0 Running f) t
runProgramTape :: Program -> Tape -> Tape
runProgramTape (Program c p Running f) (Tape b cur) = ( runProgramTape
(programIns (c!!p) (Program c p Running f) (Tape b cur))
(tapeIns (c!!p) (Program c p Running f) (Tape b cur))
)
runProgramTape (Program _ _ Halted _) t = t
getStringAfter :: String -> [Function] -> Tape -> String
getStringAfter arg f t = runProgram (Program ((function ((filter (\x -> (identifier x) == arg) f)!!0))++["HALT"]) 0 Running f) t (-1)
-- Instruction Processing --
printIns :: String -> Program -> Tape -> String
printIns ('!':arg) _ (Tape b cur)
| arg == "INT" = show (value (b!!cur))
| arg == "HEX" = showHex (value (b!!cur)) ""
| arg == "BIN" = showIntAtBase 2 intToDigit (value (b!!cur)) ""
| arg == "ASCII" = [ (chr (value (b!!cur))) ]
| arg == "NEWLINE" = "\n"
| startswith "TAPE" arg = showTape b arg cur
| otherwise = showError $ "Unknown output type\nReferring to: \""++arg++"\""
printIns ('"':arg) _ _ = init arg
printIns ('$':arg) (Program _ _ _ f) t = if (functionLoaded f arg)
then getStringAfter arg f t
else ""
printIns _ _ _ = ""
programIns :: String -> Program -> Tape -> Program
programIns "HALT" (Program c p Running f) t = (Program c p Halted f)
programIns ('[':arg) (Program c p Running f) t = compareBrackets arg c p t f
programIns ('%':arg) (Program c p Running f) t = createFunction arg c p f
programIns ('^':arg) (Program c p Running f) _ = readFunction arg c p
programIns _ (Program c p Running f) _ = (Program c (p+1) Running f)
tapeIns :: String -> Program -> Tape -> Tape
tapeIns ('+':arg) _ (Tape b cur) = if (isInteger arg)
then do let newVal = Cell $ (value (b!!cur)) + (read arg) in
Tape (replaceNth cur (newVal) b) cur
else TapeError $ "Unknown operator after \"+\"\nReferring to: \""++arg++"\""
tapeIns ('-':arg) _ (Tape b cur) = if (isInteger arg)
then do let newVal = Cell $ (value (b!!cur)) - (read arg) in
Tape (replaceNth cur (newVal) b) cur
else TapeError $ "Unknown operator after \"-\"\nReferring to: \""++arg++"\""
tapeIns ('=':arg) _ (Tape b cur) = if (isInteger arg)
then do let newVal = Cell $ read arg in
Tape (replaceNth cur (newVal) b) cur
else TapeError $ "Unknown operator after \"=\"\nReferring to: \""++arg++"\""
tapeIns ('$':arg) (Program _ _ _ f) t = if (functionLoaded f arg)
then getTapeAfter arg f t
else TapeError $ "Unknown function\nReferring to: \""++arg++"\""++(functionCorrect arg)
tapeIns ('@':arg) _ (Tape b cur)
| arg == ">" = Tape b (cur+1)
| arg == "<" = Tape b (cur-1)
| otherwise = multipleMove arg b cur
tapeIns _ _ t = t | toish/Pico | src/Process.hs | gpl-3.0 | 4,333 | 54 | 20 | 1,264 | 1,934 | 988 | 946 | 73 | 5 |
module Data.HWDict
( decode
) where
import Control.Applicative ((<$>), (<*>), liftA2)
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe, mapMaybe, listToMaybe)
import Data.Monoid (All(All, getAll))
import Data.HWDict.Entry
import Text.XML.Light
import Text.XML.Light.Lexer (XmlSource)
type Dict = [Entry]
decode :: XmlSource s => s -> Maybe Dict
decode xml =
let contents = parseXML xml
wordPages = filterWords <$> listToMaybe (onlyElems contents)
in mapMaybe pageToEntry <$> wordPages
filterWords :: Element -> [Element]
filterWords = filterChildren $ isPage <&&> notServicePage
where
isPage = (qName' "page" ==) . elName
notServicePage e =
getAll . mconcat $ map (All . notPageStartsWith e) servicePrefixes
notPageStartsWith e prefix =
not $ fromMaybe False $ (prefix `isPrefixOf`) <$> findTitle e
servicePrefixes :: [String]
servicePrefixes =
[ "MediaWiki:"
, "Wiktionary:"
, "Template:"
, "Help:"
, "Category:"
, "File:"
, "Appendix:"
, "Module:"
, "Main Page"
]
pageToEntry :: Element -> Maybe Entry
pageToEntry e = Entry <$> findTitle e <*> findMeaning e
findTitle :: Element -> Maybe String
findTitle e = strContent <$> findElementByName "title" e
findMeaning :: Element -> Maybe String
findMeaning e =
strContent <$> (findElementByName "text" =<< findElementByName "revision" e)
findElementByName :: String -> Element -> Maybe Element
findElementByName str = findElement (qName' str)
qName' :: String -> QName
qName' str =
QName
{ qName = str
, qURI = Just "http://www.mediawiki.org/xml/export-0.10/"
, qPrefix = Nothing
}
(<&&>) :: (a -> Bool) -> (a -> Bool) -> a -> Bool
(<&&>) = liftA2 (&&)
| 23ua/hwdict | src/Data/HWDict.hs | gpl-3.0 | 1,740 | 0 | 12 | 365 | 540 | 299 | 241 | 50 | 1 |
-- Copyright (c) 2013, Diego Souza
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of the <ORGANIZATION> nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
module Main where
import System.IO
import Nettty.Common
import Nettty.Connect
main :: IO ()
main = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hSetBuffering stderr LineBuffering
hSetBinaryMode stdin True
hSetBinaryMode stdout True
forkWait start
| dgvncsz0f/nettty | src/Nettty/nettty.hs | gpl-3.0 | 1,782 | 0 | 7 | 308 | 104 | 61 | 43 | 12 | 1 |
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
-- spurious warnings for view patterns
-- |
-- Copyright : (c) 2010-12 Benedikt Schmidt
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <[email protected]>
--
-- Positions and replacement in terms.
module Term.Positions
where
import Term.VTerm
import Safe
-- Positions, subterm access, subterm replacement
----------------------------------------------------------------------
-- | A position in a term is a list of integers.
type Position = [Int]
-- | @t `atPos` p@ returns the subterm of term @t@ at position @p@.
-- The standard notation for @t `atPos` p@ is @t|_p@.
-- 'atPos' accounts for AC symbols by interpreting n-ary operator
-- applications @*[t1,t2,..tk-1,tk]@ as binary applications
-- @t1*(t2*..(tk-1*tk)..)@.
atPos :: Ord a => Term a -> Position -> Term a
atPos t [] = t
atPos (viewTerm -> FApp (AC _) (a:_)) (0:ps) =
a `atPos` ps
atPos (viewTerm -> FApp (AC _) [_]) _ =
error "Term.Positions.atPos: invalid position given"
atPos (viewTerm -> FApp fsym@(AC _) (_:as)) (1:ps) =
(fApp fsym as) `atPos` ps
atPos (viewTerm -> FApp (AC _) []) _ =
error $ "Term.Positions.atPos: impossible, "
++"nullary AC symbol appliction"
atPos (viewTerm -> FApp _ as) (i:ps) = case atMay as i of
Nothing -> error "Term.Positions.atPos: invalid position given"
Just a -> a `atPos` ps
atPos (viewTerm -> Lit _) (_:_) =
error "Term.Positions.atPos: invalid position given"
-- | @t `atPosMay` p@ returns Just the subterm of term @t@ at position @p@
-- if it exists, Nothing otherwise.
atPosMay :: Ord a => Term a -> Position -> Maybe (Term a)
atPosMay t [] = Just t
atPosMay (viewTerm -> FApp (AC _) (a:_)) (0:ps) =
a `atPosMay` ps
atPosMay (viewTerm -> FApp (AC _) [_]) _ = Nothing
atPosMay (viewTerm -> FApp fsym@(AC _) (_:as)) (1:ps) =
(fApp fsym as) `atPosMay` ps
atPosMay (viewTerm -> FApp (AC _) []) _ = Nothing
atPosMay (viewTerm -> FApp _ as) (i:ps) = do
a <- as `atMay` i
t <- a `atPosMay` ps
return t
atPosMay (viewTerm -> Lit _) (_:_) = Nothing
-- | @findPos t s@ returns the position of the term @s@ inside term @t@ if @s@
-- is a subterm, or Nothing otherwise.
findPos :: Ord a => Term a -> Term a -> Maybe [Position]
findPos t t' | t == t' = Just [[]]
findPos t (viewTerm -> FApp _ ts) = foldr f Nothing $ zip [0..] $ map (findPos t) ts
where
f (_, Nothing) s = s
f (x, Just p) Nothing = Just (map (x:) p)
f (x, Just p) (Just s) = Just (s++(map (x:) p))
findPos _ (viewTerm -> Lit _) = Nothing
-- | @t `replacePos` (s,p)@ returns the term @t'@ where the subterm at position @p@
-- is replaced by @s@. The standard notation for @t `replacePos` (s,p)@ is @t[s]_p@.
-- 'replacePos' accounts for AC symbols in the same ways as 'atPos'.
-- FIXME: The AC can be optimized.
replacePos :: Ord a => Term a -> (Term a, Position) -> Term a
replacePos _ (s,[]) = s
replacePos (viewTerm -> FApp fsym@(AC _) (a:as)) (s,0:ps) =
fApp fsym ((a `replacePos` (s,ps)):as)
replacePos (viewTerm -> FApp fsym@(AC _) (a:as)) (s,1:ps) =
fApp fsym [a, (fApp fsym as) `replacePos` (s,ps)]
replacePos (viewTerm -> FApp (AC _) _) _ =
error "Term.Positions.replacePos: invalid position given"
replacePos (viewTerm -> FApp fsym as) (s,i:ps) =
if 0 <= i && i < length as
then fApp fsym ((take i as)++[as!!i `replacePos` (s,ps)]++(drop (i+1) as))
else error "Term.Positions.replacePos: invalid position given"
replacePos (viewTerm -> Lit _) (_,_:_) =
error "Term.Positions.replacePos: invalid position given"
-- | @positionsNonVar t@ returns all the non-variable positions in the term @t@.
-- 'positionsNonVar' accounts for AC symbols in the same ways as 'atPos'.
positionsNonVar :: VTerm a b -> [Position]
positionsNonVar =
go
where
go (viewTerm -> Lit (Con _)) = [[]]
go (viewTerm -> Lit (Var _)) = []
go (viewTerm -> FApp (AC _) as) = []:concat (zipWith (\i a -> map ((position i len)++) (go a))
[0..] as)
where len = length as
go (viewTerm -> FApp _ as) = []:concat (zipWith (\i a -> map (i:) (go a)) [0..] as)
position i len | i == len - 1 = replicate i 1
| otherwise = replicate i 1 ++ [0]
-- | @positions t@ returns all the positions in the term @t@.
-- 'positions' accounts for AC symbols in the same ways as 'atPos'.
positions :: (Show a, Show b) => VTerm a b -> [Position]
positions =
go
where
go (viewTerm -> Lit (Con _)) = [[]]
go (viewTerm -> Lit (Var _)) = [[]]
go (viewTerm -> FApp (AC _) as) = []:concat (zipWith (\i a -> map ((position i len)++) (go a))
[0..] as)
where len = length as
go (viewTerm -> FApp _ as) = []:concat (zipWith (\i a -> map (i:) (go a)) [0..] as)
position i len | i == len - 1 = replicate i 1
| otherwise = replicate i 1 ++ [0]
-- Return the deepest "protected" subterm with respect to a given position
-- NB: here anything but a pair or an AC symbol is an "encryption"!
deepestProtSubterm :: (Show a, Eq a) => Term a -> Position -> Maybe (Term a)
deepestProtSubterm term = f term term
where
f st _ []
| st == term && (isPair term || isAC term) = Nothing
-- If there is no protected subterm, return Nothig!
f st _ []
| otherwise = Just st
f st t@(viewTerm -> FApp _ as) (i:is) = case atMay as i of
Nothing -> error "deepestProtSubterm: invalid position given"
Just a -> f (if isPair t || isAC t then st else t) a is
| tamarin-prover/tamarin-prover | lib/term/src/Term/Positions.hs | gpl-3.0 | 6,087 | 0 | 16 | 1,815 | 2,086 | 1,087 | 999 | 87 | 5 |
import Text.ParserCombinators.Parsec
import Ignifera.GameResult
import Ignifera.Format.PgnParser
import Ignifera.Util.GameResult
main :: IO ()
main = do
print $ testParser terminationMarker showPgnMarker allGameResults
putStrLn "World"
testParser :: Eq a => Parser a -> (a -> String) -> [a] -> Bool
testParser p render = all f
where f x = case parse p "" (render x) of
Left _ -> False
Right y -> x == y
| fthomas/ignifera | test/Main.hs | gpl-3.0 | 445 | 0 | 10 | 107 | 158 | 79 | 79 | 13 | 2 |
module NeuralNetworks where
import Control.Arrow
import Control.Monad
import Control.Monad.State
import Data.Function
import Data.Vector (Vector, (!))
import qualified Data.Vector as V
import Utility
data NN where
NN :: { nnLayers :: !(Vector NNLayer) } -> NN
instance Show NN where
show NN { .. } = unlines $ "NN:" : map ((" " ++) . show) (V.toList nnLayers)
dot :: (Num a) => Vector a -> Vector a -> a
x1 `dot` x2 = V.sum $ V.zipWith (*) x1 x2
add :: (Num a) => Vector a -> Vector a -> Vector a
add = V.zipWith (+)
sub :: (Num a) => Vector a -> Vector a -> Vector a
sub = V.zipWith (-)
nn :: [Int] -> IO NN
nn [] = error "NN: number of layers must be greater than zero."
nn layers = do
nnLayers <- do
let layersP = layers ++ [1]
layers3 = zip3 layersP (tail layersP) (tail $ tail layersP)
(V.fromList <$>) $ forM layers3 $ \(fanIn, current, fanOut) -> do
nnNodes <- V.replicateM current $ do
let stretching = 2 / fromIntegral (fanIn + fanOut)
nnWeights <- V.replicateM fanIn ((* stretching) <$> randomPM1)
let nnBias = 0
return NNNode { .. }
return NNLayer { .. }
return NN { .. }
data NNLayer where
NNLayer :: { nnNodes :: !(Vector NNNode) } -> NNLayer
instance Show NNLayer where
show NNLayer { .. } = unlines $ map ((" " ++ ) . show) (V.toList nnNodes)
data ActivationFunction = SigmoidFunction | IdentityFunction
deriving Show
class DerivableFunction a where
function :: a -> BinaryFunction
derivative :: a -> BinaryFunction
instance DerivableFunction ActivationFunction where
function SigmoidFunction = (1 /) . (1 +) . exp . negate
function IdentityFunction = id
derivative SigmoidFunction = let
f = function SigmoidFunction
in uncurry (*) . (f &&& ((1 -) . f))
derivative IdentityFunction = const 1
type BinaryFunction = Double -> Double
data NNNode where
NNNode :: { nnWeights :: !(Vector Double), nnBias :: !Double } -> NNNode
deriving Show
identityNode :: Int -> NNNode
identityNode n = let
nnWeights = V.replicate n 1
nnBias = 0
in NNNode { .. }
layerForwardPass :: NNLayer -> Vector Double -> Vector Double
layerForwardPass NNLayer { .. } input = V.map (\ NNNode { .. } -> function SigmoidFunction (nnWeights `dot` input)) nnNodes
forwardPass :: NN -> Vector Double -> Vector Double
forwardPass NN { .. } input = foldl (flip layerForwardPass) input nnLayers
forwardScanl :: NN -> Vector Double -> Vector (Vector Double)
forwardScanl NN { .. } input = V.scanl (flip layerForwardPass) input nnLayers
backpropGradient :: NN -> Vector Double -> Vector Double -> NN
backpropGradient neuralNetwork input expected = let
outputs = forwardScanl neuralNetwork input
layers = nnLayers neuralNetwork
nLayers = V.length layers
outputDifference = expected `sub` V.last outputs
errors = let
processLayer rI layer = let
i = nLayers - rI - 1
processNodeLastLayer j NNNode { .. } = let
der = derivative SigmoidFunction
in der (outputs ! succ i ! j) * (outputDifference ! j)
processNode j NNNode { .. } = do
prevErr <- get
let der = derivative SigmoidFunction
return $ der (outputs ! succ i ! j) * (prevErr `dot` nnWeights)
in if
| i == pred nLayers -> do
let err = V.imap processNodeLastLayer (nnNodes layer)
put err
return err
| otherwise -> do
err <- V.imapM processNode (nnNodes layer)
put err
return err
in V.reverse $ V.imapM processLayer (V.reverse layers) `evalState` V.empty
gradients = let
makeLayer i output = let
err = errors ! i
makeNode e = let
nnWeights = V.map (e *) output
nnBias = 0
in NNNode { .. }
nnNodes = V.map makeNode err
in NNLayer { .. }
in V.imap makeLayer $ V.init outputs
in NN { nnLayers = gradients }
backpropCorrection :: Double -> NN -> NN -> NN
backpropCorrection eps gradients neuralNetwork = let
subtractGradient g n = n + g * eps
newNNLayers = V.zipWith combineLayers (nnLayers gradients) (nnLayers neuralNetwork)
combineLayers grads layer = let
combineNodes g n = let
newNNWeights = V.zipWith subtractGradient (nnWeights g) (nnWeights n)
newNNBias = nnBias g `subtractGradient` nnBias n
in NNNode { nnWeights = newNNWeights, nnBias = newNNBias }
newNNNodes = V.zipWith combineNodes (nnNodes grads) (nnNodes layer)
in NNLayer { nnNodes = newNNNodes }
in NN { nnLayers = newNNLayers }
totalGradient :: [NN] -> NN
totalGradient grads = let
combineGradients l r = let
newNNLayers = (V.zipWith combineLayers `on` nnLayers) l r
in NN { nnLayers = newNNLayers }
combineLayers l r = let
newNNNodes = (V.zipWith combineNodes `on` nnNodes) l r
in NNLayer { nnNodes = newNNNodes }
combineNodes l r = let
newNNWeights = (V.zipWith (+) `on` nnWeights) l r
newNNBias = ((+) `on` nnBias) l r
in NNNode { nnWeights = newNNWeights, nnBias = newNNBias }
scaleGradient grad = let
scaleNode node = let
newNNWeights = V.map (/ fromIntegral nGrads) (nnWeights node)
newNNBias = nnBias node / fromIntegral nGrads
in NNNode { nnWeights = newNNWeights, nnBias = newNNBias }
in NN { nnLayers = V.map (NNLayer . V.map scaleNode . nnNodes) $ nnLayers grad }
nGrads = length grads
in scaleGradient $ foldl1 combineGradients grads
meanSquaredError :: NN -> [(Vector Double, Vector Double)] -> Double
meanSquaredError neuralNetwork trainSet = let
outputs = map (forwardPass neuralNetwork . fst) trainSet
differenceSquared o e = (o - e) ** 2
residuals = zipWith (\ o e -> V.sum $ V.zipWith differenceSquared o e) outputs (map snd trainSet)
trainSetSize = length trainSet
in sum residuals / fromIntegral trainSetSize
| mrlovre/super-memory | Pro5/src/NeuralNetworks.hs | gpl-3.0 | 6,292 | 0 | 25 | 1,887 | 2,166 | 1,107 | 1,059 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.ContentCategories.Insert
-- 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)
--
-- Inserts a new content category.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.contentCategories.insert@.
module Network.Google.Resource.DFAReporting.ContentCategories.Insert
(
-- * REST Resource
ContentCategoriesInsertResource
-- * Creating a Request
, contentCategoriesInsert
, ContentCategoriesInsert
-- * Request Lenses
, cciProFileId
, cciPayload
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.contentCategories.insert@ method which the
-- 'ContentCategoriesInsert' request conforms to.
type ContentCategoriesInsertResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"contentCategories" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ContentCategory :>
Post '[JSON] ContentCategory
-- | Inserts a new content category.
--
-- /See:/ 'contentCategoriesInsert' smart constructor.
data ContentCategoriesInsert = ContentCategoriesInsert'
{ _cciProFileId :: !(Textual Int64)
, _cciPayload :: !ContentCategory
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ContentCategoriesInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cciProFileId'
--
-- * 'cciPayload'
contentCategoriesInsert
:: Int64 -- ^ 'cciProFileId'
-> ContentCategory -- ^ 'cciPayload'
-> ContentCategoriesInsert
contentCategoriesInsert pCciProFileId_ pCciPayload_ =
ContentCategoriesInsert'
{ _cciProFileId = _Coerce # pCciProFileId_
, _cciPayload = pCciPayload_
}
-- | User profile ID associated with this request.
cciProFileId :: Lens' ContentCategoriesInsert Int64
cciProFileId
= lens _cciProFileId (\ s a -> s{_cciProFileId = a})
. _Coerce
-- | Multipart request metadata.
cciPayload :: Lens' ContentCategoriesInsert ContentCategory
cciPayload
= lens _cciPayload (\ s a -> s{_cciPayload = a})
instance GoogleRequest ContentCategoriesInsert where
type Rs ContentCategoriesInsert = ContentCategory
type Scopes ContentCategoriesInsert =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient ContentCategoriesInsert'{..}
= go _cciProFileId (Just AltJSON) _cciPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy ContentCategoriesInsertResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/ContentCategories/Insert.hs | mpl-2.0 | 3,496 | 0 | 14 | 760 | 406 | 242 | 164 | 64 | 1 |
--
-- Copyright 2017-2018 Azad Bolour
-- Licensed under GNU Affero General Public License v3.0 -
-- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md
--
module Bolour.Util.Empty (
Empty(..)
) where
class Empty a
where isEmpty :: a -> Bool
| azadbolour/boardgame | haskell-server/src/Bolour/Util/Empty.hs | agpl-3.0 | 267 | 0 | 7 | 49 | 39 | 25 | 14 | 4 | 0 |
{-# LANGUAGE TemplateHaskell, DeriveGeneric, DeriveDataTypeable #-}
module Slave.Slave
( Request (..)
, Response (..)
, slaveProc
, slaveProc__static
, remoteTable
) where
import Control.Distributed.Process ( Process, ProcessId, RemoteTable
, expect, send, liftIO)
import Control.Distributed.Process.Closure
import Control.Concurrent (threadDelay)
import Control.Monad (forever)
import Data.Binary
import Data.Typeable
import GHC.Generics
data Request = Request !ProcessId !Int
deriving (Generic, Typeable)
data Response = Response !Int
deriving (Generic, Typeable)
instance Binary Request
instance Binary Response
slaveProc :: Process ()
slaveProc =
forever $ do
(Request pid num) <- expect
liftIO $ threadDelay 500000
send pid $ Response (num * 2)
remotable ['slaveProc]
remoteTable :: (RemoteTable -> RemoteTable)
remoteTable = __remoteTable
| SneakingCat/distributed-nonsense | src/Slave/Slave.hs | apache-2.0 | 1,006 | 0 | 11 | 265 | 250 | 139 | 111 | 36 | 1 |
module Probability.Repeated (
repeated
) where
import Control.Monad.State (State, runState, get, put)
import Data.Ratio ((%))
-- n-th element in the list represents the probability that the expected event
-- E such that P(E) = init will occur for the first time in (n-1)th attempt.
-- nextProb is the function that alters the ocurrence probability with each
-- subsequent attempt (might be id).
repeated' :: Rational -> (Rational -> Rational) -> [Rational]
repeated' init nextProb = fst $ runState (assemble nextProb) initial
where
initial = RepeatState init 0 init
assemble :: (Rational -> Rational) -> State RepeatState [Rational]
assemble nextProb = do
compute nextProb
state <- get
assemble nextProb >>= (\p -> return $ currentProb state : p)
compute :: (Rational -> Rational) -> State RepeatState Rational
compute nextProb = do
state <- get
let next = (1 - accumPrevProb state) * (nextProb $ lastProb state)
put $ RepeatState {
lastProb = nextProb $ lastProb state,
accumPrevProb = next + accumPrevProb state,
currentProb = next
}
return next
data RepeatState = RepeatState {
lastProb :: Rational,
accumPrevProb :: Rational,
currentProb :: Rational
}
repeated :: Rational -> (Rational -> Rational) -> [Rational]
repeated init nextProb = [((1 - init) ^ n) * apply nextProb n init | n <- [0..]]
where
apply f n val
| n < 1 = val
| otherwise = apply f (n - 1) (f val)
| Sventimir/bridge-tools | Probability/Repeated.hs | apache-2.0 | 1,588 | 0 | 13 | 448 | 451 | 239 | 212 | 30 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeFamilies #-}
module Data.Function.ArrayMemoize where
import qualified Data.Array.MArray as MArray
import Data.Array.Unboxed
import Data.Array.IO (IOUArray)
import Data.Array.ST (STArray, STUArray, runSTArray)
import Control.Monad.ST
{-| Memoize a function over a finite (sub)domain, using an array (boxed), e.g.,
@
arrayMemo (0, 20) f
@
memoizes f between from 0 to 20. -}
{-# INLINE arrayMemo #-}
arrayMemo :: (Ix a, ArrayMemoizable b) => (a, a) -> (a -> b) -> (a -> b)
arrayMemo (l, u) f =
let cache = runSTArray (do cache <- newArray_ (l, u)
mapM_ (\x -> writeArray cache x (f x)) (range (l, u))
return cache)
in \x -> cache ! x
{-| Memoize a fixed point of a function over a sub domain.
Similar to 'fix', but over 'arrayMemo', passing a function a memoized
version of itself. -}
{-# INLINE arrayMemoFix #-}
arrayMemoFix :: (Ix a, ArrayMemoizable b) => (a, a) -> ((a -> b) -> (a -> b)) -> a -> b
arrayMemoFix (l, u) f = memo_f where memo_f = arrayMemo (l, u) (f memo_f)
{-| Memoize a mutual fixed point for two functions (over sub domains of these functions). -}
{-# INLINE arrayMemoFixMutual #-}
arrayMemoFixMutual :: (ArrayMemoizable b, ArrayMemoizable d, Ix a, Ix c) => (a, a) -> (c, c) -> ((a -> b) -> (c -> d) -> (a -> b)) -> ((a -> b) -> (c -> d) -> (c -> d)) -> (a -> b)
arrayMemoFixMutual (l, u) (l', u') f g =
memo_f where memo_f = arrayMemo (l, u) (f memo_f memo_g)
memo_g = arrayMemo (l', u') (g memo_f memo_g)
{-| Memoize a mutual fixed point for three functions (over sub domains of these functions). -}
{-# INLINE arrayMemoFixMutual3 #-}
arrayMemoFixMutual3 :: (ArrayMemoizable b, ArrayMemoizable d, ArrayMemoizable f, Ix a, Ix c, Ix e) => (a, a) -> (c, c) -> (e, e) -> ((a -> b) -> (c -> d) -> (e -> f) -> (a -> b)) -> ((a -> b) -> (c -> d) -> (e -> f) -> (c -> d)) ->
((a -> b) -> (c -> d) -> (e -> f) -> (e -> f)) -> (a -> b)
arrayMemoFixMutual3 (l, u) (l', u') (l'', u'') f g h =
memo_f where memo_f = arrayMemo (l, u) (f memo_f memo_g memo_h)
memo_g = arrayMemo (l', u') (g memo_f memo_g memo_h)
memo_h = arrayMemo (l'', u'') (h memo_f memo_g memo_h)
{-| Memoize a function over a finite (sub)domain, using an unboxed 'IO' array.
This requires the incoming function to return results in the 'IO' monad, but should
preferable be pure. -}
{-# INLINE uarrayMemoFixIO #-}
uarrayMemoFixIO :: (Ix a, UArrayMemoizable b) => (a, a) -> ((a -> IO b) -> (a -> IO b)) -> a -> IO b
uarrayMemoFixIO (l, u) f =
\i -> do cache <- newUArray_ (l, u)
let f' = f (\x -> readUArray cache x)
mapM_ (\x -> (f' x) >>= (\val -> writeUArray cache x val)) (range (l, u))
f' i
{-| Memoize and discretize a function over a finite (sub)domain, using an array. e.g.
@
discretemMemo (0.0, 10.0) 2.0 f
@
returns a discretized version of f (with the discrete type defined by 'Discrete')
in the range 0.0 to 10.0 with step size 2.0 (i.e., the resulting discrete domain is
of size 5). -}
{-# INLINE discreteMemo #-}
discreteMemo :: (ArrayMemoizable b, Discretize a) => (a, a) -> a -> (a -> b) -> (Discrete a -> b)
discreteMemo (l, u) delta f =
let disc = discretize delta
cache = runSTArray (do cache <- newArray_ (disc l, disc u)
mapM_ (\x -> writeArray cache x (f (continuize delta x))) (enumFromTo (disc l) (disc u))
return cache)
in (\x -> cache ! x)
{-| Memoize and discretize a fixed point of a function over a subdomain with discretization step -}
{-# INLINE discreteMemoFix #-}
discreteMemoFix :: (ArrayMemoizable b, Discretize a) => (a, a) -> a -> ((a -> b) -> (a -> b)) ->(Discrete a -> b)
discreteMemoFix (l, u) delta f =
let disc = discretize delta
cache' = runSTArray (do cache <- newArray_ (disc l, disc u)
mapM_ (\x -> writeArray cache x (f (\x -> cache' ! (disc x)) (continuize delta x))) (enumFromTo (disc l) (disc u))
return cache)
in (\x -> cache' ! x)
{-| Memoize and quantize a function over a finite (sub)domain, using a boxed array, e.g,
@
quantizedMemo (0.0, 10.0) 2.0 f
@
memoizes f between 0.0 and 10.0 with step size 2.0 (i.e. the function is quantized into
5 parts, memoized into an array of size 5).
-}
{-# INLINE quantizedMemo #-}
quantizedMemo :: (ArrayMemoizable b, Discretize a) => (a, a) -> a -> (a -> b) -> (a -> b)
quantizedMemo (l, u) delta f =
let disc = discretize delta
cache = runSTArray (do cache <- newArray_ (disc l, succ (disc u))
mapM_ (\x -> writeArray cache x (f (continuize delta x))) (enumFromTo (disc l) (succ (disc u)))
return cache)
in (\x -> cache ! disc x)
{-| Memoize and quantize a fixed point of a function. Similar to 'fix', but using 'quantizedMemo'
to pass the fixed function a quantized memoized version of itself,
therefore memoizing any recursive calls. -}
{-# INLINE quantizedMemoFix #-}
quantizedMemoFix :: (ArrayMemoizable b, Discretize a) => (a, a) -> a -> ((a -> b) -> (a -> b)) -> (a -> b)
quantizedMemoFix (l, u) delta f = memo_f where memo_f = quantizedMemo (l, u) delta (f memo_f)
{-| Memoize and quantize a mutually recursive fixed point of two functions. -}
{-# INLINE quantizedMemoFixMutual #-}
quantizedMemoFixMutual :: (ArrayMemoizable b, ArrayMemoizable d, Discretize a, Discretize c) => (a, a) -> a -> (c, c) -> c -> ((a -> b) -> (c -> d) -> (a -> b)) -> ((a -> b) -> (c -> d) -> (c -> d)) -> (a -> b)
quantizedMemoFixMutual (l, u) delta (l', u') delta' f g =
memo_f where memo_f = quantizedMemo (l, u) delta (f memo_f memo_g)
memo_g = quantizedMemo (l', u') delta' (g memo_f memo_g)
{-| Memoize and quantize a mutually recursive fixed point of three functions. -}
{-# INLINE quantizedMemoFixMutual3 #-}
quantizedMemoFixMutual3 :: (ArrayMemoizable b, ArrayMemoizable d, ArrayMemoizable f, Discretize a, Discretize c, Discretize e) => (a, a) -> a -> (c, c) -> c -> (e, e) -> e -> ((a -> b) -> (c -> d) -> (e -> f) -> (a -> b)) -> ((a -> b) -> (c -> d) -> (e -> f) -> (c -> d)) -> ((a -> b) -> (c -> d) -> (e -> f) -> (e -> f)) -> (a -> b)
quantizedMemoFixMutual3 (l, u) delta (l', u') delta' (l'', u'') delta'' f g h =
memo_f where memo_f = quantizedMemo (l, u) delta (f memo_f memo_g memo_h)
memo_g = quantizedMemo (l', u') delta' (g memo_f memo_g memo_h)
memo_h = quantizedMemo (l'', u'') delta'' (h memo_f memo_g memo_h)
{-| 'ArrayMemoizable' defines the subset of types for which we can do array
memoization -}
class ArrayMemoizable a where
newArray_ :: (Ix i) => (i, i) -> ST s (STArray s i a)
writeArray :: (Ix i) => STArray s i a -> i -> a -> ST s ()
instance ArrayMemoizable Float where
newArray_ = MArray.newArray_
writeArray = MArray.writeArray
instance ArrayMemoizable Double where
newArray_ = MArray.newArray_
writeArray = MArray.writeArray
instance ArrayMemoizable Integer where
newArray_ = MArray.newArray_
writeArray = MArray.writeArray
instance ArrayMemoizable Int where
newArray_ = MArray.newArray_
writeArray = MArray.writeArray
instance ArrayMemoizable Bool where
newArray_ = MArray.newArray_
writeArray = MArray.writeArray
instance ArrayMemoizable Char where
newArray_ = MArray.newArray_
writeArray = MArray.writeArray
{-| 'UArrayMemoizable' defines the subset of types for which we can
do unboxed IOUArray memoization -}
class IArray UArray a => UArrayMemoizable a where
newUArray_ :: (Ix i) => (i, i) -> IO (IOUArray i a)
writeUArray :: (Ix i) => IOUArray i a -> i -> a -> IO ()
readUArray :: (Ix i) => IOUArray i a -> i -> IO a
instance UArrayMemoizable Float where
newUArray_ = MArray.newArray_
readUArray = MArray.readArray
writeUArray = MArray.writeArray
instance UArrayMemoizable Double where
newUArray_ = MArray.newArray_
readUArray = MArray.readArray
writeUArray = MArray.writeArray
instance UArrayMemoizable Int where
newUArray_ = MArray.newArray_
readUArray = MArray.readArray
writeUArray = MArray.writeArray
instance UArrayMemoizable Char where
newUArray_ = MArray.newArray_
readUArray = MArray.readArray
writeUArray = MArray.writeArray
{- Num and Enum classes for working with tuple domains -}
instance (Enum a, Enum b) => Enum (a, b) where
toEnum = undefined
succ (a, b) = (succ a, succ b)
fromEnum (a, b) = fromEnum a * fromEnum b
enumFromTo (lx, ly) (ux, uy) =
[ly..uy] >>= (\y -> [lx..ux] >>= (\x -> return (x, y)))
instance (Enum a, Enum b, Enum c) => Enum (a, b, c) where
toEnum = undefined
succ (a, b, c) = (succ a, succ b, succ c)
fromEnum (a, b, c) = fromEnum a * fromEnum b * fromEnum c
enumFromThenTo (lx, ly, lz) (nx, ny, nz) (ux, uy, uz) =
[lz,nz..uz] >>= (\z -> [ly,ny..uy] >>= (\y -> [lx,nx..ux] >>= (\x -> return (x, y, z))))
instance (Num a, Num b) => Num (a, b) where
(a1, b1) + (a2, b2) = (a1 + a2, b1 + b2)
(a1, b1) * (a2, b2) = (a1 * a2, b1 * b2)
negate (a, b) = (negate a, negate b)
abs (a, b) = (abs a, abs b)
signum (a, b) = (signum a, signum b)
fromInteger i = (0, fromInteger i)
instance (Num a, Num b, Num c) => Num (a, b, c) where
(a1, b1, c1) + (a2, b2, c2) = (a1 + a2, b1 + b2, c1 + c2)
(a1, b1, c1) * (a2, b2, c2) = (a1 * a2, b1 * b2, c1 * c2)
negate (a, b, c) = (negate a, negate b, negate c)
abs (a, b, c) = (abs a, abs b, abs c)
signum (a, b, c) = (signum a, signum b, signum c)
fromInteger i = (0, 0, fromInteger i)
{-| Discretization of float/double values and tuples -}
class (Ix (Discrete t), Enum (Discrete t)) => Discretize t where
type Discrete t
discretize :: t -> t -> Discrete t
continuize :: t -> Discrete t -> t
instance Discretize Float where
type Discrete Float = Int
discretize delta x = round' (x / delta)
where round' x = let (n,r) = properFraction x in n + (round r)
continuize delta x = (fromIntegral x) * delta
instance Discretize Double where
type Discrete Double = Int
discretize delta x = round' (x / delta)
where round' x = let (n,r) = properFraction x in n + (round r)
continuize delta x = (fromIntegral x) * delta
instance (Discretize a, Discretize b) => Discretize (a, b) where
type Discrete (a, b) = (Discrete a, Discrete b)
discretize (dx, dy) (x, y) = (discretize dx x, discretize dy y)
continuize (dx, dy) (x, y) = (continuize dx x, continuize dy y)
instance (Discretize a, Discretize b, Discretize c) => Discretize (a, b, c) where
type Discrete (a, b, c) = (Discrete a, Discrete b, Discrete c)
discretize (dx, dy, dz) (x, y, z) = (discretize dx x, discretize dy y, discretize dz z)
continuize (dx, dy, dz) (x, y, z) = (continuize dx x, continuize dy y, continuize dz z)
{-| Discretized a function function. The second parameter is the discretisation step. -}
discrete :: Discretize a => (a -> b) -> a -> (Discrete a -> b)
discrete f delta = f . (continuize delta) | dorchard/array-memoize | Data/Function/ArrayMemoize.hs | bsd-2-clause | 11,385 | 0 | 23 | 2,908 | 4,319 | 2,349 | 1,970 | 165 | 1 |
module Data.Text.Prettyprint.Doc.Render.Tutorials.TreeRenderingTutorial {-# DEPRECATED "Use \"Prettyprinter.Render.Tutorials.TreeRenderingTutorial\" instead." #-} (
module Prettyprinter.Render.Tutorials.TreeRenderingTutorial
) where
import Prettyprinter.Render.Tutorials.TreeRenderingTutorial
| quchen/prettyprinter | prettyprinter/src/Data/Text/Prettyprint/Doc/Render/Tutorials/TreeRenderingTutorial.hs | bsd-2-clause | 298 | 0 | 5 | 20 | 29 | 22 | 7 | 3 | 0 |
module Spec where
import Control.Monad.State.SubSpec
import Test.Tasty
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Testing..."
[spec]
| athanclark/sub-state | test/Spec.hs | bsd-3-clause | 173 | 0 | 6 | 30 | 52 | 30 | 22 | 8 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Andromeda.Types.Hardware.Parameter where
import Data.Typeable
import Andromeda.Types.Physics.Temperature
import Andromeda.Types.Physics.Measurement
import Andromeda.Types.Common.Value
-- First attempt (used in many modules)
data Parameter tag = Temperature | Pressure
deriving (Show, Read, Eq)
data Power -- 'Power' units for boosters...
-- Idea: http://stackoverflow.com/questions/28243383/how-can-i-read-the-metadata-of-a-type-at-runtime
data Admissible a where
AdKelvin :: Admissible Kelvin
AdCelsius :: Admissible Celsius
AdPascal :: Admissible Pascal
convertAdmissible :: Admissible a -> a -> Value -> Measurement a
convertAdmissible AdKelvin m v = toKelvinV v
convertAdmissible AdCelsius m v = toCelsiusV v
convertAdmissible AdPascal m v = toPascalV v
data Measurementable a where
MeasureKelvin :: Measurementable Kelvin
MeasureCelsius :: Measurementable Celsius
MeasurePascal :: Measurementable Pascal
-- TODO: think how to do it
--toMeasurement :: TypeRep -> Value -> forall a. Measurement a
toMeasurement (Par v m) = case cast m of
Just (m1 :: Measurement Kelvin) -> toMeasurementV v
Nothing -> case cast m of
Just (m2 :: Measurement Pascal) -> toMeasurementV v
Nothing -> case cast m of
Just (m3 :: Measurement Celsius) -> toMeasurementV v
Nothing -> error "bad cast"
-- or it:
--toMeasurement :: DataType -> Value -> Measurement a
--toMeasurement dt v = undefined
toPower :: Int -> Measurement Power
toPower v = Measurement (intValue v)
temperature :: Parameter Kelvin
temperature = Temperature
pressure :: Parameter Pascal
pressure = Pressure
temperatureKelvin :: Parameter Kelvin
temperatureKelvin = temperature
temperatureCelsius :: Parameter Celsius
temperatureCelsius = Temperature
-- Second attempt (used in HDL)
data Par = forall tag. Typeable tag => Par Value (Measurement tag)
instance Ord Par where
(Par v1 _) `compare` (Par v2 _) = v1 `compare` v2
instance Show Par where
show (Par v t) = "Par v:" ++ show v ++ " t:" ++ show t
instance Eq Par where
(Par v1 t1) == (Par v2 t2) = v1 == v2
temperaturePar = Par (toValue zeroKelvin) zeroKelvin
pressurePar = Par (toValue zeroPascal) zeroPascal
toPar :: Typeable tag => Measurement tag -> Par
toPar m@(Measurement v) = Par v m
| graninas/Andromeda | src/Andromeda/Types/Hardware/Parameter.hs | bsd-3-clause | 2,357 | 0 | 17 | 402 | 632 | 329 | 303 | -1 | -1 |
{-# OPTIONS_GHC -Wall #-}
module Optimize.Substitute (subst) where
import Control.Arrow (second, (***))
import AST.Expression.General (Expr'(..), PortImpl(..))
import qualified AST.Expression.Optimized as Optimized
import qualified AST.Pattern as Pattern
import qualified AST.Variable as V
import Elm.Utils ((|>))
import qualified Reporting.Annotation as A
subst :: String -> Optimized.Expr' -> Optimized.Expr' -> Optimized.Expr'
subst old new expression =
let f (A.A a e) = A.A a (subst old new e) in
case expression of
Range lo hi ->
Range (f lo) (f hi)
ExplicitList exprs ->
ExplicitList (map f exprs)
Binop op left right ->
Binop op (f left) (f right)
Lambda pattern body ->
if Pattern.member old pattern
then expression
else Lambda pattern (f body)
App func arg ->
App (f func) (f arg)
If branches finally ->
If (map (f *** f) branches) (f finally)
Let defs body ->
if anyShadow
then expression
else Let (map substDef defs) (f body)
where
substDef (Optimized.Definition facts pattern expr) =
Optimized.Definition facts pattern (f expr)
anyShadow =
map (\(Optimized.Definition _ p _) -> p) defs
|> any (Pattern.member old)
Var (V.Canonical home x) ->
case home of
V.Module _ ->
expression
V.BuiltIn ->
expression
V.Local ->
if x == old then new else expression
V.TopLevel _ ->
if x == old then new else expression
Case e cases ->
Case (f e) (map substCase cases)
where
substCase (pattern, expr) =
if Pattern.member old pattern
then (pattern, expr)
else (pattern, f expr)
Data tag values ->
Data tag (map f values)
Access record field ->
Access (f record) field
Update record fields ->
Update (f record) (map (second f) fields)
Record fields ->
Record (map (second f) fields)
Literal _ ->
expression
GLShader _ _ _ ->
expression
Port impl ->
Port $
case impl of
In _ _ ->
impl
Out name expr tipe ->
Out name (f expr) tipe
Task name expr tipe ->
Task name (f expr) tipe
Crash _ ->
expression
| pairyo/elm-compiler | src/Optimize/Substitute.hs | bsd-3-clause | 2,604 | 0 | 18 | 1,028 | 856 | 435 | 421 | 75 | 27 |
module Orphans where
import Data.CaseInsensitive (CI, FoldCase, mk, original)
import Data.Aeson (FromJSON(..), ToJSON(..))
instance (FoldCase a, FromJSON a) => FromJSON (CI a) where
parseJSON a = mk <$> parseJSON a
instance ToJSON a => ToJSON (CI a) where
toJSON = toJSON . original
| martyall/kafaka-test | src/Orphans.hs | bsd-3-clause | 303 | 0 | 7 | 63 | 118 | 66 | 52 | 7 | 0 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Snap.Util.Proxy.Tests (tests) where
------------------------------------------------------------------------------
import Control.Monad.State hiding (get)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.CaseInsensitive (CI(..))
import qualified Data.Map as Map
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test, path)
------------------------------------------------------------------------------
import Snap.Core hiding (setHeader)
import Snap.Test
import Snap.Test.Common
import Snap.Util.Proxy
------------------------------------------------------------------------------
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testNoProxy
, testForwardedFor
, testTrivials
]
---------------
-- Constants --
---------------
------------------------------------------------------------------------------
initialPort :: Int
initialPort = 9999
initialAddr :: ByteString
initialAddr = "127.0.0.1"
-----------
-- Tests --
-----------
------------------------------------------------------------------------------
testNoProxy :: Test
testNoProxy = testCase "proxy/no-proxy" $ do
a <- evalHandler (mkReq $ forwardedFor [("4.3.2.1", Nothing)])
(behindProxy NoProxy reportRemoteAddr)
p <- evalHandler (mkReq $ forwardedFor [("4.3.2.1", Nothing)])
(behindProxy NoProxy reportRemotePort)
assertEqual "NoProxy leaves request alone" initialAddr a
assertEqual "NoProxy leaves request alone" initialPort p
--------------------------------------------------------------------------
b <- evalHandler (mkReq $ xForwardedFor [("4.3.2.1", Nothing)])
(behindProxy NoProxy reportRemoteAddr)
assertEqual "NoProxy leaves request alone" initialAddr b
--------------------------------------------------------------------------
c <- evalHandler (mkReq $ return ())
(behindProxy NoProxy reportRemoteAddr)
assertEqual "NoProxy leaves request alone" initialAddr c
------------------------------------------------------------------------------
testForwardedFor :: Test
testForwardedFor = testCase "proxy/forwarded-for" $ do
(a,p) <- evalHandler (mkReq $ return ()) handler
assertEqual "No Forwarded-For, no change" initialAddr a
assertEqual "port" initialPort p
--------------------------------------------------------------------------
(b,_) <- evalHandler (mkReq $ forwardedFor addr) handler
assertEqual "Behind 5.6.7.8" ip b
--------------------------------------------------------------------------
(c,q) <- evalHandler (mkReq $ xForwardedFor addrs2) handler
assertEqual "Behind 5.6.7.8" ip c
assertEqual "port change" port q
where
handler = behindProxy X_Forwarded_For $ do
!a <- reportRemoteAddr
!p <- reportRemotePort
return $! (a,p)
ip = "5.6.7.8"
port = 10101
addr = [ (ip, Nothing) ]
addr2 = [ (ip, Just port) ]
addrs2 = [("4.3.2.1", Just 20202)] ++ addr2
------------------------------------------------------------------------------
testTrivials :: Test
testTrivials = testCase "proxy/trivials" $ do
coverShowInstance NoProxy
coverReadInstance NoProxy
coverEqInstance NoProxy
coverOrdInstance NoProxy
---------------
-- Functions --
---------------
------------------------------------------------------------------------------
mkReq :: RequestBuilder IO () -> RequestBuilder IO ()
mkReq m = do
get "/" Map.empty
modify $ \req -> req { rqRemoteAddr = initialAddr
, rqRemotePort = initialPort
}
m
------------------------------------------------------------------------------
reportRemoteAddr :: Snap ByteString
reportRemoteAddr = withRequest $ \req -> return $ rqRemoteAddr req
------------------------------------------------------------------------------
reportRemotePort :: Snap Int
reportRemotePort = withRequest $ \req -> return $ rqRemotePort req
------------------------------------------------------------------------------
forwardedFor' :: CI ByteString -- ^ header name
-> [(ByteString, Maybe Int)] -- ^ list of "forwarded-for"
-> RequestBuilder IO ()
forwardedFor' hdr addrs = do
setHeader hdr out
where
toStr (a, Nothing) = a
toStr (a, Just p ) = S.concat [ a, ":", S.pack $ show p ]
out = S.intercalate ", " $ map toStr addrs
------------------------------------------------------------------------------
forwardedFor :: [(ByteString, Maybe Int)]
-> RequestBuilder IO ()
forwardedFor = forwardedFor' "Forwarded-For"
------------------------------------------------------------------------------
xForwardedFor :: [(ByteString, Maybe Int)]
-> RequestBuilder IO ()
xForwardedFor = forwardedFor' "X-Forwarded-For"
| f-me/snap-core | test/suite/Snap/Util/Proxy/Tests.hs | bsd-3-clause | 5,504 | 0 | 14 | 1,334 | 1,027 | 552 | 475 | 86 | 2 |
-- 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.Numeral.HE.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Numeral.HE.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "HE Tests"
[ makeCorpusTest [Seal Numeral] corpus
]
| facebookincubator/duckling | tests/Duckling/Numeral/HE/Tests.hs | bsd-3-clause | 503 | 0 | 9 | 77 | 79 | 50 | 29 | 11 | 1 |
{-# LANGUAGE RankNTypes #-}
module Main where
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Network.HTTP.Client as HTTP
import qualified Network.Wreq.Session as S
import Network.Wreq
import Text.Xml.Lens
import Utils
import Option
import VCloud.Namespace
import VCloud.PayloadMapper
import VCloud.Prelude
vCloudVers = "1.5"
fetchVM :: AsXmlDocument t => Text -> Traversal' t Element
fetchVM n = xml...ovfNode "VirtualSystem".attributed (ix (nsName ovfNS "id").only n)
fetchVmId :: Traversal' Element Element
fetchVmId = vcloudNode "GuestCustomizationSection" .vcloudNode "VirtualMachineId"
fetchIP :: Traversal' Element Element
fetchIP = vcloudNode "NetworkConnectionSection"...vcloudNode "IpAddress"
main = do
Option {..} <- getOption
let apiUrl = vCloudURL <> "/api"
loginPath = apiUrl <> "/login"
-- we only query inside one vApp
vAppQueryPath = apiUrl <> "/vApp/vapp-" <> vAppId <>"/ovf"
-- query a specific virtual machine
S.withSessionControl (Just (HTTP.createCookieJar [])) ignoreTLSCertificatesSettings $ \sess -> do
let opts = defaults & header "Accept" .~ ["application/*+xml;version=" <> vCloudVers]
-- check action
(contentType, payload) <- lookupPayload vmAction
-- login
_ <- S.getWith (opts & auth ?~ basicAuth (Text.encodeUtf8 vCloudUser) (Text.encodeUtf8 vCloudPass)) sess loginPath
-- Get raw xml info about our vApp
raw0 <- S.getWith opts sess vAppQueryPath
let vmId = raw0 ^. responseBody . fetchVM vmName . fetchVmId.text
actionUri = apiUrl <> "/vApp/vm-" <> Text.unpack vmId <> "/action/" <> vmAction
let postOpts = maybe opts (\x -> opts & header "Content-Type" .~ [x]) contentType
-- post the action
raw1 <- S.postWith postOpts sess actionUri payload
print $ raw1 ^. responseStatus.statusMessage
let taskLink = raw1 ^. responseHeader "Location"
-- wait for a success return code
waitTask 12 (S.getWith opts sess (BC.unpack taskLink))
| PierreR/vCloudApi | src/vcloud.hs | bsd-3-clause | 2,164 | 1 | 19 | 471 | 564 | 295 | 269 | -1 | -1 |
module Spec where
import Data.PairsSpec
import Test.Tasty
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Testing..."
[spec]
| athanclark/pairs | test/Spec.hs | bsd-3-clause | 160 | 0 | 6 | 30 | 50 | 28 | 22 | 8 | 1 |
{-# LANGUAGE QuasiQuotes, RecordWildCards #-}
-- | (you should read the source for documentation: just think of this module as a config file)
module Commands.Frontends.Dragon13.Shim.Selection where
import Commands.Frontends.Dragon13.Shim.Types
import Text.InterpolatedString.Perl6
import GHC.Exts (IsString)
{-|
@
A select XYZ grammar is a special grammar which
recognizes an utterance of the form "<select> <text> [ <through> <text> ]"
where <select> and <through> can both be lists of keywords
and <text> is an arbitrary sequence of words in a specified text buffer.
@
-}
getSelectionShim :: (IsString t, Monoid t) => SelectionShimR t -> t
getSelectionShim SelectionShimR{..} = [qc|
#-*- coding: utf-8 -*-
# _selection.py
DEBUG = True
# natlink13 library
from natlinkmain import (setCheckForGrammarChanges)
from natlinkutils import (SelectGramBase)
import natlink # a DLL
# python standard library
import time
import json
import urllib2
import traceback
from collections import (namedtuple)
################################################################################
# TYPES
Properties = namedtuple('Properties', ['status', 'exclusivity', 'shouldEavesdrop', 'shouldHypothesize'])
################################################################################
# UTILITIES
# current time in milliseconds
def now():
return int(time.clock() * 1000)
def toDragonText(s):
return s.decode('utf8').encode('cp1252')
################################################################################
# INTERPOLATIONS from "H"askell
'''
H_NAME = {__SelectionShimR_name__}
H_SELECT_WORDS = {__SelectionShimR_selectWords__}
H_THROUGH_WORDS = {__SelectionShimR_throughWords__}
H_SERVER_HOST = {__SelectionShimR_serverHost__}
H_SERVER_PORT = {__SelectionShimR_serverPort__}
H_PROPERTIES = {__SelectionShimR_properties__}
'''
# example for debugging, overrides previous assignments
if DEBUG:
print "DEBUG is True"
H_PROPERTIES = Properties(status=True, exclusivity=1, shouldEavesdrop=0, shouldHypothesize=0)
H_SELECT_WORDS = ["select"]
H_THROUGH_WORDS = ["until"]
################################################################################
# THE GRAMMAR
'''
def load( self, selectWords=None, throughWord='through',throughWords=None,allResults=0, hypothesis=0 ):
'''
class MySelectionGrammar(SelectGramBase):
def __init__(self):
SelectGramBase.__init__(self)
self.load (selectWords=H_SELECT_WORDS , throughWords=H_THROUGH_WORDS , allResults=H_PROPERTIES.shouldEavesdrop, hypothesis=H_PROPERTIES.shouldHypothesize)
self.activate (exclusive=H_PROPERTIES.exclusivity)
def update(self,selectWords,throughWords):
print "MySelectionGrammar.update"
def gotBegin(self,moduleInfo):
print "MySelectionGrammar.gotBegin"
def gotResultsObject(self,recogType,resObj):
print "MySelectionGrammar.gotResultsObject"
def gotResults(self,words,start,end):
print ""
print '[MySelectionGrammar] recognition'
print (start, end)
print words
################################################################################
# TESTING
'''
e.g. "select Omnibian until symbol" should work
'''
def testMySelectionGrammar(grammar):
print "testMySelectionGrammar..."
text = ''' here is an example buffer with a weird word like Omnibian
and with punctuation, like this symbol ":" and the above double newline.
'''
text = toDragonText ( u'the peculiar Omnibian')
grammar.setSelectText(text)
print
print '[text]'
print grammar.getSelectText()
################################################################################
# BOILERPLATE
# mutable global
GRAMMAR = None
def load():
global GRAMMAR
# automatically reload on file change (not only when microphone toggles on)
setCheckForGrammarChanges(1)
GRAMMAR = MySelectionGrammar()
if DEBUG:
testMySelectionGrammar(GRAMMAR)
# GRAMMAR.initialize()
def unload():
global GRAMMAR
if GRAMMAR:
GRAMMAR.unload()
GRAMMAR = None
load()
################################################################################
''' TODO
def gotResultsObject(self,recogType,resObj):
debug.trace('SelectWinGramNL.gotResultsObject', '** invoked, resObj=%s' % repr(resObj))
if recogType == 'self':
utterance = sr_interface.SpokenUtteranceNL(resObj)
self.results_callback(utterance)
debug.trace('SelectWinGramNL.gotResultsObject', '** recogType = self')
# If there are multiple matches in the text we need to scan through
# the list of choices to find every entry which has the highest.
ranges = []
try:
bestScore = resObj.getWordInfo(0)[0][2]
verb = resObj.getWordInfo(0)[0][0]
#
# Collect selection ranges with highest score
#
for i in range(100):
#
# The candidate regions are sorted from best to worst scores.
# Loop through candidate regions until we reach one whose
# score is not the same as the first score (or until a
# natlink.outOfRange exception is raised to signal the end
# of the list of candidate regions).
#
wordInfo = resObj.getWordInfo(i)
# debug.trace('SelectWinGramNL.gotResultsObject', '** i=%s, len(wordInfo)=%s' % (i, len(wordInfo)))
# debug.trace('SelectWinGramNL.gotResultsObject', '** i=%s, len(wordInfo[0])=%s' % (i, len(wordInfo[0])))
if wordInfo[0][2] != bestScore:
#
# All remaining regions don't have as good a score as the
# first ones.
break
else:
#
# This region has the same score as the first ones. Add it
# to the candidate selection ranges.
#
#QH: if a results object is not of this Select Grammar
#also break
try:
region = resObj.getSelectInfo(self.gramObj, i)
except natlink.WrongType:
continue
if debug.tracing('SelectWinGramNL.gotResultsObject'):
debug.trace('SelectWinGramNL.gotResultsObject', 'adding region=%s' % repr(region))
true_region = (region[0] + self.vis_start,
region[1] + self.vis_start)
#
# For some reason, NatSpeak may return duplicate ranges
#
if not true_region in ranges:
ranges.append(true_region)
except natlink.OutOfRange, exceptions.IndexError:
pass
spoken = self.selection_spoken_form(resObj)
debug.trace('SelectWinGramNL.gotResultsObject', 'verb=%s, spoken=%s, ranges=%s' % (verb, spoken, repr(ranges)))
self.find_closest(verb, spoken, ranges)
'''
|]
| sboosali/commands-frontend-DragonNaturallySpeaking | sources/Commands/Frontends/Dragon13/Shim/Selection.hs | bsd-3-clause | 7,478 | 0 | 7 | 2,101 | 81 | 51 | 30 | 7 | 1 |
{-# LANGUAGE LambdaCase #-}
module Main where
import Bound
import Control.Monad
import Control.Monad.Trans
import Control.Lens
import Text.Trifecta (Result(..))
import Text.PrettyPrint.ANSI.Leijen (dullyellow, text)
import System.Console.Haskeline
import System.Environment
import System.Exit
import AST
import Eval
import Parser
import PrettyPrint
import TypeCheck
evaluate :: Module Name -> InputT IO ()
evaluate m = do
case closed m of
Nothing -> outputStrLn "Module has free variables!"
Just tyModule -> do
case typeCheckModule tyModule of
Left e -> outputPretty e
Right _ -> exprLoop tyModule
where
exprLoop :: Module (Named Type) -> InputT IO ()
exprLoop tyModule = forever $ do
outputStrLn ""
input <- getInputLine "> "
case input of
Nothing -> liftIO exitSuccess
Just s
| null s -> liftIO exitSuccess
| otherwise -> case parseFromData expr s of
Failure errs -> outputPretty errs
Success e -> evalExpr tyModule e
evalExpr :: Module (Named Type) -> Expr Name -> InputT IO ()
evalExpr tyModule e = do
let scopedExpr = abstractKeys (tyModule^.decls) e
case typeCheckExpr tyModule <$> closed scopedExpr of
Nothing -> outputStrLn "Expression has free variables!"
Just (Left err) -> outputPretty err
Just (Right (Type tyExpr)) -> do
outputPretty (nfWith m e)
outputStr $ " " ++ show (dullyellow (text "::")) ++ " "
outputPretty tyExpr
main :: IO ()
main = do
(file:_) <- getArgs
runInputT defaultSettings $ do
parseFromFile moduleParser file >>= \case
Failure errs -> outputPretty errs
Success m -> outputPretty m >> evaluate m
| merijn/lambda-except | Main.hs | bsd-3-clause | 1,876 | 0 | 20 | 582 | 571 | 272 | 299 | 52 | 7 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
module Game.Monsters.MParasite where
import Control.Lens (use, preuse, ix, zoom, (^.), (.=), (%=), (&), (.~), (%~))
import Control.Monad (when, unless, liftM, void)
import Data.Bits ((.&.), (.|.))
import Linear (V3(..), norm)
import qualified Data.Vector as V
import {-# SOURCE #-} Game.GameImportT
import Game.LevelLocalsT
import Game.GameLocalsT
import Game.CVarT
import Game.SpawnTempT
import Game.EntityStateT
import Game.EdictT
import Game.GClientT
import Game.MoveInfoT
import Game.ClientPersistantT
import Game.ClientRespawnT
import Game.MonsterInfoT
import Game.PlayerStateT
import Types
import QuakeRef
import QuakeState
import CVarVariables
import Game.Adapters
import qualified Constants
import qualified Game.GameAI as GameAI
import qualified Game.GameMisc as GameMisc
import qualified Game.GameUtil as GameUtil
import qualified Util.Lib as Lib
import qualified Util.Math3D as Math3D
modelScale :: Float
modelScale = 1.0
frameBreak01 :: Int
frameBreak01 = 0
frameBreak32 :: Int
frameBreak32 = 31
frameDeath101 :: Int
frameDeath101 = 32
frameDeath107 :: Int
frameDeath107 = 38
frameDrain01 :: Int
frameDrain01 = 39
frameDrain18 :: Int
frameDrain18 = 56
framePain101 :: Int
framePain101 = 57
framePain111 :: Int
framePain111 = 67
frameRun01 :: Int
frameRun01 = 68
frameRun02 :: Int
frameRun02 = 69
frameRun03 :: Int
frameRun03 = 70
frameRun09 :: Int
frameRun09 = 76
frameRun10 :: Int
frameRun10 = 77
frameRun15 :: Int
frameRun15 = 82
frameStand01 :: Int
frameStand01 = 83
frameStand17 :: Int
frameStand17 = 99
frameStand18 :: Int
frameStand18 = 100
frameStand21 :: Int
frameStand21 = 103
frameStand22 :: Int
frameStand22 = 104
frameStand27 :: Int
frameStand27 = 109
frameStand28 :: Int
frameStand28 = 110
frameStand35 :: Int
frameStand35 = 117
parasiteLaunch :: EntThink
parasiteLaunch =
GenericEntThink "parasite_launch" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundLaunch <- use $ mParasiteGlobals.mParasiteSoundLaunch
sound (Just selfRef) Constants.chanWeapon soundLaunch 1 Constants.attnNorm 0
return True
parasiteReelIn :: EntThink
parasiteReelIn =
GenericEntThink "parasite_reel_in" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundReelIn <- use $ mParasiteGlobals.mParasiteSoundReelIn
sound (Just selfRef) Constants.chanWeapon soundReelIn 1 Constants.attnNorm 0
return True
parasiteSight :: EntInteract
parasiteSight =
GenericEntInteract "parasite_sight" $ \selfRef _ -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundSight <- use $ mParasiteGlobals.mParasiteSoundSight
sound (Just selfRef) Constants.chanWeapon soundSight 1 Constants.attnNorm 0
return True
parasiteTap :: EntThink
parasiteTap =
GenericEntThink "parasite_tap" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundTap <- use $ mParasiteGlobals.mParasiteSoundTap
sound (Just selfRef) Constants.chanWeapon soundTap 1 Constants.attnIdle 0
return True
parasiteScratch :: EntThink
parasiteScratch =
GenericEntThink "parasite_scratch" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundScratch <- use $ mParasiteGlobals.mParasiteSoundScratch
sound (Just selfRef) Constants.chanWeapon soundScratch 1 Constants.attnIdle 0
return True
parasiteSearch :: EntThink
parasiteSearch =
GenericEntThink "parasite_search" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundSearch <- use $ mParasiteGlobals.mParasiteSoundSearch
sound (Just selfRef) Constants.chanWeapon soundSearch 1 Constants.attnIdle 0
return True
parasiteStartWalk :: EntThink
parasiteStartWalk =
GenericEntThink "parasite_start_walk" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveStartWalk)
return True
parasiteWalk :: EntThink
parasiteWalk =
GenericEntThink "parasite_walk" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveWalk)
return True
parasiteStand :: EntThink
parasiteStand =
GenericEntThink "parasite_stand" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveStand)
return True
parasiteEndFidget :: EntThink
parasiteEndFidget =
GenericEntThink "parasite_end_fidget" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveEndFidget)
return True
parasiteDoFidget :: EntThink
parasiteDoFidget =
GenericEntThink "parasite_do_fidget" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveFidget)
return True
parasiteReFidget :: EntThink
parasiteReFidget =
GenericEntThink "parasite_refidget" $ \selfRef -> do
r <- Lib.randomF
let action = if r <= 0.8
then parasiteMoveFidget
else parasiteMoveEndFidget
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
parasiteIdle :: EntThink
parasiteIdle =
GenericEntThink "parasite_idle" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveStartFidget)
return True
parasiteStartRun :: EntThink
parasiteStartRun =
GenericEntThink "parasite_start_run" $ \selfRef -> do
self <- readRef selfRef
let action = if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0
then parasiteMoveStand
else parasiteMoveStartRun
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
parasiteRun :: EntThink
parasiteRun =
GenericEntThink "parasite_run" $ \selfRef -> do
self <- readRef selfRef
let action = if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0
then parasiteMoveStand
else parasiteMoveRun
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
parasiteFramesStartFidget :: V.Vector MFrameT
parasiteFramesStartFidget =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
parasiteMoveStartFidget :: MMoveT
parasiteMoveStartFidget = MMoveT "parasiteMoveStartFidget" frameStand18 frameStand21 parasiteFramesStartFidget (Just parasiteDoFidget)
parasiteFramesFidget :: V.Vector MFrameT
parasiteFramesFidget =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 (Just parasiteScratch)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 (Just parasiteScratch)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
parasiteMoveFidget :: MMoveT
parasiteMoveFidget = MMoveT "parasiteMoveFidget" frameStand22 frameStand27 parasiteFramesFidget (Just parasiteReFidget)
parasiteFramesEndFidget :: V.Vector MFrameT
parasiteFramesEndFidget =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 (Just parasiteScratch)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
parasiteMoveEndFidget :: MMoveT
parasiteMoveEndFidget = MMoveT "parasiteMoveEndFidget" frameStand28 frameStand35 parasiteFramesEndFidget (Just parasiteStand)
parasiteFramesStand :: V.Vector MFrameT
parasiteFramesStand =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 (Just parasiteTap)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 (Just parasiteTap)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 (Just parasiteTap)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 (Just parasiteTap)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 (Just parasiteTap)
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 (Just parasiteTap)
]
parasiteMoveStand :: MMoveT
parasiteMoveStand = MMoveT "parasiteMoveStand" frameStand01 frameStand17 parasiteFramesStand (Just parasiteStand)
parasiteFramesRun :: V.Vector MFrameT
parasiteFramesRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 30 Nothing
, MFrameT (Just GameAI.aiRun) 30 Nothing
, MFrameT (Just GameAI.aiRun) 22 Nothing
, MFrameT (Just GameAI.aiRun) 19 Nothing
, MFrameT (Just GameAI.aiRun) 24 Nothing
, MFrameT (Just GameAI.aiRun) 28 Nothing
, MFrameT (Just GameAI.aiRun) 25 Nothing
]
parasiteMoveRun :: MMoveT
parasiteMoveRun = MMoveT "parasiteMoveRun" frameRun03 frameRun09 parasiteFramesRun Nothing
parasiteFramesStartRun :: V.Vector MFrameT
parasiteFramesStartRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 0 Nothing
, MFrameT (Just GameAI.aiRun) 30 Nothing
]
parasiteMoveStartRun :: MMoveT
parasiteMoveStartRun = MMoveT "parasiteMoveStartRun" frameRun01 frameRun02 parasiteFramesStartRun (Just parasiteRun)
parasiteFramesStopRun :: V.Vector MFrameT
parasiteFramesStopRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 20 Nothing
, MFrameT (Just GameAI.aiRun) 20 Nothing
, MFrameT (Just GameAI.aiRun) 12 Nothing
, MFrameT (Just GameAI.aiRun) 10 Nothing
, MFrameT (Just GameAI.aiRun) 0 Nothing
, MFrameT (Just GameAI.aiRun) 0 Nothing
]
parasiteMoveStopRun :: MMoveT
parasiteMoveStopRun = MMoveT "parasiteMoveStopRun" frameRun10 frameRun15 parasiteFramesStopRun Nothing
parasiteFramesWalk :: V.Vector MFrameT
parasiteFramesWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 30 Nothing
, MFrameT (Just GameAI.aiWalk) 30 Nothing
, MFrameT (Just GameAI.aiWalk) 22 Nothing
, MFrameT (Just GameAI.aiWalk) 19 Nothing
, MFrameT (Just GameAI.aiWalk) 24 Nothing
, MFrameT (Just GameAI.aiWalk) 28 Nothing
, MFrameT (Just GameAI.aiWalk) 25 Nothing
]
parasiteMoveWalk :: MMoveT
parasiteMoveWalk = MMoveT "parasiteMoveWalk" frameRun03 frameRun09 parasiteFramesWalk (Just parasiteWalk)
parasiteFramesStartWalk :: V.Vector MFrameT
parasiteFramesStartWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 0 Nothing
, MFrameT (Just GameAI.aiWalk) 30 (Just parasiteWalk)
]
parasiteMoveStartWalk :: MMoveT
parasiteMoveStartWalk = MMoveT "parasiteMoveStartWalk" frameRun01 frameRun02 parasiteFramesStartWalk Nothing
parasiteFramesStopWalk :: V.Vector MFrameT
parasiteFramesStopWalk =
V.fromList [ MFrameT (Just GameAI.aiWalk) 20 Nothing
, MFrameT (Just GameAI.aiWalk) 20 Nothing
, MFrameT (Just GameAI.aiWalk) 12 Nothing
, MFrameT (Just GameAI.aiWalk) 10 Nothing
, MFrameT (Just GameAI.aiWalk) 0 Nothing
, MFrameT (Just GameAI.aiWalk) 0 Nothing
]
parasiteMoveStopWalk :: MMoveT
parasiteMoveStopWalk = MMoveT "parasiteMoveStopWalk" frameRun10 frameRun15 parasiteFramesStopWalk Nothing
parasiteFramesPain1 :: V.Vector MFrameT
parasiteFramesPain1 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 6 Nothing
, MFrameT (Just GameAI.aiMove) 16 Nothing
, MFrameT (Just GameAI.aiMove) (-6) Nothing
, MFrameT (Just GameAI.aiMove) (-7) Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
parasiteMovePain1 :: MMoveT
parasiteMovePain1 = MMoveT "parasiteMovePain1" framePain101 framePain111 parasiteFramesPain1 (Just parasiteStartRun)
parasitePain :: EntPain
parasitePain =
GenericEntPain "parasite_pain" $ \selfRef _ _ _ -> do
self <- readRef selfRef
when ((self^.eHealth) < (self^.eMaxHealth) `div` 2) $
modifyRef selfRef (\v -> v & eEntityState.esSkinNum .~ 1)
levelTime <- use $ gameBaseGlobals.gbLevel.llTime
unless (levelTime < (self^.ePainDebounceTime)) $ do
modifyRef selfRef (\v -> v & ePainDebounceTime .~ levelTime + 3)
skillValue <- liftM (^.cvValue) skillCVar
unless (skillValue == 3) $ do -- no pain anims in nightmare
r <- Lib.randomF
soundPain <- if r < 0.5
then use $ mParasiteGlobals.mParasiteSoundPain1
else use $ mParasiteGlobals.mParasiteSoundPain2
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanVoice soundPain 1 Constants.attnNorm 0
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMovePain1)
parasiteDrainAttack :: EntThink
parasiteDrainAttack =
GenericEntThink "parasite_drain_attack" $ \_ -> do
io (putStrLn "MParasite.parasiteDrainAttack") >> undefined -- TODO
parasiteFramesDrain :: V.Vector MFrameT
parasiteFramesDrain =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 (Just parasiteLaunch)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 15 (Just parasiteDrainAttack) -- Target hits
, MFrameT (Just GameAI.aiCharge) 0 (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) 0 (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) 0 (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) 0 (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) (-2) (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) (-2) (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) (-3) (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) (-2) (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) 0 (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) (-1) (Just parasiteDrainAttack) -- drain
, MFrameT (Just GameAI.aiCharge) 0 (Just parasiteReelIn) -- let go
, MFrameT (Just GameAI.aiCharge) (-2) Nothing
, MFrameT (Just GameAI.aiCharge) (-2) Nothing
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
]
parasiteMoveDrain :: MMoveT
parasiteMoveDrain = MMoveT "parasiteMoveDrain" frameDrain01 frameDrain18 parasiteFramesDrain (Just parasiteStartRun)
parasiteFramesBreak :: V.Vector MFrameT
parasiteFramesBreak =
V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
, MFrameT (Just GameAI.aiCharge) 1 Nothing
, MFrameT (Just GameAI.aiCharge) 2 Nothing
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
, MFrameT (Just GameAI.aiCharge) 1 Nothing
, MFrameT (Just GameAI.aiCharge) 1 Nothing
, MFrameT (Just GameAI.aiCharge) 3 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-18) Nothing
, MFrameT (Just GameAI.aiCharge) 3 Nothing
, MFrameT (Just GameAI.aiCharge) 9 Nothing
, MFrameT (Just GameAI.aiCharge) 6 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-18) Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 8 Nothing
, MFrameT (Just GameAI.aiCharge) 9 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-18) Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
-- airborne
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- slides
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- slides
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- slides
, MFrameT (Just GameAI.aiCharge) 0 Nothing -- slides
, MFrameT (Just GameAI.aiCharge) 4 Nothing
, MFrameT (Just GameAI.aiCharge) 11 Nothing
, MFrameT (Just GameAI.aiCharge) (-2) Nothing
, MFrameT (Just GameAI.aiCharge) (-5) Nothing
, MFrameT (Just GameAI.aiCharge) 1 Nothing
]
parasiteMoveBreak :: MMoveT
parasiteMoveBreak = MMoveT "parasiteMoveBreak" frameBreak01 frameBreak32 parasiteFramesBreak (Just parasiteStartRun)
parasiteAttack :: EntThink
parasiteAttack =
GenericEntThink "parasite_attack" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveDrain)
return True
parasiteDead :: EntThink
parasiteDead =
GenericEntThink "parasite_dead" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMins .~ V3 (-16) (-16) (-24)
& eMaxs .~ V3 16 16 (-8)
& eMoveType .~ Constants.moveTypeToss
& eSvFlags %~ (.|. Constants.svfDeadMonster)
& eNextThink .~ 0)
linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity
linkEntity selfRef
return True
parasiteFramesDeath :: V.Vector MFrameT
parasiteFramesDeath =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
parasiteMoveDeath :: MMoveT
parasiteMoveDeath = MMoveT "parasiteMoveDeath" frameDeath101 frameDeath107 parasiteFramesDeath (Just parasiteDead)
parasiteDie :: EntDie
parasiteDie =
GenericEntDie "parasite_die" $ \selfRef _ _ damage _ -> do
self <- readRef selfRef
gameImport <- use $ gameBaseGlobals.gbGameImport
let soundIndex = gameImport^.giSoundIndex
sound = gameImport^.giSound
if | (self^.eHealth) <= (self^.eGibHealth) -> do -- check for gib
soundIdx <- soundIndex (Just "misc/udeath.wav")
sound (Just selfRef) Constants.chanVoice soundIdx 1 Constants.attnNorm 0
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwHead selfRef "models/objects/gibs/head2/tris.md2" damage Constants.gibOrganic
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead)
| (self^.eDeadFlag) == Constants.deadDead ->
return ()
| otherwise -> do -- regular death
soundDie <- use $ mParasiteGlobals.mParasiteSoundDie
sound (Just selfRef) Constants.chanVoice soundDie 1 Constants.attnNorm 0
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead
& eTakeDamage .~ Constants.damageYes
& eMonsterInfo.miCurrentMove .~ Just parasiteMoveDeath)
{-
- QUAKED monster_parasite (1 .5 0) (-16 -16 -24) (16 16 32) Ambush
- Trigger_Spawn Sight
-}
spMonsterParasite :: EntThink
spMonsterParasite =
GenericEntThink "SP_monster_parasite" $ \selfRef -> do
deathmatchValue <- liftM (^.cvValue) deathmatchCVar
if deathmatchValue /= 0
then do
GameUtil.freeEdict selfRef
return True
else do
gameImport <- use $ gameBaseGlobals.gbGameImport
let soundIndex = gameImport^.giSoundIndex
modelIndex = gameImport^.giModelIndex
linkEntity = gameImport^.giLinkEntity
soundIndex (Just "parasite/parpain1.wav") >>= (mParasiteGlobals.mParasiteSoundPain1 .=)
soundIndex (Just "parasite/parpain2.wav") >>= (mParasiteGlobals.mParasiteSoundPain2 .=)
soundIndex (Just "parasite/pardeth1.wav") >>= (mParasiteGlobals.mParasiteSoundDie .=)
soundIndex (Just "parasite/paratck1.wav") >>= (mParasiteGlobals.mParasiteSoundLaunch .=)
soundIndex (Just "parasite/paratck2.wav") >>= (mParasiteGlobals.mParasiteSoundImpact .=)
soundIndex (Just "parasite/paratck3.wav") >>= (mParasiteGlobals.mParasiteSoundSuck .=)
soundIndex (Just "parasite/paratck4.wav") >>= (mParasiteGlobals.mParasiteSoundReelIn .=)
soundIndex (Just "parasite/parsght1.wav") >>= (mParasiteGlobals.mParasiteSoundSight .=)
soundIndex (Just "parasite/paridle1.wav") >>= (mParasiteGlobals.mParasiteSoundTap .=)
soundIndex (Just "parasite/paridle2.wav") >>= (mParasiteGlobals.mParasiteSoundScratch .=)
soundIndex (Just "parasite/parsrch1.wav") >>= (mParasiteGlobals.mParasiteSoundSearch .=)
modelIdx <- modelIndex (Just "models/monsters/parasite/tris.md2")
modifyRef selfRef (\v -> v & eEntityState.esModelIndex .~ modelIdx
& eMins .~ V3 (-16) (-16) (-24)
& eMaxs .~ V3 16 16 24
& eMoveType .~ Constants.moveTypeStep
& eSolid .~ Constants.solidBbox
& eHealth .~ 175
& eGibHealth .~ (-50)
& eMass .~ 250
& ePain .~ Just parasitePain
& eDie .~ Just parasiteDie
& eMonsterInfo.miStand .~ Just parasiteStand
& eMonsterInfo.miWalk .~ Just parasiteStartWalk
& eMonsterInfo.miRun .~ Just parasiteStartRun
& eMonsterInfo.miAttack .~ Just parasiteAttack
& eMonsterInfo.miSight .~ Just parasiteSight
& eMonsterInfo.miIdle .~ Just parasiteIdle)
linkEntity selfRef
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just parasiteMoveStand
& eMonsterInfo.miScale .~ modelScale)
void $ think GameAI.walkMonsterStart selfRef
return True
parasiteDrainAttackOK :: V3 Float -> V3 Float -> Bool
parasiteDrainAttackOK start end =
let dir = start - end
in if norm dir > 256
then False
else let V3 a _ _ = Math3D.vectorAngles dir
a' = if a < (-180) then a + 360 else a
in if abs a' > 30
then False
else True
| ksaveljev/hake-2 | src/Game/Monsters/MParasite.hs | bsd-3-clause | 24,761 | 0 | 47 | 6,629 | 6,613 | 3,363 | 3,250 | -1 | -1 |
{-# LANGUAGE PatternGuards #-}
module Idris.Core.Unify(match_unify, unify, Fails, FailContext(..), FailAt(..),
unrecoverable) where
import Idris.Core.TT
import Idris.Core.Evaluate
import Control.Monad
import Control.Monad.State.Strict
import Data.List
import Debug.Trace
-- Unification is applied inside the theorem prover. We're looking for holes
-- which can be filled in, by matching one term's normal form against another.
-- Returns a list of hole names paired with the term which solves them, and
-- a list of things which need to be injective.
-- terms which need to be injective, with the things we're trying to unify
-- at the time
data FailAt = Match | Unify
deriving (Show, Eq)
data FailContext = FailContext { fail_sourceloc :: FC,
fail_fn :: Name,
fail_param :: Name
}
deriving (Eq, Show)
type Injs = [(TT Name, TT Name, TT Name)]
type Fails = [(TT Name, TT Name, -- unification error
Bool, -- ready to retry yet
Env, Err, [FailContext], FailAt)]
unrecoverable :: Fails -> Bool
unrecoverable = any bad
where bad (_,_,_,_, err, _, _) = unrec err
unrec (CantUnify r _ _ _ _ _) = not r
unrec (At _ e) = unrec e
unrec (Elaborating _ _ e) = unrec e
unrec (ElaboratingArg _ _ _ e) = unrec e
unrec _ = False
data UInfo = UI Int Fails
deriving Show
data UResult a = UOK a
| UPartOK a
| UFail Err
-- | Smart constructor for unification errors that takes into account the FailContext
cantUnify :: [FailContext] -> Bool -> (t, Maybe Provenance) -> (t, Maybe Provenance) -> (Err' t) -> [(Name, t)] -> Int -> Err' t
cantUnify [] r t1 t2 e ctxt i = CantUnify r t1 t2 e ctxt i
cantUnify (FailContext fc f x : prev) r t1 t2 e ctxt i =
At fc (ElaboratingArg f x
(map (\(FailContext _ f' x') -> (f', x')) prev)
(CantUnify r t1 t2 e ctxt i))
-- Solve metavariables by matching terms against each other
-- Not really unification, of course!
match_unify :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) -> [Name] -> [Name] -> [FailContext] ->
TC [(Name, TT Name)]
match_unify ctxt env (topx, xfrom) (topy, yfrom) inj holes from =
case runStateT (un [] (renameBindersTm env topx)
(renameBindersTm env topy)) (UI 0 []) of
OK (v, UI _ []) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v')
res ->
let topxn = renameBindersTm env (normalise ctxt env topx)
topyn = renameBindersTm env (normalise ctxt env topy) in
case runStateT (un [] topxn topyn)
(UI 0 []) of
OK (v, UI _ fails) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v')
Error e ->
-- just normalise the term we're matching against
case runStateT (un [] topxn topy)
(UI 0 []) of
OK (v, UI _ fails) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v')
_ -> tfail e
where
un :: [((Name, Name), TT Name)] -> TT Name -> TT Name ->
StateT UInfo
TC [(Name, TT Name)]
-- This rule is highly dubious... it certainly produces a valid answer
-- but it scares me. However, matching is never guaranteed to give a unique
-- answer, merely a valid one, so perhaps we're okay.
-- In other words: it may vanish without warning some day :)
un names x tm@(App _ (P _ f (Bind fn (Pi _ t _) sc)) a)
| (P (TCon _ _) _ _, _) <- unApply x,
holeIn env f || f `elem` holes
= let n' = uniqueName (sMN 0 "mv") (map fst env) in
checkCycle names (f, Bind n' (Lam t) x)
un names tm@(App _ (P _ f (Bind fn (Pi _ t _) sc)) a) x
| (P (TCon _ _) _ _, _) <- unApply x,
holeIn env f || f `elem` holes
= let n' = uniqueName fn (map fst env) in
checkCycle names (f, Bind n' (Lam t) x)
un names x tm@(App _ (P _ f (Bind fn (Pi _ t _) sc)) a)
| (P (DCon _ _ _) _ _, _) <- unApply x,
holeIn env f || f `elem` holes
= let n' = uniqueName (sMN 0 "mv") (map fst env) in
checkCycle names (f, Bind n' (Lam t) x)
un names tm@(App _ (P _ f (Bind fn (Pi _ t _) sc)) a) x
| (P (DCon _ _ _) _ _, _) <- unApply x,
holeIn env f || f `elem` holes
= let n' = uniqueName fn (map fst env) in
checkCycle names (f, Bind n' (Lam t) x)
un names tx@(P _ x _) tm
| tx /= tm && holeIn env x || x `elem` holes
= do sc 1; checkCycle names (x, tm)
un names tm ty@(P _ y _)
| ty /= tm && holeIn env y || y `elem` holes
= do sc 1; checkCycle names (y, tm)
un bnames (V i) (P _ x _)
| length bnames > i,
fst (fst (bnames!!i)) == x ||
snd (fst (bnames!!i)) == x = do sc 1; return []
un bnames (P _ x _) (V i)
| length bnames > i,
fst (fst (bnames!!i)) == x ||
snd (fst (bnames!!i)) == x = do sc 1; return []
un bnames (Bind x bx sx) (Bind y by sy) | notHole bx && notHole by
= do h1 <- uB bnames bx by
h2 <- un (((x, y), binderTy bx) : bnames) sx sy
combine bnames h1 h2
un names (App _ fx ax) (App _ fy ay)
= do hf <- un names fx fy
ha <- un names ax ay
combine names hf ha
un names x y
| OK True <- convEq' ctxt holes x y = do sc 1; return []
| otherwise = do UI s f <- get
let r = recoverable (normalise ctxt env x)
(normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom) (CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
if (not r) then lift $ tfail err
else do put (UI s ((x, y, True, env, err, from, Match) : f))
lift $ tfail err
uB bnames (Let tx vx) (Let ty vy) = do h1 <- un bnames tx ty
h2 <- un bnames vx vy
combine bnames h1 h2
uB bnames (Lam tx) (Lam ty) = un bnames tx ty
uB bnames (Pi i tx _) (Pi i' ty _) = un bnames tx ty
uB bnames x y = do UI s f <- get
let r = recoverable (normalise ctxt env (binderTy x))
(normalise ctxt env (binderTy y))
let err = cantUnify from r (topx, xfrom) (topy, yfrom)
(CantUnify r (binderTy x, Nothing)
(binderTy y, Nothing) (Msg "") (errEnv env) s)
(errEnv env) s
put (UI s ((binderTy x, binderTy y,
False,
env, err, from, Match) : f))
return []
notHole (Hole _) = False
notHole _ = True
-- TODO: there's an annoying amount of repetition between this and the
-- main unification function. Consider lifting it out.
-- Issue #1721 on the issue tracker: https://github.com/idris-lang/Idris-dev/issues/1721
sc i = do UI s f <- get
put (UI (s+i) f)
unifyFail x y = do UI s f <- get
let r = recoverable (normalise ctxt env x)
(normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom)
(CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
put (UI s ((x, y, True, env, err, from, Match) : f))
lift $ tfail err
combine bnames as [] = return as
combine bnames as ((n, t) : bs)
= case lookup n as of
Nothing -> combine bnames (as ++ [(n,t)]) bs
Just t' -> do ns <- un bnames t t'
let ns' = filter (\ (x, _) -> x/=n) ns
sc 1
combine bnames as (ns' ++ bs)
-- substN n tm (var, sol) = (var, subst n tm sol)
checkCycle ns p@(x, P _ x' _) | x == x' = return []
checkCycle ns p@(x, P _ _ _) = return [p]
checkCycle ns (x, tm)
| not (x `elem` freeNames tm) = checkScope ns (x, tm)
| otherwise = lift $ tfail (InfiniteUnify x tm (errEnv env))
checkScope ns (x, tm) =
-- case boundVs (envPos x 0 env) tm of
-- [] -> return [(x, tm)]
-- (i:_) -> lift $ tfail (UnifyScope x (fst (fst (ns!!i)))
-- (inst ns tm) (errEnv env))
let v = highV (-1) tm in
if v >= length ns
then lift $ tfail (Msg "SCOPE ERROR")
else return [(x, bind v ns tm)]
where inst [] tm = tm
inst ((n, _) : ns) tm = inst ns (substV (P Bound n Erased) tm)
bind i ns tm
| i < 0 = tm
| otherwise = let ((x,y),ty) = ns!!i in
App MaybeHoles (Bind y (Lam ty) (bind (i-1) ns tm))
(P Bound x ty)
renameBinders env (x, t) = (x, renameBindersTm env t)
renameBindersTm :: Env -> TT Name -> TT Name
renameBindersTm env tm = uniqueBinders (map fst env) tm
where
uniqueBinders env (Bind n b sc)
| n `elem` env
= let n' = uniqueName n env in
explicitHole $ Bind n' (fmap (uniqueBinders env) b)
(uniqueBinders (n':env) (rename n n' sc))
| otherwise = Bind n (fmap (uniqueBinders (n:env)) b)
(uniqueBinders (n:env) sc)
uniqueBinders env (App s f a) = App s (uniqueBinders env f) (uniqueBinders env a)
uniqueBinders env t = t
rename n n' (P nt x ty) | n == x = P nt n' ty
rename n n' (Bind x b sc) = Bind x (fmap (rename n n') b) (rename n n' sc)
rename n n' (App s f a) = App s (rename n n' f) (rename n n' a)
rename n n' t = t
explicitHole (Bind n (Hole ty) sc)
= Bind n (Hole ty) (instantiate (P Bound n ty) sc)
explicitHole t = t
trimSolutions (topx, xfrom) (topy, yfrom) from env topns = followSols [] (dropPairs topns)
where dropPairs [] = []
dropPairs (n@(x, P _ x' _) : ns)
| x == x' = dropPairs ns
| otherwise
= n : dropPairs
(filter (\t -> case t of
(n, P _ n' _) -> not (n == x' && n' == x)
_ -> True) ns)
dropPairs (n : ns) = n : dropPairs ns
followSols vs [] = return []
followSols vs ((n, P _ t _) : ns)
| Just t' <- lookup t ns
= do vs' <- case t' of
P _ tn _ ->
if (n, tn) `elem` vs then -- cycle
tfail (cantUnify from False (topx, xfrom) (topy, yfrom)
(Msg "") (errEnv env) 0)
else return ((n, tn) : vs)
_ -> return vs
followSols vs' ((n, t') : ns)
followSols vs (n : ns) = do ns' <- followSols vs ns
return $ n : ns'
expandLets env (x, tm) = (x, doSubst (reverse env) tm)
where
doSubst [] tm = tm
doSubst ((n, Let v t) : env) tm
= doSubst env (subst n v tm)
doSubst (_ : env) tm
= doSubst env tm
hasv :: TT Name -> Bool
hasv (V x) = True
hasv (App _ f a) = hasv f || hasv a
hasv (Bind x b sc) = hasv (binderTy b) || hasv sc
hasv _ = False
unify :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) ->
[Name] -> [Name] -> [Name] -> [FailContext] ->
TC ([(Name, TT Name)], Fails)
unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
-- traceWhen (hasv topx || hasv topy)
-- ("Unifying " ++ show topx ++ "\nAND\n" ++ show topy ++ "\n") $
-- don't bother if topx and topy are different at the head
case runStateT (un False [] (renameBindersTm env topx)
(renameBindersTm env topy)) (UI 0 []) of
OK (v, UI _ []) -> do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v', [])
res ->
let topxn = renameBindersTm env (normalise ctxt env topx)
topyn = renameBindersTm env (normalise ctxt env topy) in
-- trace ("Unifying " ++ show (topx, topy) ++ "\n\n==>\n" ++ show (topxn, topyn) ++ "\n\n") $
case runStateT (un False [] topxn topyn)
(UI 0 []) of
OK (v, UI _ fails) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
-- trace ("OK " ++ show (topxn, topyn, v, holes)) $
return (map (renameBinders env) v', reverse fails)
-- Error e@(CantUnify False _ _ _ _ _) -> tfail e
Error e -> tfail e
where
headDiff (P (DCon _ _ _) x _) (P (DCon _ _ _) y _) = x /= y
headDiff (P (TCon _ _) x _) (P (TCon _ _) y _) = x /= y
headDiff _ _ = False
injective (P (DCon _ _ _) _ _) = True
injective (P (TCon _ _) _ _) = True
injective (App _ f a) = injective f -- && injective a
injective _ = False
-- injectiveVar (P _ (MN _ _) _) = True -- TMP HACK
injectiveVar (P _ n _) = n `elem` inj
injectiveVar (App _ f a) = injectiveVar f -- && injective a
injectiveVar _ = False
injectiveApp x = injective x || injectiveVar x
notP (P _ _ _) = False
notP _ = True
sc i = do UI s f <- get
put (UI (s+i) f)
errors :: StateT UInfo TC Bool
errors = do UI s f <- get
return (not (null f))
uplus u1 u2 = do UI s f <- get
r <- u1
UI s f' <- get
if (length f == length f')
then return r
else do put (UI s f); u2
un :: Bool -> [((Name, Name), TT Name)] -> TT Name -> TT Name ->
StateT UInfo
TC [(Name, TT Name)]
un = un'
-- un fn names x y
-- = let (xf, _) = unApply x
-- (yf, _) = unApply y in
-- if headDiff xf yf then unifyFail x y else
-- uplus (un' fn names x y)
-- (un' fn names (hnf ctxt env x) (hnf ctxt env y))
un' :: Bool -> [((Name, Name), TT Name)] -> TT Name -> TT Name ->
StateT UInfo
TC [(Name, TT Name)]
un' fn names x y | x == y = return [] -- shortcut
un' fn names topx@(P (DCon _ _ _) x _) topy@(P (DCon _ _ _) y _)
| x /= y = unifyFail topx topy
un' fn names topx@(P (TCon _ _) x _) topy@(P (TCon _ _) y _)
| x /= y = unifyFail topx topy
un' fn names topx@(P (DCon _ _ _) x _) topy@(P (TCon _ _) y _)
= unifyFail topx topy
un' fn names topx@(P (TCon _ _) x _) topy@(P (DCon _ _ _) y _)
= unifyFail topx topy
un' fn names topx@(Constant _) topy@(P (TCon _ _) y _)
= unifyFail topx topy
un' fn names topx@(P (TCon _ _) x _) topy@(Constant _)
= unifyFail topx topy
un' fn bnames tx@(P _ x _) ty@(P _ y _)
| (x,y) `elem` map fst bnames || x == y = do sc 1; return []
| injective tx && not (holeIn env y || y `elem` holes)
= unifyTmpFail tx ty
| injective ty && not (holeIn env x || x `elem` holes)
= unifyTmpFail tx ty
-- pick the one bound earliest if both are holes
| tx /= ty && (holeIn env x || x `elem` holes)
&& (holeIn env y || y `elem` holes)
= case compare (envPos 0 x env) (envPos 0 y env) of
LT -> do sc 1; checkCycle bnames (x, ty)
_ -> do sc 1; checkCycle bnames (y, tx)
where envPos i n ((n',_):env) | n == n' = i
envPos i n (_:env) = envPos (i+1) n env
envPos _ _ _ = 100000
un' fn bnames xtm@(P _ x _) tm
| pureTerm tm, holeIn env x || x `elem` holes
= do UI s f <- get
-- injectivity check
x <- checkCycle bnames (x, tm)
if (notP tm && fn)
-- trace (show (x, tm, normalise ctxt env tm)) $
-- put (UI s ((tm, topx, topy) : i) f)
then unifyTmpFail xtm tm
else do sc 1
return x
| pureTerm tm, not (injective xtm) && injective tm
= do checkCycle bnames (x, tm)
unifyTmpFail xtm tm
un' fn bnames tm ytm@(P _ y _)
| pureTerm tm, holeIn env y || y `elem` holes
= do UI s f <- get
-- injectivity check
x <- checkCycle bnames (y, tm)
if (notP tm && fn)
-- trace (show (y, tm, normalise ctxt env tm)) $
-- put (UI s ((tm, topx, topy) : i) f)
then unifyTmpFail tm ytm
else do sc 1
return x
| pureTerm tm, not (injective ytm) && injective tm
= do checkCycle bnames (y, tm)
unifyTmpFail tm ytm
un' fn bnames (V i) (P _ x _)
| length bnames > i,
fst ((map fst bnames)!!i) == x ||
snd ((map fst bnames)!!i) == x = do sc 1; return []
un' fn bnames (P _ x _) (V i)
| length bnames > i,
fst ((map fst bnames)!!i) == x ||
snd ((map fst bnames)!!i) == x = do sc 1; return []
un' fn names topx@(Bind n (Hole t) sc) y = unifyTmpFail topx y
un' fn names x topy@(Bind n (Hole t) sc) = unifyTmpFail x topy
un' fn bnames appx@(App _ _ _) appy@(App _ _ _)
= unApp fn bnames appx appy
-- = uplus (unApp fn bnames appx appy)
-- (unifyTmpFail appx appy) -- take the whole lot
un' fn bnames x (Bind n (Lam t) (App _ y (P Bound n' _)))
| n == n' = un' False bnames x y
un' fn bnames (Bind n (Lam t) (App _ x (P Bound n' _))) y
| n == n' = un' False bnames x y
un' fn bnames x (Bind n (Lam t) (App _ y (V 0)))
= un' False bnames x y
un' fn bnames (Bind n (Lam t) (App _ x (V 0))) y
= un' False bnames x y
-- un' fn bnames (Bind x (PVar _) sx) (Bind y (PVar _) sy)
-- = un' False ((x,y):bnames) sx sy
-- un' fn bnames (Bind x (PVTy _) sx) (Bind y (PVTy _) sy)
-- = un' False ((x,y):bnames) sx sy
-- f D unifies with t -> D. This is dubious, but it helps with type
-- class resolution for type classes over functions.
un' fn bnames (App _ f x) (Bind n (Pi i t k) y)
| noOccurrence n y && injectiveApp f
= do ux <- un' False bnames x y
uf <- un' False bnames f (Bind (sMN 0 "uv") (Lam (TType (UVar 0)))
(Bind n (Pi i t k) (V 1)))
combine bnames ux uf
un' fn bnames (Bind n (Pi i t k) y) (App _ f x)
| noOccurrence n y && injectiveApp f
= do ux <- un' False bnames y x
uf <- un' False bnames (Bind (sMN 0 "uv") (Lam (TType (UVar 0)))
(Bind n (Pi i t k) (V 1))) f
combine bnames ux uf
un' fn bnames (Bind x bx sx) (Bind y by sy)
| sameBinder bx by
= do h1 <- uB bnames bx by
h2 <- un' False (((x,y),binderTy bx):bnames) sx sy
combine bnames h1 h2
where sameBinder (Lam _) (Lam _) = True
sameBinder (Pi i _ _) (Pi i' _ _) = True
sameBinder _ _ = False -- never unify holes/guesses/etc
un' fn bnames x y
| OK True <- convEq' ctxt holes x y = do sc 1; return []
| isUniverse x && isUniverse y = do sc 1; return []
| otherwise = do UI s f <- get
let r = recoverable (normalise ctxt env x)
(normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom) (CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
if (not r) then lift $ tfail err
else do put (UI s ((x, y, True, env, err, from, Unify) : f))
return [] -- lift $ tfail err
unApp fn bnames appx@(App _ fx ax) appy@(App _ fy ay)
-- shortcut for the common case where we just want to check the
-- arguments are correct
| (injectiveApp fx && fx == fy)
= un' False bnames ax ay
| (injectiveApp fx && injectiveApp fy)
|| (injectiveApp fx && metavarApp fy && ax == ay)
|| (injectiveApp fy && metavarApp fx && ax == ay)
= do let (headx, _) = unApply fx
let (heady, _) = unApply fy
-- fail quickly if the heads are disjoint
checkHeads headx heady
uplus
(do hf <- un' True bnames fx fy
let ax' = hnormalise hf ctxt env (substNames hf ax)
let ay' = hnormalise hf ctxt env (substNames hf ay)
ha <- un' False bnames ax' ay'
sc 1
combine bnames hf ha)
(do ha <- un' False bnames ax ay
let fx' = hnormalise ha ctxt env (substNames ha fx)
let fy' = hnormalise ha ctxt env (substNames ha fy)
hf <- un' False bnames fx' fy'
sc 1
combine bnames hf ha)
| otherwise = unifyTmpFail appx appy
where hnormalise [] _ _ t = t
hnormalise ns ctxt env t = normalise ctxt env t
checkHeads (P (DCon _ _ _) x _) (P (DCon _ _ _) y _)
| x /= y = unifyFail appx appy
checkHeads (P (TCon _ _) x _) (P (TCon _ _) y _)
| x /= y = unifyFail appx appy
checkHeads (P (DCon _ _ _) x _) (P (TCon _ _) y _)
= unifyFail appx appy
checkHeads (P (TCon _ _) x _) (P (DCon _ _ _) y _)
= unifyFail appx appy
checkHeads _ _ = return []
unArgs as [] [] = return as
unArgs as (x : xs) (y : ys)
= do let x' = hnormalise as ctxt env (substNames as x)
let y' = hnormalise as ctxt env (substNames as y)
as' <- un' False bnames x' y'
vs <- combine bnames as as'
unArgs vs xs ys
numArgs tm = let (f, args) = unApply tm in length args
metavarApp tm = let (f, args) = unApply tm in
(metavar f &&
all (\x -> metavarApp x) args
&& nub args == args) ||
globmetavar tm
metavarArgs tm = let (f, args) = unApply tm in
all (\x -> metavar x || inenv x) args
&& nub args == args
metavarApp' tm = let (f, args) = unApply tm in
all (\x -> pat x || metavar x) (f : args)
&& nub args == args
rigid (P (DCon _ _ _) _ _) = True
rigid (P (TCon _ _) _ _) = True
rigid t@(P Ref _ _) = inenv t || globmetavar t
rigid (Constant _) = True
rigid (App _ f a) = rigid f && rigid a
rigid t = not (metavar t) || globmetavar t
globmetavar t = case unApply t of
(P _ x _, _) ->
case lookupDef x ctxt of
[TyDecl _ _] -> True
_ -> False
_ -> False
metavar t = case t of
P _ x _ -> (x `notElem` usersupp &&
(x `elem` holes || holeIn env x))
|| globmetavar t
_ -> False
pat t = case t of
P _ x _ -> x `elem` holes || patIn env x
_ -> False
inenv t = case t of
P _ x _ -> x `elem` (map fst env)
_ -> False
notFn t = injective t || metavar t || inenv t
unifyTmpFail :: Term -> Term -> StateT UInfo TC [(Name, TT Name)]
unifyTmpFail x y
= do UI s f <- get
let r = recoverable (normalise ctxt env x) (normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom)
(CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
put (UI s ((topx, topy, True, env, err, from, Unify) : f))
return []
-- shortcut failure, if we *know* nothing can fix it
unifyFail x y = do UI s f <- get
let r = recoverable (normalise ctxt env x) (normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom)
(CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
put (UI s ((topx, topy, True, env, err, from, Unify) : f))
lift $ tfail err
uB bnames (Let tx vx) (Let ty vy)
= do h1 <- un' False bnames tx ty
h2 <- un' False bnames vx vy
sc 1
combine bnames h1 h2
uB bnames (Guess tx vx) (Guess ty vy)
= do h1 <- un' False bnames tx ty
h2 <- un' False bnames vx vy
sc 1
combine bnames h1 h2
uB bnames (Lam tx) (Lam ty) = do sc 1; un' False bnames tx ty
uB bnames (Pi _ tx _) (Pi _ ty _) = do sc 1; un' False bnames tx ty
uB bnames (Hole tx) (Hole ty) = un' False bnames tx ty
uB bnames (PVar tx) (PVar ty) = un' False bnames tx ty
uB bnames x y = do UI s f <- get
let r = recoverable (normalise ctxt env (binderTy x))
(normalise ctxt env (binderTy y))
let err = cantUnify from r (topx, xfrom) (topy, yfrom)
(CantUnify r (binderTy x, Nothing) (binderTy y, Nothing) (Msg "") (errEnv env) s)
(errEnv env) s
put (UI s ((binderTy x, binderTy y,
False,
env, err, from, Unify) : f))
return [] -- lift $ tfail err
checkCycle ns p@(x, P _ _ _) = return [p]
checkCycle ns (x, tm)
| not (x `elem` freeNames tm) = checkScope ns (x, tm)
| otherwise = lift $ tfail (InfiniteUnify x tm (errEnv env))
checkScope ns (x, tm) | pureTerm tm =
-- case boundVs (envPos x 0 env) tm of
-- [] -> return [(x, tm)]
-- (i:_) -> lift $ tfail (UnifyScope x (fst (fst (ns!!i)))
-- (inst ns tm) (errEnv env))
let v = highV (-1) tm in
if v >= length ns
then lift $ tfail (Msg "SCOPE ERROR")
else return [(x, bind v ns tm)]
where inst [] tm = tm
inst (((n, _), _) : ns) tm = inst ns (substV (P Bound n Erased) tm)
checkScope ns (x, tm) = lift $ tfail (Msg "HOLE ERROR")
bind i ns tm
| i < 0 = tm
| otherwise = let ((x,y),ty) = ns!!i in
App MaybeHoles (Bind y (Lam ty) (bind (i-1) ns tm))
(P Bound x ty)
combineArgs bnames args = ca [] args where
ca acc [] = return acc
ca acc (x : xs) = do x' <- combine bnames acc x
ca x' xs
combine bnames as [] = return as
combine bnames as ((n, t) : bs)
= case lookup n as of
Nothing -> combine bnames (as ++ [(n,t)]) bs
Just t' -> do ns <- un' False bnames t t'
-- make sure there's n mapping from n in ns
let ns' = filter (\ (x, _) -> x/=n) ns
sc 1
combine bnames as (ns' ++ bs)
boundVs :: Int -> Term -> [Int]
boundVs i (V j) | j < i = []
| otherwise = [j]
boundVs i (Bind n b sc) = boundVs (i + 1) sc
boundVs i (App _ f x) = let fs = boundVs i f
xs = boundVs i x in
nub (fs ++ xs)
boundVs i _ = []
highV :: Int -> Term -> Int
highV i (V j) | j > i = j
| otherwise = i
highV i (Bind n b sc) = maximum [i, highV i (binderTy b), (highV i sc - 1)]
highV i (App _ f x) = max (highV i f) (highV i x)
highV i _ = i
envPos x i [] = 0
envPos x i ((y, _) : ys) | x == y = i
| otherwise = envPos x (i + 1) ys
-- If there are any clashes of constructors, deem it unrecoverable, otherwise some
-- more work may help.
-- FIXME: Depending on how overloading gets used, this may cause problems. Better
-- rethink overloading properly...
-- ASSUMPTION: inputs are in normal form
--
-- Issue #1722 on the issue tracker https://github.com/idris-lang/Idris-dev/issues/1722
--
recoverable t@(App _ _ _) _
| (P _ (UN l) _, _) <- unApply t, l == txt "Lazy'" = False
recoverable _ t@(App _ _ _)
| (P _ (UN l) _, _) <- unApply t, l == txt "Lazy'" = False
recoverable (P (DCon _ _ _) x _) (P (DCon _ _ _) y _) = x == y
recoverable (P (TCon _ _) x _) (P (TCon _ _) y _) = x == y
recoverable (Constant _) (P (DCon _ _ _) y _) = False
recoverable (Constant x) (Constant y) = x == y
recoverable (P (DCon _ _ _) x _) (Constant _) = False
recoverable (Constant _) (P (TCon _ _) y _) = False
recoverable (P (TCon _ _) x _) (Constant _) = False
recoverable (P (DCon _ _ _) x _) (P (TCon _ _) y _) = False
recoverable (P (TCon _ _) x _) (P (DCon _ _ _) y _) = False
recoverable p@(Constant _) (App _ f a) = recoverable p f
recoverable (App _ f a) p@(Constant _) = recoverable f p
recoverable p@(P _ n _) (App _ f a) = recoverable p f
recoverable (App _ f a) p@(P _ _ _) = recoverable f p
recoverable (App _ f a) (App _ f' a')
| f == f' = recoverable a a'
recoverable (App _ f a) (App _ f' a')
= recoverable f f' -- && recoverable a a'
recoverable f (Bind _ (Pi _ _ _) sc)
| (P (DCon _ _ _) _ _, _) <- unApply f = False
| (P (TCon _ _) _ _, _) <- unApply f = False
| (Constant _) <- f = False
recoverable (Bind _ (Pi _ _ _) sc) f
| (P (DCon _ _ _) _ _, _) <- unApply f = False
| (P (TCon _ _) _ _, _) <- unApply f = False
| (Constant _) <- f = False
recoverable (Bind _ (Lam _) sc) f = recoverable sc f
recoverable f (Bind _ (Lam _) sc) = recoverable f sc
recoverable x y = True
errEnv :: [(a, Binder b)] -> [(a, b)]
errEnv = map (\(x, b) -> (x, binderTy b))
holeIn :: Env -> Name -> Bool
holeIn env n = case lookup n env of
Just (Hole _) -> True
Just (Guess _ _) -> True
_ -> False
patIn :: Env -> Name -> Bool
patIn env n = case lookup n env of
Just (PVar _) -> True
Just (PVTy _) -> True
_ -> False
| BartAdv/Idris-dev | src/Idris/Core/Unify.hs | bsd-3-clause | 32,669 | 0 | 22 | 13,932 | 13,221 | 6,580 | 6,641 | 581 | 71 |
-- 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.Temperature.ES.Rules
( rules ) where
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Temperature.Helpers
import Duckling.Temperature.Types (TemperatureData (..))
import qualified Duckling.Temperature.Types as TTemperature
import Duckling.Types
ruleLatentTempTemp :: Rule
ruleLatentTempTemp = Rule
{ name = "<latent temp> temp"
, pattern =
[ dimension Temperature
, regex "(grados?)|\x00b0"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Degree td
_ -> Nothing
}
ruleTempCelsius :: Rule
ruleTempCelsius = Rule
{ name = "<temp> Celsius"
, pattern =
[ dimension Temperature
, regex "(cent(i|\x00ed)grados?|c(el[cs]?(ius)?)?\\.?)"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Celsius td
_ -> Nothing
}
ruleTempFahrenheit :: Rule
ruleTempFahrenheit = Rule
{ name = "<temp> Fahrenheit"
, pattern =
[ dimension Temperature
, regex "f(ah?reh?n(h?eit)?)?\\.?"
]
, prod = \tokens -> case tokens of
(Token Temperature td:_) -> Just . Token Temperature $
withUnit TTemperature.Fahrenheit td
_ -> Nothing
}
ruleLatentTempTempBajoCero :: Rule
ruleLatentTempTempBajoCero = Rule
{ name = "<latent temp> temp bajo cero"
, pattern =
[ dimension Temperature
, regex "bajo cero"
]
, prod = \tokens -> case tokens of
(Token Temperature td@(TemperatureData {TTemperature.value = v}):_) ->
case TTemperature.unit td of
Nothing -> Just . Token Temperature . withUnit TTemperature.Degree $
td {TTemperature.value = - v}
_ -> Just . Token Temperature $ td {TTemperature.value = - v}
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleLatentTempTemp
, ruleLatentTempTempBajoCero
, ruleTempCelsius
, ruleTempFahrenheit
]
| rfranek/duckling | Duckling/Temperature/ES/Rules.hs | bsd-3-clause | 2,347 | 0 | 18 | 525 | 542 | 306 | 236 | 60 | 3 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.HABSim.Grib2.CSVParse.Types
-- Copyright : (C) 2017 Ricky Elrod
-- License : (see project LICENSE file)
-- Maintainer : Ricky Elrod <[email protected]>
-- Stability : experimental
--
-- This module provides utilities for parsing and filtering data from a
-- @wgrib2@-generated CSV file. Once the CSV files is generated, it can be
-- parsed and filtered in the following way (preferably with better error
-- handling):
--
-- @
-- myCsv <- 'BL.readFile' "\/path\/to\/csv.csv"
-- case 'decodeGrib' myCsv of
-- Left str -> error str
-- Right gribLines ->
-- case 'filterGrib' 38.8977 (-77.0365) 950 gribLines of
-- Nothing -> error "No entry found"
-- Just wh -> print wh
-- @
----------------------------------------------------------------------------
module Data.HABSim.Grib2.CSVParse
( module Data.HABSim.Grib2.CSVParse.Types
, gribLineToRaw
-- * Keyed/HashMap-based Grib data
, decodeKeyedGrib
, keyedGribToHM
, filterKeyedGrib
) where
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Csv
import Data.HABSim.Grib2.CSVParse.Types
import Data.HABSim.Types (Latitude (..), Longitude (..))
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as V
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 780)
import Data.Either (isRight)
#else
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
#endif
-- | A helper function that primarily exists just to help type inference.
--
-- @decodeKeyedGrib = decode NoHeader@ (where 'decode' and 'NoHeader' both come
-- from Cassava).
decodeKeyedGrib :: BL.ByteString -> Either String (V.Vector KeyedGribLine)
decodeKeyedGrib = decode NoHeader
{-# INLINE decodeKeyedGrib #-}
-- | Convert a 'V.Vector' of 'KeyedGribLine' into a 'HM.HashMap' keyed on the
-- latitude longitude, pressure, and direction of the grib line.
keyedGribToHM :: V.Vector KeyedGribLine -> HM.HashMap Key GribLine
keyedGribToHM = V.foldr (\(KeyedGribLine (Right (key, gline))) hm ->
HM.insert key gline hm) HM.empty
. V.filter (isRight . _keyedLine)
-- | Given any kind of 'GridLine' (usually either a 'UGRDGribLine' or a
-- 'VGRDGribLine', but could also be an 'OtherGribLine'), pull the raw Grib line
-- out of it.
gribLineToRaw :: GribLine -> RawGribLine
gribLineToRaw (UGRDGribLine (UGRDLine l)) = l
gribLineToRaw (VGRDGribLine (VGRDLine l)) = l
gribLineToRaw (OtherGribLine (OtherLine l)) = l
-- | Filter Grib lines from a 'V.Vector' 'GribLine'.
-- If we for some reason don't have both 'UGRD' and 'VGRD' of our filter result,
-- then we return 'Nothing'. Otherwise we return a 'GribPair' containing both.
filterKeyedGrib
:: Latitude
-> Longitude
-> Int -- ^ Pressure
-> Direction -- ^ The 'Direction' to filter for.
-> HM.HashMap Key GribLine -- ^ Input lines
-> Maybe GribLine -- ^ Output line
filterKeyedGrib (Latitude lat) (Longitude lon) pressure' dir gribLines =
let lat' = Latitude $ fromIntegral (round (lat * 4) :: Integer) / 4
lon' = Longitude $ fromIntegral (round (lon * 4) :: Integer) / 4
in HM.lookup (lon', lat', pressure', dir) gribLines
| kg4sgp/habsim | haskell/src/Data/HABSim/Grib2/CSVParse.hs | bsd-3-clause | 3,263 | 0 | 15 | 575 | 489 | 292 | 197 | 38 | 1 |
module Reverse where
import Tip
import qualified Prelude
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x:(xs ++ ys)
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]
-- lemma_assoc xs ys zs = xs ++ (ys ++ zs) === (xs ++ ys) ++ zs
--
-- lemma_rid xs = xs ++ [] === xs
--
-- lemma xs ys = rev xs ++ rev ys === rev (ys ++ xs)
conj xs = rev (rev xs) === xs
| danr/emna | examples/Reverse.hs | bsd-3-clause | 383 | 0 | 8 | 108 | 155 | 87 | 68 | 10 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Network.PeyoTLS.Extension (Extension, SignAlg(..), HashAlg(..)) where
import Control.Applicative ((<$>), (<*>))
import Data.Bits (shiftL, (.|.))
import Data.Word (Word8, Word16)
import qualified Data.ByteString as BS
import qualified Codec.Bytable.BigEndian as B
import qualified Crypto.Types.PubKey.DH as DH
import qualified Crypto.Types.PubKey.ECC as ECC
import Network.PeyoTLS.HashSignAlgorithm(HashAlg(..), SignAlg(..))
data Extension
= ESName [ServerName]
| EECurve [ECC.CurveName] | EEcPFrt [EcPointFormat]
| ESsnTicketTls BS.ByteString
| ENextProtoNego BS.ByteString
| ERenegoInfo BS.ByteString
| ERaw EType BS.ByteString
deriving Show
instance B.Bytable Extension where
encode = encodeE; decode = B.evalBytableM B.parse
instance B.Parsable Extension where
parse = parseE
encodeE :: Extension -> BS.ByteString
encodeE (ESName sn) = encodeE . ERaw TSName . B.addLen w16 $ cmap B.encode sn
encodeE (EECurve ec) = encodeE . ERaw TECurve . B.addLen w16 $ cmap B.encode ec
encodeE (EEcPFrt pf) = encodeE . ERaw TEcPFrt . B.addLen w8 $ cmap B.encode pf
encodeE (ESsnTicketTls stt) = encodeE $ ERaw TSsnTicketTls stt
encodeE (ENextProtoNego npn) = encodeE $ ERaw TNextProtoNego npn
encodeE (ERenegoInfo ri) = encodeE . ERaw TRenegoInfo $ B.addLen w8 ri
encodeE (ERaw et body) = B.encode et `BS.append` B.addLen w16 body
parseE :: B.BytableM Extension
parseE = do
(t, l) <- (,) <$> B.take 2 <*> B.take 2
case t of
TSName -> ESName <$> (flip B.list B.parse =<< B.take 2)
TECurve -> EECurve <$> (flip B.list (B.take 2) =<< B.take 2)
TEcPFrt -> EEcPFrt <$> (flip B.list (B.take 1) =<< B.take 1)
TSsnTicketTls -> ESsnTicketTls <$> B.take l
TNextProtoNego -> ENextProtoNego <$> B.take l
TRenegoInfo -> ERenegoInfo <$> (B.take =<< B.take 1)
_ -> ERaw t <$> B.take l
data EType
= TSName | TECurve | TEcPFrt | TSsnTicketTls
| TNextProtoNego | TRenegoInfo | TRaw Word16 deriving Show
instance B.Bytable EType where
encode TSName = B.encode (0 :: Word16)
encode TECurve = B.encode (10 :: Word16)
encode TEcPFrt = B.encode (11 :: Word16)
encode TSsnTicketTls = B.encode (35 :: Word16)
encode TNextProtoNego = B.encode (13172 :: Word16)
encode TRenegoInfo = B.encode (65281 :: Word16)
encode (TRaw et) = B.encode et
decode bs = case BS.unpack bs of
[w1, w2] -> Right $
case fromIntegral w1 `shiftL` 8 .|. fromIntegral w2 of
0 -> TSName
10 -> TECurve
11 -> TEcPFrt
35 -> TSsnTicketTls
13172 -> TNextProtoNego
65281 -> TRenegoInfo
et -> TRaw et
_ -> Left "Extension: EType.decode"
data ServerName = SNHostName BS.ByteString | SNRaw NameType BS.ByteString
deriving Show
instance B.Bytable ServerName where
encode (SNHostName nm) = B.encode $ SNRaw NTHostName nm
encode (SNRaw nt nm) = B.encode nt `BS.append` B.addLen w16 nm
decode = B.evalBytableM B.parse
instance B.Parsable ServerName where
parse = do
(t, n) <- (,) <$> B.take 1 <*> (B.take =<< B.take 2)
return $ case t of
NTHostName -> SNHostName n; _ -> SNRaw t n
data NameType = NTHostName | NTRaw Word8 deriving Show
instance B.Bytable NameType where
encode NTHostName = BS.pack [0]
encode (NTRaw t) = BS.pack [t]
decode bs = case BS.unpack bs of
[t] -> Right $ case t of 0 -> NTHostName; _ -> NTRaw t
_ -> Left "Extension: NameType.decode"
instance B.Bytable DH.Params where
encode (DH.Params p g) =
BS.concat [B.addLen w16 $ B.encode p, B.addLen w16 $ B.encode g]
decode = B.evalBytableM B.parse
instance B.Parsable DH.Params where
parse = DH.Params
<$> (B.take =<< B.take 2)
<*> (B.take =<< B.take 2)
instance B.Bytable DH.PublicNumber where
encode = B.addLen w16 . B.encode . \(DH.PublicNumber pn) -> pn
decode = B.evalBytableM B.parse
instance B.Parsable DH.PublicNumber where
parse = fromInteger <$> (B.take =<< B.take 2)
data EcCurveType = ExplicitPrime | ExplicitChar2 | NamedCurve | ECTRaw Word8
deriving Show
instance B.Bytable EcCurveType where
encode ExplicitPrime = BS.pack [1]
encode ExplicitChar2 = BS.pack [2]
encode NamedCurve = BS.pack [3]
encode (ECTRaw w) = BS.pack [w]
decode = B.evalBytableM B.parse
instance B.Parsable EcCurveType where
parse = do
ct <- B.head
return $ case ct of
1 -> ExplicitPrime
2 -> ExplicitChar2
3 -> NamedCurve
w -> ECTRaw w
instance B.Bytable ECC.CurveName where
encode ECC.SEC_p256r1 = B.encode (23 :: Word16)
encode ECC.SEC_p384r1 = B.encode (24 :: Word16)
encode ECC.SEC_p521r1 = B.encode (25 :: Word16)
encode _ = error "Extension.encodeCN: not implemented"
decode bs = case BS.unpack bs of
[w1, w2] -> case fromIntegral w1 `shiftL` 8 .|. fromIntegral w2 of
(23 :: Word16) -> Right ECC.SEC_p256r1
(24 :: Word16) -> Right ECC.SEC_p384r1
(25 :: Word16) -> Right ECC.SEC_p521r1
n -> Left $ "Extension: CurveName.decode: unknown curve: " ++
show n
_ -> Left "Extension: CurveName.decode: bad format"
instance B.Parsable ECC.CurveName where
parse = B.take 2
instance B.Bytable ECC.Curve where
encode c
| c == ECC.getCurveByName ECC.SEC_p256r1 =
B.encode NamedCurve `BS.append` B.encode ECC.SEC_p256r1
| otherwise = error "TlsServer.encodeC: not implemented"
decode = B.evalBytableM B.parse
instance B.Parsable ECC.Curve where
parse = ECC.getCurveByName <$> do
NamedCurve <- B.parse
B.parse
data EcPointFormat = EPFUncompressed | EPFRaw Word8 deriving Show
instance B.Bytable EcPointFormat where
encode EPFUncompressed = BS.pack [0]
encode (EPFRaw f) = BS.pack [f]
decode bs = case BS.unpack bs of
[f] -> Right $ case f of 0 -> EPFUncompressed; _ -> EPFRaw f
_ -> Left "Extension: Bytable.decode"
instance B.Bytable ECC.Point where
encode (ECC.Point x y) = B.addLen w8 $
4 `BS.cons` padd 32 0 (B.encode x) `BS.append`
padd 32 0 (B.encode y)
encode ECC.PointO = error "Extension: EC.Point.encode"
decode = B.evalBytableM B.parse
padd :: Int -> Word8 -> BS.ByteString -> BS.ByteString
padd n w s = BS.replicate (n - BS.length s) w `BS.append` s
instance B.Parsable ECC.Point where
parse = do
bs <- B.take =<< B.take 1
case BS.uncons bs of
Just (4, rest) -> return $ let (x, y) = BS.splitAt 32 rest in
ECC.Point
(either error id $ B.decode x)
(either error id $ B.decode y)
_ -> fail "Extension: ECC.Point.parse"
w8 :: Word8; w8 = undefined
w16 :: Word16; w16 = undefined
cmap :: (a -> BS.ByteString) -> [a] -> BS.ByteString
cmap = (BS.concat .) . map
| YoshikuniJujo/forest | subprojects/tls-analysis/server/src/Network/PeyoTLS/Extension.hs | bsd-3-clause | 6,473 | 28 | 18 | 1,220 | 2,600 | 1,337 | 1,263 | 164 | 7 |
-----------------------------------------------------------------------------
-- |
-- Module : Debug.Trace
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- The 'trace' function.
--
-----------------------------------------------------------------------------
module Debug.Trace (
-- * Tracing
trace -- :: String -> a -> a
) where
import Prelude
import System.IO.Unsafe
import System.IO
{-# NOINLINE trace #-}
{-|
When called, 'trace' prints the string in its first argument to
standard error, before returning the second argument as its result.
The 'trace' function is not referentially transparent, and should only
be used for debugging, or for monitoring execution. Some
implementations of 'trace' may decorate the string that\'s output to
indicate that you\'re tracing.
-}
trace :: String -> a -> a
trace string expr = unsafePerformIO $ do
hPutStr stderr string
hPutChar stderr '\n'
return expr
| OS2World/DEV-UTIL-HUGS | libraries/Debug/Trace.hs | bsd-3-clause | 1,105 | 2 | 8 | 193 | 93 | 56 | 37 | 11 | 1 |
{-# LANGUAGE CPP, DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Py.SrcLocation
-- Copyright : (c) 2009 Bernie Pope
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : ghc
--
-- Source location information for the Python lexer and parser. This module
-- provides single-point locations and spans, and conversions between them.
-----------------------------------------------------------------------------
module Language.Py.SrcLocation
-- * Construction
( SrcLocation (..)
, SrcSpan (..)
, Span (..)
, spanning
, mkSrcSpan
, combineSrcSpans
, initialSrcLocation
, spanStartPoint
-- * Modification
, incColumn
, decColumn
, incLine
, incTab
, endCol
-- * Projection of components of a span
, endRow
, startCol
, startRow
) where
import Language.Py.Pretty
import Data.Data
-- | A location for a syntactic entity from the source code.
-- The location is specified by its filename, and starting row
-- and column.
data SrcLocation
= Sloc
{ slocFilename :: !String
, slocRow :: {-# UNPACK #-} !Int
, slocColumn :: {-# UNPACK #-} !Int
}
| NoLocation
deriving (Eq, Ord, Show, Typeable, Data)
instance Pretty SrcLocation where
pretty = pretty . getSpan
-- | Types which have a span.
class Span a where
getSpan :: a -> SrcSpan
getSpan x = SpanEmpty
-- | Create a new span which encloses two spanned things.
spanning :: (Span a, Span b) => a -> b -> SrcSpan
spanning x y = combineSrcSpans (getSpan x) (getSpan y)
instance Span a => Span [a] where
getSpan [] = SpanEmpty
getSpan [x] = getSpan x
getSpan list@(x:xs) = combineSrcSpans (getSpan x) (getSpan (last list))
instance Span a => Span (Maybe a) where
getSpan Nothing = SpanEmpty
getSpan (Just x) = getSpan x
instance (Span a, Span b) => Span (Either a b) where
getSpan (Left x) = getSpan x
getSpan (Right x) = getSpan x
instance (Span a, Span b) => Span (a, b) where
getSpan (x,y) = spanning x y
instance Span SrcSpan where
getSpan = id
-- | Construct the initial source location for a file.
initialSrcLocation :: String -> SrcLocation
initialSrcLocation filename = Sloc
{ slocFilename = filename
, slocRow = 1
, slocColumn = 1
}
-- | Decrement the column of a location, only if they are on the same row.
decColumn :: Int -> SrcLocation -> SrcLocation
decColumn n loc
| n < col = loc { slocColumn = col - n }
| otherwise = loc
where
col = slocColumn loc
-- | Increment the column of a location.
incColumn :: Int -> SrcLocation -> SrcLocation
incColumn n loc@(Sloc { slocColumn = col }) = loc { slocColumn = col + n }
-- | Increment the column of a location by one tab stop.
incTab :: SrcLocation -> SrcLocation
incTab loc@(Sloc { slocColumn = col })
= loc { slocColumn = newCol }
where
newCol = col + 8 - (col - 1) `mod` 8
-- | Increment the line number (row) of a location by one.
incLine :: Int -> SrcLocation -> SrcLocation
incLine n loc@(Sloc { slocRow = row })
= loc { slocColumn = 1, slocRow = row + n }
{-
Inspired heavily by compiler/basicTypes/SrcLoc.lhs
A SrcSpan delimits a portion of a text file.
-}
-- | Source location spanning a contiguous section of a file.
data SrcSpan
-- | A span which starts and ends on the same line.
= SpanCoLinear
{ spanFilename :: !String
, spanRow :: {-# UNPACK #-} !Int
, spanStartColumn :: {-# UNPACK #-} !Int
, spanEndColumn :: {-# UNPACK #-} !Int
}
-- | A span which starts and ends on different lines.
| SpanMultiLine
{ spanFilename :: !String
, spanStartRow :: {-# UNPACK #-} !Int
, spanStartColumn :: {-# UNPACK #-} !Int
, spanEndRow :: {-# UNPACK #-} !Int
, spanEndColumn :: {-# UNPACK #-} !Int
}
-- | A span which is actually just one point in the file.
| SpanPoint
{ spanFilename :: !String
, spanRow :: {-# UNPACK #-} !Int
, spanColumn :: {-# UNPACK #-} !Int
}
-- | No span information.
| SpanEmpty
deriving (Eq,Ord,Show,Typeable,Data)
instance Pretty SrcSpan where
pretty span@(SpanCoLinear {}) = prettyMultiSpan span
pretty span@(SpanMultiLine {}) = prettyMultiSpan span
pretty span@(SpanPoint {})
= text (spanFilename span) <> colon <+>
parens (pretty (spanRow span) <> comma <> pretty (spanColumn span))
pretty SpanEmpty = empty
prettyMultiSpan :: SrcSpan -> Doc
prettyMultiSpan span
= text (spanFilename span) <> colon <+>
parens (pretty (startRow span) <> comma <> pretty (startCol span)) <> char '-' <>
parens (pretty (endRow span) <> comma <> pretty (endCol span))
instance Span SrcLocation where
getSpan loc@(Sloc {}) = SpanPoint
{ spanFilename = slocFilename loc
, spanRow = slocRow loc
, spanColumn = slocColumn loc
}
getSpan NoLocation = SpanEmpty
-- | Make a point span from the start of a span
spanStartPoint :: SrcSpan -> SrcSpan
spanStartPoint SpanEmpty = SpanEmpty
spanStartPoint span = SpanPoint
{ spanFilename = spanFilename span
, spanRow = startRow span
, spanColumn = startCol span
}
-- | Make a span from two locations. Assumption: either the
-- arguments are the same, or the left one preceeds the right one.
mkSrcSpan :: SrcLocation -> SrcLocation -> SrcSpan
mkSrcSpan NoLocation _ = SpanEmpty
mkSrcSpan _ NoLocation = SpanEmpty
mkSrcSpan loc1 loc2
| line1 == line2 = if col2 <= col1
then SpanPoint file line1 col1
else SpanCoLinear file line1 col1 col2
| otherwise = SpanMultiLine file line1 col1 line2 col2
where
line1 = slocRow loc1
line2 = slocRow loc2
col1 = slocColumn loc1
col2 = slocColumn loc2
file = slocFilename loc1
-- | Combines two 'SrcSpan' into one that spans at least all the characters
-- within both spans. Assumes the "file" part is the same in both inputs
combineSrcSpans :: SrcSpan -> SrcSpan -> SrcSpan
combineSrcSpans SpanEmpty r = r -- this seems more useful
combineSrcSpans l SpanEmpty = l
combineSrcSpans start end
= case row1 `compare` row2 of
EQ -> case col1 `compare` col2 of
EQ -> SpanPoint file row1 col1
LT -> SpanCoLinear file row1 col1 col2
GT -> SpanCoLinear file row1 col2 col1
LT -> SpanMultiLine file row1 col1 row2 col2
GT -> SpanMultiLine file row2 col2 row1 col1
where
row1 = startRow start
col1 = startCol start
row2 = endRow end
col2 = endCol end
file = spanFilename start
-- | Get the row of the start of a span.
startRow :: SrcSpan -> Int
startRow (SpanCoLinear { spanRow = row }) = row
startRow (SpanMultiLine { spanStartRow = row }) = row
startRow (SpanPoint { spanRow = row }) = row
startRow SpanEmpty = error "startRow called on empty span"
-- | Get the row of the end of a span.
endRow :: SrcSpan -> Int
endRow (SpanCoLinear { spanRow = row }) = row
endRow (SpanMultiLine { spanEndRow = row }) = row
endRow (SpanPoint { spanRow = row }) = row
endRow SpanEmpty = error "endRow called on empty span"
-- | Get the column of the start of a span.
startCol :: SrcSpan -> Int
startCol (SpanCoLinear { spanStartColumn = col }) = col
startCol (SpanMultiLine { spanStartColumn = col }) = col
startCol (SpanPoint { spanColumn = col }) = col
startCol SpanEmpty = error "startCol called on empty span"
-- | Get the column of the end of a span.
endCol :: SrcSpan -> Int
endCol (SpanCoLinear { spanEndColumn = col }) = col
endCol (SpanMultiLine { spanEndColumn = col }) = col
endCol (SpanPoint { spanColumn = col }) = col
endCol SpanEmpty = error "endCol called on empty span"
| codeq/language-py | src/Language/Py/SrcLocation.hs | bsd-3-clause | 7,609 | 0 | 14 | 1,682 | 1,948 | 1,057 | 891 | 166 | 5 |
{-# LANGUAGE RecordWildCards, PatternGuards, ScopedTypeVariables #-}
module Text.HTML.TagSoup.Implementation where
import Data.List
import Text.HTML.TagSoup.Type
import Text.HTML.TagSoup.Options
import Text.StringLike as Str
import Numeric
import Data.Char
import Control.Exception(assert)
import Control.Arrow
---------------------------------------------------------------------
-- BOTTOM LAYER
data Out
= Char Char
| Tag -- <
| TagShut -- </
| AttName
| AttVal
| TagEnd -- >
| TagEndClose -- />
| Comment -- <!--
| CommentEnd -- -->
| Entity -- &
| EntityNum -- &#
| EntityHex -- &#x
| EntityEnd -- ;
| EntityEndAtt -- missing the ; and in an attribute
| Warn String
| Pos Position
deriving (Show,Eq)
errSeen x = Warn $ "Unexpected " ++ show x
errWant x = Warn $ "Expected " ++ show x
data S = S
{s :: S
,tl :: S
,hd :: Char
,eof :: Bool
,next :: String -> Maybe S
,pos :: [Out] -> [Out]
}
expand :: Position -> String -> S
expand p text = res
where res = S{s = res
,tl = expand (positionChar p (head text)) (tail text)
,hd = if null text then '\0' else head text
,eof = null text
,next = next p text
,pos = (Pos p:)
}
next p (t:ext) (s:tr) | t == s = next (positionChar p t) ext tr
next p text [] = Just $ expand p text
next _ _ _ = Nothing
infixr &
class Outable a where (&) :: a -> [Out] -> [Out]
instance Outable Char where (&) = ampChar
instance Outable Out where (&) = ampOut
ampChar x y = Char x : y
ampOut x y = x : y
state :: String -> S
state s = expand nullPosition s
---------------------------------------------------------------------
-- TOP LAYER
output :: forall str . StringLike str => ParseOptions str -> [Out] -> [Tag str]
output ParseOptions{..} x = (if optTagTextMerge then tagTextMerge else id) $ go ((nullPosition,[]),x)
where
-- main choice loop
go :: ((Position,[Tag str]),[Out]) -> [Tag str]
go ((p,ws),xs) | p `seq` False = [] -- otherwise p is a space leak when optTagPosition == False
go ((p,ws),xs) | not $ null ws = (if optTagWarning then (reverse ws++) else id) $ go ((p,[]),xs)
go ((p,ws),Pos p2:xs) = go ((p2,ws),xs)
go x | isChar x = pos x $ TagText a : go y
where (y,a) = charsStr x
go x | isTag x = pos x $ TagOpen a b : (if isTagEndClose z then pos x $ TagClose a : go (next z) else go (skip isTagEnd z))
where (y,a) = charsStr $ next x
(z,b) = atts y
go x | isTagShut x = pos x $ (TagClose a:) $
(if not (null b) then warn x "Unexpected attributes in close tag" else id) $
if isTagEndClose z then warn x "Unexpected self-closing in close tag" $ go (next z) else go (skip isTagEnd z)
where (y,a) = charsStr $ next x
(z,b) = atts y
go x | isComment x = pos x $ TagComment a : go (skip isCommentEnd y)
where (y,a) = charsStr $ next x
go x | isEntity x = poss x ((if optTagWarning then id else filter (not . isTagWarning)) $ optEntityData a) ++ go (skip isEntityEnd y)
where (y,a) = charsStr $ next x
go x | isEntityChr x = pos x $ TagText (fromChar $ entityChr x a) : go (skip isEntityEnd y)
where (y,a) = chars $ next x
go x | Just a <- fromWarn x = if optTagWarning then pos x $ TagWarning (fromString a) : go (next x) else go (next x)
go x | isEof x = []
atts :: ((Position,[Tag str]),[Out]) -> ( ((Position,[Tag str]),[Out]) , [(str,str)] )
atts x | isAttName x = second ((a,b):) $ atts z
where (y,a) = charsStr (next x)
(z,b) = if isAttVal y then charsEntsStr (next y) else (y, empty)
atts x | isAttVal x = second ((empty,a):) $ atts y
where (y,a) = charsEntsStr (next x)
atts x = (x, [])
-- chars
chars x = charss False x
charsStr x = (id *** fromString) $ chars x
charsEntsStr x = (id *** fromString) $ charss True x
-- loop round collecting characters, if the b is set including entity
charss :: Bool -> ((Position,[Tag str]),[Out]) -> ( ((Position,[Tag str]),[Out]) , String)
charss t x | Just a <- fromChr x = (y, a:b)
where (y,b) = charss t (next x)
charss t x | t, isEntity x = second (toString n ++) $ charss t $ addWarns m z
where (y,a) = charsStr $ next x
b = not $ isEntityEndAtt y
z = if b then skip isEntityEnd y else next y
(n,m) = optEntityAttrib (a,b)
charss t x | t, isEntityChr x = second (entityChr x a:) $ charss t z
where (y,a) = chars $ next x
(z,b) = charss t $ if isEntityEnd y then next y else skip isEntityEndAtt y
charss t ((_,w),Pos p:xs) = charss t ((p,w),xs)
charss t x | Just a <- fromWarn x = charss t $ (if optTagWarning then addWarns [TagWarning $ fromString a] else id) $ next x
charss t x = (x, [])
-- utility functions
next x = second (drop 1) x
skip f x = assert (isEof x || f x) (next x)
addWarns ws x@((p,w),y) = ((p, reverse (poss x ws) ++ w), y)
pos ((p,_),_) rest = if optTagPosition then tagPosition p : rest else rest
warn x s rest = if optTagWarning then pos x $ TagWarning (fromString s) : rest else rest
poss x = concatMap (\w -> pos x [w])
entityChr x s | isEntityNum x = chr $ read s
| isEntityHex x = chr $ fst $ head $ readHex s
isEof (_,[]) = True; isEof _ = False
isChar (_,Char{}:_) = True; isChar _ = False
isTag (_,Tag{}:_) = True; isTag _ = False
isTagShut (_,TagShut{}:_) = True; isTagShut _ = False
isAttName (_,AttName{}:_) = True; isAttName _ = False
isAttVal (_,AttVal{}:_) = True; isAttVal _ = False
isTagEnd (_,TagEnd{}:_) = True; isTagEnd _ = False
isTagEndClose (_,TagEndClose{}:_) = True; isTagEndClose _ = False
isComment (_,Comment{}:_) = True; isComment _ = False
isCommentEnd (_,CommentEnd{}:_) = True; isCommentEnd _ = False
isEntity (_,Entity{}:_) = True; isEntity _ = False
isEntityChr (_,EntityNum{}:_) = True; isEntityChr (_,EntityHex{}:_) = True; isEntityChr _ = False
isEntityNum (_,EntityNum{}:_) = True; isEntityNum _ = False
isEntityHex (_,EntityHex{}:_) = True; isEntityHex _ = False
isEntityEnd (_,EntityEnd{}:_) = True; isEntityEnd _ = False
isEntityEndAtt (_,EntityEndAtt{}:_) = True; isEntityEndAtt _ = False
isWarn (_,Warn{}:_) = True; isWarn _ = False
fromChr (_,Char x:_) = Just x ; fromChr _ = Nothing
fromWarn (_,Warn x:_) = Just x ; fromWarn _ = Nothing
-- Merge all adjacent TagText bits
tagTextMerge :: StringLike str => [Tag str] -> [Tag str]
tagTextMerge (TagText x:xs) = TagText (strConcat (x:a)) : tagTextMerge b
where
(a,b) = f xs
-- additional brackets on 3 lines to work around HSE 1.3.2 bugs with pattern fixities
f (TagText x:xs) = (x:a,b)
where (a,b) = f xs
f (TagPosition{}:(x@TagText{}:xs)) = f $ x : xs
f x = g x id x
g o op (p@TagPosition{}:(w@TagWarning{}:xs)) = g o (op . (p:) . (w:)) xs
g o op (w@TagWarning{}:xs) = g o (op . (w:)) xs
g o op (p@TagPosition{}:(x@TagText{}:xs)) = f $ p : x : op xs
g o op (x@TagText{}:xs) = f $ x : op xs
g o op _ = ([], o)
tagTextMerge (x:xs) = x : tagTextMerge xs
tagTextMerge [] = []
| nfjinjing/yuuko | src/Text/HTML/TagSoup/Implementation.hs | bsd-3-clause | 7,578 | 0 | 16 | 2,258 | 3,560 | 1,883 | 1,677 | 145 | 31 |
module Example.Internal
(
) where
| smurphy8/refactor-patternmatch-with-lens | src/Example/Internal.hs | bsd-3-clause | 42 | 0 | 3 | 13 | 9 | 6 | 3 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Targets where
import Types (
Repository,PackageNode,
Variant(Variant),VariantNode,
PackageDescription,Configuration(Configuration),
FinalizedPackageDescription,
Target(Target),TargetNode,
TargetType(LibraryTarget),PackageDependency)
import Variants (loadPackageDescription)
import Packages (insertPackage)
import Web.Neo (NeoT,newNode,addNodeLabel,setNodeProperty,newEdge)
import Database.PipesGremlin (PG,scatter,gather,has,strain,nodesByLabel,nodeProperty)
import Data.Aeson (toJSON)
import Distribution.PackageDescription (library,targetBuildDepends,libBuildInfo,buildDepends)
import Distribution.PackageDescription.Configuration (finalizePackageDescription)
import Distribution.Package (Dependency(Dependency),PackageName(PackageName))
import Control.Monad (forM_,guard,(>=>))
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans (lift)
import Data.Maybe (maybeToList)
import Data.List (nub)
targetPG :: (MonadIO m) => Repository -> (Variant,VariantNode) -> PG m (Target,TargetNode)
targetPG repository (variant,variantnode) = do
target@(Target _ targettype dependencies) <- targets repository variant >>= scatter
targetnode <- lift (insertTarget targettype variantnode)
forM_ dependencies (findOrCreateDependency >=> lift . (newEdge "PACKAGEDEPENDENCY" targetnode))
return (target,targetnode)
targets :: (MonadIO m) => Repository -> Variant -> m [Target]
targets repository variant@(Variant version configuration) = do
packagedescription <- loadPackageDescription repository version
return (maybeToList (do
dependencies <- finalize configuration packagedescription >>= libraryDependencies
return (Target variant LibraryTarget dependencies)))
finalize :: Configuration -> PackageDescription -> Maybe FinalizedPackageDescription
finalize configuration packagedescription = do
let Configuration flagassignment platform compiler = configuration
eitherPackageDescription = finalizePackageDescription
flagassignment
(const True)
platform
compiler
[]
packagedescription
(finalizedPackageDescription,flagassignment') <- eitherToMaybe eitherPackageDescription
guard (flagassignment == flagassignment')
return finalizedPackageDescription
eitherToMaybe :: Either l r -> Maybe r
eitherToMaybe = either (const Nothing) Just
libraryDependencies :: FinalizedPackageDescription -> Maybe [PackageDependency]
libraryDependencies finalizedPackageDescription = do
lib <- library finalizedPackageDescription
let cabalDependencies = targetBuildDepends (libBuildInfo lib) ++ buildDepends finalizedPackageDescription
return (nub (do
Dependency (PackageName packagename) _ <- cabalDependencies
return packagename))
insertTarget :: (Monad m) => TargetType -> VariantNode -> NeoT m TargetNode
insertTarget targettype variantnode = do
targetnode <- newNode
addNodeLabel "Target" targetnode
setNodeProperty "targettype" (toJSON (show targettype)) targetnode
_ <- newEdge "TARGET" variantnode targetnode
return targetnode
findOrCreateDependency :: (Monad m) => PackageDependency -> PG m PackageNode
findOrCreateDependency packagename = do
packages <- gather (findPackage packagename)
case packages of
[] -> lift (insertPackage packagename)
[packagenode] -> return packagenode
_ -> error "Multiple packagenodes with the same packagename!"
findPackage :: (Monad m) => String -> PG m PackageNode
findPackage packagename =
nodesByLabel "Package" >>=
has (nodeProperty "packagename" >=> strain (== (toJSON packagename)))
| phischu/cabal-analysis | src/Targets.hs | bsd-3-clause | 3,735 | 0 | 16 | 614 | 980 | 513 | 467 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] to
[@ISO639-2@] ton
[@ISO639-3@] ton
[@Native name@] lea faka-Tonga
[@English name@] Tongan
-}
module Text.Numeral.Language.NLD
( ) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Control.Monad ( (>=>) )
import "base" Data.Bool ( otherwise )
import "base" Data.Function ( ($), const, fix )
import "base" Data.Maybe ( Maybe(Just) )
import "base" Data.Monoid ( Monoid )
import "base" Data.String ( IsString )
import "base" Prelude ( Integer )
import "positional-numerals" Text.Numeral.Positional ( toPositional )
--------------------------------------------------------------------------------
-- TO
--------------------------------------------------------------------------------
cardinal ∷ (Monoid s, IsString s) ⇒ Integer → Maybe s
cardinal n = toPositional f 10 n
where
f ∷ Integer → s
f 0 = "noa"
f 1 = "taha"
f 2 = "ua"
f 3 = "tolu"
f 4 = "fā"
f 5 = "nima"
f 6 = "ono"
f 7 = "fitu"
f 8 = "valu"
f 9 = "hiva"
f _ = "?"
| telser/numerals | src/Text/Numeral/Language/TON.hs | bsd-3-clause | 1,416 | 0 | 7 | 317 | 265 | 158 | 107 | 29 | 11 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Monad
import Molog
import Test.HUnit
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.TH
main = $(defaultMainGenerator)
case_2vars = runMolog (reify =<< test) @=? [Just 5]
where test :: Molog s (Term s Int)
test = do x <- fresh
y <- fresh
x `unify` (Val 5)
x `unify` y
return y
case_2vars_pair = runMolog (reify =<< test) @=? [Just (5, 5)]
where test :: Molog s (Term s (Term s Int, Term s Int))
test = do x <- fresh
y <- fresh
x `unify` (Val 5)
x `unify` y
p <- fresh
p `unify` (Val (x, y))
return p
case_disj = runMolog (reify =<< test) @=? [Just 5, Just 6]
where test :: Molog s (Term s Int)
test = do x <- fresh
msum [ x `unify` (Val 5)
, x `unify` (Val 5) >> x `unify` (Val 6)
, x `unify` (Val 6)
]
return x
| acfoltzer/Molog | test/Tests.hs | bsd-3-clause | 1,140 | 0 | 15 | 483 | 419 | 222 | 197 | 32 | 1 |
{-# OPTIONS_GHC -Wall #-}
module Main where
import Elm.Utils ((|>))
import System.Exit (exitFailure, exitSuccess)
import Messages.Types (Message(..))
import Control.Monad (when)
import Data.Maybe (isJust)
import CommandLine.Helpers
import qualified AST.Module
import qualified Flags
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Char8 as Char8
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified ElmFormat.Parse as Parse
import qualified ElmFormat.Render.Text as Render
import qualified ElmFormat.Filesystem as FS
import qualified Reporting.Error.Syntax as Syntax
import qualified Reporting.Result as Result
import qualified System.Directory as Dir
writeFile' :: FilePath -> Text.Text -> IO ()
writeFile' filename contents =
ByteString.writeFile filename $ Text.encodeUtf8 contents
-- If elm-format was successful, writes the results to the output
-- file. Otherwise, display errors and exit
writeResult
:: FilePath
-> Result.Result () Syntax.Error AST.Module.Module
-> IO ()
writeResult outputFile result =
case result of
Result.Result _ (Result.Ok modu) ->
Render.render modu
|> writeFile' outputFile
Result.Result _ (Result.Err errs) ->
do
showErrors errs
exitFailure
processFile :: FilePath -> FilePath -> IO ()
processFile inputFile outputFile =
do
putStrLn $ (r $ ProcessingFile inputFile)
input <- fmap Text.decodeUtf8 $ ByteString.readFile inputFile
Parse.parse input
|> writeResult outputFile
isEitherFileOrDirectory :: FilePath -> IO Bool
isEitherFileOrDirectory path = do
fileExists <- Dir.doesFileExist path
dirExists <- Dir.doesDirectoryExist path
return $ fileExists || dirExists
-- read input from stdin
-- if given an output file, then write there
-- otherwise, stdout
handleStdinInput :: Maybe FilePath -> IO ()
handleStdinInput outputFile = do
input <- Lazy.getContents
let parsedText = Parse.parse $ Text.decodeUtf8 $ Lazy.toStrict input
case parsedText of
Result.Result _ (Result.Ok modu) ->
do
let rendered = Render.render modu |> Text.encodeUtf8
case outputFile of
Nothing ->
Char8.putStrLn rendered
Just path -> do
writeResult path parsedText
Result.Result _ (Result.Err errs) ->
do
showErrors errs
exitFailure
handleFilesInput :: [FilePath] -> Maybe FilePath -> Bool -> IO ()
handleFilesInput inputFiles outputFile autoYes =
do
filesExist <-
all (id) <$> mapM isEitherFileOrDirectory inputFiles
when (not filesExist) $
exitFilesNotFound inputFiles
elmFiles <- concat <$> mapM FS.findAllElmFiles inputFiles
when (null elmFiles) $
exitFilesNotFound inputFiles
case elmFiles of
inputFile:[] -> do
realOutputFile <- decideOutputFile autoYes inputFile outputFile
processFile inputFile realOutputFile
_ -> do
when (isJust outputFile)
exitOnInputDirAndOutput
canOverwriteFiles <- getApproval autoYes elmFiles
when canOverwriteFiles $
mapM_ (\file -> processFile file file) elmFiles
main :: IO ()
main =
do
config <- Flags.parse
let inputFiles = (Flags._input config)
let isStdin = (Flags._stdin config)
let outputFile = (Flags._output config)
let autoYes = (Flags._yes config)
let noInputSource = null inputFiles && not isStdin
let twoInputSources = (not $ null inputFiles) && isStdin
-- when we don't have any input, stdin or otherwise
when (noInputSource) $ do
Flags.showHelpText
exitFailure
when (twoInputSources) $ do
exitTooManyInputSources
when (isStdin) $ do
handleStdinInput outputFile
exitSuccess
handleFilesInput inputFiles outputFile autoYes
| fredcy/elm-format | src/Main.hs | bsd-3-clause | 4,270 | 0 | 17 | 1,227 | 1,064 | 532 | 532 | 105 | 3 |
--------------------------------------------------------------------------
-- Copyright (c) 2007-2010, ETH Zurich.
-- All rights reserved.
--
-- This file is distributed under the terms in the attached LICENSE file.
-- If you do not find this file, copies can be found by writing to:
-- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
--
-- Architectural definitions for Barrelfish on ARMv5 ISA.
--
-- The build target is the integratorcp board on QEMU with the default
-- ARM926EJ-S cpu.
--
--------------------------------------------------------------------------
module ARMv5 where
import HakeTypes
import Path
import qualified Config
import qualified ArchDefaults
-------------------------------------------------------------------------
--
-- Architecture specific definitions for ARMv5
--
-------------------------------------------------------------------------
arch = "armv5"
archFamily = "arm"
compiler = "arm-none-linux-gnueabi-gcc"
objcopy = "arm-none-linux-gnueabi-objcopy"
objdump = "arm-none-linux-gnueabi-objdump"
ar = "arm-none-linux-gnueabi-ar"
ranlib = "arm-none-linux-gnueabi-ranlib"
cxxcompiler = "arm-none-linux-gnueabi-g++"
ourCommonFlags = [ Str "-fno-unwind-tables",
Str "-Wno-packed-bitfield-compat",
Str "-mcpu=arm926ej-s",
Str "-mapcs",
Str "-mabi=aapcs-linux",
Str "-msingle-pic-base",
Str "-mpic-register=r10",
Str "-DPIC_REGISTER=R10",
Str "-fpic",
Str "-ffixed-r9",
Str "-DTHREAD_REGISTER=R9",
Str "-Wno-unused-but-set-variable",
Str "-Wno-format" ]
cFlags = ArchDefaults.commonCFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
cxxFlags = ArchDefaults.commonCxxFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
cDefines = ArchDefaults.cDefines options
ourLdFlags = [ Str "-Wl,-section-start,.text=0x400000",
Str "-Wl,-section-start,.data=0x600000" ]
ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags
ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags
stdLibs = ArchDefaults.stdLibs arch ++ [ Str "-lgcc" ]
options = (ArchDefaults.options arch archFamily) {
optFlags = cFlags,
optCxxFlags = cxxFlags,
optDefines = cDefines,
optDependencies =
[ PreDep InstallTree arch "/include/errors/errno.h",
PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h",
PreDep InstallTree arch "/include/asmoffsets.h",
PreDep InstallTree arch "/include/romfs_size.h" ],
optLdFlags = ldFlags,
optLdCxxFlags = ldCxxFlags,
optLibs = stdLibs,
optInterconnectDrivers = ["lmp"],
optFlounderBackends = ["lmp"]
}
--
-- Compilers
--
cCompiler = ArchDefaults.cCompiler arch compiler
cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler
makeDepend = ArchDefaults.makeDepend arch compiler
makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler
cToAssembler = ArchDefaults.cToAssembler arch compiler
assembler = ArchDefaults.assembler arch compiler
archive = ArchDefaults.archive arch
linker = ArchDefaults.linker arch compiler
cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler
--
-- The kernel is "different"
--
kernelCFlags = [ Str s | s <- [ "-fno-builtin",
"-fno-unwind-tables",
"-nostdinc",
"-std=c99",
"-mcpu=arm926ej-s",
"-mapcs",
"-mabi=aapcs-linux",
"-fPIE",
"-U__linux__",
"-Wall",
"-Wshadow",
"-Wstrict-prototypes",
"-Wold-style-definition",
"-Wmissing-prototypes",
"-Wmissing-declarations",
"-Wmissing-field-initializers",
"-Wredundant-decls",
"-Werror",
"-imacros deputy/nodeputy.h",
"-fpie",
"-fno-stack-check",
"-ffreestanding",
"-fomit-frame-pointer",
"-mno-long-calls",
"-Wmissing-noreturn",
"-mno-apcs-stack-check",
"-mno-apcs-reentrant",
"-msingle-pic-base",
"-mpic-register=r10",
"-DPIC_REGISTER=R10",
"-ffixed-r9",
"-DTHREAD_REGISTER=R9",
"-Wno-unused-but-set-variable",
"-Wno-format" ]]
kernelLdFlags = [ Str "-Wl,-N",
NStr "-Wl,-Map,", Out arch "kernel.map",
Str "-fno-builtin",
Str "-nostdlib",
Str "-Wl,--fatal-warnings"
]
--
-- Link the kernel (CPU Driver)
--
linkKernel :: Options -> [String] -> [String] -> String -> HRule
linkKernel opts objs libs kbin =
let linkscript = "/kernel/linker.lds"
kbootable = kbin ++ ".bin"
in
Rules [ Rule ([ Str compiler, Str Config.cOptFlags,
NStr "-T", In BuildTree arch linkscript,
Str "-o", Out arch kbin
]
++ (optLdFlags opts)
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
[ Str "-lgcc" ]
),
-- Edit ELF header so qemu-system-arm will treat it as a Linux kernel
Rule [ In SrcTree "src" "/tools/arm-mkbootelf.sh",
Str objdump, In BuildTree arch kbin, Out arch (kbootable)],
-- Generate kernel assembly dump
Rule [ Str (objdump ++ " -d -M reg-names-raw"),
In BuildTree arch kbin, Str ">", Out arch (kbin ++ ".asm")],
Rule [ Str "cpp",
NStr "-I", NoDep SrcTree "src" "/kernel/include/arch/armv5",
Str "-D__ASSEMBLER__",
Str "-P", In SrcTree "src" "/kernel/arch/armv5/linker.lds.in",
Out arch linkscript
]
]
| daleooo/barrelfish | hake/ARMv5.hs | mit | 6,794 | 8 | 17 | 2,573 | 1,007 | 560 | 447 | 123 | 1 |
module BadPattern where
{-- snippet badExample --}
badExample (x:xs) = x + badExample xs
{-- /snippet badExample --}
{-- snippet goodExample --}
goodExample (x:xs) = x + goodExample xs
goodExample _ = 0
{-- /snippet goodExample --}
| binesiyu/ifl | examples/ch03/BadPattern.hs | mit | 239 | 0 | 7 | 44 | 60 | 33 | 27 | 4 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module InnerEar.Types.Request where
import Text.JSON
import Text.JSON.Generic
import Text.JSON.String (runGetJSON)
import InnerEar.Types.Utility
import InnerEar.Types.Handle
import InnerEar.Types.Password
import InnerEar.Types.Data
import InnerEar.Types.ExerciseId
data Request =
CreateUser Handle Password |
Authenticate Handle Password |
Deauthenticate |
PostPoint Point |
GetUserList |
GetAllRecords Handle |
GetAllExerciseEvents Handle ExerciseId
deriving (Eq,Show,Data,Typeable)
-- | decodeRequest probably shouldn't be necessary but we need to do this
-- in order to avoid "unknown constructor" errors when decoding JSON requests
-- for no obvious reason. A small price to pay for auto-derived JSON instances though...
decodeRequest :: String -> Result Request
decodeRequest = either Error fromJSON . runGetJSON readJSValue
| JamieBeverley/InnerEar | src/InnerEar/Types/Request.hs | gpl-3.0 | 888 | 0 | 6 | 126 | 152 | 91 | 61 | 21 | 1 |
{-|
Module : Css.Draw
Description : Defines the CSS for the draw page.
Defines the CSS for the draw page, which includes all of the buttons on the
draw page.
-}
module Css.Draw
(drawStyles) where
import Clay hiding (map, repeat, id, i, row, col)
import Prelude hiding ((**))
import Css.Constants
import qualified Data.Text as T
-- |Defines the CSS for the draw page.
drawStyles :: Css
drawStyles = do
colourTableCSS
mainCSS
titleDiv
canvasCSS
panelCSS
modeButtonsCSS
clickedButtonsCSS
simpleButton
inputCSS
textButtonCSS
nodeLabelCSS
elbowCSS
finishRegionCSS
{- The colour table. -}
colourTableCSS :: Css
colourTableCSS =
"#colour-table" ? do
height (px 40)
width (px 200)
mapM_ makeRule [0..length colours - 1]
where
makeRule i =
let colour = colours !! i
(row, col) = divMod i 5
in
tr # nthChild (T.pack $ show $ row + 1) **
td # nthChild (T.pack $ show $ col + 1) ? background colour
colours = [
pastelRed, pastelYellow, pastelBlue, pastelPink, white,
pastelOrange, pastelGreen, pastelPurple, pastelBrown, pastelGrey
]
{- The wrapping around the canvas elements. -}
mainCSS :: Css
mainCSS = "#main" ? do
height (pct 85)
width (pct 85)
float floatRight
position relative
"border-radius" -: "8px"
border solid (px 2) black
titleDiv :: Css
titleDiv = "#about-div" ? do
fontSize (em 1.2)
margin 0 0 0 (px 10)
{- The SVG canvas and the grid background. -}
canvasCSS :: Css
canvasCSS = do
"#background" ? do
height100
width100
"background-image" -: "url(/static/res/backgrounds/draw-background.png)"
"background-size" -: "8px"
opacity 0.3
"#mySVG" ? do
height100
width100
position absolute
top nil
left nil
{- The side panel. -}
panelCSS :: Css
panelCSS = do
"#side-panel-wrap" ? do
height (pct 85)
width (pct 15)
float floatLeft
padding (px 5) 0 (px 5) 0
border solid (px 2) black
roundCorners
backgroundColor $ parse "#008080"
overflowY auto
{- The mode buttons. -}
modeButtonsCSS :: Css
modeButtonsCSS = ".mode" ? do
width (pct 93)
padding 0 0 0 (px 5)
margin 0 0 0 (px 5)
roundCorners
fontSize (em 0.75)
border solid (px 2) "#008080"
"-webkit-transition" -: "all 0.2s"
"-moz-transition" -: "all 0.2s"
"-ms-transition" -: "all 0.2s"
"-o-transition" -: "all 0.2s"
"transition" -: "all 0.2s"
":hover" & do
"background-color" -: "#28B0A2 !important"
"color" -: "#DCDCDC !important"
cursor pointer
".clicked" & do
"background-color" -: "#28B0A2 !important"
clickedButtonsCSS :: Css
clickedButtonsCSS = ".clicked" ? do
"color" -: "#DCDCDC !important"
border solid (px 2) black
{- The input field. -}
inputCSS :: Css
inputCSS = "input" ? do
fontSize (px 16)
border solid (px 2) "#DCDCDC"
roundCorners
margin (px 5) (px 0) (px 5) (px 5)
padding0
":focus" & do
{-border solid (px 2) "#FFD700"-}
"box-shadow" -: "0 0 3px 1px #FFD700"
{- Style for simple buttons. -}
simpleButton :: Css
simpleButton = ".button" ? do
width (pct 40)
margin (px 5) (px 5) (px 5) (px 5)
padding0
roundCorners
alignCenter
fontSize (em 0.75)
border solid (px 2) "#008080"
border solid (px 2) black
"-webkit-transition" -: "all 0.2s"
"-moz-transition" -: "all 0.2s"
"-ms-transition" -: "all 0.2s"
"-o-transition" -: "all 0.2s"
"transition" -: "all 0.2s"
":hover" & do
"background-color" -: "black !important"
"color" -: "#DCDCDC !important"
cursor pointer
{- The add button. -}
textButtonCSS :: Css
textButtonCSS = "#add-text" ? do
"display" -: "inline"
margin (px 5) (px 5) (px 5) (px 5)
padding (px 2) (px 5) (px 2) (px 5)
width (pct 45)
{- The labels for a node. -}
nodeLabelCSS :: Css
nodeLabelCSS = ".mylabel" ? do
alignCenter
"stroke" -: "none"
userSelect none
"-webkit-touch-callout" -: "none"
"-webkit-user-select" -: "none"
"-khtml-user-select" -: "none"
"-moz-user-select" -: "none"
"-ms-user-select" -: "none"
"text-anchor" -: "middle"
"dominant-baseline" -: "central"
{- The invisible elbow nodes. -}
elbowCSS :: Css
elbowCSS = do
".elbow" ? do
opacity 0
":hover" & do
cursor pointer
opacity 1
".rElbow" ? do
opacity 0
":hover" & do
cursor pointer
opacity 1
{- The finish button -}
finishRegionCSS :: Css
finishRegionCSS = "#finish-region" ? do
width (pct 40)
margin (px 5) (px 5) (px 5) (px 5)
padding0
backgroundColor $ parse "#DCDCDC"
-- border solid (px 2) black
border solid (px 2) $ parse "#008080"
| hermish/courseography | app/Css/Draw.hs | gpl-3.0 | 5,005 | 0 | 18 | 1,488 | 1,449 | 677 | 772 | 160 | 1 |
-- yammat - Yet Another MateMAT
-- Copyright (C) 2015 Amedeo Molnár
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published
-- by the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Import.NoFoundation
( module Import
) where
import ClassyPrelude.Yesod as Import
import Model as Import
import Settings as Import
import Settings.StaticFiles as Import
import Yesod.Auth as Import
import Yesod.Core.Types as Import (loggerSet)
import Yesod.Default.Config2 as Import
import Yesod.Form.Bootstrap3 as Import
| nek0/yammat | Import/NoFoundation.hs | agpl-3.0 | 1,136 | 0 | 5 | 239 | 87 | 67 | 20 | 10 | 0 |
{-# LANGUAGE Haskell2010 #-}
{-# LANGUAGE DefaultSignatures #-}
module DefaultSignatures where
-- | Documentation for Foo.
class Foo a where
-- | Documentation for bar and baz.
bar, baz :: a -> String
-- | Documentation for the default signature of bar.
default bar :: Show a => a -> String
bar = show
-- | Documentation for baz'.
baz' :: String -> a
-- | Documentation for the default signature of baz'.
default baz' :: Read a => String -> a
baz' = read
| haskell/haddock | latex-test/src/DefaultSignatures/DefaultSignatures.hs | bsd-2-clause | 480 | 0 | 9 | 110 | 86 | 50 | 36 | 10 | 0 |
--
-- Benchmark code: compare http-streams and http-conduit
--
-- Copyright © 2012-2014 Operational Dynamics Consulting, Pty Ltd
--
-- The code in this file, and the program it is a part of, is made
-- available to you by its authors as open source software: you can
-- redistribute it and/or modify it under a BSD licence.
--
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -fno-warn-unused-do-bind #-}
import Criterion.Main
import GHC.Conc
{-
The actual sample request code are in separate moduels to avoid
namespace collision nightmares.
-}
import ConduitSample (sampleViaHttpConduit)
import Network.HTTP.Conduit (def, newManager)
import StreamsSample (sampleViaHttpStreams)
main :: IO ()
main = do
GHC.Conc.setNumCapabilities 4
man <- newManager def
defaultMain
[bench "http-streams" (sampleViaHttpStreams),
bench "http-conduit" (sampleViaHttpConduit man)]
putStrLn "Complete."
| laurencer/confluence-sync | vendor/http-streams/tests/ComparisonBenchmark.hs | bsd-3-clause | 927 | 0 | 11 | 165 | 124 | 70 | 54 | 15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.