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 StandaloneDeriving, FlexibleContexts, UndecidableInstances #-} newtype Fix f = In (f (Fix f)) deriving instance Show (f (Fix f)) => Show (Fix f) deriving instance Eq (f (Fix f)) => Eq (Fix f) out :: Fix f -> f (Fix f) out (In x) = x type Algebra f a = f a -> a cata :: Functor f => Algebra f a -> Fix f -> a cata phi (In x) = phi $ fmap (cata phi) x type Coalgebra f a = a -> f a ana :: Functor f => Coalgebra f a -> a -> Fix f ana psi x = In $ fmap (ana psi) (psi x) hylo :: Functor f => Algebra f a -> Coalgebra f b -> (b -> a) hylo phi psi = cata phi . ana psi {- data B b = Empty | Zero b | One b deriving (Eq, Show) type Bin = Fix B instance Functor B where fmap g Empty = Empty fmap g (Zero b) = Zero (g b) fmap g (One b) = One (g b) bin2Int :: Bin -> Int bin2Int = cata phiB phiB :: B Int -> Int phiB Empty = 0 phiB (Zero b) = b * 2 phiB (One b) = b * 2 + 1 int2bin :: Int -> Bin int2bin = ana psiB psiB :: Int -> B Int psiB 0 = Empty psiB n = (if n `mod` 2 == 0 then Zero else One) (n `div` 2) -} {- data E e = Num Int | Add e e | Mult e e deriving (Eq, Show) instance Functor E where fmap g (Num x) = Num x fmap g (Add e1 e2) = Add (g e1) (g e2) fmap g (Mult e1 e2) = Mult (g e1) (g e2) type Expr = Fix E phiE :: E Int -> Int phiE (Num x) = x phiE (Add e1 e2) = e1 + e2 phiE (Mult e1 e2) = e1 * e2 eval :: Expr -> Int eval = cata phiE phiEShow :: E String -> String phiEShow (Num x) = show x phiEShow (Add x y) = "(" ++ x ++ "+" ++ y ++ ")" phiEShow (Mult x y) = "(" ++ x ++ "*" ++ y ++ ")" en = In . Num e3 = en 3 ep35 = In (Add e3 (en 5)) emp357 = In (Mult ep35 (en 7)) em7p35 = In (Mult (en 7) ep35) phiEShowS :: E ShowS -> ShowS phiEShowS (Num x) = shows x phiEShowS (Add x y) = showString "+ " . x . showChar ' ' . y phiEShowS (Mult x y) = showString "* " . x . showChar ' ' . y type Stack = [Int] push :: Int -> Stack -> Stack push a as = a : as add :: Stack -> Stack add (a : b : cs) = (b + a) : cs mult :: Stack -> Stack mult (a : b : cs) = (b * a) : cs phiE' :: E (Stack -> Stack) -> Stack -> Stack phiE' (Num x) = push x phiE' (Add s1 s2) = \st -> add (s1 $ s2 st) phiE' (Mult s1 s2) = \st -> mult (s1 $ s2 st) eval' :: Expr -> Stack -> Stack eval' = cata phiE' -} data T a x = Leaf | Branch x a x deriving (Eq, Show) instance Functor (T a) where fmap g Leaf = Leaf fmap g (Branch a b c) = Branch (g a) b (g c) type Tree a = Fix (T a) phiTSum :: Algebra (T Integer) Integer phiTSum Leaf = 0 phiTSum (Branch a b c) = a + b + c treeSum :: Tree Integer -> Integer treeSum = cata phiTSum phiTInorder :: Algebra (T a) [a] -- T a [a] -> [a] phiTInorder Leaf = [] phiTInorder (Branch a b c) = a ++ [b] ++ c tree2listInorder :: Tree a -> [a] tree2listInorder = cata phiTInorder psiTBST :: Ord a => Coalgebra (T a) [a] -- [a] -> T a [a] psiTBST [] = Leaf psiTBST (x:xs) = let lower = filter (< x) xs higher = filter (> x) xs in Branch lower x higher list2BST :: Ord a => [a] -> Tree a list2BST = ana psiTBST sort :: Ord a => [a] -> [a] sort = hylo phiTInorder psiTBST iB l x r = In $ Branch l x r iL = In Leaf testTree = iB (iB (iB iL 2 iL) 3 (iB iL 4 iL) ) 5 (iB iL 6 (iB iL 7 iL) )
ItsLastDay/academic_university_2016-2018
subjects/Haskell/13/homework.hs
gpl-3.0
3,321
0
10
994
839
426
413
57
1
{-# LANGUAGE OverloadedStrings #-} module Database.Alteryx.CLI.PrettyPrinters ( printRecordInfo ) where import Database.Alteryx.Types import Control.Lens import Control.Newtype as NT import Data.Monoid import Data.Text as T import Data.Text.IO import Prelude hiding (putStrLn) printRecordInfo :: RecordInfo -> IO () printRecordInfo recordInfo = let printField field = putStrLn $ ( " " <> (field ^. fieldName) <> ": " <> (T.pack $ show $ field ^. fieldType) <> case field ^. fieldSize of Just x -> " - Size: " <> (T.pack $ show x) Nothing -> "" <> case field ^. fieldScale of Just x -> " - Scale: " <> (T.pack $ show x) Nothing -> "" :: Text ) in do putStrLn "RecordInfo:" mapM_ printField $ NT.unpack recordInfo
MichaelBurge/yxdb-utils
src/Database/Alteryx/CLI/PrettyPrinters.hs
gpl-3.0
842
0
19
247
248
132
116
27
3
module SugarScape.Visual.GlossRunner ( runGloss ) where import Data.IORef import Control.Monad.Random import qualified Graphics.Gloss as GLO import Graphics.Gloss.Interface.IO.Animate import Graphics.Gloss.Interface.IO.Simulate import SugarScape.Core.Scenario import SugarScape.Core.Simulation import SugarScape.Visual.Renderer runGloss :: SugarScapeScenario -> SimulationState StdGen -> SimTickOut -> Int -> AgentColoring -> SiteColoring -> IO () runGloss params initSimState initOut stepsPerSec av cv = do let winSize = (800, 800) winTitle = "SugarScape " ++ sgScenarioName params -- intiialize IORef which holds last simulation state ssRef <- newIORef initSimState if stepsPerSec > 0 then -- run stimulation, driven by Gloss simulateIO (displayGlossWindow winTitle winSize) -- window title and size white -- background stepsPerSec -- how many steps of the simulation to calculate per second (roughly, depends on rendering performance) initOut -- initial model = output of each simulation step to be rendered (modelToPicture winSize av cv) -- model-to-picture function (renderStep ssRef) -- else animateIO (displayGlossWindow winTitle winSize) white (renderStepAnimate winSize ssRef av cv) (const $ return ()) displayGlossWindow :: String -> (Int, Int) -> GLO.Display displayGlossWindow winTitle winSize = GLO.InWindow winTitle winSize (0, 0) modelToPicture :: (Int, Int) -> AgentColoring -> SiteColoring -> SimTickOut -> IO GLO.Picture modelToPicture winSize av cv (t, env, as) = return $ renderSugarScapeFrame winSize t env as av cv renderStep :: IORef (SimulationState StdGen) -> ViewPort -> Float -> SimTickOut -> IO SimTickOut renderStep ssRef _ _ _ = do ss <- readIORef ssRef (ss', out) <- simulationTick ss writeIORef ssRef ss' return out renderStepAnimate :: (Int, Int) -> IORef (SimulationState StdGen) -> AgentColoring -> SiteColoring -> Float -> IO GLO.Picture renderStepAnimate winSize ssRef av cv _ = do ss <- readIORef ssRef (ss', out) <- simulationTick ss writeIORef ssRef ss' modelToPicture winSize av cv out
thalerjonathan/phd
public/towards/SugarScape/experimental/concurrent/src/SugarScape/Visual/GlossRunner.hs
gpl-3.0
2,496
0
12
746
570
298
272
64
2
module Freenet.Pcfb ( -- * PCFB (Periodic Cipher Feed Back) Mode mkPCFB, pcfbEncipher, pcfbEncipherWord8, pcfbDecipher, pcfbDecipherWord8 ) where import Control.Applicative ( (<*>), (<$>) ) import Control.Monad ( when ) import Control.Monad.ST.Safe import Data.Bits ( xor ) import qualified Data.ByteString as B import Data.STRef import qualified Data.Vector.Unboxed as UV import qualified Data.Vector.Unboxed.Mutable as UMV import Data.Word import qualified Freenet.Rijndael as RD -- import Utils -------------------------------------------------------------------------------- -- PCFB (Periodic Cipher Feed Back) mode -------------------------------------------------------------------------------- data PCFB s = MkPCFB { _pcfbCipher :: RD.Key , _pcfbFeedback :: UMV.MVector s Word8 , _pcfbIdx :: STRef s Int } mkPCFB :: RD.Key -- ^ the underlying cipher to use -> B.ByteString -- ^ the IV (initialization vector) -> ST s (PCFB s) mkPCFB c iv | B.length iv /= 32 = error "mkPCFB: IV length must be 32" | otherwise = MkPCFB c <$> UV.thaw (bsToVec iv) <*> newSTRef 32 pcfbRefill :: PCFB s -> ST s () pcfbRefill (MkPCFB c f i) = do pos <- readSTRef i when (UMV.length f == pos) $ do ff <- UV.freeze f fm' <- UV.thaw $ bsToVec $ RD.encipher c $ vecToBs ff UMV.copy f fm' writeSTRef i 0 pcfbDecipherWord8 :: PCFB s -> Word8 -> ST s Word8 pcfbDecipherWord8 pc@(MkPCFB _ f i) x = do pcfbRefill pc fpos <- readSTRef i ff <- UMV.read f fpos UMV.write f fpos x modifySTRef i (+1) return $! x `xor` ff pcfbDecipher :: PCFB s -> B.ByteString -> ST s B.ByteString pcfbDecipher pcfb b = B.pack <$> mapM (pcfbDecipherWord8 pcfb) (B.unpack b) pcfbEncipherWord8 :: PCFB s -> Word8 -> ST s Word8 pcfbEncipherWord8 pc@(MkPCFB _ f i) x = do pcfbRefill pc fpos <- readSTRef i ff <- UMV.read f fpos modifySTRef i (+1) let result = x `xor` ff UMV.write f fpos result return $! result pcfbEncipher :: PCFB s -> B.ByteString -> ST s B.ByteString pcfbEncipher pcfb b = B.pack <$> mapM (pcfbEncipherWord8 pcfb) (B.unpack b) -- | converts a ByteString to an unboxed vector bsToVec :: B.ByteString -> UV.Vector Word8 bsToVec bs = UV.generate (B.length bs) (B.index bs) vecToBs :: UV.Vector Word8 -> B.ByteString vecToBs v = B.pack $ UV.toList v
waldheinz/ads
src/lib/Freenet/Pcfb.hs
gpl-3.0
2,378
0
14
516
813
413
400
57
1
module Database.Design.Ampersand.Classes.Relational (Relational(..) ) where import Data.Maybe import Database.Design.Ampersand.Core.AbstractSyntaxTree import Database.Design.Ampersand.ADL1.Expression import Database.Design.Ampersand.Basics class Association r => Relational r where properties :: r -> [Prop] isProp :: r -> Bool -- > tells whether the argument is a property isImin :: r -> Bool -- > tells whether the argument is equivalent to I- isTrue :: r -> Bool -- > tells whether the argument is equivalent to V isFalse :: r -> Bool -- > tells whether the argument is equivalent to V- isFunction :: r -> Bool isFunction r = null ([Uni,Tot]>-properties r) isTot :: r -> Bool -- isTot r = Tot `elem` properties r isUni :: r -> Bool -- isUni r = Uni `elem` properties r isSur :: r -> Bool -- isSur r = Sur `elem` properties r isInj :: r -> Bool -- isInj r = Inj `elem` properties r isRfx :: r -> Bool -- isRfx r = Rfx `elem` properties r isIrf :: r -> Bool -- isIrf r = Irf `elem` properties r isTrn :: r -> Bool -- isTrn r = Trn `elem` properties r isSym :: r -> Bool -- isSym r = Sym `elem` properties r isAsy :: r -> Bool -- isAsy r = Asy `elem` properties r isIdent :: r -> Bool -- > tells whether the argument is equivalent to I isEpsilon :: r -> Bool -- > tells whether the argument is equivalent to I --instance Relational Relation where -- properties rel -- = case rel of -- Rel{} -> properties (reldcl rel) -- V {} -> [Tot] -- ++[Sur] -- ++[Inj | isSingleton (source rel)] -- ++[Uni | isSingleton (target rel)] -- ++[Asy | isEndo rel, isSingleton (source rel)] -- ++[Sym | isEndo rel] -- ++[Rfx | isEndo rel] -- ++[Trn | isEndo rel] -- I{} -> [Uni,Tot,Inj,Sur,Sym,Asy,Trn,Rfx] -- isProp rel = case rel of -- Rel{} -> null ([Asy,Sym]>-properties (reldcl rel)) -- V{} -> isEndo rel && isSingleton (source rel) -- I{} -> True -- isImin rel = isImin (makeDeclaration rel) -- > tells whether the argument is equivalent to I- -- isTrue rel = case rel of -- Rel{} -> False -- V{} -> True -- I{} -> False -- isFalse _ = False -- isIdent rel = case rel of -- > tells whether the argument is equivalent to I -- Rel{} -> False -- V{} -> isEndo rel && isSingleton (source rel) -- I{} -> True instance Relational Declaration where properties d = case d of Sgn {} -> case decprps_calc d of Nothing -> decprps d Just ps -> ps Isn{} -> [Uni,Tot,Inj,Sur,Sym,Asy,Trn,Rfx] Vs{} -> [Tot,Sur] isProp d = case d of -- > tells whether the argument is a property. Sgn {} -> null ([Asy,Sym]>-properties d) Isn{} -> True Vs{} -> isEndo (sign d) && isSingleton (source d) isImin _ = False -- LET OP: Dit kan natuurlijk niet goed zijn, maar is gedetecteerd bij revision 913, toen straffeloos de Iscompl{} kon worden verwijderd. isTrue d = case d of Vs{} -> True _ -> False isFalse _ = False isIdent d = case d of Isn{} -> True -- > tells whether the argument is equivalent to I _ -> False isEpsilon _ = False isSingleton :: A_Concept -> Bool isSingleton ONE = True isSingleton _ = False -- The function "properties" does not only provide the properties provided by the Ampersand user, -- but tries to derive the most obvious multiplicity constraints as well. The more multiplicity constraints are known, -- the better the data structure that is derived. -- Not every constraint that can be proven is obtained by this function. This does not hurt Ampersand. instance Relational Expression where -- TODO: see if we can find more multiplicity constraints... properties expr = case expr of EDcD dcl -> properties dcl EDcI{} -> [Uni,Tot,Inj,Sur,Sym,Asy,Trn,Rfx] EEps a sgn -> [Tot | a == source sgn]++[Sur | a == target sgn] ++ [Uni,Inj] EDcV sgn -> [Tot] ++[Sur] ++[Inj | isSingleton (source sgn)] ++[Uni | isSingleton (target sgn)] ++[Asy | isEndo sgn, isSingleton (source sgn)] ++[Sym | isEndo sgn] ++[Rfx | isEndo sgn] ++[Trn | isEndo sgn] EBrk f -> properties f ECps (l,r) -> [m | m<-properties l `isc` properties r, m `elem` [Uni,Tot,Inj,Sur]] -- endo properties can be used and deduced by and from rules: many rules are properties (TODO) EPrd (l,r) -> [Tot | isTot l]++[Sur | isSur r]++[Rfx | isRfx l&&isRfx r]++[Trn] EKl0 e' -> [Rfx,Trn] `uni` (properties e'>-[Uni,Inj]) EKl1 e' -> [ Trn] `uni` (properties e'>-[Uni,Inj]) ECpl e' -> [p |p<-properties e', p==Sym] EFlp e' -> [fromMaybe m $ lookup m [(Uni,Inj),(Inj,Uni),(Sur,Tot),(Tot,Sur)] | m <- properties e'] -- switch Uni<->Inj and Sur<->Tot, keeping the others the same EMp1{} -> [Uni,Inj,Sym,Asy,Trn] _ -> [] -- | isTrue e == True means that e is true, i.e. the population of e is (source e * target e). -- isTrue e == False does not mean anything. -- the function isTrue is meant to produce a quick answer, without any form of theorem proving. isTrue expr = case expr of EEqu (l,r) -> l == r EInc (l,_) -> isTrue l EIsc (l,r) -> isTrue l && isTrue r EUni (l,r) -> isTrue l || isTrue r EDif (l,r) -> isTrue l && isFalse r ECps (l,r) | null ([Uni,Tot]>-properties l) -> isTrue r | null ([Sur,Inj]>-properties r) -> isTrue l | otherwise -> isTrue l && isTrue r EPrd (l,r) -> isTrue l && isTrue r || isTot l && isSur r || isRfx l && isRfx r EKl0 e -> isTrue e EKl1 e -> isTrue e EFlp e -> isTrue e ECpl e -> isFalse e EDcD{} -> False EDcI c -> isSingleton c EEps i _ -> isSingleton i EDcV{} -> True EBrk e -> isTrue e _ -> False -- TODO: find richer answers for ERrs, ELrs, EDia, ERad, and EMp1 -- | isFalse e == True means that e is false, i.e. the population of e is empty. -- isFalse e == False does not mean anything. -- the function isFalse is meant to produce a quick answer, without any form of theorem proving. isFalse expr = case expr of EEqu (l,r) -> l == notCpl r EInc (_,r) -> isFalse r EIsc (l,r) -> isFalse r || isFalse l EUni (l,r) -> isFalse r && isFalse l EDif (l,r) -> isFalse l || isTrue r ECps (l,r) -> isFalse r || isFalse l EPrd (l,r) -> isFalse r || isFalse l EKl0 e -> isFalse e EKl1 e -> isFalse e EFlp e -> isFalse e ECpl e -> isTrue e EDcD{} -> False EDcI{} -> False EEps{} -> False EDcV{} -> False EBrk e -> isFalse e _ -> False -- TODO: find richer answers for ERrs, ELrs, EDia, and ERad isProp expr = null ([Asy,Sym]>-properties expr) -- | The function isIdent tries to establish whether an expression is an identity relation. -- It does a little bit more than just test on ERel I _. -- If it returns False, this must be interpreted as: the expression is definitely not I, an may not be equal to I as far as the computer can tell on face value. isIdent expr = case expr of EEqu (l,r) -> isIdent (EIsc (EInc (l,r), EInc (r,l))) -- TODO: maybe derive something better? EInc (l,r) -> isIdent (EUni (ECpl l, r)) -- TODO: maybe derive something better? EIsc (l,r) -> isIdent l && isIdent r EUni (l,r) -> isIdent l && isIdent r EDif (l,r) -> isIdent l && isFalse r ECps (l,r) -> isIdent l && isIdent r EKl0 e -> isIdent e || isFalse e EKl1 e -> isIdent e ECpl e -> isImin e EDcD{} -> False EDcI{} -> True EEps{} -> False EDcV sgn -> isEndo sgn && isSingleton (source sgn) EBrk f -> isIdent f EFlp f -> isIdent f _ -> False -- TODO: find richer answers for ELrs, ERrs, EDia, EPrd, and ERad isEpsilon e = case e of EEps{} -> True _ -> False isImin expr' = case expr' of -- > tells whether the argument is equivalent to I- EEqu (l,r) -> isImin (EIsc (EInc (l,r), EInc (r,l))) -- TODO: maybe derive something better? EInc (l,r) -> isImin (EUni (ECpl l, r)) -- TODO: maybe derive something better? EIsc (l,r) -> isImin l && isImin r EUni (l,r) -> isImin l && isImin r EDif (l,r) -> isImin l && isFalse r ECpl e -> isIdent e EDcD dcl -> isImin dcl EDcI{} -> False EEps{} -> False EDcV{} -> False EBrk f -> isImin f EFlp f -> isImin f _ -> False -- TODO: find richer answers for ELrs, ERrs, and EDia
4ZP6Capstone2015/ampersand
src/Database/Design/Ampersand/Classes/Relational.hs
gpl-3.0
9,529
0
19
3,328
2,646
1,373
1,273
154
1
{-# LANGUAGE OverloadedStrings #-} -- Copyright (C) 2009-2011 John Millikin <[email protected]> -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module Main (main) where import Control.Concurrent (threadDelay) import Control.Monad import System.Exit import DBus import DBus.Client onFoo :: String -> String -> IO (String, String) onFoo x y = do putStrLn ("Foo " ++ show x ++ " " ++ show y) return (x, y) onBar :: String -> String -> IO (String, String) onBar x y = do putStrLn ("Bar " ++ show x ++ " " ++ show y) throwError "com.example.ErrorBar" "Bar failed" [] main :: IO () main = do -- Connect to the bus client <- connectSession -- Request a unique name on the bus. requestResult <- requestName client "com.example.exporting" [] when (requestResult /= NamePrimaryOwner) $ do putStrLn "Another service owns the \"com.example.exporting\" bus name" exitFailure -- Export two example objects export client "/a" [ autoMethod "test.iface_1" "Foo" (onFoo "hello" "a") , autoMethod "test.iface_1" "Bar" (onBar "hello" "a") ] export client "/b" [ autoMethod "test.iface_1" "Foo" (onFoo "hello") , autoMethod "test.iface_1" "Bar" (onBar "hello") ] putStrLn "Exported objects /a and /b to bus name com.example.exporting" -- Wait forever for method calls forever (threadDelay 50000)
tmishima/haskell-dbus
examples/export.hs
gpl-3.0
1,960
11
12
398
379
195
184
30
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.AppsReseller -- 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) -- -- Perform common functions that are available on the Channel Services -- console at scale, like placing orders and viewing customer information -- -- /See:/ <https://developers.google.com/google-apps/reseller/ Google Workspace Reseller API Reference> module Network.Google.AppsReseller ( -- * Service Configuration appsResellerService -- * OAuth Scopes , appsOrderReadOnlyScope , appsOrderScope -- * API Declaration , AppsResellerAPI -- * Resources -- ** reseller.customers.get , module Network.Google.Resource.Reseller.Customers.Get -- ** reseller.customers.insert , module Network.Google.Resource.Reseller.Customers.Insert -- ** reseller.customers.patch , module Network.Google.Resource.Reseller.Customers.Patch -- ** reseller.customers.update , module Network.Google.Resource.Reseller.Customers.Update -- ** reseller.resellernotify.getwatchdetails , module Network.Google.Resource.Reseller.Resellernotify.Getwatchdetails -- ** reseller.resellernotify.register , module Network.Google.Resource.Reseller.Resellernotify.Register -- ** reseller.resellernotify.unregister , module Network.Google.Resource.Reseller.Resellernotify.Unregister -- ** reseller.subscriptions.activate , module Network.Google.Resource.Reseller.Subscriptions.Activate -- ** reseller.subscriptions.changePlan , module Network.Google.Resource.Reseller.Subscriptions.ChangePlan -- ** reseller.subscriptions.changeRenewalSettings , module Network.Google.Resource.Reseller.Subscriptions.ChangeRenewalSettings -- ** reseller.subscriptions.changeSeats , module Network.Google.Resource.Reseller.Subscriptions.ChangeSeats -- ** reseller.subscriptions.delete , module Network.Google.Resource.Reseller.Subscriptions.Delete -- ** reseller.subscriptions.get , module Network.Google.Resource.Reseller.Subscriptions.Get -- ** reseller.subscriptions.insert , module Network.Google.Resource.Reseller.Subscriptions.Insert -- ** reseller.subscriptions.list , module Network.Google.Resource.Reseller.Subscriptions.List -- ** reseller.subscriptions.startPaidService , module Network.Google.Resource.Reseller.Subscriptions.StartPaidService -- ** reseller.subscriptions.suspend , module Network.Google.Resource.Reseller.Subscriptions.Suspend -- * Types -- ** SubscriptionTrialSettings , SubscriptionTrialSettings , subscriptionTrialSettings , stsIsInTrial , stsTrialEndTime -- ** ResellernotifyResource , ResellernotifyResource , resellernotifyResource , rrTopicName -- ** ResellernotifyGetwatchdetailsResponse , ResellernotifyGetwatchdetailsResponse , resellernotifyGetwatchdetailsResponse , rgrTopicName , rgrServiceAccountEmailAddresses -- ** Address , Address , address , aOrganizationName , aKind , aPostalCode , aAddressLine1 , aLocality , aContactName , aAddressLine2 , aCountryCode , aRegion , aAddressLine3 -- ** Customer , Customer , customer , cCustomerType , cCustomerDomainVerified , cResourceUiURL , cKind , cCustomerId , cAlternateEmail , cCustomerDomain , cPhoneNumber , cPostalAddress , cPrimaryAdmin -- ** ChangePlanRequest , ChangePlanRequest , changePlanRequest , cprKind , cprDealCode , cprPlanName , cprPurchaseOrderId , cprSeats -- ** SubscriptionPlanCommitmentInterval , SubscriptionPlanCommitmentInterval , subscriptionPlanCommitmentInterval , spciStartTime , spciEndTime -- ** Xgafv , Xgafv (..) -- ** SubscriptionsDeleteDeletionType , SubscriptionsDeleteDeletionType (..) -- ** SubscriptionPlan , SubscriptionPlan , subscriptionPlan , spCommitmentInterval , spIsCommitmentPlan , spPlanName -- ** CustomerCustomerType , CustomerCustomerType (..) -- ** Subscriptions , Subscriptions , subscriptions , sNextPageToken , sKind , sSubscriptions -- ** Seats , Seats , seats , seaNumberOfSeats , seaMaximumNumberOfSeats , seaLicensedNumberOfSeats , seaKind -- ** PrimaryAdmin , PrimaryAdmin , primaryAdmin , paPrimaryEmail -- ** RenewalSettings , RenewalSettings , renewalSettings , rsKind , rsRenewalType -- ** Subscription , Subscription , subscription , subCreationTime , subBillingMethod , subStatus , subTrialSettings , subSKUName , subResourceUiURL , subKind , subSKUId , subPlan , subDealCode , subCustomerId , subCustomerDomain , subSuspensionReasons , subTransferInfo , subPurchaseOrderId , subSeats , subRenewalSettings , subSubscriptionId -- ** SubscriptionTransferInfo , SubscriptionTransferInfo , subscriptionTransferInfo , stiCurrentLegacySKUId , stiTransferabilityExpirationTime , stiMinimumTransferableSeats ) where import Network.Google.Prelude import Network.Google.AppsReseller.Types import Network.Google.Resource.Reseller.Customers.Get import Network.Google.Resource.Reseller.Customers.Insert import Network.Google.Resource.Reseller.Customers.Patch import Network.Google.Resource.Reseller.Customers.Update import Network.Google.Resource.Reseller.Resellernotify.Getwatchdetails import Network.Google.Resource.Reseller.Resellernotify.Register import Network.Google.Resource.Reseller.Resellernotify.Unregister import Network.Google.Resource.Reseller.Subscriptions.Activate import Network.Google.Resource.Reseller.Subscriptions.ChangePlan import Network.Google.Resource.Reseller.Subscriptions.ChangeRenewalSettings import Network.Google.Resource.Reseller.Subscriptions.ChangeSeats import Network.Google.Resource.Reseller.Subscriptions.Delete import Network.Google.Resource.Reseller.Subscriptions.Get import Network.Google.Resource.Reseller.Subscriptions.Insert import Network.Google.Resource.Reseller.Subscriptions.List import Network.Google.Resource.Reseller.Subscriptions.StartPaidService import Network.Google.Resource.Reseller.Subscriptions.Suspend {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Google Workspace Reseller API service. type AppsResellerAPI = CustomersInsertResource :<|> CustomersPatchResource :<|> CustomersGetResource :<|> CustomersUpdateResource :<|> ResellernotifyGetwatchdetailsResource :<|> ResellernotifyRegisterResource :<|> ResellernotifyUnregisterResource :<|> SubscriptionsInsertResource :<|> SubscriptionsListResource :<|> SubscriptionsChangeRenewalSettingsResource :<|> SubscriptionsGetResource :<|> SubscriptionsActivateResource :<|> SubscriptionsSuspendResource :<|> SubscriptionsChangePlanResource :<|> SubscriptionsChangeSeatsResource :<|> SubscriptionsDeleteResource :<|> SubscriptionsStartPaidServiceResource
brendanhay/gogol
gogol-apps-reseller/gen/Network/Google/AppsReseller.hs
mpl-2.0
7,557
0
20
1,385
788
575
213
161
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Snapshots.Get -- 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) -- -- Returns the specified Snapshot resource. Get a list of available -- snapshots by making a list() request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.snapshots.get@. module Network.Google.Resource.Compute.Snapshots.Get ( -- * REST Resource SnapshotsGetResource -- * Creating a Request , snapshotsGet , SnapshotsGet -- * Request Lenses , sggSnapshot , sggProject ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.snapshots.get@ method which the -- 'SnapshotsGet' request conforms to. type SnapshotsGetResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "snapshots" :> Capture "snapshot" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Snapshot -- | Returns the specified Snapshot resource. Get a list of available -- snapshots by making a list() request. -- -- /See:/ 'snapshotsGet' smart constructor. data SnapshotsGet = SnapshotsGet' { _sggSnapshot :: !Text , _sggProject :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'SnapshotsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sggSnapshot' -- -- * 'sggProject' snapshotsGet :: Text -- ^ 'sggSnapshot' -> Text -- ^ 'sggProject' -> SnapshotsGet snapshotsGet pSggSnapshot_ pSggProject_ = SnapshotsGet' { _sggSnapshot = pSggSnapshot_ , _sggProject = pSggProject_ } -- | Name of the Snapshot resource to return. sggSnapshot :: Lens' SnapshotsGet Text sggSnapshot = lens _sggSnapshot (\ s a -> s{_sggSnapshot = a}) -- | Project ID for this request. sggProject :: Lens' SnapshotsGet Text sggProject = lens _sggProject (\ s a -> s{_sggProject = a}) instance GoogleRequest SnapshotsGet where type Rs SnapshotsGet = Snapshot type Scopes SnapshotsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient SnapshotsGet'{..} = go _sggProject _sggSnapshot (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy SnapshotsGetResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Snapshots/Get.hs
mpl-2.0
3,308
0
15
783
393
237
156
64
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.PubSub.Projects.Topics.SetIAMPolicy -- 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) -- -- Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ <https://cloud.google.com/pubsub/docs Cloud Pub/Sub API Reference> for @pubsub.projects.topics.setIamPolicy@. module Network.Google.Resource.PubSub.Projects.Topics.SetIAMPolicy ( -- * REST Resource ProjectsTopicsSetIAMPolicyResource -- * Creating a Request , projectsTopicsSetIAMPolicy , ProjectsTopicsSetIAMPolicy -- * Request Lenses , ptsipXgafv , ptsipUploadProtocol , ptsipAccessToken , ptsipUploadType , ptsipPayload , ptsipResource , ptsipCallback ) where import Network.Google.Prelude import Network.Google.PubSub.Types -- | A resource alias for @pubsub.projects.topics.setIamPolicy@ method which the -- 'ProjectsTopicsSetIAMPolicy' request conforms to. type ProjectsTopicsSetIAMPolicyResource = "v1" :> CaptureMode "resource" "setIamPolicy" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetIAMPolicyRequest :> Post '[JSON] Policy -- | Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ 'projectsTopicsSetIAMPolicy' smart constructor. data ProjectsTopicsSetIAMPolicy = ProjectsTopicsSetIAMPolicy' { _ptsipXgafv :: !(Maybe Xgafv) , _ptsipUploadProtocol :: !(Maybe Text) , _ptsipAccessToken :: !(Maybe Text) , _ptsipUploadType :: !(Maybe Text) , _ptsipPayload :: !SetIAMPolicyRequest , _ptsipResource :: !Text , _ptsipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsTopicsSetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptsipXgafv' -- -- * 'ptsipUploadProtocol' -- -- * 'ptsipAccessToken' -- -- * 'ptsipUploadType' -- -- * 'ptsipPayload' -- -- * 'ptsipResource' -- -- * 'ptsipCallback' projectsTopicsSetIAMPolicy :: SetIAMPolicyRequest -- ^ 'ptsipPayload' -> Text -- ^ 'ptsipResource' -> ProjectsTopicsSetIAMPolicy projectsTopicsSetIAMPolicy pPtsipPayload_ pPtsipResource_ = ProjectsTopicsSetIAMPolicy' { _ptsipXgafv = Nothing , _ptsipUploadProtocol = Nothing , _ptsipAccessToken = Nothing , _ptsipUploadType = Nothing , _ptsipPayload = pPtsipPayload_ , _ptsipResource = pPtsipResource_ , _ptsipCallback = Nothing } -- | V1 error format. ptsipXgafv :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Xgafv) ptsipXgafv = lens _ptsipXgafv (\ s a -> s{_ptsipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ptsipUploadProtocol :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipUploadProtocol = lens _ptsipUploadProtocol (\ s a -> s{_ptsipUploadProtocol = a}) -- | OAuth access token. ptsipAccessToken :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipAccessToken = lens _ptsipAccessToken (\ s a -> s{_ptsipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ptsipUploadType :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipUploadType = lens _ptsipUploadType (\ s a -> s{_ptsipUploadType = a}) -- | Multipart request metadata. ptsipPayload :: Lens' ProjectsTopicsSetIAMPolicy SetIAMPolicyRequest ptsipPayload = lens _ptsipPayload (\ s a -> s{_ptsipPayload = a}) -- | REQUIRED: The resource for which the policy is being specified. See the -- operation documentation for the appropriate value for this field. ptsipResource :: Lens' ProjectsTopicsSetIAMPolicy Text ptsipResource = lens _ptsipResource (\ s a -> s{_ptsipResource = a}) -- | JSONP ptsipCallback :: Lens' ProjectsTopicsSetIAMPolicy (Maybe Text) ptsipCallback = lens _ptsipCallback (\ s a -> s{_ptsipCallback = a}) instance GoogleRequest ProjectsTopicsSetIAMPolicy where type Rs ProjectsTopicsSetIAMPolicy = Policy type Scopes ProjectsTopicsSetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/pubsub"] requestClient ProjectsTopicsSetIAMPolicy'{..} = go _ptsipResource _ptsipXgafv _ptsipUploadProtocol _ptsipAccessToken _ptsipUploadType _ptsipCallback (Just AltJSON) _ptsipPayload pubSubService where go = buildClient (Proxy :: Proxy ProjectsTopicsSetIAMPolicyResource) mempty
brendanhay/gogol
gogol-pubsub/gen/Network/Google/Resource/PubSub/Projects/Topics/SetIAMPolicy.hs
mpl-2.0
5,761
0
16
1,237
785
460
325
117
1
module Sound.MikMod.Synonyms where import Foreign.C.Types type UBYTE = CUChar type SBYTE = CChar type UWORD = CUShort type SWORD = CShort type ULONG = CUInt type SLONG = CInt type BOOL = CInt decodeBool :: BOOL -> Bool decodeBool 0 = False decodeBool 1 = True decodeBool x = error ("decodeBool " ++ show x) encodeBool :: Bool -> BOOL encodeBool False = 0 encodeBool True = 1 genericEncodeBool :: Num a => Bool -> a genericEncodeBool x = if x then 1 else 0
evanrinehart/mikmod
Sound/MikMod/Synonyms.hs
lgpl-3.0
462
0
8
91
158
90
68
18
2
module SetArrow where import Set import PairSet import BoolSet infixr 1 ~>>> infixr 3 ~&&& class SetArrow a where (~>>>) :: (LatticeSet s1, LatticeSet s2, LatticeSet s3) => a s1 s2 -> a s2 s3 -> a s1 s3 (~&&&) :: (LatticeSet s1, LatticeSet s2, LatticeSet s3) => a s1 s2 -> a s1 s3 -> a s1 (PairSet s2 s3) setIfte :: (LatticeSet s1, LatticeSet s2) => a s1 BoolSet -> a s1 s2 -> a s1 s2 -> a s1 s2 setLazy :: (LatticeSet s1, LatticeSet s2) => (() -> a s1 s2) -> a s1 s2 setId :: LatticeSet s1 => a s1 s1 setConst :: (LatticeSet s1, LatticeSet s2) => (MemberType s2) -> a s1 s2 setFst :: (LatticeSet s1, LatticeSet s2) => a (PairSet s1 s2) s1 setSnd :: (LatticeSet s1, LatticeSet s2) => a (PairSet s1 s2) s2
ntoronto/drbayes
drbayes/direct/haskell-impl/SetArrow.hs
lgpl-3.0
765
0
12
204
355
182
173
18
0
module Test where import Control.Monad.State import qualified Data.Map as Map import Data.Maybe (fromJust) import Expr import Infer (inferType) import Lexer (lexer) import Parser (parseExpr, parseTy) import Test.HUnit core = [ ("head", "forall[a] list[a] -> a") , ("tail", "forall[a] list[a] -> list[a]") , ("nil", "forall[a] list[a]") , ("cons", "forall[a] (a, list[a]) -> list[a]") , ("cons_curry", "forall[a] a -> list[a] -> list[a]") , ("map", "forall[a b] (a -> b, list[a]) -> list[b]") , ("map_curry", "forall[a b] (a -> b) -> list[a] -> list[b]") , ("one", "int") , ("zero", "int") , ("succ", "int -> int") , ("plus", "(int, int) -> int") , ("eq", "forall[a] (a, a) -> bool") , ("eq_curry", "forall[a] a -> a -> bool") , ("not", "bool -> bool") , ("true", "bool") , ("false", "bool") , ("pair", "forall[a b] (a, b) -> pair[a, b]") , ("pair_curry", "forall[a b] a -> b -> pair[a, b]") , ("first", "forall[a b] pair[a, b] -> a") , ("second", "forall[a b] pair[a, b] -> b") , ("id", "forall[a] a -> a") , ("const", "forall[a b] a -> b -> a") , ("apply", "forall[a b] (a -> b, a) -> b") , ("apply_curry", "forall[a b] (a -> b) -> a -> b") , ("choose", "forall[a] (a, a) -> a") , ("choose_curry", "forall[a] a -> a -> a")] inferCases = [ ("id", "forall[a] a -> a") , ("one", "int") , ("let x = id in x", "forall[a] a -> a") , ("let x = fun y -> y in x", "forall[a] a -> a") , ("fun x -> x", "forall[a] a -> a") {-, ("fun x -> x", "forall[int] int -> int")-} , ("pair", "forall[a b] (a, b) -> pair[a, b]") {-, ("pair", "forall[z x] (x, z) -> pair[x, z]")-} , ("fun x -> let y = fun z -> z in y", "forall[a b] a -> b -> b") , ("let f = fun x -> x in let id = fun y -> y in eq(f, id)", "bool") , ("let f = fun x -> x in let id = fun y -> y in eq_curry(f)(id)", "bool") , ("let f = fun x -> x in eq(f, succ)", "bool") , ("let f = fun x -> x in eq_curry(f)(succ)", "bool") , ("let f = fun x -> x in pair(f(one), f(true))", "pair[int, bool]") , ("let f = fun x y -> let a = eq(x, y) in eq(x, y) in f", "forall[a] (a, a) -> bool") , ("let f = fun x y -> let a = eq_curry(x)(y) in eq_curry(x)(y) in f", "forall[a] (a, a) -> bool") , ("id(id)", "forall[a] a -> a") , ("choose(fun x y -> x, fun x y -> y)", "forall[a] (a, a) -> a") , ("choose_curry(fun x y -> x)(fun x y -> y)", "forall[a] (a, a) -> a") , ("let x = id in let y = let z = x(id) in z in y", "forall[a] a -> a") , ("cons(id, nil)", "forall[a] list[a -> a]") , ("cons_curry(id)(nil)", "forall[a] list[a -> a]") , ("let lst1 = cons(id, nil) in let lst2 = cons(succ, lst1) in lst2", "list[int -> int]") , ("cons_curry(id)(cons_curry(succ)(cons_curry(id)(nil)))", "list[int -> int]") , ("fun x -> let y = x in y", "forall[a] a -> a") , ("fun x -> let y = let z = x(fun x -> x) in z in y", "forall[a b] ((a -> a) -> b) -> b") , ("fun x -> fun y -> let x = x(y) in x(y)", "forall[a b] (a -> a -> b) -> a -> b") , ("fun x -> let y = fun z -> x(z) in y", "forall[a b] (a -> b) -> a -> b") , ("fun x -> let y = fun z -> x in y", "forall[a b] a -> b -> a") , ("fun x -> fun y -> let x = x(y) in fun x -> y(x)", "forall[a b c] ((a -> b) -> c) -> (a -> b) -> a -> b") , ("fun x -> let y = fun z -> z in y(y)", "forall[a b] a -> b -> b") , ("fun f -> let x = fun g y -> let _ = g(y) in eq(f, g) in x", "forall[a b] (a -> b) -> (a -> b, a) -> bool") , ("let const = fun x -> fun y -> x in const", "forall[a b] a -> b -> a") , ("let apply = fun f x -> f(x) in apply", "forall[a b] (a -> b, a) -> b") , ("let apply_curry = fun f -> fun x -> f(x) in apply_curry", "forall[a b] (a -> b) -> a -> b")] testEnv = Map.fromList [(n, fromJust . parseTy . lexer $ t) | (n, t) <- core] testInfer s = let e = fromJust . parseExpr . lexer $ s in evalState (inferType testEnv e) 0 testList = [ TestCase $ assertEqual "Lexer test 1" (lexer "())in,let_ _1Ma->==") [LPAREN,RPAREN,RPAREN,IN,COMMA ,IDENT "let_",IDENT "_1Ma",ARROW,EQUALS,EQUALS] , TestCase $ assertEqual "Lexer test 2" (lexer "let fun in") [LET,FUN,IN] , TestCase $ assertEqual "Lexer test 3" (parseExpr . lexer $ "a") (Just (Var "a")) , TestCase $ assertEqual "Parser test 1" (parseExpr . lexer $ "f(x, y)") (Just (Call (Var "f") [Var "x",Var "y"])) , TestCase $ assertEqual "Parser test 2" (parseExpr . lexer $ "f(x)(y)") (Just (Call (Call (Var "f") [Var "x"]) [Var "y"])) , TestCase $ assertEqual "Parser test 3" (parseExpr . lexer $ "let f = fun x y -> g(x, y) in f(a, b)") (Just (Let "f" (Fun ["x","y"] (Call (Var "g") [Var "x",Var "y"])) (Call (Var "f") [Var "a",Var "b"]))) , TestCase $ assertEqual "Parser test 4" (parseExpr . lexer $ "let x = a in let y = b in f(x, y)") (Just (Let "x" (Var "a") (Let "y" (Var "b") (Call (Var "f") [Var "x",Var "y"])))) ] inferList = [TestCase $ assertEqual ("Infer: " ++ s) (testInfer s) (fromJust . parseTy . lexer $ result) | (s, result) <- inferCases] main = do putStrLn "Test lexer and parser:" runTestTT $ TestList testList putStrLn "\nTest infer:" runTestTT $ TestList inferList
scturtle/InferW
Test.hs
unlicense
6,435
0
17
2,524
1,238
729
509
101
1
module HStatusBar.Decl ( Decl , decl , arg , argInt ) where import HStatusBar.Types import Text.Megaparsec hiding (string) import qualified Text.Megaparsec as MP import Text.Megaparsec.Text type Decl = Parser Module string :: Text -> Parser Text string literal = pack <$> MP.string (unpack literal) decl :: Text -> Parser () decl nme = string nme *> pure () arg :: Parser Text arg = arg' stringLiteral argInt :: Parser Int argInt = arg' intLiteral arg' :: Parser a -> Parser a arg' literal = (skipSome spaceChar *> literal) <?> "argument" stringLiteral :: Parser Text stringLiteral = between (string "\"") (string "\"") (pack <$> many ((string "\\\"" *> pure '"') <|> noneOf ("\"" :: String)) :: Parser Text) <?> "string literal" intLiteral :: Parser Int intLiteral = (read <$> some digitChar) <?> "integer literal" where read = fromMaybe 0 . readMay -- 0 won’t happen
michalrus/hstatusbar
src/HStatusBar/Decl.hs
apache-2.0
952
0
14
225
320
168
152
30
1
-- Copyright 2020 Google LLC -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Main where import Proto.Tools.BuildDefs.Haskell.Tests.Proto.CamelCaseDir.Foo import Data.ProtoLens (defMessage) main = print (defMessage :: Foo)
google/cabal2bazel
bzl/tests/proto/CamelCaseDir/CamelCaseDirTest.hs
apache-2.0
743
0
6
117
52
39
13
4
1
module AlecSequences.A269524Spec (main, spec) where import Test.Hspec import AlecSequences.A269524 (a269524) main :: IO () main = hspec spec spec :: Spec spec = describe "A269524" $ it "correctly computes the first 20 elements" $ take 20 (map a269524 [1..]) `shouldBe` expectedValue where expectedValue = [1,1,2,3,4,5,5,7,8,9,7,11,9,13,14,15,10,17,11,19]
peterokagey/haskellOEIS
test/AlecSequences/A269524Spec.hs
apache-2.0
369
0
10
59
160
95
65
10
1
{-# LANGUAGE OverloadedStrings #-} -- Copyright (C) 2009-2011 John Millikin <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Main (main) where import Control.Concurrent (threadDelay) import Control.Monad import System.Exit import DBus.Client onFoo :: String -> String -> IO (String, String) onFoo x y = do putStrLn ("Foo " ++ show x ++ " " ++ show y) return (x, y) onBar :: String -> String -> IO (String, String) onBar x y = do putStrLn ("Bar " ++ show x ++ " " ++ show y) throwError "com.example.ErrorBar" "Bar failed" [] main :: IO () main = do -- Connect to the bus client <- connectSession -- Request a unique name on the bus. requestResult <- requestName client "com.example.exporting" [] when (requestResult /= NamePrimaryOwner) $ do putStrLn "Another service owns the \"com.example.exporting\" bus name" exitFailure -- Export two example objects export client "/a" [ autoMethod "test.iface_1" "Foo" (onFoo "hello" "a") , autoMethod "test.iface_1" "Bar" (onBar "hello" "a") ] export client "/b" [ autoMethod "test.iface_1" "Foo" (onFoo "hello") , autoMethod "test.iface_1" "Bar" (onBar "hello") ] putStrLn "Exported objects /a and /b to bus name com.example.exporting" -- Wait forever for method calls forever (threadDelay 50000)
jmillikin/haskell-dbus
examples/export.hs
apache-2.0
1,864
11
12
366
375
192
183
29
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} ------------------------------------------------------------------------------ -- | This module tha handles login stuff (Snaplet.Auth needs some help) module Login where ------------------------------------------------------------------------------ import Control.Applicative import Control.Lens ((^#)) import Control.Concurrent (withMVar) import Control.Monad.Trans (liftIO, lift) import Control.Monad.Trans.Either import Control.Error.Safe (tryJust) import Lens.Family ((&), (.~)) import Data.ByteString as B import qualified Data.Text as T import qualified Data.Text.Read as T import Data.Monoid ------------------------------------------------------------------------------ import Database.SQLite.Simple as S import Snap.Core import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.SqliteSimple import Snap.Snaplet.Heist import Snap.Snaplet.Session.Backends.CookieSession import Snap.Snaplet.SqliteSimple import Snap.Util.FileServe import Heist import qualified Heist.Interpreted as I ------------------------------------------------------------------------------ import Application import qualified Db import Util ------------------------------------------------------------------------------ -- | Render login form handleLogin :: Maybe T.Text -> Handler App (AuthManager App) () handleLogin authError = heistLocal (I.bindSplices errs) $ render "login" where errs = maybe noSplices splice authError splice err = "loginError" ## I.textSplice err ------------------------------------------------------------------------------ -- | Handle login submit handleLoginSubmit :: H () handleLoginSubmit = with auth $ loginUser "login" "password" Nothing (\_ -> handleLogin . Just $ "Unknown login or incorrect password") (redirect "/community") ------------------------------------------------------------------------------ -- | Logs out and redirects the user to the site index. handleLogout :: H () handleLogout = with auth logout >> redirect "/" ------------------------------------------------------------------------------ -- | Handle new user form submit handleNewUser :: H () handleNewUser = method GET (renderNewUserForm Nothing) <|> method POST handleFormSubmit where handleFormSubmit = do authUser <- with auth $ registerUser "login" "password" either (renderNewUserForm . Just) login authUser renderNewUserForm (err :: Maybe AuthFailure) = heistLocal (I.bindSplices errs) $ render "new_user" where errs = maybe noSplices splice err splice e = "newUserError" ## I.textSplice . T.pack . show $ e login user = logRunEitherT $ lift (with auth (forceLogin user) >> redirect "/") ----------------------------------------------------------------------------- -- | Run actions with a logged in user or go back to the login screen withLoggedInUser :: (Db.User -> H ()) -> H () withLoggedInUser action = with auth currentUser >>= go where go Nothing = with auth $ handleLogin (Just "Must be logged in to view the main page") go (Just u) = logRunEitherT $ do uid <- tryJust "withLoggedInUser: missing uid" (userId u) uid' <- hoistEither (reader T.decimal (unUid uid)) return $ action (Db.User uid' (userLogin u))
santolucito/Peers
src/Login.hs
apache-2.0
3,554
0
15
723
723
394
329
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} -------------------------------------------------------------------- -- | -- Copyright : (c) McGraw Hill Financial 2014 -- License : BSD2 -- Maintainer: Stephen Compall <[email protected]> -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------- module Ermine.Loader.Filesystem ( filesystemLoader , LoadRefusal(..) , explainLoadRefusal , Freshness() ) where import Control.Applicative import Control.Exception (tryJust) import Control.Lens hiding ((<.>)) import Control.Monad.Error.Class import Control.Monad.State import Control.Monad.Trans.Except import Data.Data import Data.Function (on) import Data.Monoid import Data.Text (Text, pack) import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Text.Lens (text) import Data.Time.Clock (UTCTime) import Ermine.Loader.Core import GHC.Generics import System.Directory (getModificationTime) import System.FilePath ((</>), (<.>)) import qualified System.FilePath as P import System.IO.Error.Lens (errorType, _NoSuchThing) -- | A 'Loader' that searches an area of the filesystem for modules -- matching the given module name, and results in the textual contents -- of that module file. -- -- Non-IO errors are reported as 'LoadRefusal'. Use -- 'Ermine.Loader.Core.loaded' and 'withExceptT' to translate this to -- a monoidal type (e.g. '[]') for combination with other loaders. filesystemLoader :: (MonadIO m, MonadError LoadRefusal m) => P.FilePath -- ^ Filesystem root to start the search. -> String -- ^ File extension. -> Loader Freshness m Text Text filesystemLoader root ext = testBasedCacheLoader pathName (\pn -> trapNoSuchThing pn . TIO.readFile $ pn) (\pn -> liftM Freshness . trapNoSuchThing pn . getModificationTime $ pn) ((/=) `on` modTime) where pathName = hoistEither . runExcept . fmap (\n -> root </> n <.> ext) . moduleFileName trapNoSuchThing pn = hoistEither <=< liftIO . (lifted._Left .~ FileNotFound pn) . tryJust (^? errorType._NoSuchThing) hoistEither :: MonadError e m => Either e a -> m a hoistEither = either throwError return -- | A recoverable load error that shouldn't prevent alternative -- loaders from being tried for a given module. data LoadRefusal = FileNotFound P.FilePath -- ^ No file with that name was found. | NoFilenameMapping -- ^ There's no mapping from the module -- name to a valid filesystem name. deriving (Eq, Ord, Show, Read, Data, Typeable, Generic) explainLoadRefusal :: LoadRefusal -> Text explainLoadRefusal (FileNotFound fp) = "There was no file named " <> pack fp explainLoadRefusal NoFilenameMapping = "The module's name has no valid associated filename" newtype Freshness = Freshness {modTime :: UTCTime} deriving (Show, Read, Data, Typeable, Generic) -- | Convert a module name to a relative filename, minus the -- extension, or fail for some reason. moduleFileName :: Text -> Except LoadRefusal P.FilePath moduleFileName modName = do let modName' = modName ^.. text null (invalidChars modName) `unless` throwE NoFilenameMapping let relPath = set (mapped.filtered ('.'==)) P.pathSeparator modName' P.isValid relPath `unless` throwE NoFilenameMapping return relPath newtype ApMonoid f a = ApMonoid {runApMonoid :: f a} instance (Applicative f, Monoid a) => Monoid (ApMonoid f a) where mempty = ApMonoid $ pure mempty ApMonoid l `mappend` ApMonoid r = ApMonoid $ liftA2 mappend l r -- | Answer the positions of filesystem-invalid characters in the -- given module name, and explain the problem with each. invalidChars :: Text -> [(Int, Text)] invalidChars t = [(-1, "Can't be empty") | T.null t ] ++ [(0, "Can't start with a dot") | anyOf folded (=='.') (firstOf text t)] ++ checkChars t ++ [(T.length t - 1, "Can't end with a dot") | anyOf folded (=='.') (lastOf text t)] where checkChars = flip evalState False . runApMonoid . ifoldMapOf text (fmap ApMonoid . lookAtChar) lookAtChar :: Int -> Char -> State Bool [(Int, Text)] lookAtChar i ch = do let isDot = ch == '.' lastDot <- get put isDot return . map (i,) $ ["Empty module path components aren't allowed" | lastDot && isDot] ++ ["Disallowed character: " <> pack [ch] | P.isPathSeparator ch] ++ ["Null characters aren't allowed" | '\NUL' == ch]
PipocaQuemada/ermine
src/Ermine/Loader/Filesystem.hs
bsd-2-clause
4,874
0
14
1,129
1,097
613
484
-1
-1
import Yesod.Default.Config (fromArgs) import Yesod.Default.Main (defaultMain) import Application (withBottleStory) main :: IO () main = defaultMain fromArgs withBottleStory
konn/BottleStory
main.hs
bsd-2-clause
185
0
6
29
51
29
22
5
1
-- | The module provides feature selection functions which extract -- features present in the dataset, i.e. features which directly occure -- the dataset. module Data.CRF.Chain1.Constrained.DAG.Feature.Present ( presentFeats , presentOFeats , presentTFeats , presentSFeats ) where import Data.DAG (DAG) import qualified Data.DAG as DAG -- import Data.CRF.Chain1.Constrained.DAG.Dataset.Internal (DAG) -- import qualified Data.CRF.Chain1.Constrained.DAG.Dataset.Internal as DAG import Data.CRF.Chain1.Constrained.Core (X, Y, Lb, Feature) import qualified Data.CRF.Chain1.Constrained.Core as C -- | 'OFeature's which occur in the dataset. presentOFeats :: [DAG a (X, Y)] -> [Feature] presentOFeats = concatMap sentOFeats where sentOFeats dag = [ C.OFeature o x | edgeID <- DAG.dagEdges dag , let edgeLabel = DAG.edgeLabel edgeID dag , o <- C.unX (fst edgeLabel) , x <- lbs (snd edgeLabel) ] -- | 'TFeature's which occur in the dataset. presentTFeats :: [DAG a Y] -> [Feature] presentTFeats = concatMap sentTFeats where sentTFeats dag = [ C.TFeature x y | edgeID <- DAG.dagEdges dag , x <- lbs (DAG.edgeLabel edgeID dag) , prevEdgeID <- DAG.prevEdges edgeID dag , y <- lbs (DAG.edgeLabel prevEdgeID dag) ] -- | 'SFeature's which occur in the given dataset. presentSFeats :: [DAG a Y] -> [Feature] presentSFeats = concatMap sentSFeats where sentSFeats dag = [ C.SFeature x | edgeID <- DAG.dagEdges dag , DAG.isInitialEdge edgeID dag , x <- lbs (DAG.edgeLabel edgeID dag) ] -- | 'Feature's of all kinds which occur in the given dataset. presentFeats :: [DAG a (X, Y)] -> [Feature] presentFeats ds = presentOFeats ds ++ presentTFeats (map (fmap snd) ds) ++ presentSFeats (map (fmap snd) ds) -- | Retrieve the domain of the given probability distribution. lbs :: Y -> [Lb] lbs = map fst . C.unY
kawu/crf-chain1-constrained
src/Data/CRF/Chain1/Constrained/DAG/Feature/Present.hs
bsd-2-clause
1,954
0
13
439
520
281
239
42
1
module Language.Haskell.GhcMod.Utils where import Control.Exception (bracket) import System.Directory (getCurrentDirectory, setCurrentDirectory) import System.Process (readProcessWithExitCode) import System.Exit (ExitCode(..)) import System.IO (hPutStrLn, stderr) -- dropWhileEnd is not provided prior to base 4.5.0.0. dropWhileEnd :: (a -> Bool) -> [a] -> [a] dropWhileEnd p = foldr (\x xs -> if p x && null xs then [] else x : xs) [] extractParens :: String -> String extractParens str = extractParens' str 0 where extractParens' :: String -> Int -> String extractParens' [] _ = [] extractParens' (s:ss) level | s `elem` "([{" = s : extractParens' ss (level+1) | level == 0 = extractParens' ss 0 | s `elem` "}])" && level == 1 = s:[] | s `elem` "}])" = s : extractParens' ss (level-1) | otherwise = s : extractParens' ss level readProcess' :: String -> [String] -> IO String readProcess' cmd opts = do (rv,output,err) <- readProcessWithExitCode cmd opts "" case rv of ExitFailure val -> do hPutStrLn stderr err fail $ cmd ++ " " ++ unwords opts ++ " (exit " ++ show val ++ ")" ExitSuccess -> return output withDirectory_ :: FilePath -> IO a -> IO a withDirectory_ dir action = bracket getCurrentDirectory setCurrentDirectory (\_ -> setCurrentDirectory dir >> action)
darthdeus/ghc-mod-ng
Language/Haskell/GhcMod/Utils.hs
bsd-3-clause
1,375
0
17
310
505
261
244
31
2
module Reduction.Segmentation where import NML (Path) connectingPaths :: [Path] -> [Path] connectingPaths = id -- Haskell's identity function -- | validateSegmentation returns True when ther are no connecting paths, -- and False otherwise. validateSegmentation :: [Path] -> Bool validateSegmentation ps = null ps
maertsen/netPropCheck
Reduction/Segmentation.hs
bsd-3-clause
315
0
6
45
60
36
24
6
1
module CLasH.Normalize.NormalizeTypes where -- Standard modules import qualified Control.Monad.Trans.Writer as Writer import qualified Data.Monoid as Monoid -- GHC API import qualified CoreSyn -- Local imports import CLasH.Translator.TranslatorTypes -- Wrap a writer around a TranslatorSession, to run a single transformation -- over a single expression and track if the expression was changed. type TransformMonad = Writer.WriterT Monoid.Any TranslatorSession -- | In what context does a core expression occur? data CoreContext = AppFirst -- ^ The expression is the first -- argument of an application (i.e., -- it is applied) | AppSecond -- ^ The expression is the second -- argument of an application -- (i.e., something is applied to it) | LetBinding [CoreSyn.CoreBndr] -- ^ The expression is bound in a -- (recursive or non-recursive) let -- expression. | LetBody [CoreSyn.CoreBndr] -- ^ The expression is the body of a -- let expression | LambdaBody CoreSyn.CoreBndr -- ^ The expression is the body of a -- lambda abstraction | CaseAlt CoreSyn.CoreBndr -- ^ The expression is the body of a -- case alternative. | Other -- ^ Another context deriving (Eq, Show) -- | Transforms a CoreExpr and keeps track if it has changed. type Transform = [CoreContext] -> CoreSyn.CoreExpr -> TransformMonad CoreSyn.CoreExpr -- Predicates for each of the context types is_appfirst_ctx, is_appsecond_ctx, is_letbinding_ctx, is_letbody_ctx, is_lambdabody_ctx :: CoreContext -> Bool is_appfirst_ctx AppFirst = True is_appfirst_ctx _ = False is_appsecond_ctx AppSecond = True is_appsecond_ctx _ = False is_letbinding_ctx (LetBinding _) = True is_letbinding_ctx _ = False is_letbody_ctx (LetBody _) = True is_letbody_ctx _ = False is_lambdabody_ctx (LambdaBody _) = True is_lambdabody_ctx _ = False
christiaanb/clash
clash/CLasH/Normalize/NormalizeTypes.hs
bsd-3-clause
2,391
0
8
870
271
167
104
27
1
{-# LANGUAGE OverloadedStrings #-} {- | Module : Network.Mail.Mime.Parser.Internal.Rfc2045 Copyright : (c) 2015 Alberto Valverde González License : BSD3 Maintainer : [email protected] Stability : provisional Portability : unknown This module provides parsers for the grammar defined in RFC2045, \"Multipurpose Internet Mail Extensions\", <https://tools.ietf.org/html/rfc2045> -} module Network.Mail.Mime.Parser.Internal.Rfc2045 where import Control.Applicative ( many, pure, optional, (<$>), (<*>), (<*), (*>), (<|>)) import Data.Char (isAscii, ord) import Data.ByteString.Char8 (ByteString) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import qualified Data.ByteString.Char8 as S import Data.Monoid ((<>)) import Network.Mail.Mime.Parser.Internal.Common import Network.Mail.Mime.Parser.Types import Network.Mail.Mime.Parser.Internal.Rfc2234 import Network.Mail.Mime.Parser.Internal.Rfc2822 import Network.Mail.Mime.Parser.Internal.Rfc2047 (encoded_word) import Prelude hiding (takeWhile) attribute :: Parser ByteString attribute = fmap sToLower token composite_type :: Parser ByteString composite_type = fmap sToLower $ stringCI "message" <|> stringCI "multipart" <|> extension_token discrete_type :: Parser ByteString discrete_type = fmap sToLower $ stringCI "text" <|> stringCI "image" <|> stringCI "audio" <|> stringCI "video" <|> stringCI "application" <|> extension_token content_type :: Parser Field content_type = header "Content-Type" $ ContentType <$> type_ <*> ("/"*>subtype) <*> many (trim ";" *> content_type_parm) content_description :: Parser Field content_description = ContentDescription <$> header "Content-Description" atextstring content_encoding :: Parser Field content_encoding = ContentTransferEncoding <$> header "Content-Transfer-Encoding" mechanism mechanism :: Parser Encoding mechanism = stringCI "7bit" *> pure Binary7Bit <|> stringCI "8bit" *> pure Binary8Bit <|> stringCI "binary" *> pure Binary <|> stringCI "quoted-printable" *> pure QuotedPrintable <|> stringCI "base64" *> pure Base64 <|> (Encoding <$> x_token) <|> (Encoding <$> ietf_token) content_type_parm :: Parser ContentTypeParm content_type_parm = do (attr, val) <- parameterT case (attr,val) of ("boundary", Left v) -> return $ Boundary v ("boundary", Right _) -> fail "Unexpected Text on Boundary" ("name", v) -> return . Name . either decodeUtf8 id $ v ("charset", Left v) -> return $ Charset v ("charset", Right _) -> fail "Unexpected Text on Charset" (a, Left v) -> return $ ContentTypeParm a v (_, Right _) -> fail "Unexpected Text on ContentTypeParm" someparameter :: Parser ByteString -> Parser a -> Parser (ByteString, a) someparameter a v = (,) <$> a <*> ((trim "=") *> v) type PerhapsText = Either ByteString Text parameter :: Parser (ByteString, ByteString) parameter = someparameter attribute value parameterT :: Parser (ByteString, PerhapsText) parameterT = someparameter attribute valueT valueT :: Parser PerhapsText valueT = (Right <$> encoded) <|> (Left <$> value) where encoded = T.concat <$> quoted (many (optional fws *> encoded_word)) value :: Parser ByteString value = token <|> quoted_string_text_no_quotes type_ :: Parser ByteString type_ = discrete_type <|> composite_type subtype :: Parser ByteString subtype = extension_token <|> iana_token iana_token :: Parser ByteString iana_token = token ietf_token :: Parser ByteString ietf_token = token extension_token :: Parser ByteString extension_token = ietf_token <|> x_token x_token :: Parser ByteString x_token = fmap ("x-"<>) (stringCI "x-" *> token) token :: Parser ByteString token = takeWhile1 (\c -> isAscii c && not (isSpace c || isNoWsCtl c || c `elem` tspecials)) tspecials :: [Char] tspecials = "()<>@,;:\\\"/[]?=" mime_extension_field :: Parser Field mime_extension_field = MimeExtension <$> between (stringCI "Content-") ":" (takeWhile1 (/=':')) <*> (unstructured <* crlf) entity_headers :: Parser [Field] entity_headers = many entity_header entity_header :: Parser Field entity_header = content_type <|> content_encoding <|> content_description <|> mime_extension_field mime_message_headers :: Parser [Field] mime_message_headers = many mime_message_header mime_message_header :: Parser Field mime_message_header = entity_header <|> rfc2822_field <|> mime_version mime_version :: Parser Field mime_version = header "Mime-Version" (MimeVersion <$> readIntN 1 <*> ("." *> readIntN 1)) quoted_printable :: Parser ByteString quoted_printable = do l <- qp_line ls <- many ((S.cons '\n') <$> (crlf *> qp_line)) return $ l <> S.concat ls qp_line :: Parser ByteString qp_line = do ls <- many (qp_segment <* transport_padding <* crlf) l <- qp_part <* transport_padding return $ S.concat ls <> l qp_part :: Parser ByteString qp_part = qp_section qp_segment :: Parser ByteString qp_segment = (<>) <$> qp_section <*> transport_padding <* "=" qp_section :: Parser ByteString qp_section = do ls <- many (transport_padding1 <|> ptextstring) l <- option "" ptextstring return $ S.concat ls <> l ptextstring :: Parser ByteString ptextstring = S.concat <$> many1 (hex_octet <|> takeWhile1 isSafeChar) isSafeChar :: Char -> Bool isSafeChar c = (ord c >= 33 && ord c <= 60) || (ord c >= 62 && ord c <= 126) transport_padding :: Parser ByteString transport_padding = takeWhile isHorizontalSpace transport_padding1 :: Parser ByteString transport_padding1 = takeWhile1 isHorizontalSpace
meteogrid/mime-mail-parser
Network/Mail/Mime/Parser/Internal/Rfc2045.hs
bsd-3-clause
5,874
0
16
1,180
1,590
841
749
139
7
{-# LANGUAGE CPP #-} #ifndef MIN_VERSION_profunctors #define MIN_VERSION_profunctors(x,y,z) 0 #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Machine.Moore -- Copyright : (C) 2012 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : portable -- -- <http://en.wikipedia.org/wiki/Moore_machine> ---------------------------------------------------------------------------- module Data.Machine.Moore ( Moore(..) , logMoore , unfoldMoore ) where import Control.Applicative import Control.Comonad import Data.Copointed import Data.Machine.Plan import Data.Machine.Type import Data.Machine.Process import Data.Monoid import Data.Pointed import Data.Profunctor -- | 'Moore' machines data Moore a b = Moore b (a -> Moore a b) -- | Accumulate the input as a sequence. logMoore :: Monoid m => Moore m m logMoore = h mempty where h m = Moore m (\a -> h (m <> a)) {-# INLINE logMoore #-} -- | Construct a Moore machine from a state valuation and transition function unfoldMoore :: (s -> (b, a -> s)) -> s -> Moore a b unfoldMoore f = go where go s = case f s of (b, g) -> Moore b (go . g) {-# INLINE unfoldMoore #-} instance Automaton Moore where auto = construct . go where go (Moore b f) = do yield b await >>= go . f {-# INLINE auto #-} instance Functor (Moore a) where fmap f (Moore b g) = Moore (f b) (fmap f . g) {-# INLINE fmap #-} a <$ _ = return a {-# INLINE (<$) #-} instance Profunctor Moore where rmap = fmap {-# INLINE rmap #-} lmap f = go where go (Moore b g) = Moore b (go . g . f) {-# INLINE lmap #-} #if MIN_VERSION_profunctors(3,1,1) dimap f g = go where go (Moore b h) = Moore (g b) (go . h . f) {-# INLINE dimap #-} #endif instance Applicative (Moore a) where pure a = r where r = Moore a (const r) {-# INLINE pure #-} Moore f ff <*> Moore a fa = Moore (f a) (\i -> ff i <*> fa i) m <* _ = m {-# INLINE (<*) #-} _ *> n = n {-# INLINE (*>) #-} instance Pointed (Moore a) where point a = r where r = Moore a (const r) {-# INLINE point #-} -- | slow diagonalization instance Monad (Moore a) where return a = r where r = Moore a (const r) {-# INLINE return #-} k >>= f = j (fmap f k) where j (Moore a g) = Moore (extract a) (\x -> j $ fmap (\(Moore _ h) -> h x) (g x)) _ >> m = m instance Copointed (Moore a) where copoint (Moore b _) = b {-# INLINE copoint #-} instance Comonad (Moore a) where extract (Moore b _) = b {-# INLINE extract #-} extend f w@(Moore _ g) = Moore (f w) (extend f . g) instance ComonadApply (Moore a) where Moore f ff <@> Moore a fa = Moore (f a) (\i -> ff i <@> fa i) m <@ _ = m {-# INLINE (<@) #-} _ @> n = n {-# INLINE (@>) #-}
YoEight/machines
src/Data/Machine/Moore.hs
bsd-3-clause
2,868
0
16
667
984
516
468
71
1
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-} {-# OPTIONS_GHC -Wall #-} -- | Contains the common types used through bitcoin RPC calls, that aren't -- specific to a single submodule. module Network.Bitcoin.Types ( Client , BitcoinException(..) , HexString , TransactionID , Satoshi(..) , BTC , Account , Address ) where import Control.Exception import Data.Fixed import Data.Text ( Text ) import Data.Typeable import qualified Data.ByteString.Lazy as BL -- | 'Client' describes authentication credentials and host info for -- making API requests to the Bitcoin daemon. type Client = BL.ByteString -> IO BL.ByteString -- | A 'BitcoinException' is thrown when 'callApi encounters an -- error. The API error code is represented as an @Int@, the message as -- a @String@. -- -- It may also be thrown when the value returned by the bitcoin API wasn't -- what we expected. -- -- WARNING: Any of the functions in this module's public API may throw this -- exception. You should plan on handling it. data BitcoinException = BitcoinApiError Int Text -- ^ A 'BitcoinApiError' has an error code error -- message, as returned by bitcoind's JSON-RPC -- response. | BitcoinResultTypeError BL.ByteString -- ^ The raw JSON returned, if we can't figure out what -- actually went wrong. deriving ( Show, Read, Ord, Eq, Typeable ) instance Exception BitcoinException -- | A string returned by the bitcoind API, representing data as hex. -- -- What that data represents depends on the API call, but should be -- dcumented accordingly. type HexString = Text -- | A hexadecimal string representation of a 256-bit unsigned integer. -- -- This integer is a unique transaction identifier. type TransactionID = HexString -- | A satoshi is the smallest subdivision of bitcoins. For the resolution, -- use 'resolution' from 'Data.Fixed'. data Satoshi = Satoshi instance HasResolution Satoshi where resolution = const $ 10^(8::Integer) {-# INLINE resolution #-} -- | The type of bitcoin money, represented with a fixed-point number. type BTC = Fixed Satoshi -- | An address for sending or receiving money. type Address = HexString -- | An account on the wallet is just a label to easily specify private keys. -- -- The default account is an empty string. type Account = Text
cgaebel/network-bitcoin
src/Network/Bitcoin/Types.hs
bsd-3-clause
2,682
0
7
793
242
159
83
29
0
{-# LANGUAGE StandaloneDeriving #-} module System.TaskL.Task where import Data.ByteString.Char8 (ByteString) import Data.Map (Map) import Data.Tree (Tree(..), Forest) import System.TaskL.Strings (Label(), Name()) -- | A task, with its variable bindings and body. data Task = Task [(Label, Maybe ByteString)] Knot deriving (Eq, Ord, Show) -- | An instance of task use, similar to a command. data Use = Use { task :: Name, args :: [Arg] } deriving (Eq, Ord, Show) -- | Type of connector between task code, a task's dependencies and a task's -- requested post-actions. data Knot = Knot { code :: Code, deps :: Forest Use } deriving (Eq, Ord, Show) -- | A task body which, at present, is just a sequence of commands and their -- arguments. data Code = Commands [([Either Label ByteString], [Arg])] deriving (Eq, Ord, Show) data Arg = Scalar [Either Label ByteString] | Tail | All deriving (Eq, Ord, Show) data Module = Module { from :: ByteString, defs :: Map Name Task } deriving (Eq, Ord, Show) deriving instance (Ord t) => Ord (Tree t)
solidsnack/taskl
System/TaskL/Task.hs
bsd-3-clause
1,096
0
10
236
334
196
138
19
0
module Main where import Network.Salvia.Impl.Cgi import Network.Salvia.Handler.ExtendedFileSystem main :: IO () main = start "/code/salvia-extras" (hCgiEnv (hExtendedFileSystem ".")) ()
sebastiaanvisser/salvia-demo
src/CgiDemo.hs
bsd-3-clause
189
0
9
22
54
31
23
5
1
module Hughes where import Data.Monoid newtype Hughes a = Hughes ([a] -> [a]) runHughes :: Hughes a -> [a] runHughes (Hughes k) = k [] mkHughes :: [a] -> Hughes a mkHughes xs = Hughes (\ys -> mappend xs ys) ------------------------------------------------------------ consDumb :: a -> Hughes a -> Hughes a consDumb a h = mkHughes (a : runHughes h) cons :: a -> Hughes a -> Hughes a cons a (Hughes h) = Hughes ((a:) . h) ------------------------------------------------------------ appendDumb :: Hughes a -> Hughes a -> Hughes a appendDumb a b = mkHughes (runHughes a ++ runHughes b) instance Monoid (Hughes a) where mempty = error "todo" mappend = error "todo" ------------------------------------------------------------ snocDumb :: Hughes a -> a -> Hughes a snocDumb l a = mkHughes (runHughes l ++ [a]) snoc :: Hughes a -> a -> Hughes a snoc = error "todo"
bitemyapp/kata
Hughes.hs
bsd-3-clause
878
0
8
162
348
177
171
20
1
{-# LANGUAGE OverloadedStrings #-} import System.Environment import qualified Data.Text as T import Scraper import Analytics import Persist main :: IO () main = do args <- getArgs let boardid = case length args of 1 -> T.pack $ head args _ -> "b" Right board <- runScraper $ getBoard boardid Right db <- runDatabase $ insertBoard boardid board runAnalytics $ analyzeBoard board
k4smiley/Chan
app/Main.hs
bsd-3-clause
448
0
14
132
129
63
66
15
2
{-# LANGUAGE DeriveFunctor #-} module ProgramArgs ( parseProgramArgs , ProgramArgs(..) , Command(..) , Target(..) , CompareTarget(..) , Verbosity(..) , OutputFormat(..) ) where import Data.Foldable import Options.Applicative import LoadPackageInterface parseProgramArgs :: IO ProgramArgs parseProgramArgs = execParser $ info (helper <*> mainParser) $ mconcat [ fullDesc , header "module-diff: view and compare module interfaces" ] data Command = ShowCommand (Target String) | CompareCommand (CompareTarget String) deriving (Show, Eq, Ord) data Target a = Target { targetDB :: Maybe PackageDB , target :: a } deriving (Show, Eq, Ord, Functor) data CompareTarget a = CompareThisInstalled -- ^ compare working directory package to installed version | CompareInstalled (Target a) -- ^ compare given package to installed version | CompareThese (Target a) (Target a) -- ^ compare given packages deriving (Show, Eq, Ord, Functor) data Verbosity = Quiet | Verbose deriving (Show, Eq, Ord) data ProgramArgs = ProgramArgs { outputClassInstances :: Bool -- internal , includeNotes :: Bool -- internal , onlyShowChanges :: Bool , verbosity :: Verbosity , outputFormat :: OutputFormat , outputFile :: Maybe FilePath , programCommand :: Command } deriving (Show, Eq, Ord) data OutputFormat = OutputConsole | OutputHtml deriving (Show, Eq, Ord) mainParser :: Parser ProgramArgs mainParser = ProgramArgs <$> switch_instances <*> switch_notes <*> switch_onlyChanges <*> flag_verbosity <*> parseFormat <*> parseFile <*> parseCommand parseCommand :: Parser Command parseCommand = subparser $ mconcat [ command "show" $ info (helper <*> parseShowCommand) $ progDesc "Print an interface summary for a package or module" , command "compare" $ info (helper <*> (CompareCommand <$> parseCompare)) $ progDesc "Compare two packages or modules" ] where parseShowCommand = ShowCommand <$> parseTarget parseCompare = asum [ CompareThese <$> parseTarget <*> parseTarget , CompareInstalled <$> parseTarget , pure $ CompareThisInstalled ] parseTarget :: Parser (Target String) parseTarget = Target <$> optional db <*> argument str (metavar "TARGET") where db = option pkgDB $ mconcat [ long "package-db" , short 'd' , metavar "PATH" , help "Package DB for next TARGET" ] pkgDB :: ReadM PackageDB pkgDB = do s <- str pure $ case s of "global" -> GlobalPackageDB "user" -> UserPackageDB _ -> SpecificPackageDB s switch_instances :: Parser Bool switch_instances = switch $ mconcat [ long "instances" , help "Include class instances" , internal ] switch_notes :: Parser Bool switch_notes = switch $ mconcat [ long "notes" , help "Include hidden notes in the HTML" , internal ] switch_onlyChanges :: Parser Bool switch_onlyChanges = switch $ mconcat [ long "only-changes" , help "Only output interface changes" ] flag_verbosity :: Parser Verbosity flag_verbosity = flag Quiet Verbose $ mconcat [ long "verbose" , short 'v' , help "Print diagnostic information" ] packageSelector :: ReadM PackageSelector packageSelector = readPackageSelector <$> str parseFormat :: Parser OutputFormat parseFormat = flag OutputConsole OutputHtml $ mconcat [ long "html" , help "Output as HTML" ] parseFile :: Parser (Maybe FilePath) parseFile = optional $ option str $ mconcat [ short 'o' , help "Output file" , metavar "FILE" ]
cdxr/haskell-interface
module-diff/ProgramArgs.hs
bsd-3-clause
3,797
0
14
1,007
924
495
429
113
3
import TestImport main :: IO () main = makeFoundation >>= warp 3000
SimSaladin/rnfssp
rnfssp-media/tests/warped.hs
bsd-3-clause
70
0
6
14
26
13
13
3
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} module Forms.Search (searchForm) where import Foundation import Yesod import Data.Text (Text) import Control.Applicative searchForm :: Html -> Form ImgHost ImgHost (FormResult Text, Widget) searchForm = renderTable $ areq (selectField defaultTags) "Tag " Nothing
pankajmore/Imghost
Forms/Search.hs
bsd-3-clause
363
0
8
48
82
47
35
10
1
module Nine where ------------------------------------------------------ -- (**) Pack consecutive duplicates of list elements -- into sublists. -- If a list contains repeated elements -- they should be placed in separate sublists. ------------------------------------------------------ pack :: (Eq a) => [a] -> [[a]] pack [] = [] pack as = (takeWhile (==(head as)) as):pack (dropWhile (==(head as)) as)
michael-j-clark/hjs99
src/1to10/Nine.hs
bsd-3-clause
415
0
11
66
100
58
42
4
1
{-# LANGUAGE MultiParamTypeClasses , TemplateHaskell , ScopedTypeVariables , FlexibleInstances , FlexibleContexts , UndecidableInstances , ViewPatterns , StandaloneDeriving , DeriveFunctor , DeriveFoldable , DeriveTraversable #-} module Spire.Canonical.Types where import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State import Data.Foldable import Data.Traversable import Data.List (isPrefixOf) import Unbound.LocallyNameless hiding ( Spine ) import Spire.Options ---------------------------------------------------------------------- type Type = Value type Nom = Name Value type HNom = Name (Rebind Nom Value) type Nom2 = (Nom , Nom) type Nom3 = (Nom , Nom , Nom) type Nom4 = (Nom , Nom , Nom , Nom) type NomType = (Nom , Embed Type) ---------------------------------------------------------------------- data Value = VUnit | VBool | VEnum | VTel | VString | VType | VTag Value | VDesc Value | VPi Value (Bind Nom Value) | VSg Value (Bind Nom Value) | VFix Value Value Value Value Value Value | VEq Value Value Value Value | VTT | VTrue | VFalse | VNil | VRefl | VHere | VEmp | VThere Value | VEnd Value | VRec Value Value | VInit Value | VCons Value Value | VPair Value Value | VExt Value (Bind Nom Value) | VArg Value (Bind Nom Value) | VLam (Bind Nom Value) | VQuotes String | VNeut Nom Spine deriving Show data Elim = EApp Value | EFunc Value (Bind Nom Value) Value | EHyps Value (Bind Nom Value) (Bind Nom2 Value) Value Value | EElimUnit (Bind Nom Value) Value | EElimBool (Bind Nom Value) Value Value | EElimPair Value (Bind Nom Value) (Bind Nom Value) (Bind Nom2 Value) | EElimEq Value Value (Bind Nom2 Value) Value Value | EElimEnum (Bind Nom Value) Value (Bind Nom3 Value) | EElimTel (Bind Nom Value) Value (Bind Nom3 Value) | EElimDesc Value (Bind Nom Value) (Bind Nom Value) (Bind Nom3 Value) (Bind Nom3 Value) | EBranches (Bind Nom Value) | ECase Value (Bind Nom Value) Value | EProve Value (Bind Nom Value) (Bind Nom2 Value) (Bind Nom2 Value) Value Value | EInd Value Value Value Value Value (Bind Nom2 Value) (Bind Nom3 Value) Value deriving Show type Spine = SpineFunctor Elim data SpineFunctor a = Id | Pipe (SpineFunctor a) a deriving (Show , Functor , Foldable , Traversable) $(derive [''Value , ''Elim , ''SpineFunctor]) instance Alpha Value instance Alpha Elim instance Alpha Spine instance Eq Value where (==) = aeq instance Eq Elim where (==) = aeq instance Eq Spine where (==) = aeq deriving instance Read Value deriving instance Read Elim deriving instance Read a => Read (SpineFunctor a) ---------------------------------------------------------------------- -- ??? Why have 'Rebind' here? data Tel = Empty | Extend (Rebind NomType Tel) deriving Show $(derive [''Tel]) instance Alpha Tel snocTel :: Tel -> NomType -> Tel snocTel Empty y = Extend (rebind y Empty) snocTel (Extend (unrebind -> (x , xs))) y = Extend (rebind x (snocTel xs y)) tel2List :: Tel -> [(Nom , Type)] tel2List Empty = [] tel2List (Extend (unrebind -> ((nm , unembed -> _T) , xs))) = (nm , _T) : tel2List xs ---------------------------------------------------------------------- data VDef = VDef Nom Value Value deriving (Show , Read , Eq) type Env = [VDef] type VProg = Env ---------------------------------------------------------------------- data SpireR = SpireR { ctx :: Tel , env :: Env , conf :: Conf } emptySpireR = SpireR { ctx = Empty , env = [] , conf = error "You need to define 'conf' before using 'emptySpireR'." } data SpireS = SpireS { unifierCtx :: UnifierCtx } emptySpireS = SpireS { unifierCtx = [] } type UnifierCtx = Env type SpireM = StateT SpireS (ReaderT SpireR (ExceptT String FreshM)) ---------------------------------------------------------------------- extendCtx :: Nom -> Type -> SpireM a -> SpireM a extendCtx x _A = local (\r -> r { ctx = snocTel (ctx r) (x , Embed _A) }) extendEnv :: Nom -> Value -> Type -> SpireM a -> SpireM a extendEnv x a _A = local (\r -> r { env = VDef x a _A : (env r) }) ---------------------------------------------------------------------- wildcard = "_" wildcardR :: Nom wildcardR = s2n wildcard isWildcard :: Nom -> Bool isWildcard nm = name2String nm == wildcard ---------------------------------------------------------------------- freshR :: Fresh m => String -> m Nom freshR = fresh . s2n freshMV :: Fresh m => String -> m Nom freshMV suffix = fresh . s2n $ "?" ++ suffix isMV :: Nom -> Bool isMV nm = "?" `isPrefixOf` name2String nm -- Return the non-'?' part of a mvars string. mv2String :: Nom -> String mv2String nm = case name2String nm of '?':suffix -> suffix _ -> error $ "mv2String: not an mvar: " ++ show nm bind2 x y = bind (x , y) bind3 x y z = bind (x , y , z) sbind :: (Alpha t, Rep a) => String -> t -> Bind (Name a) t sbind x = bind (s2n x) sbind2 x y = bind2 (s2n x) (s2n y) sbind3 x y z = bind3 (s2n x) (s2n y) (s2n z) ---------------------------------------------------------------------- vPi :: String -> Value -> Value -> Value vPi s x y = VPi x (bind (s2n s) y) vBind :: String -> (Value -> Value) -> Bind Nom Value vBind x f = bind (s2n x) (f (var x)) kBind :: Value -> Bind Nom Value kBind x = bind wildcardR x rBind :: String -> (Nom -> Value) -> Bind Nom Value rBind x f = sbind x (f (s2n x)) rBind2 :: String -> String -> (Nom -> Nom -> Value) -> Bind Nom2 Value rBind2 x y f = sbind2 x y (f (s2n x) (s2n y)) var :: String -> Value var = vVar . s2n vVar :: Nom -> Value vVar nm = VNeut nm Id vProd :: Value -> Value -> Value vProd _A _B = VSg _A (bind (s2n wildcard) _B) vArr :: Value -> Value -> Value vArr _A _B = VPi _A (bind (s2n wildcard) _B) eIf :: Value -> Value -> Value -> Elim eIf _C ct cf = EElimBool (bind (s2n wildcard) _C) ct cf ---------------------------------------------------------------------- rElimUnit :: Bind Nom Value -> Value -> Nom -> Value rElimUnit _P ptt u = VNeut u (Pipe Id (EElimUnit _P ptt)) rElimBool :: Bind Nom Value -> Value -> Value -> Nom -> Value rElimBool _P pt pf b = VNeut b (Pipe Id (EElimBool _P pt pf)) rElimPair :: Type -> Bind Nom Type -> Bind Nom Type -> Bind Nom2 Value -> Nom -> Value rElimPair _A _B _P ppair ab = VNeut ab (Pipe Id (EElimPair _A _B _P ppair)) rElimEq :: Type -> Value -> Bind Nom2 Value -> Value -> Value -> Nom -> Value rElimEq _A x _P prefl y q = VNeut q (Pipe Id (EElimEq _A x _P prefl y)) rElimEnum :: Bind Nom Value -> Value -> Bind Nom3 Value -> Nom -> Value rElimEnum _P pnil pcons xs = VNeut xs (Pipe Id (EElimEnum _P pnil pcons)) rElimTel :: Bind Nom Value -> Value -> Bind Nom3 Value -> Nom -> Value rElimTel _P pemp pext _T = VNeut _T (Pipe Id (EElimTel _P pemp pext)) rElimDesc :: Value -> Bind Nom Value -> Bind Nom Value -> Bind Nom3 Value -> Bind Nom3 Value -> Nom -> Value rElimDesc _I _P pend prec parg _D = VNeut _D (Pipe Id (EElimDesc _I _P pend prec parg)) rBranches :: Nom -> Bind Nom Value -> Type rBranches _E _P = VNeut _E (Pipe Id (EBranches _P)) rFunc :: Value -> Nom -> Bind Nom Value -> Value -> Type rFunc _I _D _X i = VNeut _D (Pipe Id (EFunc _I _X i)) rHyps :: Value -> Nom -> Bind Nom Value -> Bind Nom2 Value -> Value -> Value -> Type rHyps _I _D _X _M i xs = VNeut _D (Pipe Id (EHyps _I _X _M i xs)) rProve :: Value -> Nom -> Bind Nom Value -> Bind Nom2 Value -> Bind Nom2 Value -> Value -> Value -> Type rProve _I _D _X _M m i xs = VNeut _D (Pipe Id (EProve _I _X _M m i xs)) rInd :: Value -> Value -> Value -> Value -> Value -> Bind Nom2 Value -> Bind Nom3 Value -> Value -> Nom -> Type rInd l _P _I _D p _M m i x = VNeut x (Pipe Id (EInd l _P _I _D p _M m i)) rCase :: Value -> (Bind Nom Value) -> Value -> Nom -> Value rCase _E _P cs t = VNeut t (Pipe Id (ECase _E _P cs)) ---------------------------------------------------------------------- vLam :: String -> Value -> Value vLam s b = VLam (sbind s b) vEta :: (Value -> Value) -> String -> Value vEta f s = vLam s (f (var s)) vEta2 :: (Value -> Value -> Value) -> String -> String -> Value vEta2 f s1 s2 = vLam s1 $ vLam s2 $ f (var s1) (var s2) vApp :: String -> Value -> Value vApp = vApp' . s2n vApp' :: Nom -> Value -> Value vApp' f x = VNeut f (Pipe Id (EApp x)) vApp2 :: String -> Value -> Value -> Value vApp2 f x y = VNeut (s2n f) (Pipe (Pipe Id (EApp x)) (EApp y)) vApp3 :: String -> Value -> Value -> Value -> Value vApp3 f x y z = VNeut (s2n f) (Pipe (Pipe (Pipe Id (EApp x)) (EApp y)) (EApp z)) fbind :: String -> String -> Bind Nom Value fbind = fbind' . s2n fbind' :: Nom -> String -> Bind Nom Value fbind' f x = sbind x $ vApp' f (var x) fbind2 :: String -> String -> String -> Bind Nom2 Value fbind2 f x y = sbind2 x y $ vApp2 f (var x) (var y) fbind3 :: String -> String -> String -> String -> Bind Nom3 Value fbind3 f x y z = sbind3 x y z $ vApp3 f (var x) (var y) (var z) vElimUnit :: String -> String -> String -> Value vElimUnit _P ptt u = rElimUnit (fbind _P "u") (var ptt) (s2n u) vElimBool :: String -> String -> String -> String -> Value vElimBool _P pt pf b = rElimBool (fbind _P "b") (var pt) (var pf) (s2n b) vElimPair :: String -> String -> String -> String -> String -> Value vElimPair _A _B _P ppair ab = rElimPair (var _A) (fbind _B "a") (fbind _P "xs") (fbind2 ppair "a" "b") (s2n ab) vElimEq :: String -> String -> String -> String -> String -> String -> Value vElimEq _A x _P prefl y q = rElimEq (var _A) (var x) (fbind2 _P "y" "q") (var prefl) (var y) (s2n q) vElimEnum :: String -> String -> String -> String -> Value vElimEnum _P pnil pcons xs = rElimEnum (fbind _P "xs") (var pnil) (fbind3 pcons "x" "xs" "pxs") (s2n xs) vElimTel :: String -> String -> String -> String -> Value vElimTel _P pemp pext _T = rElimTel (fbind _P "T") (var pemp) (fbind3 pext "A" "B" "pb") (s2n _T) vElimDesc :: String -> String -> String -> String -> String -> String -> Value vElimDesc _I _P pend prec parg _D = rElimDesc (var _I) (fbind _P "D") (fbind pend "i") (fbind3 prec "i" "D" "pd") (fbind3 parg "A" "B" "pb") (s2n _D) vBranches :: String -> String -> Value vBranches _E _P = rBranches (s2n _E) (fbind _P "t") vFunc :: String -> String -> String -> String -> Value vFunc _I _D _X i = rFunc (var _I) (s2n _D) (fbind _X "i") (var i) vHyps :: String -> String -> String -> String -> String -> String -> Value vHyps _I _D _X _M i xs = rHyps (var _I) (s2n _D) (fbind _X "i") (fbind2 _M "i" "x") (var i) (var xs) vProve :: String -> String -> String -> String -> String -> String -> String -> Value vProve _I _D _X _M m i xs = rProve (var _I) (s2n _D) (fbind _X "i") (fbind2 _M "i" "x") (fbind2 m "i" "x") (var i) (var xs) vInd :: String -> String -> String -> String -> String -> String -> String -> String -> String -> Value vInd l _P _I _D p _M m i x = rInd (var l) (var _P) (var _I) (var _D) (var p) (fbind2 _M "i" "x") (fbind3 m "i" "xs" "ihs") (var i) (s2n x) vCase :: String -> String -> String -> String -> Value vCase _E _P cs t = rCase (var _E) (fbind _P "t") (var cs) (s2n t) vFix :: String -> String -> String -> String -> String -> String -> Value vFix l _P _I _D p i = VFix (var l) (var _P) (var _I) (var _D) (var p) (var i) ----------------------------------------------------------------------
spire/spire
src/Spire/Canonical/Types.hs
bsd-3-clause
11,431
2
13
2,554
4,980
2,554
2,426
286
2
{-# LANGUAGE FlexibleContexts, TypeOperators #-} {-# OPTIONS_GHC -Wall #-} -- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP -- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP {-# OPTIONS_GHC -fno-warn-missing-signatures #-} ---------------------------------------------------------------------- -- | -- Module : ReificationRules.MonoPrims -- Copyright : (c) 2016 Conal Elliott -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- -- Monomorphic Prim specializations ---------------------------------------------------------------------- module ReificationRules.MonoPrims where import ReificationRules.Prim (Prim(..),CircuitIf) import ReificationRules.Misc (Unop,Binop,BinRel,(:*)) -- Synonyms, just because I don't know how to look up constructors successfully. -- -- TODO: Revisit, now that I do know how. notP = NotP andP = AndP orP = OrP pairP = PairP exlP = ExlP exrP = ExrP ifP :: CircuitIf a => Prim (Bool :* (a :* a) -> a) ifP = IfP type PowIop a = a -> Int -> a -- Prim specializations generated by "putStr monoPrimDefs" from Plugin: bEq = EqP :: Prim (BinRel Bool ) bGe = GeP :: Prim (BinRel Bool ) bGt = GtP :: Prim (BinRel Bool ) bLe = LeP :: Prim (BinRel Bool ) bLt = LtP :: Prim (BinRel Bool ) bNe = NeP :: Prim (BinRel Bool ) dAdd = AddP :: Prim (Binop Double) dCos = CosP :: Prim (Unop Double) dDivide = DivideP :: Prim (Binop Double) dEq = EqP :: Prim (BinRel Double) dExp = ExpP :: Prim (Unop Double) dGe = GeP :: Prim (BinRel Double) dGt = GtP :: Prim (BinRel Double) dLe = LeP :: Prim (BinRel Double) dLt = LtP :: Prim (BinRel Double) dMul = MulP :: Prim (Binop Double) dNe = NeP :: Prim (BinRel Double) dNegate = NegateP :: Prim (Unop Double) dPowI = PowIP :: Prim (PowIop Double) dRecip = RecipP :: Prim (Unop Double) dSin = SinP :: Prim (Unop Double) dSub = SubP :: Prim (Binop Double) fAdd = AddP :: Prim (Binop Float ) fCos = CosP :: Prim (Unop Float ) fDivide = DivideP :: Prim (Binop Float ) fEq = EqP :: Prim (BinRel Float ) fExp = ExpP :: Prim (Unop Float ) fGe = GeP :: Prim (BinRel Float ) fGt = GtP :: Prim (BinRel Float ) fLe = LeP :: Prim (BinRel Float ) fLt = LtP :: Prim (BinRel Float ) fMul = MulP :: Prim (Binop Float ) fNe = NeP :: Prim (BinRel Float ) fNegate = NegateP :: Prim (Unop Float ) fPowI = PowIP :: Prim (PowIop Float ) fRecip = RecipP :: Prim (Unop Float ) fSin = SinP :: Prim (Unop Float ) fSub = SubP :: Prim (Binop Float ) iAdd = AddP :: Prim (Binop Int ) iEq = EqP :: Prim (BinRel Int ) iGe = GeP :: Prim (BinRel Int ) iGt = GtP :: Prim (BinRel Int ) iLe = LeP :: Prim (BinRel Int ) iLt = LtP :: Prim (BinRel Int ) iMul = MulP :: Prim (Binop Int ) iNe = NeP :: Prim (BinRel Int ) iNegate = NegateP :: Prim (Unop Int ) iPowI = PowIP :: Prim (PowIop Int ) iSub = SubP :: Prim (Binop Int )
conal/reification-rules
src/ReificationRules/MonoPrims.hs
bsd-3-clause
3,182
0
11
920
980
537
443
64
1
module X86_64Inst where import CodeGen import Registers call :: String -> CodeGen Env () call f = emit $ "\tcall\t" ++ f binOp :: (RegOrImm a, RegOrImm b) => String -> a -> b -> CodeGen Env () binOp op a b | isAtSP a && isAtSP b = do sp <- getStackPointer binOp' (Ref sp) (Ref sp) | isAtSP a = do sp <- getStackPointer binOp' (Ref sp) b | isAtSP b = do sp <- getStackPointer binOp' a (Ref sp) | otherwise = binOp' a b where binOp' x y = emit $ "\t"++op++"\t"++showRegOrImm x++", "++showRegOrImm y add :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () add = binOp "addq" sub :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () sub = binOp "subq" and :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () and = binOp "andq" cmp :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () cmp = binOp "cmpq" je :: String -> CodeGen Env () je l = emit $ "\tje\t" ++ l jmp :: String -> CodeGen Env () jmp l = emit $ "\tjmp\t" ++ l label :: String -> CodeGen Env () label l = emit $ l ++ ":" mov :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () mov = binOp "movq" shr :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () shr = binOp "shrq" shl :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () shl = binOp "shlq" or :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () or = binOp "orq" not :: RegOrImm a => a -> CodeGen Env () not a = emit $ "\tnotq\t" ++ showRegOrImm a imul :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () imul = binOp "imulq" idiv :: (RegOrImm a, RegOrImm b) => a -> b -> CodeGen Env () idiv = binOp "idivq" cltd :: CodeGen Env () cltd = emit "\tcltd" ret :: CodeGen Env () ret = emit "\tret"
dagit/helisp
src/X86_64Inst.hs
bsd-3-clause
1,793
0
12
513
866
429
437
48
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module System.FastLogger ( Logger , timestampedLogEntry , combinedLogEntry , newLogger , newLoggerWithCustomErrorFunction , logMsg , stopLogger ) where ------------------------------------------------------------------------------ import Blaze.ByteString.Builder (Builder, fromByteString, fromWord8, toByteString, toLazyByteString) import Blaze.ByteString.Builder.Char.Utf8 (fromShow) import Control.Concurrent (MVar, ThreadId, forkIO, killThread, newEmptyMVar, putMVar, takeMVar, threadDelay, tryPutMVar, withMVar) import Control.Exception (AsyncException, Handler (..), SomeException, catch, catches) import Control.Monad (unless, void, when) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import Data.ByteString.Internal (c2w) import qualified Data.ByteString.Lazy.Char8 as L import Data.Int (Int64) import Data.IORef (IORef, atomicModifyIORef, newIORef, readIORef, writeIORef) import Data.Monoid (mappend, mconcat, mempty) import qualified Data.Text as T import qualified Data.Text.Encoding as T #if !MIN_VERSION_base(4,6,0) import Prelude hiding (catch) #endif import System.IO (IOMode (AppendMode), hClose, hFlush, openFile, stderr, stdout) import Snap.Internal.Http.Server.Date (getCurrentDateTime, getLogDateString) ------------------------------------------------------------------------------ -- | Holds the state for a logger. data Logger = Logger { _queuedMessages :: !(IORef Builder) , _dataWaiting :: !(MVar ()) , _loggerPath :: !(FilePath) , _loggingThread :: !(MVar ThreadId) , _errAction :: ByteString -> IO () } ------------------------------------------------------------------------------ -- | Creates a new logger, logging to the given file. If the file argument is -- \"-\", then log to stdout; if it's \"stderr\" then we log to stderr, -- otherwise we log to a regular file in append mode. The file is closed and -- re-opened every 15 minutes to facilitate external log rotation. newLogger :: FilePath -- ^ log file to use -> IO Logger newLogger = newLoggerWithCustomErrorFunction (\s -> S.hPutStr stderr s >> hFlush stderr) ------------------------------------------------------------------------------ -- | Like 'newLogger', but uses a custom error action if the logger needs to -- print an error message of its own (for instance, if it can't open the -- output file.) newLoggerWithCustomErrorFunction :: (ByteString -> IO ()) -- ^ logger uses this action to log any -- error messages of its own -> FilePath -- ^ log file to use -> IO Logger newLoggerWithCustomErrorFunction errAction fp = do q <- newIORef mempty dw <- newEmptyMVar th <- newEmptyMVar let lg = Logger q dw fp th errAction tid <- forkIO $ loggingThread lg putMVar th tid return lg ------------------------------------------------------------------------------ -- | Prepares a log message with the time prepended. timestampedLogEntry :: ByteString -> IO ByteString timestampedLogEntry msg = do timeStr <- getLogDateString return $! toByteString $! mconcat [ fromWord8 $ c2w '[' , fromByteString timeStr , fromByteString "] " , fromByteString msg ] ------------------------------------------------------------------------------ -- | Prepares a log message in \"combined\" format. combinedLogEntry :: ByteString -- ^ remote host -> Maybe ByteString -- ^ remote user -> ByteString -- ^ request line (up to you to ensure -- there are no quotes in here) -> Int -- ^ status code -> Maybe Int64 -- ^ num bytes sent -> Maybe ByteString -- ^ referer (up to you to ensure -- there are no quotes in here) -> ByteString -- ^ user agent (up to you to ensure -- there are no quotes in here) -> IO ByteString combinedLogEntry !host !mbUser !req !status !mbNumBytes !mbReferer !ua = do timeStr <- getLogDateString let !l = [ fromByteString host , fromByteString " - " , user , fromByteString " [" , fromByteString timeStr , fromByteString "] \"" , fromByteString req , fromByteString "\" " , fromShow status , space , numBytes , space , referer , fromByteString " \"" , fromByteString ua , quote ] let !output = toByteString $ mconcat l return $! output where dash = fromWord8 $ c2w '-' quote = fromWord8 $ c2w '\"' space = fromWord8 $ c2w ' ' user = maybe dash fromByteString mbUser numBytes = maybe dash fromShow mbNumBytes referer = maybe dash (\s -> mconcat [ quote , fromByteString s , quote ]) mbReferer ------------------------------------------------------------------------------ -- | Sends out a log message verbatim with a newline appended. Note: -- if you want a fancy log message you'll have to format it yourself -- (or use 'combinedLogEntry'). logMsg :: Logger -> ByteString -> IO () logMsg !lg !s = do let !s' = fromByteString s `mappend` fromWord8 (c2w '\n') atomicModifyIORef (_queuedMessages lg) $ \d -> (d `mappend` s',()) void $ tryPutMVar (_dataWaiting lg) () ------------------------------------------------------------------------------ loggingThread :: Logger -> IO () loggingThread (Logger queue notifier filePath _ errAct) = initialize >>= go where -------------------------------------------------------------------------- openIt | filePath == "-" = return stdout | filePath == "stderr" = return stderr | otherwise = openFile filePath AppendMode `catch` \(e::SomeException) -> do logInternalError $ "Can't open log file \"" ++ filePath ++ "\".\n" logInternalError $ "Exception: " ++ show e ++ "\n" logInternalError $ "Logging to stderr instead. " ++ "**THIS IS BAD, YOU OUGHT TO " ++ "FIX THIS**\n\n" return stderr -------------------------------------------------------------------------- closeIt h = unless (h == stdout || h == stderr) $ hClose h -------------------------------------------------------------------------- logInternalError = errAct . T.encodeUtf8 . T.pack -------------------------------------------------------------------------- go (href, lastOpened) = loop (href, lastOpened) `catches` [ Handler $ \(_::AsyncException) -> killit (href, lastOpened) , Handler $ \(e::SomeException) -> do logInternalError $ "logger got exception: " ++ Prelude.show e ++ "\n" threadDelay 20000000 go (href, lastOpened) ] -------------------------------------------------------------------------- initialize = do lh <- openIt href <- newIORef lh t <- getCurrentDateTime tref <- newIORef t return (href, tref) -------------------------------------------------------------------------- killit (href, lastOpened) = do flushIt (href, lastOpened) h <- readIORef href closeIt h -------------------------------------------------------------------------- flushIt (!href, !lastOpened) = do dl <- atomicModifyIORef queue $ \x -> (mempty,x) let !msgs = toLazyByteString dl h <- readIORef href (do L.hPut h msgs hFlush h) `catch` \(e::SomeException) -> do logInternalError $ "got exception writing to log " ++ filePath ++ ": " ++ show e ++ "\n" logInternalError "writing log entries to stderr.\n" mapM_ errAct $ L.toChunks msgs -- close the file every 15 minutes (for log rotation) t <- getCurrentDateTime old <- readIORef lastOpened when (t - old > 900) $ do closeIt h openIt >>= writeIORef href writeIORef lastOpened t -------------------------------------------------------------------------- loop !d = do -- wait on the notification mvar _ <- takeMVar notifier -- grab the queued messages and write them out flushIt d -- at least five seconds between log dumps threadDelay 5000000 loop d ------------------------------------------------------------------------------ -- | Kills a logger thread, causing any unwritten contents to be -- flushed out to disk stopLogger :: Logger -> IO () stopLogger lg = withMVar (_loggingThread lg) killThread
afcowie/new-snap-server
src/System/FastLogger.hs
bsd-3-clause
10,659
3
17
3,995
1,768
930
838
179
1
module Y2015.Day24 (answer1, answer2) where import Data.List (nub, sortBy, minimumBy, sortOn) import Control.Arrow (first) import Control.Monad.Trans.State import Control.Monad (guard) answer1 :: IO () answer1 = let target = sum weights `quot` 3 firstGroups = sortOn (length . fst) $ selectTarget target weights validFirstGroups = filter (\(g, rs) -> not . null $ selectTarget target rs) firstGroups bestFirstSize = length . fst $ head validFirstGroups candidates = takeWhile ((<=bestFirstSize) . length) $ map fst validFirstGroups in print $ minimum $ map product candidates answer2 :: IO () answer2 = let -- optimistic setting, maybe there is no way to partition the -- remaining presents in the 3 other spaces for a given first -- group. This thing actually work so I let go :D groups = map fst (selectTarget (sum weights `quot` 4) weights) bestSize = length $ head groups candidates = takeWhile ((<=bestSize) . length) groups in print $ minimum $ map product candidates select :: [Int] -> [(Int, [Int])] select [] = [] select (x:xs) = (x, xs) : [ (y, x : ys) | (y, ys) <- select xs ] selectTarget :: Int -> [Int] -> [([Int], [Int])] selectTarget target xs = go target xs [] where go target _ _ | target < 0 = [] go 0 xs rest = [([], xs ++ rest)] go _ [] _ = [] go target l@(x:xs) rest = let takeNone = go target xs (x : rest) takeOne = map (first ((:) x)) (go (target - x) xs rest) in takeNone ++ takeOne -- Fun with StateT to compute all possible partitions -- firstGroups' xs = flip evalStateT xs $ do -- let target = sum xs `quot` 4 -- g1 <- StateT (selectTarget target) -- g2 <- StateT (selectTarget target) -- guard . not $ null g2 -- g3 <- StateT (selectTarget target) -- guard . not $ null g3 -- return g1 weights = [ 1 , 2 , 3 , 5 , 7 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 , 101 , 103 , 107 , 109 , 113 ] testWeights :: [Int] testWeights = [1 .. 5] ++ [7 .. 11]
geekingfrog/advent-of-code
src/Y2015/Day24.hs
bsd-3-clause
2,293
0
15
750
745
421
324
68
4
module AnimPaint where import Rumpus import qualified Data.Sequence as Seq maxBlots = 1000 start :: Start start = do initialPosition <- getPosition setState (initialPosition, Seq.empty :: Seq EntityID) myDragContinues ==> \_ -> withState $ \(lastPosition, blots) -> do newPose <- getPose let newPosition = newPose ^. translation when (distance lastPosition newPosition > 0.1) $ do let (newBlots, oldBlots) = Seq.splitAt maxBlots blots forM_ oldBlots removeEntity let i = fromIntegral (Seq.length newBlots) * 0.1 newBlot <- spawnChild $ do myPose ==> newPose myShape ==> Cube mySize ==> 0.1 --myBody ==> Animated myTransformType ==> AbsolutePose myColor ==> colorHSL (newPosition ^. _x) 0.7 0.8 myUpdate ==> do n <- (+ i) <$> getNow let ySize = sin n * 0.2 setSize (V3 0.1 ySize 0.1) setPose $ newPose !*! positionRotation 0 (axisAngle (V3 0 1 0) n) setState (newPosition, newBlot <| newBlots)
lukexi/rumpus
pristine/Painting/AnimPaint.hs
bsd-3-clause
1,310
0
28
556
346
169
177
29
1
{-# LANGUAGE ViewPatterns, TupleSections, PatternGuards, BangPatterns #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} module Supercompile.Drive (supercompile) where import Supercompile.Match import Supercompile.Residualise import Supercompile.Split import Core.FreeVars import Core.Renaming import Core.Syntax import Evaluator.Evaluate import Evaluator.FreeVars import Evaluator.Syntax import Termination.Terminate import Name import Renaming import StaticFlags import Utilities import qualified Data.Map as M import Data.Ord import qualified Data.Set as S supercompile :: Term -> Term supercompile e = traceRender ("all input FVs", fvs) $ runScpM fvs $ fmap snd $ sc [] state where fvs = termFreeVars e state = (Heap M.empty reduceIdSupply, [], (mkIdentityRenaming $ S.toList fvs, tagTerm tagIdSupply e)) -- -- == Termination == -- -- Other functions: -- Termination.Terminate.terminate -- This family of functions is the whole reason that I have to thread Tag information throughout the rest of the code: stateTagBag :: State -> TagBag stateTagBag (Heap h _, k, (_, e)) = pureHeapTagBag h `plusTagBag` stackTagBag k `plusTagBag` taggedTermTagBag e pureHeapTagBag :: PureHeap -> TagBag pureHeapTagBag = plusTagBags . map (taggedTagBag 5 . unTaggedTerm . snd) . M.elems stackTagBag :: Stack -> TagBag stackTagBag = plusTagBags . map (taggedTagBag 3) taggedTermTagBag :: TaggedTerm -> TagBag taggedTermTagBag = taggedTagBag 2 . unTaggedTerm taggedTagBag :: Int -> Tagged a -> TagBag taggedTagBag cls = tagTagBag cls . tag tagTagBag :: Int -> Tag -> TagBag tagTagBag cls = mkTagBag . return . injectTag cls -- -- == The drive loop == -- reduce :: State -> State reduce = go emptyHistory where go hist state | not eVALUATE_PRIMOPS, (_, _, (_, TaggedTerm (Tagged _ (PrimOp _ _)))) <- state = state | otherwise = case step state of Nothing -> state Just state' | intermediate state' -> go hist state' | otherwise -> case terminate hist (stateTagBag state') of Stop -> state' Continue hist' -> go hist' state' intermediate :: State -> Bool intermediate (_, _, (_, TaggedTerm (Tagged _ (Var _)))) = False intermediate _ = True data Promise = P { fun :: Var, -- Name assigned in output program fvs :: [Out Var], -- Abstracted over these variables meaning :: State -- Minimum adequate term } data ScpState = ScpState { inputFvs :: FreeVars, -- NB: we do not abstract the h functions over these variables. This helps typechecking and gives GHC a chance to inline the definitions. promises :: [Promise], outs :: [(Var, Out Term)], names :: [Var] } get :: ScpM ScpState get = ScpM $ \s -> (s, s) put :: ScpState -> ScpM () put s = ScpM $ \_ -> (s, ()) modify :: (ScpState -> ScpState) -> ScpM () modify f = fmap f get >>= put freshHName :: ScpM Var freshHName = ScpM $ \s -> (s { names = tail (names s) }, expectHead "freshHName" (names s)) newtype ScpM a = ScpM { unScpM :: ScpState -> (ScpState, a) } instance Functor ScpM where fmap = liftM instance Monad ScpM where return x = ScpM $ \s -> (s, x) (!mx) >>= fxmy = ScpM $ \s -> case unScpM mx s of (s, x) -> unScpM (fxmy x) s runScpM :: FreeVars -> ScpM (Out Term) -> Out Term runScpM input_fvs (ScpM f) = letRec (sortBy (comparing ((read :: String -> Int) . drop 1 . name_string . fst)) $ outs s) e' where (s, e') = f init_s init_s = ScpState { promises = [], names = map (\i -> name $ "h" ++ show (i :: Int)) [0..], outs = [], inputFvs = input_fvs } sc, sc' :: History -> State -> ScpM (FreeVars, Out Term) sc hist = memo (sc' hist) sc' hist state = case terminate hist (stateTagBag state) of Stop -> split (sc hist) state Continue hist' -> split (sc hist') (reduce state) memo :: (State -> ScpM (FreeVars, Out Term)) -> State -> ScpM (FreeVars, Out Term) memo opt state = traceRenderM (">sc", residualiseState state) >> do (ps, input_fvs) <- fmap (promises &&& inputFvs) get case [ (S.fromList (rn_fvs (fvs p)), fun p `varApps` rn_fvs tb_noninput_fvs) | p <- ps , Just rn_lr <- [match (meaning p) state] , let rn_fvs = map (safeRename ("tieback: FVs " ++ pPrintRender (fun p)) rn_lr) -- NB: If tb contains a dead PureHeap binding (hopefully impossible) then it may have a free variable that I can't rename, so "rename" will cause an error. Not observed in practice yet. (tb_input_fvs, tb_noninput_fvs) = partition (`S.member` input_fvs) (fvs p) -- Because we don't abstract over top-level free variables (this is necessary for type checking e.g. polymorphic uses of error): , all (\x -> rename rn_lr x == x) tb_input_fvs ] of res:_ -> {- traceRender ("tieback", residualiseState state, fst res) $ -} do traceRenderM ("<sc", residualiseState state, res) return res [] -> {- traceRender ("new drive", residualiseState state) $ -} do x <- freshHName let vs = stateFreeVars state vs_list = S.toList vs noninput_vs_list = filter (`S.notMember` input_fvs) vs_list traceRenderM ("memo", x, vs_list) `seq` return () promise P { fun = x, fvs = vs_list, meaning = state } (_fvs', e') <- opt state assertRender ("sc: FVs", _fvs', vs) (_fvs' `S.isSubsetOf` vs) $ return () traceRenderM ("<sc", residualiseState state, (S.fromList vs_list, e')) bind x (lambdas noninput_vs_list e') return (vs, x `varApps` noninput_vs_list) promise :: Promise -> ScpM () promise p = modify (\s -> s { promises = p : promises s }) bind :: Var -> Out Term -> ScpM () bind x e = modify (\s -> s { outs = (x, e) : outs s }) traceRenderM :: Pretty a => a -> ScpM () --traceRenderM x mx = fmap length history >>= \indent -> traceRender (nest indent (pPrint x)) mx traceRenderM x = traceRender (pPrint x) (return ())
batterseapower/supercompilation-by-evaluation
Supercompile/Drive.hs
bsd-3-clause
6,032
0
21
1,449
1,996
1,060
936
114
4
module Hive.Error ( HiveError(..) , displayHiveError ) where import Mitchell.Prelude import Data.HexBoard (BoardIndex) import Hive.Bug data HiveError = OneHiveRule | FreedomToMoveRule BoardIndex BoardIndex | NoSuchBug Bug [Bug] | NoQueenByTurn4 | IndexOutOfBounds BoardIndex | PlaceOnOccupiedCell | PlaceNextToOpponent | QueenNotYetPlaced | MoveSrcNoTile | MoveSrcOpponentTile | NonAdjacentMove BoardIndex BoardIndex | SlideToOccupiedCell BoardIndex | GrasshopperMoveLength | HopOverUnoccupiedCell | HopToOccupiedCell | HopInCrookedLine | SpiderMoveLength | SpiderBacktrack | BeetleMoveLength | QueenMoveLength | LadybugMove | MosquitoMove [Bug] deriving Show displayHiveError :: HiveError -> Text displayHiveError = \case OneHiveRule -> "Move violates the One Hive Rule" FreedomToMoveRule i j -> "Cannot slide from " ++ show i ++ " to " ++ show j ++ " per the Freedom to Move Rule" NoSuchBug bug bugs -> "No " ++ show bug ++ " in " ++ show bugs NoQueenByTurn4 -> "Must place Queen on or before turn 4" IndexOutOfBounds i -> "Index " ++ show i ++ " out of bounds" PlaceOnOccupiedCell -> "Cannot place bug on occupied cell" PlaceNextToOpponent -> "Cannot place bug next to opponent's cell" QueenNotYetPlaced -> "Cannot move a bug before the Queen is placed" MoveSrcNoTile -> "Cannot move no bug" MoveSrcOpponentTile -> "Cannot move opponent's bug" NonAdjacentMove i j -> "Cannot move from " ++ show i ++ " to " ++ show j SlideToOccupiedCell i -> "Cannot move to occupied cell at " ++ show i GrasshopperMoveLength -> "Grasshopper must hop over at least one cell" HopOverUnoccupiedCell -> "Grasshopper may only hop over occupied cells" HopToOccupiedCell -> "Grasshopper must hop to unoccupied cell" HopInCrookedLine -> "Grasshopper must hop in a straight line" SpiderMoveLength -> "Spider must move exactly three cells" SpiderBacktrack -> "Spider may not backtrack" BeetleMoveLength -> "Beetle may only move one cell" QueenMoveLength -> "Queen may only move one cell" LadybugMove -> "Ladybug must move three spaces: two on top of the hive, then one down" MosquitoMove bugs -> "Mosquito may only move as one of " ++ show bugs
mitchellwrosen/hive
hive/src/Hive/Error.hs
bsd-3-clause
2,311
0
12
509
390
206
184
-1
-1
module Shopskell where import Shopskell.Internal
thaume/shopskell
src/Shopskell.hs
bsd-3-clause
50
0
4
6
9
6
3
2
0
{-# LANGUAGE OverloadedStrings #-} module System.MassFileSpec (main, spec) where import Test.Hspec import Test.QuickCheck import Data.Time import System.MassFile main :: IO () main = hspec spec dayStub :: Integer -> UTCTime dayStub n = (UTCTime (ModifiedJulianDay n) (fromIntegral n)) nextDayStub :: UTCTime nextDayStub = dayStub 1 spec :: Spec spec = do describe "testTime" $ do it "should decode yyyy-mm-dd to valid UTC" $ do testTime "1858-11-17" `shouldBe` (Right $ dayStub 0) describe "testTimeRange" $ do it "should return true if an old UTC time is greater than a new one" $ do (testTimeRange (OldTime $ dayStub 0) (NewTime $ nextDayStub )) `shouldBe` True describe "makeRangeFilter" $ do it "should return true if test time is between old and new" $ do makeRangeFilter (OldTime $ dayStub 0) (NewTime $ dayStub 3 ) (TestTime $ dayStub 2) `shouldBe` True makeRangeFilter (OldTime $ dayStub 1) (NewTime $ dayStub 3 ) (TestTime $ dayStub 0) `shouldBe` False makeRangeFilter (OldTime $ dayStub 1) (NewTime $ dayStub 3 ) (TestTime $ dayStub 4) `shouldBe` False -- describe "lensMfName" $ do -- it "should get back what is put in" $ do -- (lensMfName
smurphy8/massFileHandler
test/System/MassFileSpec.hs
bsd-3-clause
1,251
0
18
286
370
188
182
25
1
module Scheduler where import Control.Concurrent import Control.Concurrent.MVar import Control.Monad import Data.Map (Map(..)) import Data.Maybe import Data.Time import qualified Data.Map as Map import ThreadManager import Util data Scheduler = Scheduler { manager :: ThreadManager, lock :: MVar (), tasks :: MVar (Map (UTCTime, Int) (IO ())), waitTId :: MVar (Maybe ThreadId), counter :: MVar Int } locked :: Scheduler -> IO a -> IO a locked scheduler action = modifyMVar (lock scheduler) $ \() -> do v <- action return $! ((), v) mkScheduler :: ThreadManager -> IO Scheduler mkScheduler tm = do lock <- newMVar () tasks <- newMVar $ Map.empty waitTId <- newMVar Nothing counter <- newMVar 0 return $! Scheduler { manager = tm, lock = lock, tasks = tasks, waitTId = waitTId, counter = counter } schedule :: Scheduler -> UTCTime -> IO () -> IO () schedule scheduler when task = locked scheduler $ do -- Store the new task n <- modifyMVar (counter scheduler) $ \n -> return (n + 1, n) modifyMVar_ (tasks scheduler) $ return . Map.insert (when, n) task -- Kill the old wake-up thread and spawn a new one modifyMVar_ (waitTId scheduler) $ \tid -> do maybe (return ()) killThread tid tid' <- fork (manager scheduler) "Scheduler-run" $ run scheduler return $ Just tid' schedule' :: Scheduler -> NominalDiffTime -> IO () -> IO () schedule' scheduler offset task = do now <- getCurrentTime schedule scheduler (offset `addUTCTime` now) task run :: Scheduler -> IO () run scheduler = do -- Pick the earliest task ((time, _), task) <- locked scheduler $ withMVar (tasks scheduler) $ return . Map.findMin -- Wait until it's time now <- getCurrentTime let wait = ceiling $ 10^6 * (toRational $ time `diffUTCTime` now) longThreadDelay wait -- Remove the task from the queue and run it locked scheduler $ do modifyMVar_ (tasks scheduler) $ return . Map.deleteMin void $ fork (manager scheduler) "Scheduler-exec" task -- Schedule next task moreTasks <- locked scheduler $ withMVar (tasks scheduler) $ return . not . Map.null when (moreTasks) $ run scheduler
Ornedan/dom3statusbot
Scheduler.hs
bsd-3-clause
2,363
0
16
661
795
403
392
53
1
{-# LANGUAGE RecordWildCards, ScopedTypeVariables, PatternGuards #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} module Development.Shake.Database( Time, offsetTime, Duration, duration, Trace, Database, withDatabase, Ops(..), build, Depends, progress, Stack, emptyStack, showStack, topStack, showJSON, checkValid, ) where import Development.Shake.Classes import Development.Shake.Binary import Development.Shake.Pool import Development.Shake.Value import Development.Shake.Errors import Development.Shake.Storage import Development.Shake.Types import Development.Shake.Special import Development.Shake.Util import Development.Shake.Intern as Intern import Control.Exception import Control.Monad import qualified Data.HashSet as Set import qualified Data.HashMap.Strict as Map import Data.IORef import Data.Maybe import Data.List import Data.Monoid type Map = Map.HashMap --------------------------------------------------------------------- -- UTILITY TYPES newtype Step = Step Word32 deriving (Eq,Ord,Show,Binary,NFData,Hashable,Typeable) incStep (Step i) = Step $ i + 1 --------------------------------------------------------------------- -- CALL STACK data Stack = Stack (Maybe Key) [Id] showStack :: Database -> Stack -> IO [String] showStack Database{..} (Stack _ xs) = do status <- withLock lock $ readIORef status return $ reverse $ map (maybe "<unknown>" (show . fst) . flip Map.lookup status) xs addStack :: Id -> Key -> Stack -> Stack addStack x key (Stack _ xs) = Stack (Just key) $ x : xs topStack :: Stack -> String topStack (Stack key _) = maybe "<unknown>" show key checkStack :: [Id] -> Stack -> Maybe Id checkStack new (Stack _ old) | bad:_ <- old `intersect` new = Just bad | otherwise = Nothing emptyStack :: Stack emptyStack = Stack Nothing [] --------------------------------------------------------------------- -- CENTRAL TYPES type Trace = (BS, Time, Time) -- (message, start, end) -- | Invariant: The database does not have any cycles when a Key depends on itself data Database = Database {lock :: Lock ,intern :: IORef (Intern Key) ,status :: IORef (Map Id (Key, Status)) ,step :: Step ,journal :: Id -> (Key, Status {- Loaded or Missing -}) -> IO () ,diagnostic :: String -> IO () -- logging function ,assume :: Maybe Assume } data Status = Ready Result -- I have a value | Error SomeException -- I have been run and raised an error | Loaded Result -- Loaded from the database | Waiting Pending (Maybe Result) -- Currently checking if I am valid or building | Missing -- I am only here because I got into the Intern table data Result = Result {result :: Value -- the result associated with the Key ,built :: {-# UNPACK #-} !Step -- when it was actually run ,changed :: {-# UNPACK #-} !Step -- the step for deciding if it's valid ,depends :: [[Id]] -- dependencies ,execution :: {-# UNPACK #-} !Duration -- how long it took when it was last run (seconds) ,traces :: [Trace] -- a trace of the expensive operations (start/end in seconds since beginning of run) } newtype Pending = Pending (IORef (IO ())) -- you must run this action when you finish, while holding DB lock -- after you have set the result to Error or Ready instance Show Pending where show _ = "Pending" statusType Ready{} = "Ready" statusType Error{} = "Error" statusType Loaded{} = "Loaded" statusType Waiting{} = "Waiting" statusType Missing{} = "Missing" isError Error{} = True; isError _ = False isWaiting Waiting{} = True; isWaiting _ = False isReady Ready{} = True; isReady _ = False -- All the waiting operations are only valid when isWaiting type Waiting = Status afterWaiting :: Waiting -> IO () -> IO () afterWaiting (Waiting (Pending p) _) act = modifyIORef'' p (>> act) newWaiting :: Maybe Result -> IO Waiting newWaiting r = do ref <- newIORef $ return (); return $ Waiting (Pending ref) r runWaiting :: Waiting -> IO () runWaiting (Waiting (Pending p) _) = join $ readIORef p -- Wait for a set of actions to complete -- If the action returns True, the function will not be called again -- If the first argument is True, the thing is ended waitFor :: [(a, Waiting)] -> (Bool -> a -> IO Bool) -> IO () waitFor ws@(_:_) act = do todo <- newIORef $ length ws forM_ ws $ \(k,w) -> afterWaiting w $ do t <- readIORef todo when (t /= 0) $ do b <- act (t == 1) k writeIORef'' todo $ if b then 0 else t - 1 getResult :: Status -> Maybe Result getResult (Ready r) = Just r getResult (Loaded r) = Just r getResult (Waiting _ r) = r getResult _ = Nothing --------------------------------------------------------------------- -- OPERATIONS newtype Depends = Depends {fromDepends :: [Id]} deriving (NFData) data Ops = Ops {stored :: Key -> IO (Maybe Value) -- ^ Given a Key and a Value from the database, check it still matches the value stored on disk ,execute :: Stack -> Key -> IO (Either SomeException (Value, [Depends], Duration, [Trace])) -- ^ Given a chunk of stack (bottom element first), and a key, either raise an exception or successfully build it } -- | Return either an exception (crash), or (how much time you spent waiting, the value) build :: Pool -> Database -> Ops -> Stack -> [Key] -> IO (Either SomeException (Duration,Depends,[Value])) build pool Database{..} Ops{..} stack ks = do join $ withLock lock $ do is <- forM ks $ \k -> do is <- readIORef intern case Intern.lookup k is of Just i -> return i Nothing -> do (is, i) <- return $ Intern.add k is writeIORef'' intern is modifyIORef'' status $ Map.insert i (k,Missing) return i whenJust (checkStack is stack) $ \bad -> do status <- readIORef status uncurry errorRuleRecursion $ case Map.lookup bad status of Nothing -> (Nothing, Nothing) Just (k,_) -> (Just $ typeKey k, Just $ show k) vs <- mapM (reduce stack) is let errs = [e | Error e <- vs] if all isReady vs then return $ return $ Right (0, Depends is, [result r | Ready r <- vs]) else if not $ null errs then return $ return $ Left $ head errs else do wait <- newBarrier waitFor (filter (isWaiting . snd) $ zip is vs) $ \finish i -> do s <- readIORef status let done x = do signalBarrier wait x; return True case Map.lookup i s of Just (_, Error e) -> done (True, Left e) -- on error make sure we immediately kick off our parent Just (_, Ready{}) | finish -> done (False, Right [result r | i <- is, let Ready r = snd $ fromJust $ Map.lookup i s]) | otherwise -> return False return $ do (dur,res) <- duration $ blockPool pool $ waitBarrier wait return $ case res of Left e -> Left e Right v -> Right (dur,Depends is,v) where (#=) :: Id -> (Key, Status) -> IO Status i #= (k,v) = do s <- readIORef status writeIORef'' status $ Map.insert i (k,v) s diagnostic $ maybe "Missing" (statusType . snd) (Map.lookup i s) ++ " -> " ++ statusType v ++ ", " ++ maybe "<unknown>" (show . fst) (Map.lookup i s) return v atom x = let s = show x in if ' ' `elem` s then "(" ++ s ++ ")" else s -- Rules for each eval* function -- * Must NOT lock -- * Must have an equal return to what is stored in the db at that point -- * Must not return Loaded reduce :: Stack -> Id -> IO Status reduce stack i = do s <- readIORef status case Map.lookup i s of Nothing -> err $ "interned value missing from database, " ++ show i Just (k, Missing) -> run stack i k Nothing Just (k, Loaded r) -> do b <- case assume of Just AssumeDirty -> return False Just AssumeSkip -> return True _ -> fmap (== Just (result r)) $ stored k diagnostic $ "valid " ++ show b ++ " for " ++ atom k ++ " " ++ atom (result r) if not b then run stack i k $ Just r else check stack i k r (depends r) Just (k, res) -> return res run :: Stack -> Id -> Key -> Maybe Result -> IO Waiting run stack i k r = do w <- newWaiting r addPool pool $ do let norm = do res <- execute (addStack i k stack) k return $ case res of Left err -> Error err Right (v,deps,execution,traces) -> let c | Just r <- r, result r == v = changed r | otherwise = step in Ready Result{result=v,changed=c,built=step,depends=map fromDepends deps,..} res <- case r of Just r | assume == Just AssumeClean -> do v <- stored k case v of Just v -> return $ Ready r{result=v} Nothing -> norm _ -> norm ans <- withLock lock $ do ans <- i #= (k, res) runWaiting w return ans case ans of Ready r -> do diagnostic $ "result " ++ atom k ++ " = " ++ atom (result r) journal i (k, Loaded r) -- leave the DB lock before appending Error _ -> do diagnostic $ "result " ++ atom k ++ " = error" journal i (k, Missing) _ -> return () i #= (k, w) check :: Stack -> Id -> Key -> Result -> [[Id]] -> IO Status check stack i k r [] = i #= (k, Ready r) check stack i k r (ds:rest) = do vs <- mapM (reduce (addStack i k stack)) ds let ws = filter (isWaiting . snd) $ zip ds vs if any isError vs || any (> built r) [changed | Ready Result{..} <- vs] then run stack i k $ Just r else if null ws then check stack i k r rest else do self <- newWaiting $ Just r waitFor ws $ \finish d -> do s <- readIORef status let buildIt = do b <- run stack i k $ Just r afterWaiting b $ runWaiting self return True case Map.lookup d s of Just (_, Error{}) -> buildIt Just (_, Ready r2) | changed r2 > built r -> buildIt | finish -> do res <- check stack i k r rest if not $ isWaiting res then runWaiting self else afterWaiting res $ runWaiting self return True | otherwise -> return False i #= (k, self) --------------------------------------------------------------------- -- PROGRESS -- Does not need to set shakeRunning, done by something further up progress :: Database -> IO Progress progress Database{..} = do s <- readIORef status return $ foldl' f mempty $ map snd $ Map.elems s where f s (Ready Result{..}) = if step == built then s{countBuilt = countBuilt s + 1, timeBuilt = timeBuilt s + execution} else s{countSkipped = countSkipped s + 1, timeSkipped = timeSkipped s + execution} f s (Loaded Result{..}) = s{countUnknown = countUnknown s + 1, timeUnknown = timeUnknown s + execution} f s (Waiting _ r) = let (d,c) = timeTodo s t | Just Result{..} <- r = let d2 = d + execution in d2 `seq` (d2,c) | otherwise = let c2 = c + 1 in c2 `seq` (d,c2) in s{countTodo = countTodo s + 1, timeTodo = t} f s _ = s --------------------------------------------------------------------- -- QUERY DATABASE -- | Given a map of representing a dependency order (with a show for error messages), find an ordering for the items such -- that no item points to an item before itself. -- Raise an error if you end up with a cycle. dependencyOrder :: (Eq a, Hashable a) => (a -> String) -> Map a [a] -> [a] -- Algorithm: -- Divide everyone up into those who have no dependencies [Id] -- And those who depend on a particular Id, Dep :-> Maybe [(Key,[Dep])] -- Where d :-> Just (k, ds), k depends on firstly d, then remaining on ds -- For each with no dependencies, add to list, then take its dep hole and -- promote them either to Nothing (if ds == []) or into a new slot. -- k :-> Nothing means the key has already been freed dependencyOrder shw status = f (map fst noDeps) $ Map.map Just $ Map.fromListWith (++) [(d, [(k,ds)]) | (k,d:ds) <- hasDeps] where (noDeps, hasDeps) = partition (null . snd) $ Map.toList status f [] mp | null bad = [] | otherwise = error $ unlines $ "Internal invariant broken, database seems to be cyclic" : map (" " ++) bad ++ ["... plus " ++ show (length badOverflow) ++ " more ..." | not $ null badOverflow] where (bad,badOverflow) = splitAt 10 $ [shw i | (i, Just _) <- Map.toList mp] f (x:xs) mp = x : f (now++xs) later where Just free = Map.lookupDefault (Just []) x mp (now,later) = foldl' g ([], Map.insert x Nothing mp) free g (free, mp) (k, []) = (k:free, mp) g (free, mp) (k, d:ds) = case Map.lookupDefault (Just []) d mp of Nothing -> g (free, mp) (k, ds) Just todo -> (free, Map.insert d (Just $ (k,ds) : todo) mp) -- | Eliminate all errors from the database, pretending they don't exist resultsOnly :: Map Id (Key, Status) -> Map Id (Key, Result) resultsOnly mp = Map.map (\(k, v) -> (k, let Just r = getResult v in r{depends = map (filter (isJust . flip Map.lookup keep)) $ depends r})) keep where keep = Map.filter (isJust . getResult . snd) mp removeStep :: Map Id (Key, Result) -> Map Id (Key, Result) removeStep = Map.filter (\(k,_) -> k /= stepKey) showJSON :: Database -> IO String showJSON Database{..} = do status <- fmap (removeStep . resultsOnly) $ readIORef status let order = let shw i = maybe "<unknown>" (show . fst) $ Map.lookup i status in dependencyOrder shw $ Map.map (concat . depends . snd) status ids = Map.fromList $ zip order [0..] steps = let xs = Set.toList $ Set.fromList $ concat [[changed, built] | (_,Result{..}) <- Map.elems status] in Map.fromList $ zip (reverse $ sort xs) [0..] f (k, Result{..}) = let xs = ["name:" ++ show (show k) ,"built:" ++ showStep built ,"changed:" ++ showStep changed ,"depends:" ++ show (mapMaybe (`Map.lookup` ids) (concat depends)) ,"execution:" ++ show execution] ++ ["traces:[" ++ intercalate "," (map showTrace traces) ++ "]" | traces /= []] showStep i = show $ fromJust $ Map.lookup i steps showTrace (a,b,c) = "{start:" ++ show b ++ ",stop:" ++ show c ++ ",command:" ++ show (unpack a) ++ "}" in ["{" ++ intercalate ", " xs ++ "}"] return $ "[" ++ intercalate "\n," (concat [maybe (error "Internal error in showJSON") f $ Map.lookup i status | i <- order]) ++ "\n]" checkValid :: Database -> (Key -> IO (Maybe Value)) -> IO () checkValid Database{..} stored = do status <- readIORef status diagnostic "Starting validity/lint checking" -- Do not use a forM here as you use too much stack space bad <- (\f -> foldM f [] (Map.toList status)) $ \seen (i,v) -> case v of (key, Ready Result{..}) -> do good <- fmap (== Just result) $ stored key diagnostic $ "Checking if " ++ show key ++ " is " ++ show result ++ ", " ++ if good then "passed" else "FAILED" return $ [show key ++ " is no longer " ++ show result | not good && not (specialAlwaysRebuilds result)] ++ seen _ -> return seen if null bad then diagnostic "Validity/lint check passed" else error $ unlines $ "Error: Dependencies have changed since being built:" : bad --------------------------------------------------------------------- -- STORAGE -- To simplify journaling etc we smuggle the Step in the database, with a special StepKey newtype StepKey = StepKey () deriving (Show,Eq,Typeable,Hashable,Binary,NFData) stepKey :: Key stepKey = newKey $ StepKey () toStepResult :: Step -> Result toStepResult i = Result (newValue i) i i [] 0 [] fromStepResult :: Result -> Step fromStepResult = fromValue . result withDatabase :: ShakeOptions -> (String -> IO ()) -> (Database -> IO a) -> IO a withDatabase opts diagnostic act = do registerWitness $ StepKey () registerWitness $ Step 0 witness <- currentWitness withStorage opts diagnostic witness $ \mp2 journal -> do let mp1 = Intern.fromList [(k, i) | (i, (k,_)) <- Map.toList mp2] (mp1, stepId) <- case Intern.lookup stepKey mp1 of Just stepId -> return (mp1, stepId) Nothing -> do (mp1, stepId) <- return $ Intern.add stepKey mp1 return (mp1, stepId) intern <- newIORef mp1 status <- newIORef mp2 let step = case Map.lookup stepId mp2 of Just (_, Loaded r) -> incStep $ fromStepResult r _ -> Step 1 journal stepId (stepKey, Loaded $ toStepResult step) lock <- newLock act Database{assume=shakeAssume opts,..} instance BinaryWith Witness Step where putWith _ x = put x getWith _ = get instance BinaryWith Witness Result where putWith ws (Result x1 x2 x3 x4 x5 x6) = putWith ws x1 >> put x2 >> put x3 >> put x4 >> put x5 >> put x6 getWith ws = do x1 <- getWith ws; x2 <- get; x3 <- get; x4 <- get; x5 <- get; x6 <- get; return $ Result x1 x2 x3 x4 x5 x6 instance BinaryWith Witness Status where putWith ctx Missing = putWord8 0 putWith ctx (Loaded x) = putWord8 1 >> putWith ctx x putWith ctx x = err $ "putWith, Cannot write Status with constructor " ++ statusType x getWith ctx = do i <- getWord8; if i == 0 then return Missing else fmap Loaded $ getWith ctx
nh2/shake
Development/Shake/Database.hs
bsd-3-clause
19,144
8
32
6,219
6,355
3,214
3,141
329
24
quickSort :: Ord a => [a] -> [a] quickSort [] = [] quickSort (x:xs) = quickSort(left) ++ [ x ] ++ quickSort(right) where left = [y | y <- xs, y < x] right = [z | z <- xs, z >= x]
zubie7a/Programming_Paradigms
3_Functional_Programming/Haskell_2_Quicksort/quicksort.hs
mit
223
0
9
87
123
65
58
5
1
{-# LANGUAGE TemplateHaskell #-} module Fun.Quiz.Type where import Autolib.Reader import Autolib.ToDoc import Data.Typeable data Fun_Quiz2 = Fun_Quiz2 deriving ( Eq, Ord, Read, Show, Typeable ) $(derives [makeReader, makeToDoc] [''Fun_Quiz2]) data Param = Param { expression_size :: Int , table_size :: Int } deriving ( Typeable ) example :: Param example = Param { expression_size = 10 , table_size = 10 } $(derives [makeReader, makeToDoc] [''Param]) -- local variables: -- mode: haskell -- end:
florianpilz/autotool
src/Fun/Quiz/Type.hs
gpl-2.0
526
6
9
102
160
93
67
15
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.DynamoDB.Query -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- A /Query/ operation uses the primary key of a table or a secondary index -- to directly access items from that table or index. -- -- Use the /KeyConditionExpression/ parameter to provide a specific hash -- key value. The /Query/ operation will return all of the items from the -- table or index with that hash key value. You can optionally narrow the -- scope of the /Query/ operation by specifying a range key value and a -- comparison operator in /KeyConditionExpression/. You can use the -- /ScanIndexForward/ parameter to get results in forward or reverse order, -- by range key or by index key. -- -- Queries that do not return results consume the minimum number of read -- capacity units for that type of read operation. -- -- If the total number of items meeting the query criteria exceeds the -- result set size limit of 1 MB, the query stops and results are returned -- to the user with the /LastEvaluatedKey/ element to continue the query in -- a subsequent operation. Unlike a /Scan/ operation, a /Query/ operation -- never returns both an empty result set and a /LastEvaluatedKey/ value. -- /LastEvaluatedKey/ is only provided if the results exceed 1 MB, or if -- you have used the /Limit/ parameter. -- -- You can query a table, a local secondary index, or a global secondary -- index. For a query on a table or on a local secondary index, you can set -- the /ConsistentRead/ parameter to 'true' and obtain a strongly -- consistent result. Global secondary indexes support eventually -- consistent reads only, so do not specify /ConsistentRead/ when querying -- a global secondary index. -- -- /See:/ <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html AWS API Reference> for Query. -- -- This operation returns paginated results. module Network.AWS.DynamoDB.Query ( -- * Creating a Request query , Query -- * Request Lenses , qKeyConditions , qProjectionExpression , qAttributesToGet , qExpressionAttributeNames , qFilterExpression , qQueryFilter , qConsistentRead , qExpressionAttributeValues , qReturnConsumedCapacity , qScanIndexForward , qLimit , qSelect , qKeyConditionExpression , qConditionalOperator , qExclusiveStartKey , qIndexName , qTableName -- * Destructuring the Response , queryResponse , QueryResponse -- * Response Lenses , qrsLastEvaluatedKey , qrsCount , qrsScannedCount , qrsItems , qrsConsumedCapacity , qrsResponseStatus ) where import Network.AWS.DynamoDB.Types import Network.AWS.DynamoDB.Types.Product import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Represents the input of a /Query/ operation. -- -- /See:/ 'query' smart constructor. data Query = Query' { _qKeyConditions :: !(Maybe (Map Text Condition)) , _qProjectionExpression :: !(Maybe Text) , _qAttributesToGet :: !(Maybe (List1 Text)) , _qExpressionAttributeNames :: !(Maybe (Map Text Text)) , _qFilterExpression :: !(Maybe Text) , _qQueryFilter :: !(Maybe (Map Text Condition)) , _qConsistentRead :: !(Maybe Bool) , _qExpressionAttributeValues :: !(Maybe (Map Text AttributeValue)) , _qReturnConsumedCapacity :: !(Maybe ReturnConsumedCapacity) , _qScanIndexForward :: !(Maybe Bool) , _qLimit :: !(Maybe Nat) , _qSelect :: !(Maybe Select) , _qKeyConditionExpression :: !(Maybe Text) , _qConditionalOperator :: !(Maybe ConditionalOperator) , _qExclusiveStartKey :: !(Maybe (Map Text AttributeValue)) , _qIndexName :: !(Maybe Text) , _qTableName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Query' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qKeyConditions' -- -- * 'qProjectionExpression' -- -- * 'qAttributesToGet' -- -- * 'qExpressionAttributeNames' -- -- * 'qFilterExpression' -- -- * 'qQueryFilter' -- -- * 'qConsistentRead' -- -- * 'qExpressionAttributeValues' -- -- * 'qReturnConsumedCapacity' -- -- * 'qScanIndexForward' -- -- * 'qLimit' -- -- * 'qSelect' -- -- * 'qKeyConditionExpression' -- -- * 'qConditionalOperator' -- -- * 'qExclusiveStartKey' -- -- * 'qIndexName' -- -- * 'qTableName' query :: Text -- ^ 'qTableName' -> Query query pTableName_ = Query' { _qKeyConditions = Nothing , _qProjectionExpression = Nothing , _qAttributesToGet = Nothing , _qExpressionAttributeNames = Nothing , _qFilterExpression = Nothing , _qQueryFilter = Nothing , _qConsistentRead = Nothing , _qExpressionAttributeValues = Nothing , _qReturnConsumedCapacity = Nothing , _qScanIndexForward = Nothing , _qLimit = Nothing , _qSelect = Nothing , _qKeyConditionExpression = Nothing , _qConditionalOperator = Nothing , _qExclusiveStartKey = Nothing , _qIndexName = Nothing , _qTableName = pTableName_ } -- | This is a legacy parameter, for backward compatibility. New applications -- should use /KeyConditionExpression/ instead. Do not combine legacy -- parameters and expression parameters in a single API call; otherwise, -- DynamoDB will return a /ValidationException/ exception. -- -- The selection criteria for the query. For a query on a table, you can -- have conditions only on the table primary key attributes. You must -- provide the hash key attribute name and value as an 'EQ' condition. You -- can optionally provide a second condition, referring to the range key -- attribute. -- -- If you don\'t provide a range key condition, all of the items that match -- the hash key will be retrieved. If a /FilterExpression/ or /QueryFilter/ -- is present, it will be applied after the items are retrieved. -- -- For a query on an index, you can have conditions only on the index key -- attributes. You must provide the index hash attribute name and value as -- an 'EQ' condition. You can optionally provide a second condition, -- referring to the index key range attribute. -- -- Each /KeyConditions/ element consists of an attribute name to compare, -- along with the following: -- -- - /AttributeValueList/ - One or more values to evaluate against the -- supplied attribute. The number of values in the list depends on the -- /ComparisonOperator/ being used. -- -- For type Number, value comparisons are numeric. -- -- String value comparisons for greater than, equals, or less than are -- based on ASCII character code values. For example, 'a' is greater -- than 'A', and 'a' is greater than 'B'. For a list of code values, -- see <http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters>. -- -- For Binary, DynamoDB treats each byte of the binary data as unsigned -- when it compares binary values. -- -- - /ComparisonOperator/ - A comparator for evaluating attributes, for -- example, equals, greater than, less than, and so on. -- -- For /KeyConditions/, only the following comparison operators are -- supported: -- -- 'EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN' -- -- The following are descriptions of these comparison operators. -- -- - 'EQ' : Equal. -- -- /AttributeValueList/ can contain only one /AttributeValue/ of -- type String, Number, or Binary (not a set type). If an item -- contains an /AttributeValue/ element of a different type than -- the one specified in the request, the value does not match. For -- example, '{\"S\":\"6\"}' does not equal '{\"N\":\"6\"}'. Also, -- '{\"N\":\"6\"}' does not equal '{\"NS\":[\"6\", \"2\", \"1\"]}'. -- -- - 'LE' : Less than or equal. -- -- /AttributeValueList/ can contain only one /AttributeValue/ -- element of type String, Number, or Binary (not a set type). If -- an item contains an /AttributeValue/ element of a different type -- than the one provided in the request, the value does not match. -- For example, '{\"S\":\"6\"}' does not equal '{\"N\":\"6\"}'. -- Also, '{\"N\":\"6\"}' does not compare to -- '{\"NS\":[\"6\", \"2\", \"1\"]}'. -- -- - 'LT' : Less than. -- -- /AttributeValueList/ can contain only one /AttributeValue/ of -- type String, Number, or Binary (not a set type). If an item -- contains an /AttributeValue/ element of a different type than -- the one provided in the request, the value does not match. For -- example, '{\"S\":\"6\"}' does not equal '{\"N\":\"6\"}'. Also, -- '{\"N\":\"6\"}' does not compare to -- '{\"NS\":[\"6\", \"2\", \"1\"]}'. -- -- - 'GE' : Greater than or equal. -- -- /AttributeValueList/ can contain only one /AttributeValue/ -- element of type String, Number, or Binary (not a set type). If -- an item contains an /AttributeValue/ element of a different type -- than the one provided in the request, the value does not match. -- For example, '{\"S\":\"6\"}' does not equal '{\"N\":\"6\"}'. -- Also, '{\"N\":\"6\"}' does not compare to -- '{\"NS\":[\"6\", \"2\", \"1\"]}'. -- -- - 'GT' : Greater than. -- -- /AttributeValueList/ can contain only one /AttributeValue/ -- element of type String, Number, or Binary (not a set type). If -- an item contains an /AttributeValue/ element of a different type -- than the one provided in the request, the value does not match. -- For example, '{\"S\":\"6\"}' does not equal '{\"N\":\"6\"}'. -- Also, '{\"N\":\"6\"}' does not compare to -- '{\"NS\":[\"6\", \"2\", \"1\"]}'. -- -- - 'BEGINS_WITH' : Checks for a prefix. -- -- /AttributeValueList/ can contain only one /AttributeValue/ of -- type String or Binary (not a Number or a set type). The target -- attribute of the comparison must be of type String or Binary -- (not a Number or a set type). -- -- - 'BETWEEN' : Greater than or equal to the first value, and less -- than or equal to the second value. -- -- /AttributeValueList/ must contain two /AttributeValue/ elements -- of the same type, either String, Number, or Binary (not a set -- type). A target attribute matches if the target value is greater -- than, or equal to, the first element and less than, or equal to, -- the second element. If an item contains an /AttributeValue/ -- element of a different type than the one provided in the -- request, the value does not match. For example, '{\"S\":\"6\"}' -- does not compare to '{\"N\":\"6\"}'. Also, '{\"N\":\"6\"}' does -- not compare to '{\"NS\":[\"6\", \"2\", \"1\"]}' -- -- For usage examples of /AttributeValueList/ and /ComparisonOperator/, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.html Legacy Conditional Parameters> -- in the /Amazon DynamoDB Developer Guide/. qKeyConditions :: Lens' Query (HashMap Text Condition) qKeyConditions = lens _qKeyConditions (\ s a -> s{_qKeyConditions = a}) . _Default . _Map; -- | A string that identifies one or more attributes to retrieve from the -- table. These attributes can include scalars, sets, or elements of a JSON -- document. The attributes in the expression must be separated by commas. -- -- If no attribute names are specified, then all attributes will be -- returned. If any of the requested attributes are not found, they will -- not appear in the result. -- -- For more information, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html Accessing Item Attributes> -- in the /Amazon DynamoDB Developer Guide/. -- -- /ProjectionExpression/ replaces the legacy /AttributesToGet/ parameter. qProjectionExpression :: Lens' Query (Maybe Text) qProjectionExpression = lens _qProjectionExpression (\ s a -> s{_qProjectionExpression = a}); -- | This is a legacy parameter, for backward compatibility. New applications -- should use /ProjectionExpression/ instead. Do not combine legacy -- parameters and expression parameters in a single API call; otherwise, -- DynamoDB will return a /ValidationException/ exception. -- -- This parameter allows you to retrieve attributes of type List or Map; -- however, it cannot retrieve individual elements within a List or a Map. -- -- The names of one or more attributes to retrieve. If no attribute names -- are provided, then all attributes will be returned. If any of the -- requested attributes are not found, they will not appear in the result. -- -- Note that /AttributesToGet/ has no effect on provisioned throughput -- consumption. DynamoDB determines capacity units consumed based on item -- size, not on the amount of data that is returned to an application. -- -- You cannot use both /AttributesToGet/ and /Select/ together in a /Query/ -- request, /unless/ the value for /Select/ is 'SPECIFIC_ATTRIBUTES'. (This -- usage is equivalent to specifying /AttributesToGet/ without any value -- for /Select/.) -- -- If you query a local secondary index and request only attributes that -- are projected into that index, the operation will read only the index -- and not the table. If any of the requested attributes are not projected -- into the local secondary index, DynamoDB will fetch each of these -- attributes from the parent table. This extra fetching incurs additional -- throughput cost and latency. -- -- If you query a global secondary index, you can only request attributes -- that are projected into the index. Global secondary index queries cannot -- fetch attributes from the parent table. qAttributesToGet :: Lens' Query (Maybe (NonEmpty Text)) qAttributesToGet = lens _qAttributesToGet (\ s a -> s{_qAttributesToGet = a}) . mapping _List1; -- | One or more substitution tokens for attribute names in an expression. -- The following are some use cases for using /ExpressionAttributeNames/: -- -- - To access an attribute whose name conflicts with a DynamoDB reserved -- word. -- -- - To create a placeholder for repeating occurrences of an attribute -- name in an expression. -- -- - To prevent special characters in an attribute name from being -- misinterpreted in an expression. -- -- Use the __#__ character in an expression to dereference an attribute -- name. For example, consider the following attribute name: -- -- - 'Percentile' -- -- The name of this attribute conflicts with a reserved word, so it cannot -- be used directly in an expression. (For the complete list of reserved -- words, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html Reserved Words> -- in the /Amazon DynamoDB Developer Guide/). To work around this, you -- could specify the following for /ExpressionAttributeNames/: -- -- - '{\"#P\":\"Percentile\"}' -- -- You could then use this substitution in an expression, as in this -- example: -- -- - '#P = :val' -- -- Tokens that begin with the __:__ character are /expression attribute -- values/, which are placeholders for the actual value at runtime. -- -- For more information on expression attribute names, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html Accessing Item Attributes> -- in the /Amazon DynamoDB Developer Guide/. qExpressionAttributeNames :: Lens' Query (HashMap Text Text) qExpressionAttributeNames = lens _qExpressionAttributeNames (\ s a -> s{_qExpressionAttributeNames = a}) . _Default . _Map; -- | A string that contains conditions that DynamoDB applies after the -- /Query/ operation, but before the data is returned to you. Items that do -- not satisfy the /FilterExpression/ criteria are not returned. -- -- A /FilterExpression/ is applied after the items have already been read; -- the process of filtering does not consume any additional read capacity -- units. -- -- For more information, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#FilteringResults Filter Expressions> -- in the /Amazon DynamoDB Developer Guide/. -- -- /FilterExpression/ replaces the legacy /QueryFilter/ and -- /ConditionalOperator/ parameters. qFilterExpression :: Lens' Query (Maybe Text) qFilterExpression = lens _qFilterExpression (\ s a -> s{_qFilterExpression = a}); -- | This is a legacy parameter, for backward compatibility. New applications -- should use /FilterExpression/ instead. Do not combine legacy parameters -- and expression parameters in a single API call; otherwise, DynamoDB will -- return a /ValidationException/ exception. -- -- A condition that evaluates the query results after the items are read -- and returns only the desired values. -- -- This parameter does not support attributes of type List or Map. -- -- A /QueryFilter/ is applied after the items have already been read; the -- process of filtering does not consume any additional read capacity -- units. -- -- If you provide more than one condition in the /QueryFilter/ map, then by -- default all of the conditions must evaluate to true. In other words, the -- conditions are ANDed together. (You can use the /ConditionalOperator/ -- parameter to OR the conditions instead. If you do this, then at least -- one of the conditions must evaluate to true, rather than all of them.) -- -- Note that /QueryFilter/ does not allow key attributes. You cannot define -- a filter condition on a hash key or range key. -- -- Each /QueryFilter/ element consists of an attribute name to compare, -- along with the following: -- -- - /AttributeValueList/ - One or more values to evaluate against the -- supplied attribute. The number of values in the list depends on the -- operator specified in /ComparisonOperator/. -- -- For type Number, value comparisons are numeric. -- -- String value comparisons for greater than, equals, or less than are -- based on ASCII character code values. For example, 'a' is greater -- than 'A', and 'a' is greater than 'B'. For a list of code values, -- see <http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters>. -- -- For type Binary, DynamoDB treats each byte of the binary data as -- unsigned when it compares binary values. -- -- For information on specifying data types in JSON, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html JSON Data Format> -- in the /Amazon DynamoDB Developer Guide/. -- -- - /ComparisonOperator/ - A comparator for evaluating attributes. For -- example, equals, greater than, less than, etc. -- -- The following comparison operators are available: -- -- 'EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN' -- -- For complete descriptions of all comparison operators, see the -- <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html Condition> -- data type. -- qQueryFilter :: Lens' Query (HashMap Text Condition) qQueryFilter = lens _qQueryFilter (\ s a -> s{_qQueryFilter = a}) . _Default . _Map; -- | Determines the read consistency model: If set to 'true', then the -- operation uses strongly consistent reads; otherwise, the operation uses -- eventually consistent reads. -- -- Strongly consistent reads are not supported on global secondary indexes. -- If you query a global secondary index with /ConsistentRead/ set to -- 'true', you will receive a /ValidationException/. qConsistentRead :: Lens' Query (Maybe Bool) qConsistentRead = lens _qConsistentRead (\ s a -> s{_qConsistentRead = a}); -- | One or more values that can be substituted in an expression. -- -- Use the __:__ (colon) character in an expression to dereference an -- attribute value. For example, suppose that you wanted to check whether -- the value of the /ProductStatus/ attribute was one of the following: -- -- 'Available | Backordered | Discontinued' -- -- You would first need to specify /ExpressionAttributeValues/ as follows: -- -- '{ \":avail\":{\"S\":\"Available\"}, \":back\":{\"S\":\"Backordered\"}, \":disc\":{\"S\":\"Discontinued\"} }' -- -- You could then use these values in an expression, such as this: -- -- 'ProductStatus IN (:avail, :back, :disc)' -- -- For more information on expression attribute values, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html Specifying Conditions> -- in the /Amazon DynamoDB Developer Guide/. qExpressionAttributeValues :: Lens' Query (HashMap Text AttributeValue) qExpressionAttributeValues = lens _qExpressionAttributeValues (\ s a -> s{_qExpressionAttributeValues = a}) . _Default . _Map; -- | Undocumented member. qReturnConsumedCapacity :: Lens' Query (Maybe ReturnConsumedCapacity) qReturnConsumedCapacity = lens _qReturnConsumedCapacity (\ s a -> s{_qReturnConsumedCapacity = a}); -- | Specifies the order in which to return the query results - either -- ascending ('true') or descending ('false'). -- -- Items with the same hash key are stored in sorted order by range key .If -- the range key data type is Number, the results are stored in numeric -- order. For type String, the results are returned in order of ASCII -- character code values. For type Binary, DynamoDB treats each byte of the -- binary data as unsigned. -- -- If /ScanIndexForward/ is 'true', DynamoDB returns the results in order, -- by range key. This is the default behavior. -- -- If /ScanIndexForward/ is 'false', DynamoDB sorts the results in -- descending order by range key, and then returns the results to the -- client. qScanIndexForward :: Lens' Query (Maybe Bool) qScanIndexForward = lens _qScanIndexForward (\ s a -> s{_qScanIndexForward = a}); -- | The maximum number of items to evaluate (not necessarily the number of -- matching items). If DynamoDB processes the number of items up to the -- limit while processing the results, it stops the operation and returns -- the matching values up to that point, and a key in /LastEvaluatedKey/ to -- apply in a subsequent operation, so that you can pick up where you left -- off. Also, if the processed data set size exceeds 1 MB before DynamoDB -- reaches this limit, it stops the operation and returns the matching -- values up to the limit, and a key in /LastEvaluatedKey/ to apply in a -- subsequent operation to continue the operation. For more information, -- see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html Query and Scan> -- in the /Amazon DynamoDB Developer Guide/. qLimit :: Lens' Query (Maybe Natural) qLimit = lens _qLimit (\ s a -> s{_qLimit = a}) . mapping _Nat; -- | The attributes to be returned in the result. You can retrieve all item -- attributes, specific item attributes, the count of matching items, or in -- the case of an index, some or all of the attributes projected into the -- index. -- -- - 'ALL_ATTRIBUTES' - Returns all of the item attributes from the -- specified table or index. If you query a local secondary index, then -- for each matching item in the index DynamoDB will fetch the entire -- item from the parent table. If the index is configured to project -- all item attributes, then all of the data can be obtained from the -- local secondary index, and no fetching is required. -- -- - 'ALL_PROJECTED_ATTRIBUTES' - Allowed only when querying an index. -- Retrieves all attributes that have been projected into the index. If -- the index is configured to project all attributes, this return value -- is equivalent to specifying 'ALL_ATTRIBUTES'. -- -- - 'COUNT' - Returns the number of matching items, rather than the -- matching items themselves. -- -- - 'SPECIFIC_ATTRIBUTES' - Returns only the attributes listed in -- /AttributesToGet/. This return value is equivalent to specifying -- /AttributesToGet/ without specifying any value for /Select/. -- -- If you query a local secondary index and request only attributes -- that are projected into that index, the operation will read only the -- index and not the table. If any of the requested attributes are not -- projected into the local secondary index, DynamoDB will fetch each -- of these attributes from the parent table. This extra fetching -- incurs additional throughput cost and latency. -- -- If you query a global secondary index, you can only request -- attributes that are projected into the index. Global secondary index -- queries cannot fetch attributes from the parent table. -- -- If neither /Select/ nor /AttributesToGet/ are specified, DynamoDB -- defaults to 'ALL_ATTRIBUTES' when accessing a table, and -- 'ALL_PROJECTED_ATTRIBUTES' when accessing an index. You cannot use both -- /Select/ and /AttributesToGet/ together in a single request, unless the -- value for /Select/ is 'SPECIFIC_ATTRIBUTES'. (This usage is equivalent -- to specifying /AttributesToGet/ without any value for /Select/.) -- -- If you use the /ProjectionExpression/ parameter, then the value for -- /Select/ can only be 'SPECIFIC_ATTRIBUTES'. Any other value for /Select/ -- will return an error. qSelect :: Lens' Query (Maybe Select) qSelect = lens _qSelect (\ s a -> s{_qSelect = a}); -- | The condition that specifies the key value(s) for items to be retrieved -- by the /Query/ action. -- -- The condition must perform an equality test on a single hash key value. -- The condition can also perform one of several comparison tests on a -- single range key value. /Query/ can use /KeyConditionExpression/ to -- retrieve one item with a given hash and range key value, or several -- items that have the same hash key value but different range key values. -- -- The hash key equality test is required, and must be specified in the -- following format: -- -- 'hashAttributeName' /=/ ':hashval' -- -- If you also want to provide a range key condition, it must be combined -- using /AND/ with the hash key condition. Following is an example, using -- the __=__ comparison operator for the range key: -- -- 'hashAttributeName' /=/ ':hashval' /AND/ 'rangeAttributeName' /=/ -- ':rangeval' -- -- Valid comparisons for the range key condition are as follows: -- -- - 'rangeAttributeName' /=/ ':rangeval' - true if the range key is -- equal to ':rangeval'. -- -- - 'rangeAttributeName' /\</ ':rangeval' - true if the range key is -- less than ':rangeval'. -- -- - 'rangeAttributeName' /\<=/ ':rangeval' - true if the range key is -- less than or equal to ':rangeval'. -- -- - 'rangeAttributeName' />/ ':rangeval' - true if the range key is -- greater than ':rangeval'. -- -- - 'rangeAttributeName' />=/ ':rangeval' - true if the range key is -- greater than or equal to ':rangeval'. -- -- - 'rangeAttributeName' /BETWEEN/ ':rangeval1' /AND/ ':rangeval2' - -- true if the range key is greater than or equal to ':rangeval1', and -- less than or equal to ':rangeval2'. -- -- - /begins_with (/'rangeAttributeName', ':rangeval'/)/ - true if the -- range key begins with a particular operand. (You cannot use this -- function with a range key that is of type Number.) Note that the -- function name 'begins_with' is case-sensitive. -- -- Use the /ExpressionAttributeValues/ parameter to replace tokens such as -- ':hashval' and ':rangeval' with actual values at runtime. -- -- You can optionally use the /ExpressionAttributeNames/ parameter to -- replace the names of the hash and range attributes with placeholder -- tokens. This option might be necessary if an attribute name conflicts -- with a DynamoDB reserved word. For example, the following -- /KeyConditionExpression/ parameter causes an error because /Size/ is a -- reserved word: -- -- - 'Size = :myval' -- -- To work around this, define a placeholder (such a '#S') to represent the -- attribute name /Size/. /KeyConditionExpression/ then is as follows: -- -- - '#S = :myval' -- -- For a list of reserved words, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html Reserved Words> -- in the /Amazon DynamoDB Developer Guide/. -- -- For more information on /ExpressionAttributeNames/ and -- /ExpressionAttributeValues/, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html Using Placeholders for Attribute Names and Values> -- in the /Amazon DynamoDB Developer Guide/. -- -- /KeyConditionExpression/ replaces the legacy /KeyConditions/ parameter. qKeyConditionExpression :: Lens' Query (Maybe Text) qKeyConditionExpression = lens _qKeyConditionExpression (\ s a -> s{_qKeyConditionExpression = a}); -- | This is a legacy parameter, for backward compatibility. New applications -- should use /FilterExpression/ instead. Do not combine legacy parameters -- and expression parameters in a single API call; otherwise, DynamoDB will -- return a /ValidationException/ exception. -- -- A logical operator to apply to the conditions in a /QueryFilter/ map: -- -- - 'AND' - If all of the conditions evaluate to true, then the entire -- map evaluates to true. -- -- - 'OR' - If at least one of the conditions evaluate to true, then the -- entire map evaluates to true. -- -- If you omit /ConditionalOperator/, then 'AND' is the default. -- -- The operation will succeed only if the entire map evaluates to true. -- -- This parameter does not support attributes of type List or Map. qConditionalOperator :: Lens' Query (Maybe ConditionalOperator) qConditionalOperator = lens _qConditionalOperator (\ s a -> s{_qConditionalOperator = a}); -- | The primary key of the first item that this operation will evaluate. Use -- the value that was returned for /LastEvaluatedKey/ in the previous -- operation. -- -- The data type for /ExclusiveStartKey/ must be String, Number or Binary. -- No set data types are allowed. qExclusiveStartKey :: Lens' Query (HashMap Text AttributeValue) qExclusiveStartKey = lens _qExclusiveStartKey (\ s a -> s{_qExclusiveStartKey = a}) . _Default . _Map; -- | The name of an index to query. This index can be any local secondary -- index or global secondary index on the table. Note that if you use the -- /IndexName/ parameter, you must also provide /TableName./ qIndexName :: Lens' Query (Maybe Text) qIndexName = lens _qIndexName (\ s a -> s{_qIndexName = a}); -- | The name of the table containing the requested items. qTableName :: Lens' Query Text qTableName = lens _qTableName (\ s a -> s{_qTableName = a}); instance AWSPager Query where page rq rs | stop (rs ^. qrsLastEvaluatedKey) = Nothing | stop (rs ^. qrsItems) = Nothing | otherwise = Just $ rq & qExclusiveStartKey .~ rs ^. qrsLastEvaluatedKey instance AWSRequest Query where type Rs Query = QueryResponse request = postJSON dynamoDB response = receiveJSON (\ s h x -> QueryResponse' <$> (x .?> "LastEvaluatedKey" .!@ mempty) <*> (x .?> "Count") <*> (x .?> "ScannedCount") <*> (x .?> "Items" .!@ mempty) <*> (x .?> "ConsumedCapacity") <*> (pure (fromEnum s))) instance ToHeaders Query where toHeaders = const (mconcat ["X-Amz-Target" =# ("DynamoDB_20120810.Query" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.0" :: ByteString)]) instance ToJSON Query where toJSON Query'{..} = object (catMaybes [("KeyConditions" .=) <$> _qKeyConditions, ("ProjectionExpression" .=) <$> _qProjectionExpression, ("AttributesToGet" .=) <$> _qAttributesToGet, ("ExpressionAttributeNames" .=) <$> _qExpressionAttributeNames, ("FilterExpression" .=) <$> _qFilterExpression, ("QueryFilter" .=) <$> _qQueryFilter, ("ConsistentRead" .=) <$> _qConsistentRead, ("ExpressionAttributeValues" .=) <$> _qExpressionAttributeValues, ("ReturnConsumedCapacity" .=) <$> _qReturnConsumedCapacity, ("ScanIndexForward" .=) <$> _qScanIndexForward, ("Limit" .=) <$> _qLimit, ("Select" .=) <$> _qSelect, ("KeyConditionExpression" .=) <$> _qKeyConditionExpression, ("ConditionalOperator" .=) <$> _qConditionalOperator, ("ExclusiveStartKey" .=) <$> _qExclusiveStartKey, ("IndexName" .=) <$> _qIndexName, Just ("TableName" .= _qTableName)]) instance ToPath Query where toPath = const "/" instance ToQuery Query where toQuery = const mempty -- | Represents the output of a /Query/ operation. -- -- /See:/ 'queryResponse' smart constructor. data QueryResponse = QueryResponse' { _qrsLastEvaluatedKey :: !(Maybe (Map Text AttributeValue)) , _qrsCount :: !(Maybe Int) , _qrsScannedCount :: !(Maybe Int) , _qrsItems :: !(Maybe [Map Text AttributeValue]) , _qrsConsumedCapacity :: !(Maybe ConsumedCapacity) , _qrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'QueryResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qrsLastEvaluatedKey' -- -- * 'qrsCount' -- -- * 'qrsScannedCount' -- -- * 'qrsItems' -- -- * 'qrsConsumedCapacity' -- -- * 'qrsResponseStatus' queryResponse :: Int -- ^ 'qrsResponseStatus' -> QueryResponse queryResponse pResponseStatus_ = QueryResponse' { _qrsLastEvaluatedKey = Nothing , _qrsCount = Nothing , _qrsScannedCount = Nothing , _qrsItems = Nothing , _qrsConsumedCapacity = Nothing , _qrsResponseStatus = pResponseStatus_ } -- | The primary key of the item where the operation stopped, inclusive of -- the previous result set. Use this value to start a new operation, -- excluding this value in the new request. -- -- If /LastEvaluatedKey/ is empty, then the \"last page\" of results has -- been processed and there is no more data to be retrieved. -- -- If /LastEvaluatedKey/ is not empty, it does not necessarily mean that -- there is more data in the result set. The only way to know when you have -- reached the end of the result set is when /LastEvaluatedKey/ is empty. qrsLastEvaluatedKey :: Lens' QueryResponse (HashMap Text AttributeValue) qrsLastEvaluatedKey = lens _qrsLastEvaluatedKey (\ s a -> s{_qrsLastEvaluatedKey = a}) . _Default . _Map; -- | The number of items in the response. -- -- If you used a /QueryFilter/ in the request, then /Count/ is the number -- of items returned after the filter was applied, and /ScannedCount/ is -- the number of matching items before> the filter was applied. -- -- If you did not use a filter in the request, then /Count/ and -- /ScannedCount/ are the same. qrsCount :: Lens' QueryResponse (Maybe Int) qrsCount = lens _qrsCount (\ s a -> s{_qrsCount = a}); -- | The number of items evaluated, before any /QueryFilter/ is applied. A -- high /ScannedCount/ value with few, or no, /Count/ results indicates an -- inefficient /Query/ operation. For more information, see -- <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#Count Count and ScannedCount> -- in the /Amazon DynamoDB Developer Guide/. -- -- If you did not use a filter in the request, then /ScannedCount/ is the -- same as /Count/. qrsScannedCount :: Lens' QueryResponse (Maybe Int) qrsScannedCount = lens _qrsScannedCount (\ s a -> s{_qrsScannedCount = a}); -- | An array of item attributes that match the query criteria. Each element -- in this array consists of an attribute name and the value for that -- attribute. qrsItems :: Lens' QueryResponse [HashMap Text AttributeValue] qrsItems = lens _qrsItems (\ s a -> s{_qrsItems = a}) . _Default . _Coerce; -- | Undocumented member. qrsConsumedCapacity :: Lens' QueryResponse (Maybe ConsumedCapacity) qrsConsumedCapacity = lens _qrsConsumedCapacity (\ s a -> s{_qrsConsumedCapacity = a}); -- | The response status code. qrsResponseStatus :: Lens' QueryResponse Int qrsResponseStatus = lens _qrsResponseStatus (\ s a -> s{_qrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-dynamodb/gen/Network/AWS/DynamoDB/Query.hs
mpl-2.0
37,492
0
17
7,597
2,956
1,931
1,025
252
1
-- Module : Network.AWS.Internal -- Copyright : (c) 2013 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Network.AWS.Internal ( -- * Internal Modules module Internal ) where import Control.Error as Internal import GHC.Generics as Internal import Network.AWS.Internal.Instances as Internal import Network.AWS.Internal.Request as Internal import Network.AWS.Internal.Signing as Internal import Network.AWS.Internal.String as Internal import Network.AWS.Internal.Time as Internal import Network.AWS.Internal.Types as Internal import Network.AWS.Internal.XML as Internal import Network.HTTP.QueryString.Pickle as Internal import Text.XML.Expat.Pickle.Generic as Internal
brendanhay/amazonka-limited
src/Network/AWS/Internal.hs
mpl-2.0
1,148
0
4
268
119
93
26
14
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.MachineLearning.CreateDataSourceFromRedshift -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Creates a 'DataSource' from <http://aws.amazon.com/redshift/ Amazon Redshift>. A 'DataSource' references data that -- can be used to perform either 'CreateMLModel', 'CreateEvaluation' or 'CreateBatchPrediction' operations. -- -- 'CreateDataSourceFromRedshift' is an asynchronous operation. In response to 'CreateDataSourceFromRedshift', Amazon Machine Learning (Amazon ML) immediately returns and sets the 'DataSource' status to 'PENDING'. After the 'DataSource' is created and ready for use, Amazon -- ML sets the 'Status' parameter to 'COMPLETED'. 'DataSource' in 'COMPLETED' or 'PENDING' -- status can only be used to perform 'CreateMLModel', 'CreateEvaluation', or 'CreateBatchPrediction' operations. -- -- If Amazon ML cannot accept the input source, it sets the 'Status' parameter -- to 'FAILED' and includes an error message in the 'Message' attribute of the 'GetDataSource' operation response. -- -- The observations should exist in the database hosted on an Amazon Redshift -- cluster and should be specified by a 'SelectSqlQuery'. Amazon ML executes <http://docs.aws.amazon.com/redshift/latest/dg/t_Unloading_tables.html Unload> command in Amazon Redshift to transfer the result set of 'SelectSqlQuery' -- to 'S3StagingLocation.' -- -- After the 'DataSource' is created, it's ready for use in evaluations and batch -- predictions. If you plan to use the 'DataSource' to train an 'MLModel', the 'DataSource' requires another item -- a recipe. A recipe describes the observation -- variables that participate in training an 'MLModel'. A recipe describes how -- each input variable will be used in training. Will the variable be included -- or excluded from training? Will the variable be manipulated, for example, -- combined with another variable or split apart into word combinations? The -- recipe provides answers to these questions. For more information, see the -- Amazon Machine Learning Developer Guide. -- -- <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_CreateDataSourceFromRedshift.html> module Network.AWS.MachineLearning.CreateDataSourceFromRedshift ( -- * Request CreateDataSourceFromRedshift -- ** Request constructor , createDataSourceFromRedshift -- ** Request lenses , cdsfrComputeStatistics , cdsfrDataSourceId , cdsfrDataSourceName , cdsfrDataSpec , cdsfrRoleARN -- * Response , CreateDataSourceFromRedshiftResponse -- ** Response constructor , createDataSourceFromRedshiftResponse -- ** Response lenses , cdsfrrDataSourceId ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.MachineLearning.Types import qualified GHC.Exts data CreateDataSourceFromRedshift = CreateDataSourceFromRedshift { _cdsfrComputeStatistics :: Maybe Bool , _cdsfrDataSourceId :: Text , _cdsfrDataSourceName :: Maybe Text , _cdsfrDataSpec :: RedshiftDataSpec , _cdsfrRoleARN :: Text } deriving (Eq, Read, Show) -- | 'CreateDataSourceFromRedshift' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cdsfrComputeStatistics' @::@ 'Maybe' 'Bool' -- -- * 'cdsfrDataSourceId' @::@ 'Text' -- -- * 'cdsfrDataSourceName' @::@ 'Maybe' 'Text' -- -- * 'cdsfrDataSpec' @::@ 'RedshiftDataSpec' -- -- * 'cdsfrRoleARN' @::@ 'Text' -- createDataSourceFromRedshift :: Text -- ^ 'cdsfrDataSourceId' -> RedshiftDataSpec -- ^ 'cdsfrDataSpec' -> Text -- ^ 'cdsfrRoleARN' -> CreateDataSourceFromRedshift createDataSourceFromRedshift p1 p2 p3 = CreateDataSourceFromRedshift { _cdsfrDataSourceId = p1 , _cdsfrDataSpec = p2 , _cdsfrRoleARN = p3 , _cdsfrDataSourceName = Nothing , _cdsfrComputeStatistics = Nothing } -- | The compute statistics for a 'DataSource'. The statistics are generated from -- the observation data referenced by a 'DataSource'. Amazon ML uses the -- statistics internally during 'MLModel' training. This parameter must be set to 'true' if the ''DataSource'' needs to be used for 'MLModel' training cdsfrComputeStatistics :: Lens' CreateDataSourceFromRedshift (Maybe Bool) cdsfrComputeStatistics = lens _cdsfrComputeStatistics (\s a -> s { _cdsfrComputeStatistics = a }) -- | A user-supplied ID that uniquely identifies the 'DataSource'. cdsfrDataSourceId :: Lens' CreateDataSourceFromRedshift Text cdsfrDataSourceId = lens _cdsfrDataSourceId (\s a -> s { _cdsfrDataSourceId = a }) -- | A user-supplied name or description of the 'DataSource'. cdsfrDataSourceName :: Lens' CreateDataSourceFromRedshift (Maybe Text) cdsfrDataSourceName = lens _cdsfrDataSourceName (\s a -> s { _cdsfrDataSourceName = a }) -- | The data specification of an Amazon Redshift 'DataSource': -- -- DatabaseInformation - 'DatabaseName ' - Name of the Amazon Redshift -- database. ' ClusterIdentifier ' - Unique ID for the Amazon Redshift cluster. -- -- DatabaseCredentials - AWS Identity abd Access Management (IAM) credentials -- that are used to connect to the Amazon Redshift database. -- -- SelectSqlQuery - Query that is used to retrieve the observation data for the 'Datasource'. -- -- S3StagingLocation - Amazon Simple Storage Service (Amazon S3) location for -- staging Amazon Redshift data. The data retrieved from Amazon Relational -- Database Service (Amazon RDS) using 'SelectSqlQuery' is stored in this location. -- -- DataSchemaUri - Amazon S3 location of the 'DataSchema'. -- -- DataSchema - A JSON string representing the schema. This is not required if 'DataSchemaUri' is specified. -- -- DataRearrangement - A JSON string representing the splitting requirement of -- a 'Datasource'. -- -- -- Sample - ' "{\"randomSeed\":\"some-random-seed\",\"splitting\":{\"percentBegin\":10,\"percentEnd\":60}}"' -- -- cdsfrDataSpec :: Lens' CreateDataSourceFromRedshift RedshiftDataSpec cdsfrDataSpec = lens _cdsfrDataSpec (\s a -> s { _cdsfrDataSpec = a }) -- | A fully specified role Amazon Resource Name (ARN). Amazon ML assumes the role -- on behalf of the user to create the following: -- -- A security group to allow Amazon ML to execute the 'SelectSqlQuery' query on -- an Amazon Redshift cluster -- -- An Amazon S3 bucket policy to grant Amazon ML read/write permissions on the 'S3StagingLocation' -- -- cdsfrRoleARN :: Lens' CreateDataSourceFromRedshift Text cdsfrRoleARN = lens _cdsfrRoleARN (\s a -> s { _cdsfrRoleARN = a }) newtype CreateDataSourceFromRedshiftResponse = CreateDataSourceFromRedshiftResponse { _cdsfrrDataSourceId :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'CreateDataSourceFromRedshiftResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'cdsfrrDataSourceId' @::@ 'Maybe' 'Text' -- createDataSourceFromRedshiftResponse :: CreateDataSourceFromRedshiftResponse createDataSourceFromRedshiftResponse = CreateDataSourceFromRedshiftResponse { _cdsfrrDataSourceId = Nothing } -- | A user-supplied ID that uniquely identifies the datasource. This value should -- be identical to the value of the 'DataSourceID' in the request. cdsfrrDataSourceId :: Lens' CreateDataSourceFromRedshiftResponse (Maybe Text) cdsfrrDataSourceId = lens _cdsfrrDataSourceId (\s a -> s { _cdsfrrDataSourceId = a }) instance ToPath CreateDataSourceFromRedshift where toPath = const "/" instance ToQuery CreateDataSourceFromRedshift where toQuery = const mempty instance ToHeaders CreateDataSourceFromRedshift instance ToJSON CreateDataSourceFromRedshift where toJSON CreateDataSourceFromRedshift{..} = object [ "DataSourceId" .= _cdsfrDataSourceId , "DataSourceName" .= _cdsfrDataSourceName , "DataSpec" .= _cdsfrDataSpec , "RoleARN" .= _cdsfrRoleARN , "ComputeStatistics" .= _cdsfrComputeStatistics ] instance AWSRequest CreateDataSourceFromRedshift where type Sv CreateDataSourceFromRedshift = MachineLearning type Rs CreateDataSourceFromRedshift = CreateDataSourceFromRedshiftResponse request = post "CreateDataSourceFromRedshift" response = jsonResponse instance FromJSON CreateDataSourceFromRedshiftResponse where parseJSON = withObject "CreateDataSourceFromRedshiftResponse" $ \o -> CreateDataSourceFromRedshiftResponse <$> o .:? "DataSourceId"
romanb/amazonka
amazonka-ml/gen/Network/AWS/MachineLearning/CreateDataSourceFromRedshift.hs
mpl-2.0
9,508
0
9
1,733
787
495
292
86
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Servers.MainServer where import Lib.ServantHelpers import Servant.API import Servers.AdminServer import Servers.AuthServer import Servers.ProjectServer import Servers.TenantServer type MainAPI = AdminAPI :<|> AuthAPI :<|> ProjectAPI :<|> TenantAPI mainAPI :: Proxy MainAPI mainAPI = Proxy mainServer :: Server MainAPI mainServer = adminServer :<|> authServer :<|> projectServer :<|> tenantServer
virtualsaleslab/simplestore
src/Servers/MainServer.hs
unlicense
601
0
7
193
94
54
40
20
1
{- | Composable statistics. See * <http://squing.blogspot.com/2008/11/beautiful-folding.html> * <http://sneezy.cs.nott.ac.uk/fplunch/weblog/?p=232> -} {-# LANGUAGE ExistentialQuantification #-} module Math.Probably.FoldingStats where import Control.Applicative import Data.Foldable data Fold b c = forall a. F (a -> b -> a) a (a -> c) (a -> a -> a) instance Functor (Fold a) where fmap = flip after instance Applicative (Fold a) where pure x = F (\_ _ -> ()) () (\_ -> x) (\_ _-> ()) f <*> g = (uncurry ($)) `fmap` both f g -- :: Fold a (b->c, b) {-instance Bounded Double where minBound = -1e-200 maxBound = 1e-200 -} -- | A strict pair type data P a b = P !a !b -- * combinators both :: Fold b c -> Fold b c' -> Fold b (c, c') both (F f x c pc) (F g y c' pc') = F (comb f g) (P x y) (c *** c') $ \(P a1 a2) (P a1' a2')->P (pc a1 a1') (pc' a2 a2') where comb f g (P a a') b = P (f a b) (g a' b) (***) f g (P x y) = (f x, g y) after :: Fold b c -> (c -> c') -> Fold b c' after (F f x c pc) d = F f x (d . c) pc before :: Fold b' c -> (b-> b') -> Fold b c before (F f x c pc) d = F (\acc nxt -> f acc $ d nxt) x c pc bothWith :: (c -> c' -> d) -> Fold b c -> Fold b c' -> Fold b d bothWith combiner f1 f2 = after (both f1 f2) (uncurry combiner) -- * Running statistics progressively :: Fold b c -> [b] -> [c] progressively (F f x c _) = map c . (scanl f x) runStat :: (Foldable t) => Fold b c -> t b -> c runStat (F f x c _) = c . (foldl' f x) --runStatU :: (UA b) => Fold b c -> UArr b -> c --runStatU (F f x c _) = c . (foldlU f x) runStatOnMany :: Fold b c -> [[b]] -> [c] runStatOnMany _ [] = [] runStatOnMany (F f x c _) xss = map c $ foldl' f' (replicate n x) xss where n = length xss f' = zipWith f -- * primitive statistics sumF :: Num a => Fold a a sumF = F (+) 0 id (+) sumSqrF :: Num a => Fold a a sumSqrF = before sumF square square :: (Num a) => a -> a square x = x*x productF :: Num a => Fold a a productF = F (*) 1 id (*) lengthF :: Fold a Int lengthF = F (const . (+1)) 0 id (+) realLengthF :: Fractional a => Fold b a realLengthF = fromIntegral `fmap` lengthF dotProdF :: Num a => Fold (a,a) a dotProdF = before sumF $ uncurry (*) maxF :: (Num a, Ord a, Bounded a) => Fold a a maxF = F (max) (minBound) id (max) minF :: (Num a, Ord a, Bounded a) => Fold a a minF = F (min) (maxBound) id (min) maxFrom :: (Num a, Ord a) => a -> Fold a a maxFrom mnb = F (max) (mnb) id (max) minFrom :: (Num a, Ord a) => a -> Fold a a minFrom mxb = F (min) (mxb ) id (min) minLocF :: (Num a, Ord a, Bounded a) => Fold a (a, Int) minLocF = F (\(minv, minn, curn) v -> if v < minv then (v,curn, curn+1) else (minv, minn, curn+1)) (maxBound, -1, 0) (\(x,y,z)->(x,y)) (undefined) stdDevF, stdDevPF :: Floating a => Fold a a stdDevF = sqrt <$> varF stdDevPF = sqrt <$> varPF varF, varPF :: Fractional a => Fold a a varF = f <$> nSumSumSqr where f ((s0, s1), s2) = (s0*s2-s1*s1)/(s0*(s0-1)) varPF = f <$> nSumSumSqr where f ((s0, s1), s2) = recip (s0*s0)*(s0*s2-s1*s1) sumSqrDivN :: Fractional a => Fold a a sumSqrDivN = pure (*) <*> ((recip . decr) `fmap` realLengthF) <*> sumSqrF where decr x = x-1 meanF :: Fractional a => Fold a a meanF = pure (/) <*> sumF <*> realLengthF meanSDF :: Floating a => Fold a (a,a) meanSDF = f <$> nSumSumSqr where f ((s0, s1), s2) = (s1/s0, sqrt $ (s0*s2-s1*s1)/(s0*(s0-1))) meanSDNF :: Floating a => Fold a (a,a,a) meanSDNF = f <$> nSumSumSqr where f ((s0, s1), s2) = (s1/s0, sqrt $ (s0*s2-s1*s1)/(s0*(s0-1)), s0) meanSEMF :: Floating a => Fold a (a,a) meanSEMF = f <$> nSumSumSqr where f ((s0, s1), s2) = (s1/s0, (sqrt $ (s0*s2-s1*s1)/(s0*(s0-1)))/sqrt s0) -- * More statisitcs muLogNormalF :: Floating a => Fold a a muLogNormalF = pure (/) <*> before sumF log <*> realLengthF varLogNormalF ::Floating a => Fold a a varLogNormalF = pure (-) <*> before meanF (square . log) <*> after muLogNormalF square where square x = x*x sdLogNormalF ::Floating a => Fold a a sdLogNormalF = fmap sqrt varLogNormalF logNormalF :: Floating a => Fold a (a,a) logNormalF = both muLogNormalF sdLogNormalF -- | The frequency of changes, based on a comparator jumpFreqByF :: (a->a->Bool) -> Fold a Double jumpFreqByF p = F f ini c comb where f (Nothing, countj , total) new = (Just new, countj, total) f (Just old, countj, total) new | p old new = (Just new, countj, total+1) | otherwise = (Just new, countj+1, total+1) ini = (Nothing, 0, 0) c (_, j, t) = realToFrac j/realToFrac t comb (_, a, b) (_, c, d) = (Nothing, a+c, d+b) regressF :: Fold (Double, Double) (Double, Double) regressF = post <$> ( dotProdF `both` (before sumF fst) `both` (before sumF snd) `both` (before sumF (square . fst)) `both` realLengthF) where post ((((dotp, sx), sy), sqrx), len) = let nume = dotp - sx*sy/len denom = sqrx - square sx/len slope = nume/denom in (slope, sy/len - sx*slope/len) nSumSumSqr :: Fractional a => Fold a ((a, a), a) nSumSumSqr = (realLengthF `both` sumF `both` (before sumF square)) gammaF :: Fold Double (Double,Double) gammaF = let final mn lmn = let s = log mn - lmn kapprox = (3-s+sqrt((s-3)**2+24*s))/(12*s) theta = recip kapprox * mn in (kapprox, theta) in pure final <*> meanF <*> before meanF log
glutamate/probably
Math/Probably/FoldingStats.hs
bsd-3-clause
5,601
16
22
1,537
2,880
1,544
1,336
120
2
{-# OPTIONS -fno-warn-orphans #-} module Main (main) where import Control.DeepSeq import Criterion.Main import Network import Network.BitTorrent.Exchange.Protocol as BT import Data.Torrent.Block as BT import Data.Torrent.Bitfield as BT instance NFData PortNumber where rnf = rnf . (fromIntegral :: PortNumber -> Int) instance NFData BlockIx where rnf (BlockIx a b c) = a `deepseq` b `deepseq` rnf c instance NFData Block where rnf (Block a b c) = a `deepseq` b `deepseq` rnf c instance NFData Bitfield instance NFData Message where rnf (Have i) = rnf i rnf (Bitfield b) = rnf b rnf (Request b) = rnf b rnf (Piece b) = rnf b rnf (Cancel b) = rnf b rnf (Port i) = rnf i rnf _ = () -- other fields are forced by pattern matching {- encodeMessages :: [Message] -> ByteString encodeMessages xs = runPut (mapM_ put xs) decodeMessages :: ByteString -> Either String [Message] decodeMessages = runGet (many get) -} main :: IO () main = defaultMain []
DavidAlphaFox/bittorrent
bench/Main.hs
bsd-3-clause
989
0
8
206
306
165
141
25
1
module Blockchain.Communication ( recvMsg, sendMsg ) where import Control.Monad.IO.Class import Control.Monad.Trans import Data.Binary.Put import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import System.IO import Blockchain.Data.RLP import Blockchain.Context import Blockchain.Display import Blockchain.Data.Wire import Blockchain.Frame import Blockchain.RLPx ethereumHeader::B.ByteString->Put ethereumHeader payload = do putWord32be 0x22400891 putWord32be $ fromIntegral $ B.length payload putByteString payload sendCommand::Handle->B.ByteString->IO () sendCommand handle payload = do let theData2 = runPut $ ethereumHeader payload BL.hPut handle theData2 sendMessage::Handle->Message->ContextM () sendMessage handle msg = do let (pType, pData) = wireMessage2Obj msg liftIO $ sendCommand handle $ B.cons pType $ rlpSerialize pData sendMsg::Message->EthCryptM ContextM () sendMsg msg = do lift $ displayMessage True msg let (pType, pData) = wireMessage2Obj msg encryptAndPutFrame $ B.cons pType $ rlpSerialize pData recvMsg::EthCryptM ContextM Message recvMsg = do frameData <- getAndDecryptFrame let packetType = fromInteger $ rlpDecode $ rlpDeserialize $ B.take 1 frameData packetData = rlpDeserialize $ B.drop 1 frameData return $ obj2WireMessage packetType packetData
jamshidh/ethereum-vm
src/Blockchain/Communication.hs
bsd-3-clause
1,363
0
12
209
415
210
205
40
1
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, TypeSynonymInstances #-} -- | -- Module : Where -- Copyright : 2003 Shae Erisson -- -- License: lGPL -- -- Slightly specialised version of Where for associating projects with their urls. -- Code almost all copied. module Plugin.Where (theModule) where import Plugin import Lambdabot.Util (confirmation) import qualified Data.ByteString.Char8 as P import qualified Data.Map as M $(plugin "Where") type WhereState = M.Map P.ByteString P.ByteString type WhereWriter = WhereState -> LB () -- type Where m a = ModuleT WhereState m a instance Module WhereModule WhereState where moduleCmds _ = ["where", "url", "what", "where+" ] moduleHelp _ s = case s of "where" -> "where <key>. Return element associated with key" "what" -> "what <key>. Return element associated with key" "url" -> "url <key>. Return element associated with key" "where+" -> "where+ <key> <elem>. Define an association" moduleDefState _ = return M.empty moduleSerialize _ = Just mapPackedSerial process_ _ cmd rest = list $ withMS $ \factFM writer -> case words rest of [] -> return "@where <key>, return element associated with key" (fact:dat) -> processCommand factFM writer (lowerCaseString fact) cmd (unwords dat) ------------------------------------------------------------------------ processCommand :: WhereState -> WhereWriter -> String -> String -> String -> LB String processCommand factFM writer fact cmd dat = case cmd of "where" -> return $ getWhere factFM fact "what" -> return $ getWhere factFM fact -- an alias "url" -> return $ getWhere factFM fact -- an alias "where+" -> updateWhere True factFM writer fact dat _ -> return "Unknown command." getWhere :: WhereState -> String -> String getWhere fm fact = case M.lookup (P.pack fact) fm of Nothing -> "I know nothing about " ++ fact ++ "." Just x -> P.unpack x updateWhere :: Bool -> WhereState -> WhereWriter -> String -> String -> LB String updateWhere _guard factFM writer fact dat = do writer $ M.insert (P.pack fact) (P.pack dat) factFM random confirmation
dmalikov/lambdabot
Plugin/Where.hs
mit
2,326
0
13
594
540
279
261
40
5
import System infinity = 1/0 delta = sqrt e where e = encodeFloat (floatRadix e) (-floatDigits e) infixl 7 .*, *| data Vector = V !Double !Double !Double deriving (Show, Eq) s *| V x y z = V (s * x) (s * y) (s * z) instance Num Vector where V x y z + V x' y' z' = V (x + x') (y + y') (z + z') V x y z - V x' y' z' = V (x - x') (y - y') (z - z') fromInteger i = V x x x where x = fromInteger i V x y z .* V x' y' z' = x * x' + y * y' + z * z' vlength r = sqrt (r .* r) unitise r = 1 / vlength r *| r data Scene = Sphere !Vector !Double | Group !Vector !Double Scene Scene Scene Scene Scene deriving (Show) ray_sphere (V dx dy dz) (V vx vy vz) r = let disc = vx * vx + vy * vy + vz * vz - r * r in if disc < 0 then infinity else let b = vx * dx + vy * dy + vz * dz b2 = b * b in if b2 < disc then infinity else let disk = sqrt(b2 - disc) t1 = b - disk in if t1 > 0 then t1 else b + disk ray_sphere' (V ox oy oz) (V dx dy dz) (V cx cy cz) r = let vx = cx - ox; vy = cy - oy; vz = cz - oz vv = vx * vx + vy * vy + vz * vz b = vx * dx + vy * dy + vz * dz disc = b * b - vv + r * r in disc >= 0 && b + sqrt disc >= 0 data Hit = H {l :: !Double, nv :: Vector } intersect dir@(V dx dy dz) hit s = case s of Sphere center@(V cx cy cz) radius -> let l' = ray_sphere dir center radius in if l' >= l hit then hit else let x = l' * dx - cx y = l' * dy - cy z = l' * dz - cz il = 1 / sqrt(x * x + y * y + z * z) in H {l = l', nv = V (il * x) (il * y) (il * z) } Group center radius a b c d e -> let l' = ray_sphere dir center radius in if l' >= l hit then hit else let f h s = intersect dir h s in f (f (f (f (f hit a) b) c) d) e intersect' orig dir s = case s of Sphere center radius -> ray_sphere' orig dir center radius Group center radius a b c d e -> let f s = intersect' orig dir s in ray_sphere' orig dir center radius && (f a || f b || f c || f d || f e) neg_light = unitise (V 1 3 (-2)) ray_trace dir scene = let hit = intersect dir (H infinity 0) scene in if l hit == infinity then 0 else let n = nv hit in let g = n .* neg_light in if g < 0 then 0 else if intersect' (l hit *| dir + delta *| n) neg_light scene then 0 else g fold5 f x a b c d e = f (f (f (f (f x a) b) c) d) e create level c r = let obj = Sphere c r in if level == 1 then obj else let a = 3 * r / sqrt 12 in let bound (c, r) s = case s of Sphere c' r' -> (c, max r (vlength (c - c') + r')) Group _ _ v w x y z -> fold5 bound (c, r) v w x y z in let aux x' z' = create (level - 1 :: Int) (c + V x' a z') (0.5 * r) in let w = aux (-a) (-a); x = aux a (-a) in let y = aux (-a) a; z = aux a a in let (c1, r1) = fold5 bound (c + V 0 r 0, 0) obj w x y z in Group c1 r1 obj w x y z ss = 4 pixel_vals n scene y x = sum [ let f a da = a - n / 2 + da / ss; d = unitise (V (f x dx) (f y dy) n) in ray_trace d scene | dx <- [0..ss-1], dy <- [0..ss-1] ] main = do [level,ni] <- fmap (map read) getArgs let n = fromIntegral ni scene = create level (V 0 (-1) 4) 1 scale x = 0.5 + 255 * x / (ss*ss) picture = [ toEnum $ truncate $ scale $ pixel_vals n scene y x | y <- [n-1,n-2..0], x <- [0..n-1]] putStrLn $ "P5\n" ++ show ni ++ " " ++ show ni ++ "\n255\n" ++ picture
hvr/jhc
regress/tests/7_large/RayT.hs
mit
3,400
24
23
1,152
2,104
1,058
1,046
100
4
{-# LANGUAGE TypeFamilies #-} module Kind where import Data.Kind (Type) class C (a :: Type -> Type) where type T a foo :: a x -> T a foo = undefined
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/Kind.hs
bsd-3-clause
156
0
8
38
58
33
25
-1
-1
{- Copyright (C) 2007-2015 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.TeXMath Copyright : Copyright (C) 2007-2015 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of TeX math to a list of 'Pandoc' inline elements. -} module Text.Pandoc.Readers.TeXMath ( texMathToInlines ) where import Text.Pandoc.Definition import Text.TeXMath -- | Converts a raw TeX math formula to a list of 'Pandoc' inlines. -- Defaults to raw formula between @$@ or @$$@ characters if entire formula -- can't be converted. texMathToInlines :: MathType -> String -- ^ String to parse (assumes @'\n'@ line endings) -> [Inline] texMathToInlines mt inp = case writePandoc dt `fmap` readTeX inp of Right (Just ils) -> ils _ -> [Str (delim ++ inp ++ delim)] where (dt, delim) = case mt of DisplayMath -> (DisplayBlock, "$$") InlineMath -> (DisplayInline, "$")
gbataille/pandoc
src/Text/Pandoc/Readers/TeXMath.hs
gpl-2.0
1,801
0
12
429
152
87
65
13
3
{-# LANGUAGE TypeFamilies, GADTs #-} module T8368 where data Foo = Bar data family Fam a data instance Fam a where MkFam :: Foo
ghc-android/ghc
testsuite/tests/indexed-types/should_fail/T8368.hs
bsd-3-clause
135
0
5
31
31
20
11
6
0
module Main(main) where import Numeric import Data.Ratio main = print ((fromRat (132874 % 23849))::Double)
beni55/ghcjs
test/pkg/base/Numeric/num001.hs
mit
109
0
10
16
44
26
18
4
1
module Graphics.UI.SDL00Spec where --import Graphics.UI.SDL00 import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "RTLD LIBSDL" $ do it "load/free libsdl" $ do pending
kkardzis/sdlhs
test/Graphics/UI/SDL00Spec.hs
isc
217
0
12
51
64
33
31
9
1
{-# LANGUAGE MultiParamTypeClasses #-} module Universe.Objects.Celestial ( CelestialBody(..) , Star(..) , StarSpectrumClass(..) , StarLifeStage(..) , Planet(..) , PlanetClass(..) , Comet(..) , Asteroid(..) ) where import Universe.Objects data StarSpectrumClass = TODO -- TODO data StarLifeStage = TODO' -- TODO data PlanetClass = Todo -- TODO class (CelestialBody obj coordSys id d) => Star obj coordSys id d where spectrumClass :: obj -> StarSpectrumClass starLifeStage :: obj -> StarLifeStage class (CelestialBody obj d coordSys id) => Planet obj d coordSys id where planetClass :: obj -> PlanetClass class (CelestialBody obj d coordSys id) => Comet obj d coordSys id class (CelestialBody obj d coordSys id) => Asteroid obj d coordSys id
fehu/hgt
core-universe/src/Universe/Objects/Celestial.hs
mit
846
0
7
215
238
138
100
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiWayIf #-} module HsToCoq.Plugin (plugin) where import Data.Text (pack) import Control.Monad.IO.Class import System.IO import GhcPlugins hiding (vcat) import Unique import TcType import qualified Pretty import qualified Outputable import HsToCoq.Coq.Gallina hiding (Type, Let, App, Name) import HsToCoq.Coq.Gallina.Orphans () import HsToCoq.Coq.Gallina.Util hiding (Var) import HsToCoq.Coq.Pretty import HsToCoq.PrettyPrint #if __GLASGOW_HASKELL__ >= 806 type PluginPass = CorePluginPass #endif -- | A more convenient Gallina application operator (<:) :: Term -> [Term] -> Term n <: xs = appList n (map PosArg xs) class ToTerm a where t :: a -> Term instance ToTerm (Tickish b) where t _ = undefined instance ToTerm Int where t n = InScope (Num (fromIntegral n)) "N" instance ToTerm Module where t (Module a b) = App2 "Mk_Module" (t a) (t b) instance ToTerm IndefUnitId where t _ = "default" instance ToTerm DefUnitId where t _ = "default" instance ToTerm UnitId where t (IndefiniteUnitId a) = "IndefiniteUnitId" <: [t a] t (DefiniteUnitId a) = "DefiniteUnitId" <: [t a] instance ToTerm ModuleName where t _ = "default" instance ToTerm Type where t _ = "default" instance ToTerm NameSpace where t _ = "default" instance ToTerm FastString where t f = HsString (pack (unpackFS f)) instance ToTerm OccName where t o = "Mk_OccName" <: [t (occNameSpace o), t (occNameFS o)] instance ToTerm Unique where t u = "MkUnique" <: [t (getKey u)] instance ToTerm SrcSpan where t _ = "default" instance ToTerm Name where t n = "Mk_Name" <: [ if | isWiredInName n -> App3 "WiredIn" (t (nameModule n)) "default" (if isBuiltInSyntax n then "BuiltInSyntax" else "UserSyntax") | isExternalName n -> App1 "External" (t (nameModule n)) | isInternalName n -> "Internal" | isSystemName n -> "System" , t (nameOccName n) , t (nameUnique n) , t (nameSrcSpan n) ] instance ToTerm Var where t v | isTyVar v = "Mk_TyVar" <: [t a, t b, t c] | isTcTyVar v = "Mk_TcTyVar" <: [ t a , t b , t c , t (tcTyVarDetails v) ] | isId v = "Mk_Id" <: [ t a , t b , t c , if isGlobalId v then "GlobalId" else "LocalId" <: [if isExportedId v then "Exported" else "NotExported"] , t (idDetails v) , t (idInfo v) ] | otherwise = error "What kind of Var is that?" where a = varName v b = getKey (getUnique v) c = varType v instance ToTerm Coercion where t _ = "default" instance ToTerm AltCon where t _ = "default" instance ToTerm Literal where t _ = "default" instance ToTerm IdInfo where t _ = "default" instance ToTerm IdDetails where t _ = "default" instance ToTerm TcType.TcTyVarDetails where t _ = "default" instance (ToTerm a, ToTerm b) => ToTerm (a, b) where t (x, y) = App2 "pair" (t x) (t y) instance (ToTerm a, ToTerm b, ToTerm c) => ToTerm (a, b, c) where t (x, y, z) = App3 "pair3" (t x) (t y) (t z) instance ToTerm b => ToTerm (Expr b) where t (Var n) = App1 "Mk_Var" (t n) t (Lit l) = App1 "Lit" (t l) t (App e a) = App2 "App" (t e) (t a) t (Lam a e) = App2 "Lam" (t a) (t e) t (Let n e) = App2 "Let" (t n) (t e) t (Case e n u l) = appList "Case" [PosArg (t e), PosArg (t n), PosArg (t u), PosArg (t l)] t (Cast e u) = App2 "Cast" (t e) (t u) t (Tick i e) = App2 "Tick" (t i) (t e) t (Type u) = App1 "Type_" (t u) t (Coercion u) = App1 "Coercion" (t u) instance ToTerm b => ToTerm (Bind b) where t (NonRec n e) = App2 "NonRec" (t n) (t e) t (Rec xs) = App1 "Rec" (t xs) instance ToTerm a => ToTerm [a] where t [] = "nil" t (x : xs) = App2 "cons" (t x) (t xs) plugin :: Plugin plugin = defaultPlugin { installCoreToDos = install } install :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo] install _ xs = return $ pass : xs where pass = CoreDoPluginPass "GHC.Proof" proofPass proofPass :: PluginPass -- ModGuts -> CoreM ModGuts proofPass guts@ModGuts {..} = do dflags <- getDynFlags liftIO $ withFile coq WriteMode $ \h -> do printSDocLn Pretty.PageMode dflags h (defaultDumpStyle dflags) $ Outputable.vcat ["(*", Outputable.ppr mg_binds, "*)"] hPrettyPrint h $ vcat (map renderGallina mod) return guts where name = moduleNameSlashes (moduleName mg_module) coq = name ++ ".v" mod :: [Sentence] mod = [ ModuleSentence (Require Nothing (Just Import) ["Core"]) , ModuleSentence (Require Nothing (Just Import) ["Name"]) , ModuleSentence (Require Nothing (Just Import) ["OccName"]) , ModuleSentence (Require Nothing (Just Import) ["Module"]) , ModuleSentence (Require Nothing (Just Import) ["Unique"]) , ModuleSentence (Require Nothing (Just Import) ["GHC.Tuple"]) , ModuleSentence (Require Nothing (Just Import) ["GHC.Err"]) , ModuleSentence (Require Nothing (Just Import) ["Coq.NArith.BinNat"]) , DefinitionSentence (DefinitionDef Global "program" [] (Just (Qualid "CoreProgram")) body NotExistingClass) ] body :: Term body = t mg_binds hPrettyPrint :: MonadIO m => Handle -> Doc -> m () hPrettyPrint h = liftIO . displayIO h . renderPretty 0.67 120
antalsz/hs-to-coq
src/lib/HsToCoq/Plugin.hs
mit
5,931
4
15
1,834
2,209
1,127
1,082
153
1
{- | Module : Main Description : Entry point. Parses command line arguments and runs program Copyright : (c) Peter Uhlenbruck 2017 License : MIT Licence -} module Main where import System.Environment import Interpreter import System.IO as IO import Data.ByteString.Lazy as BS main :: IO () main = do args <- getArgs let (program, inputs) = parseArgs args ins <- sequence inputs command <- program sequence_ $ fmap (run command) ins {- The Interpreter will read the program from the file provided in the first argument, or as a string passed in the the -c option. The program will be run for each file provided or use stdin as input if no input file provided in the argument list. -} parseArgs :: [String] -> (IO String, [IO ByteString]) parseArgs ["-c", command] = (return command, [BS.getContents]) parseArgs ("-c" : command : inputFiles) = (return command, fmap BS.readFile inputFiles) parseArgs [file] = (IO.readFile file, [BS.getContents]) parseArgs (file : inputFiles) = (IO.readFile file, fmap BS.readFile inputFiles)
puhlenbruck/hf
app/Main.hs
mit
1,065
0
10
204
255
137
118
17
1
module L.Util.Utils ( (|>) ,bind2 ,bind3 ,endsWith ,extract ,mkString ,strip ,zipWithIndex ) where import Data.List (|>) :: (a -> b) -> (b -> c) -> a -> c (|>) = flip (.) mkString :: String -> [String] -> String mkString s l = concat $ intersperse s l endsWith :: String -> String -> Bool endsWith = isSuffixOf extract :: Either String a -> a extract = either error id zipWithIndex :: [a] -> [(a, Int)] zipWithIndex as = zip as [0..] wschars :: String wschars = " \t\r\n" strip :: String -> String strip = lstrip . rstrip lstrip :: String -> String lstrip s = case s of [] -> [] (x:xs) -> if elem x wschars then lstrip xs else s rstrip :: String -> String rstrip = reverse . lstrip . reverse bind2 :: Monad m => (a -> b -> m c) -> m a -> m b -> m c bind2 f ma mb = do a <- ma; b <- mb; f a b bind3 :: Monad m => (a -> b -> c -> m d) -> m a -> m b -> m c -> m d bind3 f ma mb mc = do a <- ma; b <- mb; c <- mc; f a b c
joshcough/L5-Haskell
src/L/Util/Utils.hs
mit
962
0
11
260
498
263
235
35
3
{-# LANGUAGE CPP #-} module GHCJS.DOM.MutationEvent ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.MutationEvent #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.MutationEvent #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/MutationEvent.hs
mit
352
0
5
33
33
26
7
4
0
module Zwerg.Options where import Zwerg.Prelude data Options = Options { effectsLevel :: Int , backgroundLevel :: Int } defaultOptions :: Options defaultOptions = Options { effectsLevel = 5 , backgroundLevel = 5 }
zmeadows/zwerg
lib/Zwerg/Options.hs
mit
235
0
8
54
56
35
21
9
1
{-| Module : Haste.GAPI.GPlus.Person Description : Functions for working on persons Copyright : (c) Jonathan Skårstedt, 2016 License : MIT Maintainer : [email protected] Stability : experimental Portability : Haste Functions which maps to the Google API -} module Haste.GAPI.GPlus.Person where -- | Haste.GAPI.Result type parameter data Person
nyson/haste-gapi
Haste/GAPI/GPlus/Person.hs
mit
372
0
3
63
13
10
3
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html module Stratosphere.Resources.ApiGatewayApiKey where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.ApiGatewayApiKeyStageKey -- | Full data type definition for ApiGatewayApiKey. See 'apiGatewayApiKey' -- for a more convenient constructor. data ApiGatewayApiKey = ApiGatewayApiKey { _apiGatewayApiKeyCustomerId :: Maybe (Val Text) , _apiGatewayApiKeyDescription :: Maybe (Val Text) , _apiGatewayApiKeyEnabled :: Maybe (Val Bool) , _apiGatewayApiKeyGenerateDistinctId :: Maybe (Val Bool) , _apiGatewayApiKeyName :: Maybe (Val Text) , _apiGatewayApiKeyStageKeys :: Maybe [ApiGatewayApiKeyStageKey] , _apiGatewayApiKeyValue :: Maybe (Val Text) } deriving (Show, Eq) instance ToResourceProperties ApiGatewayApiKey where toResourceProperties ApiGatewayApiKey{..} = ResourceProperties { resourcePropertiesType = "AWS::ApiGateway::ApiKey" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("CustomerId",) . toJSON) _apiGatewayApiKeyCustomerId , fmap (("Description",) . toJSON) _apiGatewayApiKeyDescription , fmap (("Enabled",) . toJSON) _apiGatewayApiKeyEnabled , fmap (("GenerateDistinctId",) . toJSON) _apiGatewayApiKeyGenerateDistinctId , fmap (("Name",) . toJSON) _apiGatewayApiKeyName , fmap (("StageKeys",) . toJSON) _apiGatewayApiKeyStageKeys , fmap (("Value",) . toJSON) _apiGatewayApiKeyValue ] } -- | Constructor for 'ApiGatewayApiKey' containing required fields as -- arguments. apiGatewayApiKey :: ApiGatewayApiKey apiGatewayApiKey = ApiGatewayApiKey { _apiGatewayApiKeyCustomerId = Nothing , _apiGatewayApiKeyDescription = Nothing , _apiGatewayApiKeyEnabled = Nothing , _apiGatewayApiKeyGenerateDistinctId = Nothing , _apiGatewayApiKeyName = Nothing , _apiGatewayApiKeyStageKeys = Nothing , _apiGatewayApiKeyValue = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apikey-customerid agakCustomerId :: Lens' ApiGatewayApiKey (Maybe (Val Text)) agakCustomerId = lens _apiGatewayApiKeyCustomerId (\s a -> s { _apiGatewayApiKeyCustomerId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apikey-description agakDescription :: Lens' ApiGatewayApiKey (Maybe (Val Text)) agakDescription = lens _apiGatewayApiKeyDescription (\s a -> s { _apiGatewayApiKeyDescription = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apikey-enabled agakEnabled :: Lens' ApiGatewayApiKey (Maybe (Val Bool)) agakEnabled = lens _apiGatewayApiKeyEnabled (\s a -> s { _apiGatewayApiKeyEnabled = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apikey-generatedistinctid agakGenerateDistinctId :: Lens' ApiGatewayApiKey (Maybe (Val Bool)) agakGenerateDistinctId = lens _apiGatewayApiKeyGenerateDistinctId (\s a -> s { _apiGatewayApiKeyGenerateDistinctId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apikey-name agakName :: Lens' ApiGatewayApiKey (Maybe (Val Text)) agakName = lens _apiGatewayApiKeyName (\s a -> s { _apiGatewayApiKeyName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apikey-stagekeys agakStageKeys :: Lens' ApiGatewayApiKey (Maybe [ApiGatewayApiKeyStageKey]) agakStageKeys = lens _apiGatewayApiKeyStageKeys (\s a -> s { _apiGatewayApiKeyStageKeys = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apikey-value agakValue :: Lens' ApiGatewayApiKey (Maybe (Val Text)) agakValue = lens _apiGatewayApiKeyValue (\s a -> s { _apiGatewayApiKeyValue = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/ApiGatewayApiKey.hs
mit
4,195
0
14
501
733
417
316
55
1
module Problem0002 where fibonaccis = 1 : 2 : zipWith (+) fibonaccis (tail fibonaccis) evenFibonaccisLessThan maxNumber = [x | x <- takeWhile (<= maxNumber) fibonaccis, x `mod` 2 == 0] sumOfEvenFibonacciesLessThan :: Integer -> Integer sumOfEvenFibonacciesLessThan maxNumber = sum (evenFibonaccisLessThan maxNumber)
Sobieck00/practice
pe/nonvisualstudio/haskell/OldWork/Implementation/Problem0002.hs
mit
323
0
9
48
100
54
46
5
1
{-# LANGUAGE OverloadedStrings, LambdaCase #-} module Abyss.Game (initGame, Action (..)) where import Prelude hiding ((.), id) import Abyss.Stats import Abyss.Item (Item) import qualified Abyss.Item as Item import qualified Abyss.Spell as Spell import qualified Abyss.Monster as Monster import Core.Types import Core.Engine import Core.Monad import Core.DijkstraMap import Component.Activator import Component.AI import Component.Name import Component.Modifier import Gen.Dungeon import Gen.Level import Control.Monad import qualified Data.Map as Map import Data.Maybe (listToMaybe) import qualified Data.Serialize as S import Data.Aeson ((.:)) import qualified Data.Aeson as J import Data.Text (Text) import qualified Data.ByteString as BS import qualified Data.Text.Encoding as T bump :: ARef -> Dir4 -> Game k Level () bump self dir = do l <- access (loc <# aref self) occupier <- listToMaybe . living (\a -> a ^. loc == move4 dir l) <$> level blocked <- access (ix (move4 dir l) <# solid) case occupier of Just mon -> self `meleeAttack` mon Nothing -> do when blocked $ self `activate` move4 dir l loc <# aref self != if blocked then l else move4 dir l data Action = Move Dir4 | Skip | Activate Dir4 | Cast Text (Row, Col) | Pickup (Row, Col) deriving Show parseDir4 :: MonadPlus m => Text -> m Dir4 parseDir4 "N" = pure N4 parseDir4 "E" = pure E4 parseDir4 "S" = pure S4 parseDir4 "W" = pure W4 parseDir4 _ = mzero parseSkip :: MonadPlus m => Text -> m Action parseSkip t | t == "skip" = return Skip | otherwise = mzero instance J.FromJSON Action where parseJSON v = msum [ J.withObject "move" (\obj -> fmap Move (parseDir4 =<< obj .: "move")) v , J.withText "skip" parseSkip v , J.withObject "activate" (\obj -> fmap Activate (parseDir4 =<< obj .: "activate")) v , flip (J.withObject "cast") v $ \obj -> do n <- obj .: "name" r <- obj .: "row" c <- obj .: "col" return (Cast n (r, c)) , flip (J.withObject "pickup") v $ \obj -> do r <- obj .: "row" c <- obj .: "col" return (Pickup (r, c)) ] putText :: S.Putter Text putText txt = S.put (BS.length bs) >> S.putByteString bs where bs = T.encodeUtf8 txt getText :: S.Get Text getText = fmap T.decodeUtf8 (S.getByteString =<< S.get) instance S.Serialize Action where put (Move d) = S.putWord8 0x00 >> S.put d put Skip = S.putWord8 0x01 put (Activate d) = S.putWord8 0x02 >> S.put d put (Cast s l) = S.putWord8 0x03 >> putText s >> S.put l put (Pickup l) = S.putWord8 0x04 >> S.put l get = S.getWord8 >>= \case 0x00 -> Move <$> S.get 0x01 -> return Skip 0x02 -> Activate <$> S.get 0x03 -> Cast <$> getText <*> S.get 0x04 -> Pickup <$> S.get _ -> error "Invalid action!" rooms :: [(Int, Int)] rooms = [(6,7),(6,5),(4,4),(3,4),(4,2)] ++ concat (repeat [(3,3),(2,2),(2,2),(2,1)]) ritualChamber = [ "###+#+###" , "# #" , "# #" , "# #" , "# * #" , "# #" , "# #" , "# #" , "###+#+###" ] hallway = [ "#################" , "# #" , "# # # # #" , "+ +" , "# # # # #" , "# #" , "#################" ] levelOne :: LevelSpec levelOne = LevelSpec { generator = dungeonGen (ritualChamber : hallway : map plainRoom rooms) , initializer = defaultInitializer , monsterCount = 40 , monsterTable = [ (10, Egg 'Z' White Monster.zombie) , (10, Egg 'S' White Monster.skeleton) ] , itemCount = 40 , itemTable = [ (10, (Item.longswordP2, 1)) , (10, (Item.greenPotion, 1)) , (10, (Item.redPotion, 1)) ] } inventoryList :: [(Item, Int)] -> Inventory inventoryList items = Inventory (Map.fromList (map (\(item, count) -> (Item.name item, count)) items)) initGame :: Game Action Level () initGame = do loadLevel levelOne actor player != Name "Player" actor player != inventoryList [(Item.longswordP2, 1), (Item.redPotion, 32)] baseHP <# actor player != 50 game game :: Game Action Level () game = do (AIModifier aiM) <- modified player noTurn . aiM . handleAct =<< turn modifyLevel shadowCast playerDMap ~= mkDijkstraMap <$> (pure <$> access (loc <# aref player)) <*> access solid runEffects refs <- monsters <$> level forM_ refs $ \ref -> do (Hurt amount) <- modified ref hp <- getL baseHP <$> modified ref monster <- access (aref ref) if (hp - amount) <= 0 || dead monster then aref ref %= kill else runAI ref (Hurt amount) <- modified player hp <- getL baseHP <$> modified player isDead <- dead <$> access (aref player) if (hp - amount) <= 0 || isDead then aref player %= kill >> return () else game handleAct :: Action -> Game () Level () handleAct (Move dir) = bump player dir handleAct Skip = return () handleAct (Activate dir) = do pLoc <- access (loc <# aref player) player `activate` move4 dir pLoc handleAct (Cast sname l) = case Spell.target (Map.findWithDefault Spell.fizzle sname Spell.every) of Spell.None eff -> cast eff Spell.Location eff -> cast (eff l) Spell.Actor eff -> do occupier <- listToMaybe . living (\a -> a ^. loc == l) <$> level case occupier of Just mon -> cast (eff mon) Nothing -> cast Spell.fizzleEffect handleAct (Pickup l) = access (floorItem l) >>= \case Nothing -> return () Just item -> do pLoc <- access (loc <# aref player) (Telekinesis distance) <- modified player if manhattan l pLoc > distance then message "Item is too far" >> return () else floorItem l != Nothing >> actor player %= addItem item
jameshsmith/HRL
Server/Abyss/Game.hs
mit
6,283
0
17
2,020
2,304
1,194
1,110
168
6
-- Informatics 1 - Functional Programming -- Lab week tutorial part II -- -- import Data.Char import PicturesSVG import Test.QuickCheck import Data.List.Split -- Exercise 1 -- write the correct type and the definition for isFENChar :: Char -> Bool isFENChar ch = elem (toLower ch) ['r', 'n', 'b', 'q', 'k', 'p', '/'] || isDigit ch -- Exercise 2.a -- write a recursive definition for besideList :: [Picture] -> Picture besideList pictures = if length pictures == 1 then head pictures else beside (head pictures) (besideList (tail pictures)) -- Exercise 2.c -- write the correct type and the definition for toClear :: Int -> Picture toClear n = besideList (replicate n clear) -- Exercise 3 -- write the correct type and the definition for fenCharToPicture :: Char -> Picture fenCharToPicture 'r' = rook fenCharToPicture 'n' = knight fenCharToPicture 'b' = bishop fenCharToPicture 'q' = queen fenCharToPicture 'k' = king fenCharToPicture 'p' = pawn fenCharToPicture 'R' = rook fenCharToPicture 'N' = knight fenCharToPicture 'B' = bishop fenCharToPicture 'Q' = queen fenCharToPicture 'K' = king fenCharToPicture 'P' = pawn fenCharToPicture ch = if isDigit ch then toClear (digitToInt ch) else Empty -- Exercise 4 -- write the correct type and the definition for isFenRow :: [Char] -> Bool isFenRow row = if (length row) > 8 then False else null (filter (not.isFENChar) row) -- Exercise 6.a -- write a recursive definition for fenCharsToPictures :: String -> [Picture] fenCharsToPictures str = if length str == 1 then fenCharToPicture(head str) : [] else [fenCharToPicture (head str)] ++ (fenCharsToPictures (tail str)) -- Exercise 6.b -- write the correct type and the definition of fenRowToPicture :: [Char] -> Picture fenRowToPicture str = if isFenRow str then besideList (fenCharsToPictures str) else Empty -- Exercise 7 -- write the correct type and the definition of mySplitOn :: String -> [[Char]] mySplitOn str = splitOn "/" str -- Exercise 8.a -- write a recursive definition for fenRowsToPictures :: [String] -> [Picture] fenRowsToPictures str = if length str == 1 then fenRowToPicture(head str) : [] else [fenRowToPicture (head str)] ++ (fenRowsToPictures (tail str)) -- Exercise 8.b -- write the correct type and the definition of aboveList :: [Picture] -> Picture aboveList pictures = if length pictures == 1 then head pictures else above (head pictures) (aboveList (tail pictures)) -- Exercise 8.c -- write the correct type and the definition of fenToPicture :: String -> Picture fenToPicture str = aboveList (fenRowsToPictures (mySplitOn str)) -- Exercise 9.0 --Empty board functions emptyRow :: Picture emptyRow = repeatH 4 (beside whiteSquare blackSquare) otherEmptyRow :: Picture otherEmptyRow = flipV emptyRow middleBoard :: Picture middleBoard = above (above emptyRow otherEmptyRow) (above emptyRow otherEmptyRow) emptyBoard :: Picture emptyBoard = above middleBoard middleBoard -- Exercise 9 -- write the correct type and the definition of chessBoard :: String -> Picture chessBoard str = over (fenToPicture str) emptyBoard -- Exercise 10 -- write the correct type and definition of -- allowedMoved
PavelClaudiuStefan/FMI
An_3_Semestru_1/ProgramareDeclarativa/Laboratoare/Laborator2/lab2chess.hs
cc0-1.0
3,556
0
10
922
815
439
376
59
2
-- -*- mode: haskell -*- {-# LANGUAGE TemplateHaskell, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses, FlexibleContexts, FlexibleInstances #-} module Fun.Cache -- $Id$ ( Cache -- abstrakt , empty , find , insert ) where import Prelude hiding ( lookup ) import Autolib.FiniteMap import Autolib.ToDoc hiding ( empty ) import Autolib.Reader class ( Ord k , Reader (FiniteMap k e) , ToDoc (FiniteMap k e) ) => CacheC k e instance ( Ord k , Reader (FiniteMap k e) , ToDoc (FiniteMap k e) ) => CacheC k e data CacheC k e => Cache k e = Cache ( FiniteMap k e ) $(derives [makeReader, makeToDoc] [''Cache]) empty :: CacheC k e => Cache k e empty = Cache emptyFM find :: CacheC k e => Cache k e -> k -> Maybe e find (Cache c) k = lookupFM c k insert :: CacheC k e => Cache k e -> k -> e -> Cache k e insert (Cache c) k e = Cache (addToFM c k e)
Erdwolf/autotool-bonn
src/Fun/Cache.hs
gpl-2.0
904
2
9
217
338
178
160
-1
-1
{-| Print some statistics for the journal. -} {-# LANGUAGE OverloadedStrings #-} module Hledger.Cli.Commands.Stats ( statsmode ,stats ) where import Data.List import Data.Maybe import Data.Ord import Data.HashSet (size, fromList) -- import Data.Text (Text) import qualified Data.Text as T import Data.Time.Calendar import System.Console.CmdArgs.Explicit import Text.Printf import qualified Data.Map as Map import Hledger import Hledger.Cli.CliOptions import Prelude hiding (putStr) import Hledger.Cli.Utils (writeOutput) statsmode = (defCommandMode $ ["stats"] ++ aliases) { modeHelp = "show some journal statistics" `withAliases` aliases ,modeGroupFlags = Group { groupUnnamed = [ flagReq ["output-file","o"] (\s opts -> Right $ setopt "output-file" s opts) "FILE" "write output to FILE. A file extension matching one of the above formats selects that format." ] ,groupHidden = [] ,groupNamed = [generalflagsgroup1] } } where aliases = [] -- like Register.summarisePostings -- | Print various statistics for the journal. stats :: CliOpts -> Journal -> IO () stats opts@CliOpts{reportopts_=reportopts_} j = do d <- getCurrentDay let q = queryFromOpts d reportopts_ l = ledgerFromJournal q j reportspan = (ledgerDateSpan l) `spanDefaultsFrom` (queryDateSpan False q) intervalspans = splitSpan (interval_ reportopts_) reportspan showstats = showLedgerStats l d s = intercalate "\n" $ map showstats intervalspans writeOutput opts s showLedgerStats :: Ledger -> Day -> DateSpan -> String showLedgerStats l today span = unlines $ map (\(label,value) -> concatBottomPadded [printf fmt1 label, value]) stats where fmt1 = "%-" ++ show w1 ++ "s: " -- fmt2 = "%-" ++ show w2 ++ "s" w1 = maximum $ map (length . fst) stats -- w2 = maximum $ map (length . show . snd) stats stats = [ ("Main file" :: String, path) -- ++ " (from " ++ source ++ ")") ,("Included files", unlines $ drop 1 $ journalFilePaths j) ,("Transactions span", printf "%s to %s (%d days)" (start span) (end span) days) ,("Last transaction", maybe "none" show lastdate ++ showelapsed lastelapsed) ,("Transactions", printf "%d (%0.1f per day)" tnum txnrate) ,("Transactions last 30 days", printf "%d (%0.1f per day)" tnum30 txnrate30) ,("Transactions last 7 days", printf "%d (%0.1f per day)" tnum7 txnrate7) ,("Payees/descriptions", show $ size $ fromList $ map (tdescription) ts) ,("Accounts", printf "%d (depth %d)" acctnum acctdepth) ,("Commodities", printf "%s (%s)" (show $ length cs) (T.intercalate ", " cs)) -- Transactions this month : %(monthtxns)s (last month in the same period: %(lastmonthtxns)s) -- Unmarked transactions : %(unmarked)s -- Days since reconciliation : %(reconcileelapsed)s -- Days since last transaction : %(recentelapsed)s ] where j = ljournal l path = journalFilePath j ts = sortBy (comparing tdate) $ filter (spanContainsDate span . tdate) $ jtxns j as = nub $ map paccount $ concatMap tpostings ts cs = Map.keys $ commodityStylesFromAmounts $ concatMap amounts $ map pamount $ concatMap tpostings ts lastdate | null ts = Nothing | otherwise = Just $ tdate $ last ts lastelapsed = maybe Nothing (Just . diffDays today) lastdate showelapsed Nothing = "" showelapsed (Just days) = printf " (%d %s)" days' direction where days' = abs days direction | days >= 0 = "days ago" :: String | otherwise = "days from now" tnum = length ts start (DateSpan (Just d) _) = show d start _ = "" end (DateSpan _ (Just d)) = show d end _ = "" days = fromMaybe 0 $ daysInSpan span txnrate | days==0 = 0 | otherwise = fromIntegral tnum / fromIntegral days :: Double tnum30 = length $ filter withinlast30 ts withinlast30 t = d >= addDays (-30) today && (d<=today) where d = tdate t txnrate30 = fromIntegral tnum30 / 30 :: Double tnum7 = length $ filter withinlast7 ts withinlast7 t = d >= addDays (-7) today && (d<=today) where d = tdate t txnrate7 = fromIntegral tnum7 / 7 :: Double acctnum = length as acctdepth | null as = 0 | otherwise = maximum $ map accountNameLevel as
ony/hledger
hledger/Hledger/Cli/Commands/Stats.hs
gpl-3.0
4,723
0
14
1,413
1,248
662
586
81
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} module Controllers.HomeController( ) where import Controller.Types(Action) import Controller(defaultControllerResponse, responseBadRequest) --import Routing(findRoute) import qualified DB
shinjiro-itagaki/shinjirecs
shinjirecs-api/src/Controllers/HomeController.hs
gpl-3.0
299
0
5
29
38
26
12
7
0
module P21NumToNameSpec (main,spec) where import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck((==>)) import Control.Exception(evaluate) -- for testing errors thrown by pure code import P21NumToName hiding (main) main :: IO () main = hspec spec spec :: Spec spec = do describe "getMonth" $ do it "gives January on input 1" $ getMonth 1 `shouldBe` "January" it "gives February on input 2" $ getMonth 2 `shouldBe` "February" it "gives March on input 3" $ getMonth 3 `shouldBe` "March" it "gives April on input 4" $ getMonth 4 `shouldBe` "April" it "gives May on input 5" $ getMonth 5 `shouldBe` "May" it "gives June on input 6" $ getMonth 6 `shouldBe` "June" it "gives July on input 7" $ getMonth 7 `shouldBe` "July" it "gives August on input 8" $ getMonth 8 `shouldBe` "August" it "gives September on input 9" $ getMonth 9 `shouldBe` "September" it "gives October on input 10" $ getMonth 10 `shouldBe` "October" it "gives November on input 11" $ getMonth 11 `shouldBe` "November" it "gives December on input 12" $ getMonth 12 `shouldBe` "December" it "gives error on input 0" $ evaluate (getMonth 0) `shouldThrow` errorCall "Unknown month" it "gives error on input 13" $ evaluate (getMonth 13) `shouldThrow` errorCall "Unknown month" prop "gives same result as getMonth' for any number 1..12" $ \m -> m>0 && m<13 ==> getMonth m `shouldBe` getMonth' m describe "getMonth'" $ do it "gives January on input 1" $ getMonth' 1 `shouldBe` "January" it "gives February on input 2" $ getMonth' 2 `shouldBe` "February" it "gives March on input 3" $ getMonth' 3 `shouldBe` "March" it "gives April on input 4" $ getMonth' 4 `shouldBe` "April" it "gives May on input 5" $ getMonth' 5 `shouldBe` "May" it "gives June on input 6" $ getMonth' 6 `shouldBe` "June" it "gives July on input 7" $ getMonth' 7 `shouldBe` "July" it "gives August on input 8" $ getMonth' 8 `shouldBe` "August" it "gives September on input 9" $ getMonth' 9 `shouldBe` "September" it "gives October on input 10" $ getMonth' 10 `shouldBe` "October" it "gives November on input 11" $ getMonth' 11 `shouldBe` "November" it "gives December on input 12" $ getMonth' 12 `shouldBe` "December" it "gives error on input 0" $ evaluate (getMonth' 0) `shouldThrow` errorCall "Map.!: given key is not an element in the map" it "gives error on input 13" $ evaluate (getMonth' 13) `shouldThrow` errorCall "Map.!: given key is not an element in the map"
ciderpunx/57-exercises-for-programmers
test/P21NumToNameSpec.hs
gpl-3.0
2,829
0
16
822
714
348
366
70
1
#! /usr/bin/env nix-shell #! nix-shell -i runhaskell #! nix-shell -E "let ghc = n.haskellPackages.ghcWithPackages (p: [p.base-unicode-symbols p.X11]); d = n.mkShell { buildInputs = [ghc]; }; n = import (fetchTarball { url = \"https://github.com/NixOS/nixpkgs/archive/a3fa481cb683d619ab9e1a64877f3c0c5fd24f40.tar.gz\"; sha256 = \"0y5dzi3npv13vyacmb4q93j0cpg6gjgvylq4ckjjvcb6szdsizqi\"; }) {}; in d" -- Author: Viacheslav Lotsmanov -- License: GNU/GPLv3 https://raw.githubusercontent.com/unclechu/place-cursor-at/master/LICENSE {-# OPTIONS_GHC -Wall -fprint-potential-instances #-} {-# LANGUAGE UnicodeSyntax, BangPatterns, MultiWayIf, ViewPatterns, ScopedTypeVariables, GADTs #-} {-# LANGUAGE LambdaCase, DerivingStrategies, GeneralizedNewtypeDeriving #-} import Prelude.Unicode ((∘), (÷), (≡), (⧺), (∧), (≥)) import Data.Bifunctor (first) import Data.Bits ((.|.)) import Data.Char (toUpper) import Data.Function (fix) import Data.Functor ((<&>)) import Data.List (find) import Numeric.Natural import Text.ParserCombinators.ReadP (satisfy) import Text.Read (ReadPrec, Read (readPrec), lift, choice, readMaybe) import Control.Applicative ((<|>)) import Control.Arrow ((***), (&&&)) import Control.Concurrent (forkFinally) import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar) import Control.Exception (SomeException, try, throwIO) import Control.Monad (forever, forM_, foldM, void) import System.Environment (getArgs) import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras ( SizeHints (..) , pMinSizeBit , pMaxSizeBit , changeProperty8 , propModeReplace , queryTree , getTextProperty , TextProperty (tp_value) , killClient ) import Graphics.X11.Xinerama ( xineramaQueryScreens , XineramaScreenInfo (..) ) import Foreign.C.String (castCharToCChar, peekCString) import Foreign.ForeignPtr (ForeignPtr, mallocForeignPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import Foreign.Ptr (Ptr) import Foreign.Storable (Storable (poke)) foreign import ccall unsafe "XlibExtras.h XSetWMNormalHints" xSetWMNormalHints ∷ Display → Window → Ptr SizeHints → IO () foreign import ccall unsafe "XlibExtras.h XSetWMSizeHints" xSetWMSizeHints ∷ Display → Window → Ptr SizeHints → Int → IO () s, w, h, letterPaddingX, letterPaddingY, offsetPercent ∷ Num a ⇒ a s = 40; w = s; h = s letterPaddingX = 10; letterPaddingY = 10 offsetPercent = 10 windowClassName ∷ String windowClassName = "place-cursor-at" data Pos = PosLT | PosCT | PosRT | PosLC | PosCC | PosRC | PosLB | PosCB | PosRB deriving stock (Eq, Show, Enum, Bounded) instance Read Pos where readPrec = go where go = choice $ lift <$> x insStr a b = void $ satisfy ((a ≡) ∘ toUpper) *> satisfy ((b ≡) ∘ toUpper) x = [ PosLT <$ insStr 'L' 'T', PosCT <$ insStr 'C' 'T', PosRT <$ insStr 'R' 'T' , PosLC <$ insStr 'L' 'C', PosCC <$ insStr 'C' 'C', PosRC <$ insStr 'R' 'C' , PosLB <$ insStr 'L' 'B', PosCB <$ insStr 'C' 'B', PosRB <$ insStr 'R' 'B' ] data Letter = Q | W | E | A | S | D | Z | X | C deriving stock (Eq, Show) letterToKeyCode ∷ Letter → KeyCode letterToKeyCode = \case Q → 24; W → 25; E → 26 A → 38; S → 39; D → 40 Z → 52; X → 53; C → 54 positionToLetter ∷ Pos → Letter positionToLetter = \case PosLT → Q; PosCT → W; PosRT → E PosLC → A; PosCC → S; PosRC → D PosLB → Z; PosCB → X; PosRB → C -- | Position relative to either X or Y axis data AbstractPos = MinPos -- ^ Left of Top | MiddlePos -- ^ Center | MaxPos -- ^ Right or Bottom deriving stock (Eq, Show) getAbstractPosX ∷ Pos → AbstractPos getAbstractPosX = \case PosLT → MinPos; PosLC → MinPos; PosLB → MinPos PosCT → MiddlePos; PosCC → MiddlePos; PosCB → MiddlePos PosRT → MaxPos; PosRC → MaxPos; PosRB → MaxPos getAbstractPosY ∷ Pos → AbstractPos getAbstractPosY = \case PosLT → MinPos; PosCT → MinPos; PosRT → MinPos PosLC → MiddlePos; PosCC → MiddlePos; PosRC → MiddlePos PosLB → MaxPos; PosCB → MaxPos; PosRB → MaxPos abstractPosToCoordinate ∷ Fractional a ⇒ a → AbstractPos → a abstractPosToCoordinate x = \case MinPos → x × offsetPercent ÷ 100 MiddlePos → x ÷ 2 MaxPos → x × (100 - offsetPercent) ÷ 100 -- | Command-line arguments data Argv = Argv { argvOnDisplay ∷ Maybe SpecificScreenNumber -- ^ Jump to specific display , argvToPosition ∷ Maybe Pos -- ^ Jump to specific position on screen (GUI wont be shown) } deriving stock (Show, Eq) emptyArgv ∷ Argv emptyArgv = Argv Nothing Nothing -- | Screen number that starts with 0. -- -- N.B. In "Read" and "Show" instances it starts with 1. -- When parsed or printed it either decrements or increments. newtype SpecificScreenNumber = SpecificScreenNumber { fromSpecificScreenNumber ∷ Natural } deriving newtype (Eq, Enum) -- | Prints wrapped number as a string. -- -- N.B. But printed number increments, it starts with 1 (instead of 0). instance Show SpecificScreenNumber where show = fromSpecificScreenNumber • succ • show -- | It reads screen number as plain number that starts with 1. -- -- N.B. Wrapped value is decremented. instance Read SpecificScreenNumber where readPrec = (readPrec ∷ ReadPrec Natural) >>= \x → if x ≡ 0 then fail $ unwords ["Incorrect screen number", show x, " (must start with 1)"] else pure ∘ pred ∘ SpecificScreenNumber $ x main ∷ IO () main = do doneHandler ← mkDoneHandler (dpy, rootWnd) ← (id &&& defaultRootWindow) <$> openDisplay "" killPreviousInstanceIfExists dpy (xsn, justGoToPos') ← let reducer argv x = case (readMaybe x <&> \x' → argv { argvOnDisplay = Just x' }) <|> (readMaybe x <&> \x' → argv { argvToPosition = Just x' }) of Just updatedArgv → pure updatedArgv Nothing → fail $ "Unexpected argument: " ⧺ show x in (getArgs >>= foldM reducer emptyArgv) <&> (argvOnDisplay &&& argvToPosition) !xsi ← getScreenInfo dpy xsn let xX, xY, xW, xH ∷ Rational relativeX, relativeY ∷ Pos → Rational from f = fromIntegral $ f xsi xX = from xsi_x_org xY = from xsi_y_org xW = from xsi_width xH = from xsi_height relativeX = getAbstractPosX • abstractPosToCoordinate xW relativeY = getAbstractPosY • abstractPosToCoordinate xH toPosition ∷ Rational → Position toPosition = fromInteger ∘ round windows ∷ [(Letter, (Position, Position))] windows = [minBound..maxBound] <&> \pos → let x, y ∷ Rational x = xX + relativeX pos - (w ÷ 2) y = xY + relativeY pos - (h ÷ 2) in (positionToLetter pos, (toPosition x, toPosition y)) places ∷ [(Pos, (Position, Position))] places = [minBound..maxBound] <&> \pos → let x, y ∷ Rational x = xX + relativeX pos y = xY + relativeY pos in (pos, (toPosition x, toPosition y)) case justGoToPos' of Just pos → case lookup pos places of Just (x, y) → do placeCursorAt dpy rootWnd x y closeDisplay dpy Nothing → fail $ "Unexpectedly fail to find a 'place' by " ⧺ show pos Nothing → do closeDisplay dpy let places' = places <&> first (letterToKeyCode ∘ positionToLetter) let done = doneWithIt doneHandler forM_ windows $ windowInstance (done (pure ())) places' • (`forkFinally` done) waitBeforeItIsDone doneHandler >>= either throwIO pure -- | Kill previous instance of *place-cursor-at* killPreviousInstanceIfExists ∷ Display → IO () killPreviousInstanceIfExists dpy = go where go = findPreyToKill (defaultRootWindow dpy) >>= mapM_ (killClient dpy) findPreyToKill ∷ Window → IO [Window] findPreyToKill = ($ []) $ fix $ \again acc !wnd → isPlaceCursorAtWindow wnd >>= \case False → foldM again acc =<< getChildWindows wnd True → slurpAllChildren acc wnd where slurpAllChildren acc !wnd = foldM slurpAllChildren (wnd : acc) =<< getChildWindows wnd getChildWindows ∷ Window → IO [Window] getChildWindows wnd = queryTree dpy wnd <&> \(_, _, x) → x isPlaceCursorAtWindow ∷ Window → IO Bool isPlaceCursorAtWindow wnd = x where x = try matchByWindowClass <&> either (const False ∷ IOError → Bool) id matchByWindowClass = getTextProperty dpy wnd wM_CLASS >>= tp_value • peekCString >>= (≡ windowClassName) • pure -- | Get info about screen either under cursor or specified by an argument. getScreenInfo ∷ Display → Maybe SpecificScreenNumber → IO XineramaScreenInfo getScreenInfo dpy specificScreen = go where xineramaFailureMsg = unwords [ "Could not obtain Xinerama screens information," , "check that libXinerama dependency is installed" , "and Xinerama X11 extension is active!" ] isSpecifiedScreen ∷ SpecificScreenNumber → XineramaScreenInfo → Bool isSpecifiedScreen (SpecificScreenNumber (toInteger • fromInteger → n)) = xsi_screen_number • (≡ n) isScreenUnderCursor ∷ (Integer, Integer) → XineramaScreenInfo → Bool isScreenUnderCursor (mX, mY) screenInfo = x where f = fromIntegral (x1, y1) = (f (xsi_x_org screenInfo), f (xsi_y_org screenInfo)) (x2, y2) = (x1 + f (xsi_width screenInfo), y1 + f (xsi_height screenInfo)) x = (mX ≥ x1 ∧ mY ≥ y1) ∧ (mX < x2 ∧ mY < y2) go = do screens ← xineramaQueryScreens dpy >>= maybe (fail xineramaFailureMsg) pure (predicateFn ∷ XineramaScreenInfo → Bool, failureMsg ∷ String) ← case specificScreen of Nothing → do mouseCoords ← mousePos dpy (defaultRootWindow dpy) <&> (fromIntegral *** fromIntegral) let failureMsg = unwords [ "Could not find a screen which is under cursor, something went wrong" , "(mouse position:", show mouseCoords ⧺ ", screens:", show screens ⧺ ")" ] pure (isScreenUnderCursor mouseCoords, failureMsg) Just screenNum → let failureMsg = unwords [ "Could not find screen number", show screenNum , "(by Xinerama screen number", show (fromSpecificScreenNumber screenNum) ⧺ ")," , "specified screen number is probably out of range" , "(screens:", show screens ⧺ ")" ] in pure (isSpecifiedScreen screenNum, failureMsg) maybe (fail failureMsg) pure (find predicateFn screens) windowInstance ∷ IO () → [(KeyCode, (Position, Position))] → (Letter, (Position, Position)) → IO () windowInstance done places (letter, (wndX, wndY)) = do dpy ← openDisplay "" let rootWnd = defaultRootWindow dpy screen = defaultScreen dpy gc = defaultGC dpy screen blackPx = blackPixel dpy screen whitePx = whitePixel dpy screen setLineAttributes dpy gc 3 0 0 0 -- Increase line thickness setForeground dpy gc whitePx let placeAt ∷ Position → Position → IO () placeAt = placeCursorAt dpy rootWnd wnd ← createSimpleWindow dpy rootWnd 0 0 w h 0 whitePx blackPx shPtr ← allocSH xSetWMNormalHints dpy wnd shPtr xSetWMSizeHints dpy wnd shPtr $ pMinSizeBit .|. pMaxSizeBit storeName dpy wnd $ "Place Cursor At [" ⧺ show letter ⧺ "]" changeProperty8 dpy wnd wM_CLASS sTRING propModeReplace $ castCharToCChar <$> windowClassName mapWindow dpy wnd placeWindowAt dpy wnd wndX wndY selectInput dpy wnd $ keyPressMask .|. exposureMask () <$ allocaXEvent (forever ∘ evLoop done dpy wnd gc placeAt letter places) allocSH ∷ IO (Ptr SizeHints) allocSH = go where go = malloc >>= unsafeForeignPtrToPtr • \ptr → ptr <$ poke ptr sh malloc ∷ IO (ForeignPtr SizeHints) malloc = mallocForeignPtr sh ∷ SizeHints sh = SizeHints { sh_min_size = Just (w, h) , sh_max_size = Just (w, h) , sh_resize_inc = Nothing , sh_aspect = Nothing , sh_base_size = Nothing , sh_win_gravity = Nothing } mousePos ∷ Display → Window → IO (Integer, Integer) mousePos dpy wnd = f <$> queryPointer dpy wnd where f (_, _, _, rootX, rootY, _, _, _) = (toInteger rootX, toInteger rootY) placeWindowAt ∷ Display → Window → Position → Position → IO () placeWindowAt dpy wnd x y = moveResizeWindow dpy wnd x y w h placeCursorAt ∷ Display → Window → Position → Position → IO () placeCursorAt dpy wnd x y = f where f = warpPointer dpy wnd wnd 0 0 0 0 x y evLoop ∷ IO () → Display → Window → GC → (Position → Position → IO ()) → Letter → [(KeyCode, (Position, Position))] → XEventPtr → IO () evLoop done dpy wnd gc placeAt letter places evPtr = do nextEvent dpy evPtr evType ← get_EventType evPtr let getKeyCode (_, _, _, _, _, _, _, _, keyCode, _) = keyCode if | evType ≡ keyPress → get_KeyEvent evPtr >>= getKeyCode • handleKey done placeAt places letter | evType ≡ expose → draw dpy wnd gc letter | otherwise → pure () handleKey ∷ IO () → (Position → Position → IO ()) → [(KeyCode, (Position, Position))] → Letter → KeyCode → IO () handleKey done placeAt places letter keyCode | keyCode ≡ 9 = done -- Escape | keyCode ≡ 36 = resolve ∘ letterToKeyCode $ letter -- Enter | otherwise = resolve keyCode where coordsByKeyCode keyCode' = snd <$> find ((≡ keyCode') ∘ fst) places resolve (coordsByKeyCode → Just coords) = uncurry placeAt coords >> done resolve _ = pure () data LinePointsRelativity = Absolute | Relative deriving stock (Eq, Show) data Line = Line LinePointsRelativity [Point] deriving stock (Eq, Show) draw ∷ Display → Window → GC → Letter → IO () draw dpy wnd gc (letterToLines → linesToRender) = forM_ linesToRender $ \(Line rel points) → let f n rescale = (round ∷ Rational → Position) ∘ rescale ∘ fromIntegral $ n rescaledPoints = points <&> \(Point x y) → Point (f x (× ((pred w - letterPaddingX × 2) ÷ 100))) (f y (× ((pred h - letterPaddingY × 2) ÷ 100))) coordMode = case rel of Absolute → coordModeOrigin Relative → coordModePrevious shiftPadding = case rel of Absolute → fmap shift Relative → \case (x : xs) → shift x : xs; [] → [] where shift (Point x y) = Point (x + letterPaddingX) (y + letterPaddingY) in drawLines dpy wnd gc (shiftPadding rescaledPoints) coordMode -- | Manually draw letters using simple lines. -- -- Coordinates are like percents, in range form 0 to 100. letterToLines ∷ Letter → [Line] letterToLines = \case Q → [ Line Absolute $ let spacer = 0 in [ Point roundCorner 0 , Point (100 - roundCorner) 0 , Point 100 roundCorner , Point 100 (100 - roundCorner - spacer) , Point (100 - roundCorner) (100 - spacer) , Point roundCorner (100 - spacer) , Point 0 (100 - spacer - roundCorner) , Point 0 roundCorner , Point roundCorner 0 ] , Line Relative [ Point 105 125 , Point (-50) (-50) ] ] W → [ Line Absolute [ Point 0 0 , Point 0 100 , Point 50 55 , Point 100 100 , Point 100 0 ] ] E → [ Line Absolute [ Point 110 0 , Point 0 0 , Point 0 45 , Point 110 45 ] , Line Absolute [ Point 0 50 , Point 0 100 , Point 110 100 ] ] A → [ Line Absolute [ Point 0 110 , Point 0 roundCorner , Point roundCorner 0 , Point (100 - roundCorner) 0 , Point 100 roundCorner , Point 100 110 ] , Line Absolute [ Point 0 60 , Point 100 60 ] ] S → [ Line Absolute [ Point 100 roundCorner , Point (100 - roundCorner) 0 , Point roundCorner 0 , Point 0 roundCorner , Point 0 (48 - roundCorner) , Point roundCorner 48 , Point (100 - roundCorner) 48 , Point 100 (48 + roundCorner) , Point 100 (100 - roundCorner) , Point (100 - roundCorner) 100 , Point roundCorner 100 , Point 0 (100 - roundCorner) ] ] D → [ Line Absolute $ let roundCorner' = (round ∷ Rational → Position) (fromIntegral roundCorner × (3/2)) in [ Point 0 0 , Point 0 100 , Point (100 - roundCorner') 100 , Point 100 (100 - roundCorner') , Point 100 roundCorner' , Point (100 - roundCorner') 0 , Point 0 0 ] ] Z → [ Line Absolute [ Point 0 0 , Point 90 0 , Point 5 100 , Point 105 100 ] ] X → [ Line Absolute [ Point 0 0 , Point 103 103 ] , Line Absolute [ Point 0 100 , Point 103 (-3) ] ] C → [ Line Absolute [ Point 100 (roundCorner + 8) , Point 100 roundCorner , Point (100 - roundCorner) 0 , Point roundCorner 0 , Point 0 roundCorner , Point 0 (100 - roundCorner) , Point roundCorner 100 , Point (100 - roundCorner) 100 , Point 100 (100 - roundCorner) , Point 100 (100 - (roundCorner + 8)) ] ] where roundCorner = 12 data DoneApi = DoneApi { doneWithIt ∷ Either SomeException () → IO () , waitBeforeItIsDone ∷ IO (Either SomeException ()) } mkDoneHandler ∷ IO DoneApi mkDoneHandler = newEmptyMVar <&> \mvar → DoneApi { doneWithIt = putMVar mvar , waitBeforeItIsDone = readMVar mvar } (•) ∷ (a → b) → (b → c) → a → c (•) = flip (∘) infixl 9 • {-# INLINE (•) #-} -- This operator is provided by newer version of ‘base-unicode-symbols’. -- This adds support for older snaphots. (×) ∷ Num a ⇒ a → a → a (×) = (Prelude.*) infixl 7 × {-# INLINE (×) #-}
unclechu/place-cursor-at
src/place-cursor-at.hs
gpl-3.0
18,643
0
22
5,085
5,599
2,984
2,615
-1
-1
{-# LANGUAGE CPP, OverloadedStrings #-} {-| hledger-web - a hledger add-on providing a web interface. Copyright (c) 2007-2012 Simon Michael <[email protected]> Released under GPL version 3 or later. -} module Hledger.Web.Main where -- yesod scaffold imports import Yesod.Default.Config --(fromArgs) -- import Yesod.Default.Main (defaultMain) import Settings -- (parseExtra) import Application (makeApplication) import Data.String import Network.Wai.Handler.Warp (runSettings, defaultSettings, setHost, setPort) import Network.Wai.Handler.Launch (runHostPortUrl) -- #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Control.Monad (when) import Data.Text (pack) import System.Exit (exitSuccess) import System.IO (hFlush, stdout) import Text.Printf import Prelude hiding (putStrLn) import Hledger import Hledger.Utils.UTF8IOCompat (putStrLn) import Hledger.Cli hiding (progname,prognameandversion) import Hledger.Web.WebOptions hledgerWebMain :: IO () hledgerWebMain = do opts <- getHledgerWebOpts when (debug_ (cliopts_ opts) > 0) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts) runWith opts runWith :: WebOpts -> IO () runWith opts | "help" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStr (showModeUsage webmode) >> exitSuccess | "version" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStrLn prognameandversion >> exitSuccess | "binary-filename" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStrLn (binaryfilename progname) | otherwise = do requireJournalFileExists =<< (head `fmap` journalFilePathFromOpts (cliopts_ opts)) -- XXX head should be safe for now withJournalDo' opts web withJournalDo' :: WebOpts -> (WebOpts -> Journal -> IO ()) -> IO () withJournalDo' opts cmd = do f <- head `fmap` journalFilePathFromOpts (cliopts_ opts) -- XXX head should be safe for now -- https://github.com/simonmichael/hledger/issues/202 -- -f- gives [Error#yesod-core] <stdin>: hGetContents: illegal operation (handle is closed) for some reason -- Also we may be writing to this file. Just disallow it. when (f == "-") $ error' "hledger-web doesn't support -f -, please specify a file path" readJournalFile Nothing Nothing True f >>= either error' (cmd opts . journalApplyAliases (aliasesFromOpts $ cliopts_ opts)) -- | The web command. web :: WebOpts -> Journal -> IO () web opts j = do d <- getCurrentDay let initq = queryFromOpts d $ reportopts_ $ cliopts_ opts j' = filterJournalTransactions initq j h = host_ opts p = port_ opts u = base_url_ opts staticRoot = pack <$> file_url_ opts appconfig = AppConfig{appEnv = Development ,appHost = fromString h ,appPort = p ,appRoot = pack u ,appExtra = Extra "" Nothing staticRoot } app <- makeApplication opts j' appconfig -- XXX would like to allow a host name not just an IP address here _ <- printf "Starting web app on IP address %s port %d with base url %s\n" h p u if serve_ opts then do putStrLn "Press ctrl-c to quit" hFlush stdout let warpsettings = setHost (fromString h) $ setPort p $ defaultSettings Network.Wai.Handler.Warp.runSettings warpsettings app else do putStrLn "Starting web browser..." putStrLn "Web app will auto-exit after a few minutes with no browsers (or press ctrl-c)" hFlush stdout Network.Wai.Handler.Launch.runHostPortUrl h p "" app
mstksg/hledger
hledger-web/Hledger/Web/Main.hs
gpl-3.0
3,613
0
17
823
837
437
400
68
2
module Nacc where import Data.List --import Data.Tuple.Select import Text.Printf import Types import Utils alt :: Acc -> [Nacc] -> Acc alt acc naccs = altAcc where nacc = find (\n -> acc == (ncAcc n)) naccs altAcc = case nacc of Just n -> ncAlt n Nothing -> "Error: couldn't find alt nacc" -- FIXME do better than this showAcc :: Acc -> String showAcc acc = printf "%-6.6s" acc showNaccAcc :: Nacc -> String showNaccAcc nacc = showAcc $ ncAcc nacc showNacc :: Nacc -> String showNacc nacc = let Nacc _ acc _ _ desc = nacc in (showAcc acc) ++ " " ++ desc --printf "%-6.6s %s" acc desc
blippy/sifi
src/Nacc.hs
gpl-3.0
624
0
12
152
206
108
98
20
2
-- Tests the assembler by reading in the files from the ASM program directory -- and testing the assembled result against the matching files in the HACK program directory import Hack.Assembler import Control.Arrow ((***)) import Control.Monad (when) import Data.Char (digitToInt) import Data.Word (Word16) import System.Directory (getCurrentDirectory) import System.FilePath ((</>)) assert :: Bool -> a -> a assert False x = error "Assert failed!" assert True x = x bin2wrd :: String -> Word16 bin2wrd s = foldl (\a b -> 2 * a + fromIntegral (digitToInt b)) 0 $ dropWhile (=='0') s readHack :: String -> [Word16] readHack s = map bin2wrd $ lines s readAsm :: FilePath -> String -> [Word16] readAsm n s = either (\a -> error (show (("Failed during parsing step in " ++ n):a))) (either (\b -> error (show (("Failed during assembling step in " ++ n):b))) id . assemble) $ parseAssembly s readPair :: (FilePath,FilePath) -> IO ((FilePath,String),(FilePath,String)) readPair (a,b) = do am <- readFile a bm <- readFile b return ((a,am),(b,bm)) main = do cwd <- getCurrentDirectory let dirasm = cwd </> "programs" </> "asm" let dirhack = cwd </> "programs" </> "hack" let filepairs = [("add.asm","add.hack") ,("max.asm","max.hack"),("MaxL.asm","max.hack") ,("pong.asm","pong.hack"),("PongL.asm","pong.hack") ,("rect.asm","rect.hack"),("RectL.asm","rect.hack")] let filepaths = map ((</>) dirasm *** (</>) dirhack) filepairs contentpairs <- mapM readPair filepaths let wordpairs = map (\((an,a),(bn,b)) -> ((an,readAsm an a), (bn,readHack b))) contentpairs mapM_ (\((an,a),(_,b)) -> when (a /= b) $ error ("Incorrect assembly result for " ++ an)) wordpairs
goakley/Hackskell
src/tests/test_assembler.hs
gpl-3.0
1,735
0
18
327
691
380
311
33
1
module Math.Structure.Ring.Division where import Prelude hiding ( (+), (-), negate, subtract , (*), (/), recip, (^), (^^) ) import Math.Structure.Additive import Math.Structure.Multiplicative import Math.Structure.Ring.Integral class (IntegralDomain r, MultiplicativeGroup (NonZero r)) => DivisionRing r
martinra/algebraic-structures
src/Math/Structure/Ring/Division.hs
gpl-3.0
353
2
8
82
100
67
33
-1
-1
-- Copyright © 2014 Bart Massey -- Based on material Copyright © 2013 School of Haskell -- https://www.fpcomplete.com/school/advanced-haskell/ -- building-a-file-hosting-service-in-yesod -- This work is made available under the "GNU AGPL v3", as -- specified the terms in the file COPYING in this -- distribution. {-# LANGUAGE OverloadedStrings #-} module Handler.Down where import Data.Text import Data.Text.Encoding import Text.Printf import Yesod import Foundation getDownR :: Int -> Handler TypedContent getDownR faid = do fa <- getById faid let mime = encodeUtf8 $ pack $ fileAssocMime fa let conts = toContent $ fileAssocContents fa addHeader "Content-Disposition" $ pack $ printf "attachment; filename=\"%s\"" $ fileAssocName fa sendResponse (mime, conts)
BartMassey/hgallery
Handler/Down.hs
agpl-3.0
802
0
11
142
138
72
66
15
1
{-# LANGUAGE OverloadedStrings, TemplateHaskell, TypeFamilies #-} module Model.Party.Types ( PartyRow(..) , Party(..) , Loaded(..) , loadedToMaybe , Account(..) , getPartyId , SiteAuth(..) , nobodyParty , rootParty , staffParty , nobodySiteAuth , blankParty , blankAccount ) where import qualified Data.ByteString as BS import qualified Data.Text as T import Instances.TH.Lift () import Language.Haskell.TH.Lift (deriveLiftMany) import Has (Has(..)) import Model.URL (URI) import Model.Kind import Model.Id.Types import Model.Permission.Types import Model.ORCID type instance IdType Party = Int32 data PartyRow = PartyRow { partyId :: Id Party , partySortName :: T.Text , partyPreName :: Maybe T.Text , partyORCID :: Maybe ORCID , partyAffiliation :: Maybe T.Text , partyURL :: Maybe URI } -- deriving (Show) -- (Eq) -- | Represents users, institutions, labs, *and* groups. data Party = Party { partyRow :: !PartyRow , partyAccount :: Maybe Account -- , partySiteAccess :: Access -- site-level access this party is granted under root (currently SiteAuth only) , partySiteAccess :: !(Loaded Permission) -- ^ See accessSite' field of Access type. -- Only some queries populate (load) this value. , partyPermission :: Permission -- ^ permission current user has over this party , partyAccess :: Maybe Access -- ^ direct authorization this party has granted to current user } -- | When loading a graph of objects, some queries will neglect loading -- all related objects. Use this type to indicate an object which isn't loaded -- by all queries. data Loaded a = -- TODO: move this to a utility module when used more widely Loaded a | NotLoaded -- | Transform a Loaded value into the a Maybe value loadedToMaybe :: Loaded a -> Maybe a loadedToMaybe (Loaded v) = Just v loadedToMaybe NotLoaded = Nothing data Account = Account { accountEmail :: BS.ByteString , accountParty :: Party } instance Has (Id Party) Party where view = getPartyId getPartyId :: Party -> Id Party getPartyId = partyId . partyRow instance Has Party Account where view = accountParty instance Has (Id Party) Account where view = getPartyId . accountParty instance Has Access Party where view Party{ partyAccess = Just a } = a view _ = mempty instance Kinded Party where kindOf _ = "party" -- | TODO: clarify. This is not necessarily a session, but... some user (human -- being) who has been granted access to the site. There is a corner case -- indirection because sometimes a job runs a human being. data SiteAuth = SiteAuth { siteAccount :: Account -- ^ maybe should be Party (for nobody) , accountPasswd :: Maybe BS.ByteString , siteAccess :: Access -- ^ Still figuring out what an 'Access' is. } instance Has Account SiteAuth where view = siteAccount instance Has Party SiteAuth where view = view . siteAccount instance Has (Id Party) SiteAuth where view = view . siteAccount instance Has Access SiteAuth where view = siteAccess deriveLiftMany [''PartyRow, ''Party, ''Account, ''Loaded] -- The values below assume a minimalist loading of each object, with no -- related objects loaded. nobodyParty, rootParty, staffParty :: Party -- TODO: load on startup from service module nobodyParty = Party (PartyRow (Id (-1)) (T.pack "Everybody") Nothing Nothing Nothing Nothing) Nothing NotLoaded PermissionREAD Nothing rootParty = Party (PartyRow (Id 0) (T.pack "Databrary") Nothing Nothing Nothing Nothing) Nothing NotLoaded PermissionSHARED Nothing staffParty = Party (PartyRow (Id 2) (T.pack "Staff") Nothing Nothing (Just (T.pack "Databrary")) Nothing) Nothing NotLoaded PermissionPUBLIC Nothing -- this is unfortunate, mainly to avoid untangling Party.SQL nobodySiteAuth :: SiteAuth nobodySiteAuth = SiteAuth { siteAccount = Account { accountEmail = "[email protected]" , accountParty = Party { partyRow = PartyRow { partyId = Id (-1) , partySortName = "Nobody" , partyPreName = Nothing , partyORCID = Nothing , partyAffiliation = Nothing , partyURL = Nothing } , partyAccount = Nothing , partySiteAccess = NotLoaded , partyPermission = PermissionREAD , partyAccess = Just minBound } } , accountPasswd = Nothing , siteAccess = mempty } -- | Uninitialized Party object to be used in creating new parties (and accounts) blankParty :: Party blankParty = Party { partyRow = PartyRow { partyId = error "blankParty" , partySortName = "" , partyPreName = Nothing , partyORCID = Nothing , partyAffiliation = Nothing , partyURL = Nothing } , partyAccount = Nothing , partySiteAccess = NotLoaded , partyPermission = PermissionNONE , partyAccess = Nothing } -- | Uninitialized Account object to be used in creating new accounts blankAccount :: Account blankAccount = Account { accountParty = blankParty{ partyAccount = Just blankAccount } , accountEmail = error "blankAccount" }
databrary/databrary
src/Model/Party/Types.hs
agpl-3.0
5,196
0
15
1,197
1,058
621
437
-1
-1
-- -- Copyright (C) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -- USA -- -- -- | Evaluate Haskell at runtime, using runtime compilation and dynamic -- loading. Arguments are compiled to native code, and dynamically -- loaded, returning a Haskell value representing the compiled argument. -- The underlying implementation treats 'String' arguments as the source -- for plugins to be compiled at runtime. -- module System.Eval.Haskell ( eval, eval_, unsafeEval, unsafeEval_, typeOf, mkHsValues, {- hs_eval_b, -- return a Bool hs_eval_c, -- return a CChar hs_eval_i, -- return a CInt hs_eval_s, -- return a CString -} module System.Eval.Utils, ) where import System.Eval.Utils import System.Plugins.Make import System.Plugins.Load import Data.Dynamic ( Dynamic ) import Data.Typeable ( Typeable ) import Data.Either ( ) import Data.Map as Map import Data.Char import System.IO ( ) import System.Directory import System.Random import System.IO.Unsafe -- import Foreign.C -- import Foreign -- | 'eval' provides a typesafe (to a limit) form of runtime evaluation -- for Haskell -- a limited form of /runtime metaprogramming/. The -- 'String' argument to 'eval' is a Haskell source fragment to evaluate -- at rutime. @imps@ are a list of module names to use in the context of -- the compiled value. -- -- The value returned by 'eval' is constrained to be 'Typeable' -- -- meaning we can perform a /limited/ runtime typecheck, using the -- 'dynload' function. One consequence of this is that the code must -- evaluate to a monomorphic value (which will be wrapped in a -- 'Dynamic'). -- -- If the evaluated code typechecks under the 'Typeable' constraints, -- 'Just v' is returned. 'Nothing' indicates typechecking failed. -- Typechecking may fail at two places: when compiling the argument, or -- when typechecking the splice point. 'eval' resembles a -- metaprogramming 'run' operator for /closed/ source fragments. -- -- To evaluate polymorphic values you need to wrap them in data -- structures using rank-N types. -- -- Examples: -- -- > do i <- eval "1 + 6 :: Int" [] :: IO (Maybe Int) -- > when (isJust i) $ putStrLn (show (fromJust i)) -- eval :: Typeable a => String -> [Import] -> IO (Maybe a) eval src imps = do pwd <- getCurrentDirectory (cmdline,loadpath) <- getPaths tmpf <- mkUniqueWith dynwrap src imps status <- make tmpf cmdline m_rsrc <- case status of MakeSuccess _ obj -> do m_v <- dynload obj [pwd] loadpath symbol case m_v of LoadFailure _ -> return Nothing LoadSuccess _ rsrc -> return $ Just rsrc MakeFailure err -> mapM_ putStrLn err >> return Nothing makeCleaner tmpf return m_rsrc -- -- | 'eval_' is a variety of 'eval' with all the internal hooks -- available. You are able to set any extra arguments to the compiler -- (for example, optimisation flags) or dynamic loader, as well as -- having any errors returned in an 'Either' type. -- eval_ :: Typeable a => String -- ^ code to compile -> [Import] -- ^ any imports -> [String] -- ^ extra make flags -> [FilePath] -- ^ (package.confs) for load -> [FilePath] -- ^ include paths load is to search in -> IO (Either [String] (Maybe a)) -- ^ either errors, or maybe a well typed value eval_ src mods args ldflags incs = do pwd <- getCurrentDirectory (cmdline,loadpath) <- getPaths -- find path to altdata tmpf <- mkUniqueWith dynwrap src mods status <- make tmpf $ ["-O0"] ++ cmdline ++ args m_rsrc <- case status of MakeSuccess _ obj -> do m_v <- dynload obj (pwd:incs) (loadpath++ldflags) symbol return $ case m_v of LoadFailure e -> Left e LoadSuccess _ rsrc -> Right (Just rsrc) MakeFailure err -> return $ Left err makeCleaner tmpf return m_rsrc -- | Sometimes when constructing string fragments to evaluate, the -- programmer is able to provide some other constraint on the evaluated -- string, such that the evaluated expression will be typesafe, without -- requiring a 'Typeable' constraint. In such cases, the monomorphic -- restriction is annoying. 'unsafeEval' removes any splice-point -- typecheck, with an accompanying obligation on the programmer to -- ensure that the fragment evaluated will be typesafe at the point it -- is spliced. -- -- An example of how to do this would be to wrap the fragment in a call -- to 'show'. The augmented fragment would then be checked when compiled -- to return a 'String', and the programmer can rely on this, without -- requiring a splice-point typecheck, and thus no 'Typeable' -- restriction. -- -- Note that if you get the proof wrong, your program will likely -- segfault. -- -- Example: -- -- > do s <- unsafeEval "map toUpper \"haskell\"" ["Data.Char"] -- > when (isJust s) $ putStrLn (fromJust s) -- unsafeEval :: String -> [Import] -> IO (Maybe a) unsafeEval src mods = do pwd <- getCurrentDirectory tmpf <- mkUniqueWith wrap src mods status <- make tmpf [] m_rsrc <- case status of MakeSuccess _ obj -> do m_v <- load obj [pwd] [] symbol case m_v of LoadFailure _ -> return Nothing LoadSuccess _ rsrc -> return $ Just rsrc MakeFailure err -> mapM_ putStrLn err >> return Nothing makeCleaner tmpf return m_rsrc -- -- | 'unsafeEval_' is a form of 'unsafeEval' with all internal hooks -- exposed. This is useful for application wishing to return error -- messages to users, to specify particular libraries to link against -- and so on. -- unsafeEval_ :: String -- ^ code to compile -> [Import] -- ^ any imports -> [String] -- ^ make flags -> [FilePath] -- ^ (package.confs) for load -> [FilePath] -- ^ include paths load is to search in -> IO (Either [String] a) unsafeEval_ src mods args ldflags incs = do pwd <- getCurrentDirectory tmpf <- mkUniqueWith wrap src mods status <- make tmpf args e_rsrc <- case status of MakeSuccess _ obj -> do m_v <- load obj (pwd:incs) ldflags symbol case m_v of LoadFailure e -> return $ Left e LoadSuccess _ rsrc -> return $ Right rsrc MakeFailure err -> return $ Left err makeCleaner tmpf return e_rsrc ------------------------------------------------------------------------ -- -- | 'mkHsValues' is a helper function for converting 'Data.Map's -- of names and values into Haskell code. It relies on the assumption of -- names and values into Haskell code. It relies on the assumption that -- the passed values' Show instances produce valid Haskell literals -- (this is true for all Prelude types). -- mkHsValues :: (Show a) => Map.Map String a -> String mkHsValues values = concat $ elems $ Map.mapWithKey convertToHs values where convertToHs :: (Show a) => String -> a -> String convertToHs name value = name ++ " = " ++ show value ++ "\n" ------------------------------------------------------------------------ -- -- | Return a compiled value's type, by using Dynamic to get a -- representation of the inferred type. -- typeOf :: String -> [Import] -> IO String typeOf src mods = do pwd <- getCurrentDirectory (cmdline,loadpath) <- getPaths tmpf <- mkUniqueWith dynwrap src mods status <- make tmpf cmdline ty <- case status of MakeSuccess _ obj -> do m_v <- load obj [pwd] loadpath symbol :: IO (LoadStatus Dynamic) case m_v of LoadFailure _ -> return "<failure>" LoadSuccess _ v -> return $ (init . tail) $ show v MakeFailure err -> mapM_ putStrLn err >> return [] makeCleaner tmpf return ty dynwrap :: String -> String -> [Import] -> String dynwrap expr nm mods = "module "++nm++ "( resource ) where\n" ++ concatMap (\m-> "import "++m++"\n") mods ++ "import Data.Dynamic\n" ++ "resource = let { "++x++" = \n" ++ "{-# LINE 1 \"<eval>\" #-}\n" ++ expr ++ ";} in toDyn "++x where x = ident () ident () = unsafePerformIO $ sequence (take 3 (repeat $ getStdRandom (randomR (97,122)) >>= return . chr)) -- --------------------------------------------------------------------- -- unsafe wrapper -- wrap :: String -> String -> [Import] -> String wrap expr nm mods = "module "++nm++ "( resource ) where\n" ++ concatMap (\m-> "import "++m++"\n") mods ++ "resource = let { "++x++" = \n" ++ "{-# LINE 1 \"<Plugins.Eval>\" #-}\n" ++ expr ++ ";} in "++x where x = ident () -- what is this big variable name? -- its a random value, so that it won't clash if the accidently mistype -- an unbound 'x' or 'v' in their code.. it won't reveal the internal -- structure of the wrapper, which is annoying in irc use by lambdabot {- ------------------------------------------------------------------------ -- -- And for our friends in foreign parts -- -- TODO needs to accept char** to import list -- -- -- return NULL pointer if an error occured. -- foreign export ccall hs_eval_b :: CString -> IO (Ptr CInt) foreign export ccall hs_eval_c :: CString -> IO (Ptr CChar) foreign export ccall hs_eval_i :: CString -> IO (Ptr CInt) foreign export ccall hs_eval_s :: CString -> IO CString ------------------------------------------------------------------------ -- -- TODO implement a marshalling for Dynamics, so that we can pass that -- over to the C side for checking. -- hs_eval_b :: CString -> IO (Ptr CInt) hs_eval_b s = do m_v <- eval_cstring s case m_v of Nothing -> return nullPtr Just v -> new (fromBool v) hs_eval_c :: CString -> IO (Ptr CChar) hs_eval_c s = do m_v <- eval_cstring s case m_v of Nothing -> return nullPtr Just v -> new (castCharToCChar v) -- should be Integral hs_eval_i :: CString -> IO (Ptr CInt) hs_eval_i s = do m_v <- eval_cstring s :: IO (Maybe Int) case m_v of Nothing -> return nullPtr Just v -> new (fromIntegral v :: CInt) hs_eval_s :: CString -> IO CString hs_eval_s s = do m_v <- eval_cstring s case m_v of Nothing -> return nullPtr Just v -> newCString v -- -- convenience -- eval_cstring :: Typeable a => CString -> IO (Maybe a) eval_cstring cs = do s <- peekCString cs eval s [] -- TODO use eval() -}
sheganinans/plugins
src/System/Eval/Haskell.hs
lgpl-2.1
11,677
0
19
3,114
1,674
879
795
121
3
-- | Tutorial example based on -- http://haskell-distributed-next.github.io/tutorials/ch-tutorial1.html import Control.Concurrent (threadDelay) import Control.Monad (forever) import Control.Distributed.Process import Control.Distributed.Process.Node import Network.Transport.TCP (createTransport, defaultTCPParameters) replyBack :: (ProcessId, String) -> Process () replyBack (sender, msg) = send sender msg logMessage :: String -> Process () logMessage msg = say $ "handling " ++ msg main :: IO () main = do Right t <- createTransport "127.0.0.1" "10501" defaultTCPParameters node <- newLocalNode t initRemoteTable forkProcess node $ do -- Spawn another worker on the local node echoPid <- spawnLocal $ forever $ do -- Test our matches in order against each message in the queue receiveWait [match logMessage, match replyBack] -- The `say` function sends a message to a process registered as "logger". -- By default, this process simply loops through its mailbox and sends -- any received log message strings it finds to stderr. say "send some messages!" send echoPid "hello" self <- getSelfPid send echoPid (self, "hello") -- `expectTimeout` waits for a message or times out after "delay" m <- expectTimeout 1000000 case m of -- Die immediately - throws a ProcessExitException with the given reason. Nothing -> die "nothing came back!" (Just s) -> say $ "got " ++ s ++ " back!" return () -- A 1 second wait. Otherwise the main thread can terminate before -- our messages reach the logging process or get flushed to stdio liftIO $ threadDelay (1*1000000) return ()
alanz/cloud-haskell-play
src/tut1.hs
unlicense
1,672
0
16
340
333
168
165
27
2
fib = (!!) fibs . pred where fibs = 0 : 1 : map f [2..] f n = (fibs !! (n - 2)) + (fibs !! (n - 1)) -- This part is related to the Input/Output and can be used as it is -- Do not modify it main = do input <- getLine print . fib . (read :: String -> Int) $ input
itsbruce/hackerrank
func/recur/fibs.hs
unlicense
285
0
11
90
117
63
54
6
1
module Palindromes.A298481 (a298481)where import Helpers.PalindromicPartition (binaryRepresentation, postPalindromeTails) a298481 :: Int -> Int a298481 n = recurse 0 [binaryRepresentation n] where recurse k tails | count > 0 = count | otherwise = recurse (k + 1) (concatMap postPalindromeTails tails) where count = length $ filter (=="") tails
peterokagey/haskellOEIS
src/Palindromes/A298481.hs
apache-2.0
362
0
11
65
123
64
59
8
1
{-# LANGUAGE TypeFamilies, TypeOperators, FlexibleContexts, MultiParamTypeClasses, FlexibleInstances, ScopedTypeVariables, UndecidableInstances #-} {- | Module : Data.YokoRaw Copyright : (c) The University of Kansas 2012 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : see LANGUAGE pragmas (... GHC) This is the entire library, excluding the fancy builder of precise cases from "Data.Yoko.SmartPreciseCase". -} module Data.YokoRaw (module Data.Yoko.Representation, module Data.Yoko.View, -- * Building fields type consumers one, (|||), (||.), (.||), (.|.), -- * Operations on disbanded data types disbanded, band, ConDCOf, precise_case, -- * Operations on sums of fields types (:-:), Embed, Partition, embed, inject, partition, project, -- * Forgetting @yoko@'s extra structure reps, EachGeneric, EachRep, ig_from, Equal, -- * Bundled Template Haskell module Data.Yoko.TH) where import Data.Yoko.TypeBasics import Data.Yoko.Representation import Data.Yoko.View import Data.Yoko.TypeSums (Embed, Partition, (:-:)) import qualified Data.Yoko.TypeSums as TypeSums import Data.Yoko.Each import Data.Yoko.TH -- | @one@ extends a function that consumes a fields type to a function that -- consumes a disbanded data type containing just that fields type. one :: (dc -> a) -> N dc -> a one = foldN infixl 6 ||| -- | Combines two functions that consume disbanded data types into a function -- that consumes their union. All fields types must be from the same data type. (|||) :: (Codomain sumL ~ Codomain sumR) => (sumL -> a) -> (sumR -> a) -> sumL :+: sumR -> a (|||) = foldPlus infixl 9 .|. infixr 8 .||, ||. -- | @f .|. g = one f '|||' one g@ f .|. g = one f ||| one g -- | @f .|| g = one f '|||' g@ f .|| g = one f ||| g -- | @f ||. g = f '|||' one g@ f ||. g = f ||| one g -- | @disbanded@ injects a fields type into its disbanded range disbanded :: Embed (N dc) (DCs (Codomain dc)) => dc -> DCs (Codomain dc) disbanded = TypeSums.inject -- | @band@s a disbanded data type back into its normal data type. -- -- Since 'Disbanded' is a type family, the range of @band@ determines the @t@ -- type variable. band :: forall t. Each (ConDCOf t) (DCs t) => DCs t -> t band = each (Proxy :: Proxy (ConDCOf t)) rejoin class (Codomain dc ~ t, DC dc) => ConDCOf t dc instance (Codomain dc ~ t, DC dc) => ConDCOf t dc embed :: (Codomain sub ~ Codomain sup, Embed sub sup) => sub -> sup embed = TypeSums.embed -- | @inject@s a fields type into a sum of fields types. inject :: Embed (N dc) sum => dc -> sum inject = TypeSums.inject -- | @partition@s a sum of fields type into a specified sum of fields types and -- the remaining sum. partition :: (Codomain sum ~ Codomain sub, Partition sum sub (sum :-: sub)) => sum -> Either sub (sum :-: sub) partition = TypeSums.partition -- | @project@s a single fields type out of a disbanded data type. project :: (Codomain sum ~ Codomain dc, Partition sum (N dc) (sum :-: N dc)) => sum -> Either dc (sum :-: N dc) project = TypeSums.project -- TODO need a MapSum just like MapRs, use a RPV for rep -- | @reps@ maps a disbanded data type to its sum-of-products representation. reps :: EachGeneric sum => sum -> EachRep sum reps = repEach type family EachRep sum type instance EachRep (N a) = Rep a type instance EachRep (a :+: b) = EachRep a :+: EachRep b class EachGeneric sum where repEach :: sum -> EachRep sum ; objEach :: EachRep sum -> sum instance Generic a => EachGeneric (N a) where repEach (N x) = rep x ; objEach = N . obj instance (EachGeneric a, EachGeneric b) => EachGeneric (a :+: b) where repEach = mapPlus repEach repEach objEach = mapPlus objEach objEach -- | @precise_case@ is an exactly-typed case: the second argument is the -- discriminant, the first argument is the default case, and the third argument -- approximates a list of alternatives. -- -- @ -- precise_case default x $ -- (\(C0_ ...) -> ...) '.||' -- (\(C1_ ...) -> ...) '.|.' -- (\(C2_ ...) -> ...) -- @ -- -- In this example, @C0_@, @C1_@, and @C2_@ are fields types. The other fields -- types for the same data type are handled with the @default@ function. precise_case :: (Codomain dcs ~ t, Codomain (DCs t) ~ t, DT t, Partition (DCs t) dcs (DCs t :-: dcs)) => (DCs t :-: dcs -> a) -> t -> (dcs -> a) -> a precise_case g x f = either f g $ partition $ disband x -- | @ig_from x =@ 'reps $ disband' @x@ is a convenience. It approximates the -- @instant-generics@ view, less the @CEq@ annotations. ig_from :: (DT t, EachGeneric (DCs t)) => t -> EachRep (DCs t) ig_from x = reps $ disband x
nfrisby/yoko
Data/YokoRaw.hs
bsd-2-clause
4,705
0
10
982
1,136
627
509
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Opengl.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:14 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Opengl ( module Qtc.Classes.Opengl , module Qtc.Classes.Opengl_h , module Qtc.ClassTypes.Opengl , module Qtc.Enums.Opengl.QGL , module Qtc.Opengl.QGLColormap , module Qtc.Opengl.QGLContext , module Qtc.Opengl.QGLContext_h , module Qtc.Opengl.QGLFormat , module Qtc.Enums.Opengl.QGLFormat , module Qtc.Opengl.QGLFramebufferObject , module Qtc.Opengl.QGLFramebufferObject_h , module Qtc.Enums.Opengl.QGLFramebufferObject , module Qtc.Opengl.QGLPixelBuffer , module Qtc.Opengl.QGLPixelBuffer_h , module Qtc.Opengl.QGLWidget , module Qtc.Opengl.QGLWidget_h ) where import Qtc.ClassTypes.Opengl import Qtc.Classes.Opengl import Qtc.Classes.Opengl_h import Qtc.Enums.Opengl.QGL import Qtc.Opengl.QGLColormap import Qtc.Opengl.QGLContext import Qtc.Opengl.QGLContext_h import Qtc.Opengl.QGLFormat import Qtc.Enums.Opengl.QGLFormat import Qtc.Opengl.QGLFramebufferObject import Qtc.Opengl.QGLFramebufferObject_h import Qtc.Enums.Opengl.QGLFramebufferObject import Qtc.Opengl.QGLPixelBuffer import Qtc.Opengl.QGLPixelBuffer_h import Qtc.Opengl.QGLWidget import Qtc.Opengl.QGLWidget_h
uduki/hsQt
Qtc/Opengl.hs
bsd-2-clause
1,533
0
5
196
226
159
67
34
0
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QDialog.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:14 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QDialog ( QqDialog(..) ,result ,setModal ,setResult ,showExtension ,qDialog_delete ,qDialog_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QDialog ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QDialog_userMethod" qtc_QDialog_userMethod :: Ptr (TQDialog a) -> CInt -> IO () instance QuserMethod (QDialogSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QDialog_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QDialog ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QDialog_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QDialog_userMethodVariant" qtc_QDialog_userMethodVariant :: Ptr (TQDialog a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QDialogSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QDialog_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqDialog x1 where qDialog :: x1 -> IO (QDialog ()) instance QqDialog (()) where qDialog () = withQDialogResult $ qtc_QDialog foreign import ccall "qtc_QDialog" qtc_QDialog :: IO (Ptr (TQDialog ())) instance QqDialog ((QWidget t1)) where qDialog (x1) = withQDialogResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog1 cobj_x1 foreign import ccall "qtc_QDialog1" qtc_QDialog1 :: Ptr (TQWidget t1) -> IO (Ptr (TQDialog ())) instance QqDialog ((QWidget t1, WindowFlags)) where qDialog (x1, x2) = withQDialogResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog2 cobj_x1 (toCLong $ qFlags_toInt x2) foreign import ccall "qtc_QDialog2" qtc_QDialog2 :: Ptr (TQWidget t1) -> CLong -> IO (Ptr (TQDialog ())) instance Qaccept (QDialog ()) (()) where accept x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_accept_h cobj_x0 foreign import ccall "qtc_QDialog_accept_h" qtc_QDialog_accept_h :: Ptr (TQDialog a) -> IO () instance Qaccept (QDialogSc a) (()) where accept x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_accept_h cobj_x0 instance QadjustPosition (QDialog ()) ((QWidget t1)) where adjustPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_adjustPosition cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_adjustPosition" qtc_QDialog_adjustPosition :: Ptr (TQDialog a) -> Ptr (TQWidget t1) -> IO () instance QadjustPosition (QDialogSc a) ((QWidget t1)) where adjustPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_adjustPosition cobj_x0 cobj_x1 instance QcloseEvent (QDialog ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_closeEvent_h" qtc_QDialog_closeEvent_h :: Ptr (TQDialog a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QDialogSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_closeEvent_h cobj_x0 cobj_x1 instance QcontextMenuEvent (QDialog ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_contextMenuEvent_h" qtc_QDialog_contextMenuEvent_h :: Ptr (TQDialog a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QDialogSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_contextMenuEvent_h cobj_x0 cobj_x1 instance Qdone (QDialog ()) ((Int)) where done x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_done_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QDialog_done_h" qtc_QDialog_done_h :: Ptr (TQDialog a) -> CInt -> IO () instance Qdone (QDialogSc a) ((Int)) where done x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_done_h cobj_x0 (toCInt x1) instance Qevent (QDialog ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_event_h" qtc_QDialog_event_h :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QDialogSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_event_h cobj_x0 cobj_x1 instance QeventFilter (QDialog ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDialog_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDialog_eventFilter" qtc_QDialog_eventFilter :: Ptr (TQDialog a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QDialogSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDialog_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDialog_eventFilter_h" qtc_QDialog_eventFilter_h :: Ptr (TQDialog a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance Qexec (QDialog a) (()) (IO (Int)) where exec x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_exec cobj_x0 foreign import ccall "qtc_QDialog_exec" qtc_QDialog_exec :: Ptr (TQDialog a) -> IO CInt instance Qextension (QDialog a) (()) (IO (QWidget ())) where extension x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_extension cobj_x0 foreign import ccall "qtc_QDialog_extension" qtc_QDialog_extension :: Ptr (TQDialog a) -> IO (Ptr (TQWidget ())) instance QisSizeGripEnabled (QDialog a) (()) where isSizeGripEnabled x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_isSizeGripEnabled cobj_x0 foreign import ccall "qtc_QDialog_isSizeGripEnabled" qtc_QDialog_isSizeGripEnabled :: Ptr (TQDialog a) -> IO CBool instance QkeyPressEvent (QDialog ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_keyPressEvent_h" qtc_QDialog_keyPressEvent_h :: Ptr (TQDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QDialogSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyPressEvent_h cobj_x0 cobj_x1 instance QqminimumSizeHint (QDialog ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QDialog_minimumSizeHint_h" qtc_QDialog_minimumSizeHint_h :: Ptr (TQDialog a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QDialogSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QDialog ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDialog_minimumSizeHint_qth_h" qtc_QDialog_minimumSizeHint_qth_h :: Ptr (TQDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QDialogSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance Qorientation (QDialog a) (()) (IO (QtOrientation)) where orientation x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_orientation cobj_x0 foreign import ccall "qtc_QDialog_orientation" qtc_QDialog_orientation :: Ptr (TQDialog a) -> IO CLong instance Qreject (QDialog ()) (()) where reject x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_reject_h cobj_x0 foreign import ccall "qtc_QDialog_reject_h" qtc_QDialog_reject_h :: Ptr (TQDialog a) -> IO () instance Qreject (QDialogSc a) (()) where reject x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_reject_h cobj_x0 instance QresizeEvent (QDialog ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_resizeEvent_h" qtc_QDialog_resizeEvent_h :: Ptr (TQDialog a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QDialogSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_resizeEvent_h cobj_x0 cobj_x1 result :: QDialog a -> (()) -> IO (Int) result x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_result cobj_x0 foreign import ccall "qtc_QDialog_result" qtc_QDialog_result :: Ptr (TQDialog a) -> IO CInt instance QsetExtension (QDialog a) ((QWidget t1)) where setExtension x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_setExtension cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_setExtension" qtc_QDialog_setExtension :: Ptr (TQDialog a) -> Ptr (TQWidget t1) -> IO () setModal :: QDialog a -> ((Bool)) -> IO () setModal x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setModal cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_setModal" qtc_QDialog_setModal :: Ptr (TQDialog a) -> CBool -> IO () instance QsetOrientation (QDialog a) ((QtOrientation)) where setOrientation x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setOrientation cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDialog_setOrientation" qtc_QDialog_setOrientation :: Ptr (TQDialog a) -> CLong -> IO () setResult :: QDialog a -> ((Int)) -> IO () setResult x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setResult cobj_x0 (toCInt x1) foreign import ccall "qtc_QDialog_setResult" qtc_QDialog_setResult :: Ptr (TQDialog a) -> CInt -> IO () instance QsetSizeGripEnabled (QDialog a) ((Bool)) where setSizeGripEnabled x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setSizeGripEnabled cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_setSizeGripEnabled" qtc_QDialog_setSizeGripEnabled :: Ptr (TQDialog a) -> CBool -> IO () instance QsetVisible (QDialog ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_setVisible_h" qtc_QDialog_setVisible_h :: Ptr (TQDialog a) -> CBool -> IO () instance QsetVisible (QDialogSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setVisible_h cobj_x0 (toCBool x1) instance QshowEvent (QDialog ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_showEvent_h" qtc_QDialog_showEvent_h :: Ptr (TQDialog a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QDialogSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_showEvent_h cobj_x0 cobj_x1 showExtension :: QDialog a -> ((Bool)) -> IO () showExtension x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_showExtension cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_showExtension" qtc_QDialog_showExtension :: Ptr (TQDialog a) -> CBool -> IO () instance QqsizeHint (QDialog ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint_h cobj_x0 foreign import ccall "qtc_QDialog_sizeHint_h" qtc_QDialog_sizeHint_h :: Ptr (TQDialog a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QDialogSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint_h cobj_x0 instance QsizeHint (QDialog ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDialog_sizeHint_qth_h" qtc_QDialog_sizeHint_qth_h :: Ptr (TQDialog a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QDialogSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h qDialog_delete :: QDialog a -> IO () qDialog_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_delete cobj_x0 foreign import ccall "qtc_QDialog_delete" qtc_QDialog_delete :: Ptr (TQDialog a) -> IO () qDialog_deleteLater :: QDialog a -> IO () qDialog_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_deleteLater cobj_x0 foreign import ccall "qtc_QDialog_deleteLater" qtc_QDialog_deleteLater :: Ptr (TQDialog a) -> IO () instance QactionEvent (QDialog ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_actionEvent_h" qtc_QDialog_actionEvent_h :: Ptr (TQDialog a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QDialogSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QDialog ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_addAction" qtc_QDialog_addAction :: Ptr (TQDialog a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QDialogSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_addAction cobj_x0 cobj_x1 instance QchangeEvent (QDialog ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_changeEvent_h" qtc_QDialog_changeEvent_h :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QDialogSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_changeEvent_h cobj_x0 cobj_x1 instance Qcreate (QDialog ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_create cobj_x0 foreign import ccall "qtc_QDialog_create" qtc_QDialog_create :: Ptr (TQDialog a) -> IO () instance Qcreate (QDialogSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_create cobj_x0 instance Qcreate (QDialog ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_create1" qtc_QDialog_create1 :: Ptr (TQDialog a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QDialogSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_create1 cobj_x0 cobj_x1 instance Qcreate (QDialog ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QDialog_create2" qtc_QDialog_create2 :: Ptr (TQDialog a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QDialogSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QDialog ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QDialog_create3" qtc_QDialog_create3 :: Ptr (TQDialog a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QDialogSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QDialog ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_destroy cobj_x0 foreign import ccall "qtc_QDialog_destroy" qtc_QDialog_destroy :: Ptr (TQDialog a) -> IO () instance Qdestroy (QDialogSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_destroy cobj_x0 instance Qdestroy (QDialog ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_destroy1" qtc_QDialog_destroy1 :: Ptr (TQDialog a) -> CBool -> IO () instance Qdestroy (QDialogSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QDialog ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QDialog_destroy2" qtc_QDialog_destroy2 :: Ptr (TQDialog a) -> CBool -> CBool -> IO () instance Qdestroy (QDialogSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QDialog ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_devType_h cobj_x0 foreign import ccall "qtc_QDialog_devType_h" qtc_QDialog_devType_h :: Ptr (TQDialog a) -> IO CInt instance QdevType (QDialogSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_devType_h cobj_x0 instance QdragEnterEvent (QDialog ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dragEnterEvent_h" qtc_QDialog_dragEnterEvent_h :: Ptr (TQDialog a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QDialogSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QDialog ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dragLeaveEvent_h" qtc_QDialog_dragLeaveEvent_h :: Ptr (TQDialog a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QDialogSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QDialog ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dragMoveEvent_h" qtc_QDialog_dragMoveEvent_h :: Ptr (TQDialog a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QDialogSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QDialog ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_dropEvent_h" qtc_QDialog_dropEvent_h :: Ptr (TQDialog a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QDialogSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_dropEvent_h cobj_x0 cobj_x1 instance QenabledChange (QDialog ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_enabledChange" qtc_QDialog_enabledChange :: Ptr (TQDialog a) -> CBool -> IO () instance QenabledChange (QDialogSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QDialog ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_enterEvent_h" qtc_QDialog_enterEvent_h :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QDialogSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_enterEvent_h cobj_x0 cobj_x1 instance QfocusInEvent (QDialog ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_focusInEvent_h" qtc_QDialog_focusInEvent_h :: Ptr (TQDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QDialogSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusInEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QDialog ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_focusNextChild cobj_x0 foreign import ccall "qtc_QDialog_focusNextChild" qtc_QDialog_focusNextChild :: Ptr (TQDialog a) -> IO CBool instance QfocusNextChild (QDialogSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_focusNextChild cobj_x0 instance QfocusNextPrevChild (QDialog ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_focusNextPrevChild" qtc_QDialog_focusNextPrevChild :: Ptr (TQDialog a) -> CBool -> IO CBool instance QfocusNextPrevChild (QDialogSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusOutEvent (QDialog ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_focusOutEvent_h" qtc_QDialog_focusOutEvent_h :: Ptr (TQDialog a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QDialogSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_focusOutEvent_h cobj_x0 cobj_x1 instance QfocusPreviousChild (QDialog ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_focusPreviousChild cobj_x0 foreign import ccall "qtc_QDialog_focusPreviousChild" qtc_QDialog_focusPreviousChild :: Ptr (TQDialog a) -> IO CBool instance QfocusPreviousChild (QDialogSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_focusPreviousChild cobj_x0 instance QfontChange (QDialog ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_fontChange" qtc_QDialog_fontChange :: Ptr (TQDialog a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QDialogSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QDialog ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QDialog_heightForWidth_h" qtc_QDialog_heightForWidth_h :: Ptr (TQDialog a) -> CInt -> IO CInt instance QheightForWidth (QDialogSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_heightForWidth_h cobj_x0 (toCInt x1) instance QhideEvent (QDialog ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_hideEvent_h" qtc_QDialog_hideEvent_h :: Ptr (TQDialog a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QDialogSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_hideEvent_h cobj_x0 cobj_x1 instance QinputMethodEvent (QDialog ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_inputMethodEvent" qtc_QDialog_inputMethodEvent :: Ptr (TQDialog a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QDialogSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QDialog ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDialog_inputMethodQuery_h" qtc_QDialog_inputMethodQuery_h :: Ptr (TQDialog a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QDialogSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent (QDialog ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_keyReleaseEvent_h" qtc_QDialog_keyReleaseEvent_h :: Ptr (TQDialog a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QDialogSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlanguageChange (QDialog ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_languageChange cobj_x0 foreign import ccall "qtc_QDialog_languageChange" qtc_QDialog_languageChange :: Ptr (TQDialog a) -> IO () instance QlanguageChange (QDialogSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_languageChange cobj_x0 instance QleaveEvent (QDialog ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_leaveEvent_h" qtc_QDialog_leaveEvent_h :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QDialogSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QDialog ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDialog_metric" qtc_QDialog_metric :: Ptr (TQDialog a) -> CLong -> IO CInt instance Qmetric (QDialogSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance QmouseDoubleClickEvent (QDialog ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mouseDoubleClickEvent_h" qtc_QDialog_mouseDoubleClickEvent_h :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QDialogSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QDialog ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mouseMoveEvent_h" qtc_QDialog_mouseMoveEvent_h :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QDialogSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QDialog ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mousePressEvent_h" qtc_QDialog_mousePressEvent_h :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QDialogSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QDialog ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_mouseReleaseEvent_h" qtc_QDialog_mouseReleaseEvent_h :: Ptr (TQDialog a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QDialogSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_mouseReleaseEvent_h cobj_x0 cobj_x1 instance Qmove (QDialog ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDialog_move1" qtc_QDialog_move1 :: Ptr (TQDialog a) -> CInt -> CInt -> IO () instance Qmove (QDialogSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QDialog ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QDialog_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QDialog_move_qth" qtc_QDialog_move_qth :: Ptr (TQDialog a) -> CInt -> CInt -> IO () instance Qmove (QDialogSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QDialog_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QDialog ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_move cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_move" qtc_QDialog_move :: Ptr (TQDialog a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QDialogSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_move cobj_x0 cobj_x1 instance QmoveEvent (QDialog ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_moveEvent_h" qtc_QDialog_moveEvent_h :: Ptr (TQDialog a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QDialogSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QDialog ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_paintEngine_h cobj_x0 foreign import ccall "qtc_QDialog_paintEngine_h" qtc_QDialog_paintEngine_h :: Ptr (TQDialog a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QDialogSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_paintEngine_h cobj_x0 instance QpaintEvent (QDialog ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_paintEvent_h" qtc_QDialog_paintEvent_h :: Ptr (TQDialog a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QDialogSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_paintEvent_h cobj_x0 cobj_x1 instance QpaletteChange (QDialog ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_paletteChange" qtc_QDialog_paletteChange :: Ptr (TQDialog a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QDialogSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QDialog ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_repaint cobj_x0 foreign import ccall "qtc_QDialog_repaint" qtc_QDialog_repaint :: Ptr (TQDialog a) -> IO () instance Qrepaint (QDialogSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_repaint cobj_x0 instance Qrepaint (QDialog ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QDialog_repaint2" qtc_QDialog_repaint2 :: Ptr (TQDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QDialogSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QDialog ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_repaint1" qtc_QDialog_repaint1 :: Ptr (TQDialog a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QDialogSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QDialog ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_resetInputContext cobj_x0 foreign import ccall "qtc_QDialog_resetInputContext" qtc_QDialog_resetInputContext :: Ptr (TQDialog a) -> IO () instance QresetInputContext (QDialogSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_resetInputContext cobj_x0 instance Qresize (QDialog ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QDialog_resize1" qtc_QDialog_resize1 :: Ptr (TQDialog a) -> CInt -> CInt -> IO () instance Qresize (QDialogSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QDialog ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_resize" qtc_QDialog_resize :: Ptr (TQDialog a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QDialogSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_resize cobj_x0 cobj_x1 instance Qresize (QDialog ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QDialog_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QDialog_resize_qth" qtc_QDialog_resize_qth :: Ptr (TQDialog a) -> CInt -> CInt -> IO () instance Qresize (QDialogSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QDialog_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QDialog ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QDialog_setGeometry1" qtc_QDialog_setGeometry1 :: Ptr (TQDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QDialogSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QDialog ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_setGeometry" qtc_QDialog_setGeometry :: Ptr (TQDialog a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QDialogSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QDialog ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QDialog_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QDialog_setGeometry_qth" qtc_QDialog_setGeometry_qth :: Ptr (TQDialog a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QDialogSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QDialog_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QDialog ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_setMouseTracking" qtc_QDialog_setMouseTracking :: Ptr (TQDialog a) -> CBool -> IO () instance QsetMouseTracking (QDialogSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_setMouseTracking cobj_x0 (toCBool x1) instance QtabletEvent (QDialog ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_tabletEvent_h" qtc_QDialog_tabletEvent_h :: Ptr (TQDialog a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QDialogSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QDialog ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_updateMicroFocus cobj_x0 foreign import ccall "qtc_QDialog_updateMicroFocus" qtc_QDialog_updateMicroFocus :: Ptr (TQDialog a) -> IO () instance QupdateMicroFocus (QDialogSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_updateMicroFocus cobj_x0 instance QwheelEvent (QDialog ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_wheelEvent_h" qtc_QDialog_wheelEvent_h :: Ptr (TQDialog a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QDialogSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_wheelEvent_h cobj_x0 cobj_x1 instance QwindowActivationChange (QDialog ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialog_windowActivationChange" qtc_QDialog_windowActivationChange :: Ptr (TQDialog a) -> CBool -> IO () instance QwindowActivationChange (QDialogSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QDialog ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_childEvent" qtc_QDialog_childEvent :: Ptr (TQDialog a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QDialogSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QDialog ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDialog_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QDialog_connectNotify" qtc_QDialog_connectNotify :: Ptr (TQDialog a) -> CWString -> IO () instance QconnectNotify (QDialogSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDialog_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QDialog ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_customEvent" qtc_QDialog_customEvent :: Ptr (TQDialog a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QDialogSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QDialog ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDialog_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QDialog_disconnectNotify" qtc_QDialog_disconnectNotify :: Ptr (TQDialog a) -> CWString -> IO () instance QdisconnectNotify (QDialogSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDialog_disconnectNotify cobj_x0 cstr_x1 instance Qreceivers (QDialog ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDialog_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QDialog_receivers" qtc_QDialog_receivers :: Ptr (TQDialog a) -> CWString -> IO CInt instance Qreceivers (QDialogSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QDialog_receivers cobj_x0 cstr_x1 instance Qsender (QDialog ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sender cobj_x0 foreign import ccall "qtc_QDialog_sender" qtc_QDialog_sender :: Ptr (TQDialog a) -> IO (Ptr (TQObject ())) instance Qsender (QDialogSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialog_sender cobj_x0 instance QtimerEvent (QDialog ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialog_timerEvent" qtc_QDialog_timerEvent :: Ptr (TQDialog a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QDialogSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialog_timerEvent cobj_x0 cobj_x1
uduki/hsQt
Qtc/Gui/QDialog.hs
bsd-2-clause
46,205
0
14
7,875
15,912
8,066
7,846
-1
-1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Web.Pagure.Users -- Copyright : (C) 2015 Ricky Elrod -- License : BSD2 (see LICENSE file) -- Maintainer : Ricky Elrod <[email protected]> -- Stability : experimental -- Portability : ghc (lens) -- -- Access to the \"Users\" endpoints of the Pagure API. ---------------------------------------------------------------------------- module Web.Pagure.Users where import Control.Lens import Data.Aeson.Lens import qualified Data.Text as T import Network.Wreq import Web.Pagure.Internal.Wreq import Web.Pagure.Types import Web.Pagure.Types.User -- | Access the @/users@ endpoint. -- -- Example: -- -- @ -- >>> import Web.Pagure -- >>> let pc = PagureConfig "https://pagure.io" Nothing -- >>> runPagureT users pc -- ["adamwill","alphacc","asamalik","ausil","bkabrda","bochecha",[...] -- @ users :: Maybe T.Text -- ^ Optional pattern to search for -> PagureT [Username] users pattern = do opts <- pagureWreqOptions let opts' = case pattern of Nothing -> opts Just p -> opts & param "pattern" .~ [p] resp <- pagureGetWith opts' "users" return $ resp ^.. responseBody . key "users" . values . _String -- | Access the @/groups@ endpoint. -- -- Example: -- -- @ -- >>> import Web.Pagure -- >>> let pc = PagureConfig "https://pagure.io" Nothing -- >>> runPagureT groups pc -- ["releng","Fedora-Infra"] -- @ groups :: Maybe T.Text -- ^ Optional pattern to search for -> PagureT [Group] groups pattern = do opts <- pagureWreqOptions let opts' = case pattern of Nothing -> opts Just p -> opts & param "pattern" .~ [p] resp <- pagureGetWith opts' "groups" return $ resp ^.. responseBody . key "groups" . values . _String -- | Access the @/user/[username]@ endpoint. -- -- Example: -- -- @ -- >>> import Web.Pagure -- >>> let pc = PagureConfig "https://pagure.io" Nothing -- >>> runPagureT (userInfo "codeblock") pc -- @ userInfo :: Username -> PagureT (Maybe UserResponse) userInfo u = do resp <- asJSON =<< pagureGet ("user/" ++ T.unpack u) return $ resp ^. responseBody
fedora-infra/pagure-haskell
src/Web/Pagure/Users.hs
bsd-2-clause
2,150
0
15
371
387
216
171
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ViewPatterns #-} -- | Simple code motion transformation performing common sub-expression elimination and variable -- hoisting. Note that the implementation is very inefficient. -- -- The code is based on an implementation by Gergely Dévai. module Language.Syntactic.Sharing.SimpleCodeMotion3 ( mkSubEnvDefault , codeMotion3 , reifySmart ) where import Control.Applicative (Const (..)) import Control.Monad.State import Data.Set as Set hiding (size) import Data.Typeable import Language.Syntactic import Language.Syntactic.Constructs.Binding import Language.Syntactic.Constructs.Binding.HigherOrder import Language.Syntactic.Sharing.SimpleCodeMotion (PrjDict (..), InjDict (..), MkInjDict, prjDictFO) -- | Substituting a sub-expression. Assumes no variable capturing in the -- expressions involved. substitute :: forall dom a b . (ConstrainedBy dom Typeable, AlphaEq dom dom dom [(VarId,VarId)]) => ASTF dom a -- ^ Sub-expression to be replaced -> ASTF dom a -- ^ Replacing sub-expression -> ASTF dom b -- ^ Whole expression -> ASTF dom b substitute x y a | Dict <- exprDictSub pTypeable y , Dict <- exprDictSub pTypeable a , Just y' <- gcast y, alphaEq x a = y' | otherwise = subst a where subst :: AST dom c -> AST dom c subst (f :$ a) = subst f :$ substitute x y a subst a = a -- | Count the number of occurrences of a sub-expression count :: forall dom a b . AlphaEq dom dom dom [(VarId,VarId)] => ASTF dom a -- ^ Expression to count -> ASTF dom b -- ^ Expression to count in -> Int count a b | alphaEq a b = 1 | otherwise = cnt b where cnt :: AST dom c -> Int cnt (f :$ b) = cnt f + count a b cnt _ = 0 -- | Environment for the expression in the 'choose' function data Env dom = Env { inLambda :: Bool -- ^ Whether the current expression is inside a lambda , counter :: ASTE dom -> Int -- ^ Counting the number of occurrences of an expression in the -- environment , dependencies :: Set VarId -- ^ The set of variables that are not allowed to occur in the chosen -- expression } independent :: PrjDict dom -> Env dom -> AST dom a -> Bool independent pd env (Sym (prjVariable pd -> Just v)) = not (v `member` dependencies env) independent pd env (f :$ a) = independent pd env f && independent pd env a independent _ _ _ = True isVariable :: PrjDict dom -> ASTF dom a -> Bool isVariable pd (Sym (prjVariable pd -> Just _)) = True isVariable pd _ = False -- | Checks whether a sub-expression in a given environment can be lifted out liftable :: PrjDict dom -> Env dom -> ASTF dom a -> Bool liftable pd env a = independent pd env a && not (isVariable pd a) && heuristic -- Lifting dependent expressions is semantically incorrect -- Lifting variables would cause `codeMotion` to loop where heuristic = inLambda env || (counter env (ASTE a) > 1) -- | Update the environment when going under a lambda that binds the given variable. This lambda is -- assumed to be called multiple times, so that hoisting is worthwhile. lamEnv :: VarId -> Env dom -> Env dom lamEnv v env = env { inLambda = True , dependencies = insert v (dependencies env) } -- | Update the environment when going under a lambda that binds the given variable. This lambda is -- assumed to be called only once, so that hoisting is not worthwhile. lamEnvOneShot :: VarId -> Env dom -> Env dom lamEnvOneShot v env = env { inLambda = False , dependencies = insert v (dependencies env) } -- | Function that gives a list of sub-expressions and their environment. A 'Nothing' result means -- \"default behavior\" (see 'mkSubEnvDefault'). -- -- The purpose of this function is to be able to declare certain binding constructs as "one-shot". -- This is done by not setting the 'inLambda' flag for sub-expressions that are under one-shot -- lambdas but rather inherit it from the parent environment. data MkSubEnv dom = MkSubEnv { mkSubEnv :: forall sig . Env dom -> dom sig -> Args (AST dom) sig -> Maybe [(ASTE dom, Env dom)] } -- | Default implementation of 'MkSubEnv' mkSubEnvDefault :: MkSubEnv dom mkSubEnvDefault = MkSubEnv $ \_ _ _ -> Nothing -- | List the sub-expressions and their environments. 'Let' bindings are handled first, to make sure -- that these are always treated as one-shot binders. Next, the supplied 'MkSubEnv' is given the -- chance to compute the result. If it doesn't, the expression is handled in a standard way. subTermsEnv :: Project Let dom => PrjDict dom -> MkSubEnv dom -> Env dom -> dom sig -> Args (AST dom) sig -> [(ASTE dom, Env dom)] subTermsEnv pd ed env lt (a :* (Sym lam :$ b) :* Nil) | Just Let <- prj lt , Just v <- prjLambda pd lam = [(ASTE a, env), (ASTE b, lamEnvOneShot v env)] subTermsEnv pd ed env s args | Just as <- mkSubEnv ed env s args = as subTermsEnv pd ed env lam (body :* Nil) | Just v <- prjLambda pd lam = [(ASTE body, lamEnv v env)] subTermsEnv pd ed env _ args = listArgs (\a -> (ASTE a, env)) args -- | A sub-expression chosen to be shared together with an evidence that it can actually be shared -- in the whole expression under consideration data Chosen dom a where Chosen :: InjDict dom b a -> ASTF dom b -> Chosen dom a -- | Choose a sub-expression to share choose :: forall dom a . (AlphaEq dom dom dom [(VarId,VarId)], Project Let dom) => (forall c. ASTF dom c -> Bool) -> PrjDict dom -> MkInjDict dom -> MkSubEnv dom -> ASTF dom a -> Maybe (Chosen dom a) choose hoistOver pd mkId mkSub a = chooseEnvSub initEnv a where initEnv = Env { inLambda = False , counter = \(ASTE b) -> count b a , dependencies = empty } chooseEnv :: Env dom -> ASTF dom b -> Maybe (Chosen dom a) chooseEnv env b = this `mplus` that -- Prefer `this` because it must be larger than `that` where this = do guard $ liftable pd env b id <- mkId b a return $ Chosen id b that = do guard $ hoistOver b chooseEnvSub env b -- | Like 'chooseEnv', but does not consider the top expression for sharing chooseEnvSub :: Env dom -> ASTF dom b -> Maybe (Chosen dom a) chooseEnvSub env a = Prelude.foldr (\(ASTE b, e) a -> chooseEnv e b `mplus` a) Nothing (simpleMatch (subTermsEnv pd mkSub env) a :: [(ASTE dom, Env dom)]) -- | Perform common sub-expression elimination and variable hoisting codeMotion :: forall dom m a . ( ConstrainedBy dom Typeable , AlphaEq dom dom dom [(VarId,VarId)] , Project Let dom , MonadState VarId m ) => (forall c. ASTF dom c -> Bool) -- ^ Control wether a sub-expression can be hoisted over the given expression -> PrjDict dom -> MkInjDict dom -> MkSubEnv dom -> ASTF dom a -> m (ASTF dom a) codeMotion hoistOver pd mkId mkSub a | Just (Chosen id b) <- choose hoistOver pd mkId mkSub a = share id b | otherwise = descend a where share :: InjDict dom b a -> ASTF dom b -> m (ASTF dom a) share id b = do b' <- codeMotion hoistOver pd mkId mkSub b v <- get; put (v+1) let x = Sym (injVariable id v) body <- codeMotion hoistOver pd mkId mkSub $ substitute b x a return $ Sym (injLet id) :$ b' :$ (Sym (injLambda id v) :$ body) descend :: AST dom b -> m (AST dom b) descend (lt :$ a :$ (Sym lam :$ b)) | Just Let <- prj lt , Just _ <- prjLambda pd lam = do a' <- descend a b' <- codeMotion hoistOver pd mkId mkSub b return $ lt :$ a' :$ (Sym lam :$ b') descend (f :$ a) = liftM2 (:$) (descend f) (codeMotion hoistOver pd mkId mkSub a) descend a = return a fixIter :: (AlphaEq dom dom dom [(VarId, VarId)], Monad m) => Int -> (ASTF dom a -> m (ASTF dom a)) -> (ASTF dom a -> m (ASTF dom a)) fixIter 0 f a = return a fixIter limit f a = do a' <- f a if alphaEq a a' then return a else fixIter (limit-1) f a' -- | Perform common sub-expression elimination and variable hoisting codeMotion3 :: forall dom m a . ( ConstrainedBy dom Typeable , AlphaEq dom dom dom [(VarId,VarId)] , Project Let dom , MonadState VarId m ) => Int -- Max number of iterations -> (forall c. ASTF dom c -> Bool) -- ^ Control wether a sub-expression can be hoisted over the given expression -> PrjDict dom -> MkInjDict dom -> MkSubEnv dom -> ASTF dom a -> m (ASTF dom a) codeMotion3 limit hoistOver pd mkId mkSub = fixIter limit $ codeMotion hoistOver pd mkId mkSub -- | Like 'reify' but with common sub-expression elimination and variable hoisting reifySmart :: forall dom p pVar a . ( AlphaEq dom dom (FODomain dom p pVar) [(VarId,VarId)] , Syntactic a , Domain a ~ HODomain dom p pVar , p :< Typeable , Project Let (FODomain dom p pVar) ) => Int -- Max number of iterations -> (forall c. ASTF (FODomain dom p pVar) c -> Bool) -> MkInjDict (FODomain dom p pVar) -> MkSubEnv (FODomain dom p pVar) -> a -> ASTF (FODomain dom p pVar) (Internal a) reifySmart limit hoistOver mkId mkSub = flip evalState 0 . (codeMotion3 limit hoistOver prjDictFO mkId mkSub <=< reifyM . desugar)
emwap/feldspar-language
src/Language/Syntactic/Sharing/SimpleCodeMotion3.hs
bsd-3-clause
9,687
0
16
2,579
2,878
1,471
1,407
-1
-1
{-# Language FlexibleContexts #-} -- | Names specific to western music tradition module Temporal.Music.Western( -- * Basic functions -- | All basic functions (composition, time stretching, -- dynamic changing of volume and pitch etc, etc) live in this module. module Temporal.Music, -- * Volume -- | Dynamics values form 9-level equally spaced grid. -- They are from quietest -- to loudest: piano pianissimo (ppp), pianissimo (pp), piano (p), -- mezzo piano (mp), mezzo forte (mf), forte (f), fortissimo (ff), -- forte fortissimo (fff). -- These modifiers change level relative to the current level. -- It means that -- -- > piano . forte = id pppiano, ppiano, piano, mpiano, mforte, forte, fforte, ffforte, -- ** Shortcuts to set dynamics level. ppp', pp', p', mp', mf', f', ff', fff', -- ** Envelops dim, cresc, -- * Score rondo, reprise, -- * Tempo -- | Tempo terms specify not a rigid value but tempo range. So all -- terms are functions from relative power of term (it's value -- of type Double from 0 to 1) to some tempo value. Zero means -- the lowest value from tempo range and one means the highest value. -- To be used with 'bpm' function. Tempo, lento, largo, larghetto, grave, adagio, adagietto, andante, andantino, moderato, allegretto, allegro, vivace, presto, prestissimo ) where import Temporal.Music pppiano, ppiano, piano, mpiano, mforte, forte, fforte, ffforte :: (VolumeLike a) => Score a -> Score a pppiano = quieter 4; ppiano = quieter 3; piano = quieter 2 mpiano = quieter 1; mforte = louder 1; forte = louder 2; fforte = louder 3; ffforte = louder 4; ppp', pp', p', mp', mf', f', ff', fff' :: (VolumeLike a) => Score a -> Score a ppp' = pppiano; pp' = ppiano; p' = piano; mp' = mpiano; mf' = mforte; f' = forte; ff' = fforte; fff' = ffforte; -- | diminuendo dim :: VolumeLike a => Accent -> Score a -> Score a dim = withAccent . (*) . negate -- | crescendo cresc :: VolumeLike a => Accent -> Score a -> Score a cresc = withAccent . (*) --------------------------------------- -- forms -- | rondo form -- -- >rondo a b c = mel [a, b, a, c, a] rondo :: Score a -> Score a -> Score a -> Score a rondo a b c = mel [a, b, a, c, a] -- | reprise form -- -- >reprise a b1 b2 = mel [a, b1, a, b2] reprise :: Score a -> Score a -> Score a -> Score a reprise a b c = mel [a, b, a, c] --------------------------------------- -- tempo type Tempo = Double largoRange, larghettoRange, adagioRange, adagiettoRange, andanteRange, andantinoRange, moderatoRange, allegroRange, allegrettoRange, vivaceRange, prestoRange, prestissimoRange :: (Double, Double) largoRange = ( 40, 60) larghettoRange = ( 60, 66) adagioRange = ( 66, 76) adagiettoRange = ( 70, 80) andanteRange = ( 76, 80) andantinoRange = ( 80,100) moderatoRange = (101,110) allegrettoRange = (115,125) allegroRange = (120,139) vivaceRange = (135,160) prestoRange = (168,200) prestissimoRange = (200,230) getTempo :: (Tempo, Tempo) -> Double -> Tempo getTempo (a, b) x = a + (b - a) * x -- | very slow (40-60 bpm), like largo lento :: Double -> Tempo lento = largo -- | very slow (40-60 bpm) largo :: Double -> Tempo largo = getTempo largoRange -- | rather broadly (60-66 bpm) larghetto :: Double -> Tempo larghetto = getTempo larghettoRange -- | slow and sloemn (60 - 66 bpm) grave :: Double -> Tempo grave = larghetto -- | slow and stately (literally "at ease") (66-76 bpm) adagio :: Double -> Tempo adagio = getTempo adagioRange -- | rather slow (70-80 bpm) adagietto :: Double -> Tempo adagietto = getTempo adagiettoRange -- | at awalking pace (76-80 bpm) andante :: Double -> Tempo andante = getTempo andanteRange -- | slightly faster then andante (80-100 bpm) andantino :: Double -> Tempo andantino = getTempo andantinoRange -- | moderately (101-110 bpm) moderato :: Double -> Tempo moderato = getTempo moderatoRange -- | moderately fast (115-125 bpm) allegretto :: Double -> Tempo allegretto = getTempo allegrettoRange -- | fast, at 'march tempo' (120-139 bpm) allegro :: Double -> Tempo allegro = getTempo allegroRange -- | lively and fast (135-160 bpm) vivace :: Double -> Tempo vivace = getTempo vivaceRange -- | very fast (168-200 bpm) presto :: Double -> Tempo presto = getTempo prestoRange -- | extremely fast (200 - 230 bpm) prestissimo :: Double -> Tempo prestissimo = getTempo prestissimoRange
spell-music/temporal-music-notation-western
src/Temporal/Music/Western.hs
bsd-3-clause
4,623
8
8
1,094
1,024
627
397
79
1
{- Texture3D.hs (adapted from texture3d.c which is (c) Silicon Graphics, Inc) Copyright (c) Sven Panne 2002-2005 <[email protected]> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE This program demonstrates using a three-dimensional texture. It creates a 3D texture and then renders two rectangles with different texture coordinates to obtain different "slices" of the 3D texture. -} import Control.Monad ( unless ) import Foreign ( withArray ) import System.Exit ( exitFailure, exitWith, ExitCode(ExitSuccess) ) import Graphics.UI.GLUT -- Create checkerboard image imageSize :: TextureSize3D imageSize = TextureSize3D 16 16 16 withImage :: (PixelData (Color3 GLubyte) -> IO ()) -> IO () withImage act = withArray [ Color3 (s * 17) (t * 17) (r * 17) | r <- [ 0 .. fromIntegral d - 1 ], t <- [ 0 .. fromIntegral h - 1 ], s <- [ 0 .. fromIntegral w - 1 ] ] $ act . PixelData RGB UnsignedByte where (TextureSize3D w h d) = imageSize myInit :: IO () myInit = do clearColor $= Color4 0 0 0 0 shadeModel $= Flat depthFunc $= Just Less rowAlignment Unpack $= 1 [texName] <- genObjectNames 1 textureBinding Texture3D $= Just texName textureWrapMode Texture3D S $= (Repeated, Clamp) textureWrapMode Texture3D T $= (Repeated, Clamp) textureWrapMode Texture3D R $= (Repeated, Clamp) textureFilter Texture3D $= ((Nearest, Nothing), Nearest) withImage $ texImage3D NoProxy 0 RGB' imageSize 0 texture Texture3D $= Enabled display :: DisplayCallback display = do clear [ ColorBuffer, DepthBuffer ] -- resolve overloading, not needed in "real" programs let texCoord3f = texCoord :: TexCoord3 GLfloat -> IO () vertex3f = vertex :: Vertex3 GLfloat -> IO () renderPrimitive Quads $ do texCoord3f (TexCoord3 0 0 0); vertex3f (Vertex3 (-2.25) (-1) 0) texCoord3f (TexCoord3 0 1 0); vertex3f (Vertex3 (-2.25) 1 0) texCoord3f (TexCoord3 1 1 1); vertex3f (Vertex3 (-0.25) 1 0) texCoord3f (TexCoord3 1 0 1); vertex3f (Vertex3 (-0.25) (-1) 0) texCoord3f (TexCoord3 0 0 1); vertex3f (Vertex3 0.25 (-1) 0) texCoord3f (TexCoord3 0 1 1); vertex3f (Vertex3 0.25 1 0) texCoord3f (TexCoord3 1 1 0); vertex3f (Vertex3 2.25 1 0) texCoord3f (TexCoord3 1 0 0); vertex3f (Vertex3 2.25 (-1) 0) flush reshape :: ReshapeCallback reshape size@(Size w h) = do viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity perspective 60 (fromIntegral w / fromIntegral h) 1 30 matrixMode $= Modelview 0 loadIdentity translate (Vector3 0 0 (-4 :: GLfloat)) keyboard :: KeyboardMouseCallback keyboard (Char '\27') Down _ _ = exitWith ExitSuccess keyboard _ _ _ _ = return () main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ] initialWindowSize $= Size 250 250 initialWindowPosition $= Position 100 100 createWindow progName -- we have to do this *after* createWindow, otherwise we have no OpenGL context exts <- get glExtensions unless ("GL_EXT_texture3D" `elem` exts) $ do putStrLn "Sorry, this demo requires the GL_EXT_texture3D extension." exitFailure myInit reshapeCallback $= Just reshape displayCallback $= display keyboardMouseCallback $= Just keyboard mainLoop
FranklinChen/hugs98-plus-Sep2006
packages/GLUT/examples/RedBook/Texture3D.hs
bsd-3-clause
3,479
0
14
799
1,114
541
573
71
1
module Main where import Language.Haskell.Exts.Pretty (prettyPrint) import Language.Haskell.Exts.Syntax import System.Environment import qualified Data.Map as M import Text.Printf import DSL import Combinators import Utils convertors = [ ("Word8", ("W8#", "indexWord8OffAddr#")) , ("Word", ("W#", "indexWord8OffAddr#")) ] data TableSz = Table1d Int | Table2d Int Int deriving (Show,Eq) getTableLength (Table name tys fields) | length tys == 2 = if all isField fields then Table1d (length fields) else unsupported " 1d table contains rows" | length tys == 3 = let r = map getElemRow fields in if all (== (head r)) r then Table2d (length fields) (head r) else unsupported " row not of same size" | otherwise = unsupported "" where unsupported r = error ("unsupported table " ++ name ++ " length " ++ show (length tys) ++ r) isAllFields = all isField getElemRow (TableRow f) | all isField f = length f | otherwise = unsupported (" row contains rows") isField (TableField _) = True isField _ = False process atoms = do let (mod, mapTypes) = foldl transform (iniModule, M.empty) atoms putStrLn $ prettyPrint mod where iniModule = addImport (mkImport "GHC.Prim") $ addImport (mkImport "GHC.Word") $ addImport (mkImport "GHC.Types") $ addPragma (mkModulePragma "BangPatterns") $ addPragma (mkModulePragma "MagicHash") $ mkModule "Table" transform acc (Struct _ _) = acc transform (mod, acc) (Enum n fields) = do (mod, fst $ foldl (addField) (acc,0) fields) where addField (acc,n) (fname, mval) = let current = maybe n numberToInt mval nacc = M.insert fname current acc in (nacc, current+1) transform (mod, acc) t@(Table n tys tfields) = case tableSz of Table1d x -> let nmod = addDecl (mkF (doCamelCase n)) $ addDecl (mkTypesig (doCamelCase n)) mod in (nmod, acc) Table2d x y -> let nmod = addDecl (mkF (doCamelCase n)) $ addDecl (mkTypesig (doCamelCase n)) mod in (nmod, acc) where fieldsToNumb :: TableElem -> String fieldsToNumb (TableField "__") = replicate 1 (toEnum 0xff) fieldsToNumb (TableField s) = case M.lookup s acc of Just i -> replicate 1 (toEnum i) Nothing -> replicate 1 (toEnum (read s :: Int)) fieldsToNumb (TableRow e) = concatMap fieldsToNumb e tableSz = getTableLength t mkTypesig n = TypeSig dummyLoc [Ident n] $ case tys of [a,b] -> TyFun (mkTyCon a) (mkTyCon b) [a,b,c] -> TyFun (mkTyCon a) (TyFun (mkTyCon b) (mkTyCon c)) _ -> error "unsupported length" tdata = concat $ map (fieldsToNumb) tfields tableLit = Lit $ PrimString tdata patConstructorMatch constructor var = PParen (PApp (UnQual (Ident constructor)) [PVar (Ident var)]) mkF fname = mkFunBindWithBinds fname patMatchs Nothing body [ mkPatBindBang "table" tableLit ] where patMatchs = case tableSz of Table1d _ -> [ patConstructorMatch "W8#" "w" ] Table2d _ _ -> [ patConstructorMatch "W8#" "w1", patConstructorMatch "W8#" "w2" ] body = App (Con (UnQual (Ident retConstructor))) (Paren (App (App (Var (UnQual (Ident indexFct))) (Var (UnQual (Ident "table")))) (Paren (App (Var (UnQual (Ident "word2Int#"))) (indexer))) )) indexFct = maybe (error ("unknown type: " ++ show indexer)) snd $ lookup (head tys) convertors retConstructor = maybe (error ("unknown type: " ++ show (last tys))) fst $ lookup (last tys) convertors indexer = case tableSz of Table1d _ -> (Var $ UnQual (Ident "w")) Table2d x _ -> Paren (App (App (Var (UnQual (Ident "plusWord#"))) (Paren (App (App (Var (UnQual (Ident "timesWord#"))) (Var (UnQual (Ident "w1"))) ) (Paren (App (Var (UnQual (Ident "int2Word#"))) (Lit (PrimInt (fromIntegral x))))) )) ) (Var (UnQual (Ident "w2"))) ) main = do args <- getArgs case args of [x] -> readDSL x >>= process
vincenthz/hs-gen-storable
src/GenTable.hs
bsd-3-clause
5,833
0
30
2,804
1,642
826
816
94
11
module Data.BtcExchanges ( Currency (..) , CurrencyPair (..) , Exchange (..) , counter , base ) where data Exchange = Btce | Campbx | Bitstamp deriving (Show, Eq, Read) data Currency = USD | AUD | CAD | CHF | CNY | DKK | EUR | GBP | HKD | JPY | NZD | PLN | RUB | SEK | SGD | THB | BTC | LTC deriving (Show, Eq, Read) data CurrencyPair = BTCUSD | BTCAUD | BTCCAD | BTCCHF | BTCCNY | BTCDKK | BTCEUR | BTCGBP | BTCHKD | BTCJPY | BTCNZD | BTCPLN | BTCRUB | BTCSEK | BTCSGD | BTCTHB | LTCUSD | LTCBTC deriving (Eq, Read) instance Show CurrencyPair where show BTCUSD = "btc_usd" show BTCAUD = "btc_aud" show BTCCAD = "btc_cad" show BTCCHF = "btc_chf" show BTCCNY = "btc_cny" show BTCDKK = "btc_dkk" show BTCEUR = "btc_eur" show BTCGBP = "btc_gbp" show BTCHKD = "btc_hkd" show BTCJPY = "btc_jpy" show BTCNZD = "btc_nsd" show BTCPLN = "btc_pln" show BTCRUB = "btc_rub" show BTCSEK = "btc_sek" show BTCSGD = "btc_sgd" show BTCTHB = "btc_thb" show LTCUSD = "ltc_usd" show LTCBTC = "ltc_btc" base :: CurrencyPair -> Currency base BTCUSD = BTC base BTCAUD = BTC base BTCCAD = BTC base BTCCHF = BTC base BTCCNY = BTC base BTCDKK = BTC base BTCEUR = BTC base BTCGBP = BTC base BTCHKD = BTC base BTCJPY = BTC base BTCNZD = BTC base BTCPLN = BTC base BTCRUB = BTC base BTCSEK = BTC base BTCSGD = BTC base BTCTHB = BTC base LTCUSD = LTC base LTCBTC = LTC counter :: CurrencyPair -> Currency counter BTCUSD = USD counter BTCAUD = AUD counter BTCCAD = CAD counter BTCCHF = CHF counter BTCCNY = CNY counter BTCDKK = DKK counter BTCEUR = EUR counter BTCGBP = GBP counter BTCHKD = HKD counter BTCJPY = JPY counter BTCNZD = NZD counter BTCPLN = PLN counter BTCRUB = RUB counter BTCSEK = SEK counter BTCSGD = SGD counter BTCTHB = THB counter LTCUSD = USD counter LTCBTC = BTC
RobinKrom/BtcExchanges
src/Data/BtcExchanges.hs
bsd-3-clause
2,216
0
6
805
663
360
303
83
1
module EFA.IO.PLTParser where import EFA.Signal.Record (SigId(SigId)) import EFA.IO.Parser (number, eol) import Text.ParserCombinators.Parsec import Control.Applicative ((*>), liftA2) import Control.Monad.HT (void) type Tables v = ([v], [Table v]) type Table v = (SigId, [v]) datasetToken :: Parser () datasetToken = string "DataSet:" *> spaces pltFile :: (Read v) => Parser (Tables v) pltFile = do removeClutter liftA2 (,) timeTable $ eol *> endBy dataTable eol timeTable :: (Read v) => Parser [v] timeTable = datasetToken *> string "time\n" *> table dataTable :: (Read v) => Parser (Table v) dataTable = liftA2 (,) (datasetToken *> fmap SigId name) table table :: (Read v) => Parser [v] table = endBy (fmap snd dataline) eol name :: Parser String name = manyTill anyChar eol dataline :: (Read v) => Parser (v,v) dataline = liftA2 (,) number (string ", " *> number) removeClutter :: Parser () removeClutter = void $ manyTill line (string "\n") line :: Parser String line = manyTill (noneOf "\n\r") eol
energyflowanalysis/efa-2.1
src/EFA/IO/PLTParser.hs
bsd-3-clause
1,026
0
10
181
427
235
192
28
1
{-# OPTIONS -Wall -fno-warn-missing-signatures #-} module TweetProxy.Types where data Config = Config { configListen :: Int, configKey :: String, configSecret :: String }
passy/tweetproxy
src/TweetProxy/Types.hs
bsd-3-clause
185
0
8
37
34
22
12
6
0
module Framework.Location.Api where import Data.Text import Control.Monad.Reader hiding ( join ) import Control.Monad.Error ( throwError ) import Control.Monad.State ( get ) import Framework.Profile as Profile import Common.Location.Types import DB.Location.LocationAction import Common.Location.Instances.Create import Framework.Location.Instances.Location import Framework.Location.Classes hiding ( chat ) import Framework.Location.Instances.View.LocationView import Common.Classes as Classes ( view, create, delete, delete', add' ) import qualified Framework.Location.Classes as Location import Data.Text ( Text, pack ) import Common.Location.View -- removed UserId since these will run with MonadReader Profile m data LocationApi = Join LocationId | Leave | Look LocationId -- will include data previously requested with ReceiveChat | Chat Text LocationId | Create LocationOptions -- will probably patern match on LocationId to determine type of location, ignore id | Delete LocationId join :: LocationId -> LocationAction LocationView join locationId = do userId <- getCurrentUserId oldLocationId <- getUserLocation userId setLocation locationId userId onLeave oldLocationId onJoin locationId view locationId tryJoin :: LocationId -> LocationAction LocationView tryJoin locationId = do userId <- getCurrentUserId oldLocationId <- getUserLocation userId canLeave <- canLeave oldLocationId canJoin <- canJoin locationId if canJoin && canLeave then join locationId else view oldLocationId tryLeave :: LocationAction LocationView tryLeave = do userId <- getCurrentUserId currentLocationId <- getUserLocation userId exit <- exit currentLocationId tryJoin exit leave :: LocationAction LocationView leave = getCurrentUserId >>= getUserLocation >>= join chat :: Text -> LocationId -> LocationAction LocationView chat text locationId = do userName <- getCurrentUserName Location.chat (userName, text) locationId view locationId create :: LocationOptions -> LocationAction LocationView create locationOptions = add (Classes.create locationOptions) >>= view delete :: LocationId -> LocationAction LocationView delete locationId = do DB.Location.LocationAction.delete locationId return $ LVMessage $ pack "Deleted." runLocationApi :: LocationApi -> LocationAction LocationView runLocationApi (Join locationId) = tryJoin locationId runLocationApi Leave = tryLeave runLocationApi (Look locationId) = view locationId runLocationApi (Chat text locationId) = chat text locationId runLocationApi (Delete locationId) = Framework.Location.Api.delete locationId runLocationApi (Create locationOptions) = Framework.Location.Api.create locationOptions
ojw/admin-and-dev
src/Framework/Location/Api.hs
bsd-3-clause
2,751
0
9
423
647
339
308
64
2