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 OverloadedStrings #-} module Y2017.M11.D08.Solution where {-- Yesterday, you loaded up a set of recommended articles and married them with some scoring of those articles ... we left a slot open for the keywords used in their scoring (which we parsed in Y2017.M11.D03). Today we are going to fill that slot. Given the set of recommended articles: --} import Y2017.M11.D07.Solution -- their scores: import Y2017.M11.D06.Solution -- and the set of keyphrases associated with (well, all) articles: import Y2017.M11.D03.Solution import Data.Aeson import Data.Aeson.Encode.Pretty import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.Map as Map -- first, define a JSON instance for the keyphrases: {-- instance ToJSON Keyphrase where toJSON (KW strength (SQS str)) = object ["strength" .= strength, "keyphrase" .= str] -- move this definition to Y2017.M11.D07.Solution --} -- And now, save out the recommendation with score and keyphrases as JSON saveRecs :: FilePath -> KeyphraseMap -> [Recommendation] -> IO () saveRecs outputfile keyphrases = BL.writeFile outputfile . showRecs keyphrases showRecs :: KeyphraseMap -> [Recommendation] -> ByteString showRecs keyphrases = encodePretty . map (\rec -> rec { scoreKWs = keyphrases Map.! fromIntegral (scoreIdx rec) }) -- assume recs starts with an empty list for article_keyphrase -- Use the recommendation file, the score file and the keyphrases file in their -- respective directories {-- >>> scores <- readScoreFile scoreFile >>> recs <- readRecs "Y2017/M11/D07/recommend.json" >>> marriage = marry recs scores >>> kws <- readCompressedKeyphrases (kwDir ++ "kw_index_file.txt.gz") >>> length kws 9835 ... 9835 articles indexed with keyphrases >>> saveRecs "Y2017/M11/D08/recommends.json" kws marriage ... and BOOM! we have our recommendations with keyphrases and scores, printed prettily! --}
geophf/1HaskellADay
exercises/HAD/Y2017/M11/D08/Solution.hs
mit
1,971
0
14
322
191
118
73
17
1
module ExampleBroadcast where import Control.Applicative import Control.Monad import Control.Concurrent (threadDelay) import MVC import MVC.Prelude as MVC import qualified Pipes.Network.TCP as TCP import Data.ByteString (ByteString) import Control.Concurrent.Async import Control.Concurrent.STM newtype Broadcast a = Broadcast { unBroadcast :: TVar (Output a) } broadcast :: STM (Output a, Broadcast a) broadcast = do tvar <- newTVar mempty let output = Output $ \a -> do o <- readTVar tvar send o a return (output, Broadcast tvar) {-# INLINABLE broadcast #-} subscribe :: Buffer a -> Broadcast a -> IO (Input a) subscribe buffer (Broadcast tvar) = do (output, input) <- spawn buffer atomically $ modifyTVar' tvar (mappend output) return input {-# INLINABLE subscribe #-} newtype Funnel a = Funnel { unFunnnel :: TVar (Input a) } funnel :: STM (Funnel a, Input a) funnel = do tvar <- newTVar mempty let input = Input $ do i <- readTVar tvar recv i return (Funnel tvar, input) {-# INLINABLE funnel #-} widen :: Buffer a -> Funnel a -> IO (Output a) widen buffer (Funnel tvar) = do (output, input) <- spawn buffer atomically $ modifyTVar' tvar (mappend input) return output {-# INLINABLE widen #-} broadcastServer :: (String, String) -> Managed (View ByteString, Controller ByteString) broadcastServer (h,p) = join $ managed $ \k -> do -- make a Broadcast channel (outB, refB, refF, inF) <- atomically $ do (outB', refB') <- broadcast (refF', inF') <- funnel return (outB', refB', refF', inF') let server = TCP.listen (TCP.Host h) p $ \(sock,_) -> forever $ TCP.acceptFork sock $ \(sock',_) -> do inClient <- subscribe Unbounded refB outClient <- widen Unbounded refF aIn <- async $ runEffect $ for (fromInput inClient) (lift . TCP.send sock') aOut <- async $ runEffect $ TCP.fromSocket sock' 4096 >-> toOutput outClient void $ waitAnyCancel [aIn, aOut] let v = asSink (void . atomically . MVC.send outB) c = asInput inF withAsync server $ \_ -> k ((,) <$> pure v <*> (pure c <> keepOpenController)) keepOpenController :: Managed (Controller a) keepOpenController = MVC.producer Single $ do lift $ threadDelay (365 * 24 * 60 * 60 * 10^6) return ()
tonyday567/mvc-extended
test/ExampleBroadcast.hs
mit
2,513
0
24
716
893
452
441
59
1
{-| Module : Stmt Description : Tests for statements Copyright : (c) Jacob Errington and Frederic Lafrance, 2016 License : MIT Maintainer : goto@mail.jerrington.me Stability : experimental -} {-# LANGUAGE OverloadedStrings #-} module Parser.Stmt ( statement ) where import Language.GoLite import Language.GoLite.Syntax.SrcAnn import Language.GoLite.Syntax.Sugar as Sugar import Core import Parser.For import Parser.If import Parser.Switch import Parser.StmtDecl import Parser.Simple -- | Used for a specific test with blocks. varDeclStmt :: [id] -> Maybe ty -> [e] -> Fix (StatementF (Declaration tyDecl (VarDecl id ty e)) ex i a c) varDeclStmt i t e = Fix $ DeclStmt $ VarDecl $ VarDeclBody i t e statement :: SpecWith () statement = do describe "assignStmt" assign describe "shortVarDecl" shortVariableDeclaration describe "exprStmt" expressionStatement describe "simpleStmt" simpleStatement describe "varDecl" variableDeclaration describe "typeDecl" typeDeclaration describe "break/continue/fallthrough" simpleKeywordStmts describe "blockStmt" blockStatement describe "switchStmt" switchStatement describe "forStmt" forStatement describe "ifStmt" ifStatement describe "returnStmt" returnStatement describe "printStmt" printStatement simpleKeywordStmts :: SpecWith () simpleKeywordStmts = do let parseStmt = parseOnly (fmap (map bareStmt) stmt) it "parses the keywords `break`, `continue` and `fallthrough`" $ do parseStmt "break" `shouldBe` r [breakStmt] parseStmt "continue" `shouldBe` r [continueStmt] -- fallthrough is not supported parseStmt "fallthrough" `shouldSatisfy` isLeft it "does not parses if the keywords are missing a semi" $ do parseStmt "break {}" `shouldSatisfy` isLeft parseStmt "continue {}" `shouldSatisfy` isLeft blockStatement :: SpecWith () blockStatement = do let parseBlock = parseOnly (fmap bareStmt blockStmt) it "parses a block containing one, many or no statements" $ do parseBlock "{}" `shouldBe` r (block []) parseBlock "{x++\n}" `shouldBe` r (block [increment (variable "x")]) parseBlock "{x++\ny++\n}" `shouldBe` r (block [ increment (variable "x") , increment (variable "y") ] ) it "doesn't parse if one of the enclosing statements don't have a semi" $ do parseBlock "{x++}" `shouldSatisfy` isLeft parseBlock "{x++; y++}" `shouldSatisfy` isLeft it "doesn't parse if the block doesn't have a semi" $ do parseBlock "{} {}" `shouldSatisfy` isLeft it "parses nested blocks" $ do parseBlock "{x++;{y++;{z++;};};}" `shouldBe` r (block [ increment (variable "x") , block [ increment (variable "y") , block [ increment (variable "z") ] ] ] ) it "handles statements parsers that return multiple statements" $ do parseBlock "{var (x = 2; y = 3;); x++;}" `shouldBe` r (block [ varDeclStmt ["x"] Nothing [int 2] , varDeclStmt ["y"] Nothing [int 3] , increment (variable "x") ] ) it "does not parse if there are no or missing braces" $ do parseBlock "x++" `shouldSatisfy` isLeft parseBlock "{x++" `shouldSatisfy` isLeft parseBlock "x++;}" `shouldSatisfy` isLeft returnStatement :: SpecWith () returnStatement = do let parseReturn = parseOnly (fmap bareStmt returnStmtP) it "parses return statements with or without an expression" $ do parseReturn "return" `shouldBe` r (returnStmt Nothing) parseReturn "return 3" `shouldBe` r (returnStmt $ Just (int 3)) it "does not parse return statements with more than one expression" $ do parseReturn "return 3, 3" `shouldSatisfy` isLeft it "does not parse if there is no `return` keyword" $ do parseReturn "3, 3" `shouldSatisfy` isLeft parseReturn "3" `shouldSatisfy` isLeft it "needs a semi if there is no expr, or no semi if there is an expr" $ do parseReturn "return; 3" `shouldSatisfy` isLeft parseReturn "return\n 3" `shouldSatisfy` isLeft parseReturn "return {}" `shouldSatisfy` isLeft printStatement :: SpecWith () printStatement = do let parsePrint = parseOnly (fmap bareStmt printStmtP) it "parses print statements with or without expressions" $ do parsePrint "print()" `shouldBe` r (printStmt []) parsePrint "print(3)" `shouldBe` r (printStmt [int 3]) parsePrint "print(3, 4)" `shouldBe` r (printStmt [int 3, int 4]) parsePrint "println()" `shouldBe` r (printStmt [stringLit "\n"]) parsePrint "println(3)" `shouldBe` r (printStmt [int 3, stringLit "\n"]) parsePrint "println(3, 4)" `shouldBe` r (printStmt [int 3, int 4, stringLit "\n"]) it "does not parse if the keyword is missing" $ do parsePrint "(3)" `shouldSatisfy` isLeft parsePrint "(3, 4)" `shouldSatisfy` isLeft it "does not parse if one of the expressions has a semi" $ do parsePrint "print(3;)" `shouldSatisfy` isLeft parsePrint "print(3;, 4)" `shouldSatisfy` isLeft parsePrint "print(4, 3;)" `shouldSatisfy` isLeft parsePrint "print(;)" `shouldSatisfy` isLeft parsePrint "println(3;)" `shouldSatisfy` isLeft parsePrint "println(3;, 4)" `shouldSatisfy` isLeft parsePrint "println(4, 3;)" `shouldSatisfy` isLeft parsePrint "println(;)" `shouldSatisfy` isLeft it "does not parse if the parens are missing/malformed" $ do parsePrint "print 3" `shouldSatisfy` isLeft parsePrint "print(3" `shouldSatisfy` isLeft parsePrint "print 3)" `shouldSatisfy` isLeft parsePrint "println 3" `shouldSatisfy` isLeft parsePrint "println(3" `shouldSatisfy` isLeft parsePrint "println 3)" `shouldSatisfy` isLeft it "does not parse if the keyword has an explicit semi" $ do parsePrint "print; (3)" `shouldSatisfy` isLeft parsePrint "print\n (3)" `shouldSatisfy` isRight parsePrint "println; (3)" `shouldSatisfy` isLeft parsePrint "println\n (3)" `shouldSatisfy` isRight
djeik/goto
test/Parser/Stmt.hs
mit
6,670
0
21
1,926
1,522
735
787
129
1
import FPPrac stijgend :: [Number] -> Bool stijgend [x] = True stijgend (x:xs) | x > head xs = False | otherwise = stijgend xs zwakStijgend :: [Number] -> Bool zwakStijgend [x] = True zwakStijgend xs | last xs < average (take (length xs - 1) xs) = False | otherwise = zwakStijgend (take (length xs - 1) xs) average :: [Number] -> Number average xs = sum xs / fromIntegral (length xs)
tcoenraad/functioneel-programmeren
practica/serie2/5.increasing.hs
mit
419
0
14
108
201
98
103
11
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module CTT where import Control.Applicative import Data.List import Data.Maybe import Data.Map (Map,(!),filterWithKey,elems) import qualified Data.Map as Map import Text.PrettyPrint as PP import Connections -------------------------------------------------------------------------------- -- | Terms data Loc = Loc { locFile :: String , locPos :: (Int,Int) } deriving Eq type Ident = String type LIdent = String -- Telescope (x1 : A1) .. (xn : An) type Tele = [(Ident,Ter)] data Label = OLabel LIdent Tele -- Object label | PLabel LIdent Tele [Name] (System Ter) -- Path label deriving (Eq,Show) -- OBranch of the form: c x1 .. xn -> e -- PBranch of the form: c x1 .. xn i1 .. im -> e data Branch = OBranch LIdent [Ident] Ter | PBranch LIdent [Ident] [Name] Ter deriving (Eq,Show) -- Declarations: x : A = e type Decl = (Ident,(Ter,Ter)) declIdents :: [Decl] -> [Ident] declIdents decls = [ x | (x,_) <- decls ] declTers :: [Decl] -> [Ter] declTers decls = [ d | (_,(_,d)) <- decls ] declTele :: [Decl] -> Tele declTele decls = [ (x,t) | (x,(t,_)) <- decls ] declDefs :: [Decl] -> [(Ident,Ter)] declDefs decls = [ (x,d) | (x,(_,d)) <- decls ] labelTele :: Label -> (LIdent,Tele) labelTele (OLabel c ts) = (c,ts) labelTele (PLabel c ts _ _) = (c,ts) labelName :: Label -> LIdent labelName = fst . labelTele labelTeles :: [Label] -> [(LIdent,Tele)] labelTeles = map labelTele lookupLabel :: LIdent -> [Label] -> Maybe Tele lookupLabel x xs = lookup x (labelTeles xs) lookupPLabel :: LIdent -> [Label] -> Maybe (Tele,[Name],System Ter) lookupPLabel x xs = listToMaybe [ (ts,is,es) | PLabel y ts is es <- xs, x == y ] branchName :: Branch -> LIdent branchName (OBranch c _ _) = c branchName (PBranch c _ _ _) = c lookupBranch :: LIdent -> [Branch] -> Maybe Branch lookupBranch _ [] = Nothing lookupBranch x (b:brs) = case b of OBranch c _ _ | x == c -> Just b | otherwise -> lookupBranch x brs PBranch c _ _ _ | x == c -> Just b | otherwise -> lookupBranch x brs -- Terms data Ter = App Ter Ter | Pi Ter | Lam Ident Ter Ter | Where Ter [Decl] | Var Ident | U -- Sigma types: | Sigma Ter | Pair Ter Ter | Fst Ter | Snd Ter -- constructor c Ms | Con LIdent [Ter] | PCon LIdent Ter [Ter] [Formula] -- c A ts phis (A is the data type) -- branches c1 xs1 -> M1,..., cn xsn -> Mn | Split Ident Loc Ter [Branch] -- labelled sum c1 A1s,..., cn Ans (assumes terms are constructors) | Sum Loc Ident [Label] -- TODO: should only contain OLabels | HSum Loc Ident [Label] -- undefined and holes | Undef Loc Ter -- Location and type | Hole Loc -- Id type | IdP Ter Ter Ter | Path Name Ter | AppFormula Ter Formula -- Kan composition and filling | Comp Ter Ter (System Ter) | Fill Ter Ter (System Ter) -- Glue | Glue Ter (System Ter) | GlueElem Ter (System Ter) deriving Eq -- For an expression t, returns (u,ts) where u is no application and t = u ts unApps :: Ter -> (Ter,[Ter]) unApps = aux [] where aux :: [Ter] -> Ter -> (Ter,[Ter]) aux acc (App r s) = aux (s:acc) r aux acc t = (t,acc) mkApps :: Ter -> [Ter] -> Ter mkApps (Con l us) vs = Con l (us ++ vs) mkApps t ts = foldl App t ts mkWheres :: [[Decl]] -> Ter -> Ter mkWheres [] e = e mkWheres (d:ds) e = Where (mkWheres ds e) d -------------------------------------------------------------------------------- -- | Values data Val = VU | Ter Ter Env | VPi Val Val | VSigma Val Val | VPair Val Val | VCon LIdent [Val] | VPCon LIdent Val [Val] [Formula] -- Id values | VIdP Val Val Val | VPath Name Val | VComp Val Val (System Val) -- Glue values | VGlue Val (System Val) | VGlueElem Val (System Val) -- Composition for HITs; the type is constant | VHComp Val Val (System Val) -- Neutral values: | VVar Ident Val | VFst Val | VSnd Val | VUnGlueElem Val Val (System Val) | VSplit Val Val | VApp Val Val | VAppFormula Val Formula | VLam Ident Val Val deriving Eq isNeutral :: Val -> Bool isNeutral v = case v of Ter Undef{} _ -> True Ter Hole{} _ -> True VVar{} -> True VComp{} -> True VFst{} -> True VSnd{} -> True VSplit{} -> True VApp{} -> True VAppFormula{} -> True VUnGlueElem{} -> True _ -> False isNeutralSystem :: System Val -> Bool isNeutralSystem = any isNeutral . elems -- isNeutralPath :: Val -> Bool -- isNeutralPath (VPath _ v) = isNeutral v -- isNeutralPath _ = True mkVar :: Int -> String -> Val -> Val mkVar k x = VVar (x ++ show k) mkVarNice :: [String] -> String -> Val -> Val mkVarNice xs x = VVar (head (ys \\ xs)) where ys = x:map (\n -> x ++ show n) [0..] unCon :: Val -> [Val] unCon (VCon _ vs) = vs unCon v = error $ "unCon: not a constructor: " ++ show v isCon :: Val -> Bool isCon VCon{} = True isCon _ = False -- Constant path: <_> v constPath :: Val -> Val constPath = VPath (Name "_") -------------------------------------------------------------------------------- -- | Environments data Ctxt = Empty | Upd Ident Ctxt | Sub Name Ctxt | Def [Decl] Ctxt deriving (Show,Eq) -- The Idents and Names in the Ctxt refer to the elements in the two -- lists. This is more efficient because acting on an environment now -- only need to affect the lists and not the whole context. type Env = (Ctxt,[Val],[Formula]) emptyEnv :: Env emptyEnv = (Empty,[],[]) def :: [Decl] -> Env -> Env def ds (rho,vs,fs) = (Def ds rho,vs,fs) sub :: (Name,Formula) -> Env -> Env sub (i,phi) (rho,vs,fs) = (Sub i rho,vs,phi:fs) upd :: (Ident,Val) -> Env -> Env upd (x,v) (rho,vs,fs) = (Upd x rho,v:vs,fs) upds :: [(Ident,Val)] -> Env -> Env upds xus rho = foldl (flip upd) rho xus updsTele :: Tele -> [Val] -> Env -> Env updsTele tele vs = upds (zip (map fst tele) vs) subs :: [(Name,Formula)] -> Env -> Env subs iphis rho = foldl (flip sub) rho iphis mapEnv :: (Val -> Val) -> (Formula -> Formula) -> Env -> Env mapEnv f g (rho,vs,fs) = (rho,map f vs,map g fs) valAndFormulaOfEnv :: Env -> ([Val],[Formula]) valAndFormulaOfEnv (_,vs,fs) = (vs,fs) valOfEnv :: Env -> [Val] valOfEnv = fst . valAndFormulaOfEnv formulaOfEnv :: Env -> [Formula] formulaOfEnv = snd . valAndFormulaOfEnv domainEnv :: Env -> [Name] domainEnv (rho,_,_) = domCtxt rho where domCtxt rho = case rho of Empty -> [] Upd _ e -> domCtxt e Def ts e -> domCtxt e Sub i e -> i : domCtxt e -- Extract the context from the environment, used when printing holes contextOfEnv :: Env -> [String] contextOfEnv rho = case rho of (Empty,_,_) -> [] (Upd x e,VVar n t:vs,fs) -> (n ++ " : " ++ show t) : contextOfEnv (e,vs,fs) (Upd x e,v:vs,fs) -> (x ++ " = " ++ show v) : contextOfEnv (e,vs,fs) (Def _ e,vs,fs) -> contextOfEnv (e,vs,fs) (Sub i e,vs,phi:fs) -> (show i ++ " = " ++ show phi) : contextOfEnv (e,vs,fs) -------------------------------------------------------------------------------- -- | Pretty printing instance Show Env where show = render . showEnv True showEnv :: Bool -> Env -> Doc showEnv b e = let -- This decides if we should print "x = " or not names x = if b then text x <+> equals else PP.empty showEnv1 e = case e of (Upd x env,u:us,fs) -> showEnv1 (env,us,fs) <+> names x <+> showVal u <> comma (Sub i env,us,phi:fs) -> showEnv1 (env,us,fs) <+> names (show i) <+> text (show phi) <> comma (Def _ env,vs,fs) -> showEnv1 (env,vs,fs) _ -> showEnv b e in case e of (Empty,_,_) -> PP.empty (Def _ env,vs,fs) -> showEnv b (env,vs,fs) (Upd x env,u:us,fs) -> parens (showEnv1 (env,us,fs) <+> names x <+> showVal u) (Sub i env,us,phi:fs) -> parens (showEnv1 (env,us,fs) <+> names (show i) <+> text (show phi)) instance Show Loc where show = render . showLoc showLoc :: Loc -> Doc showLoc (Loc name (i,j)) = text (show (i,j) ++ " in " ++ name) showFormula :: Formula -> Doc showFormula phi = case phi of _ :\/: _ -> parens (text (show phi)) _ :/\: _ -> parens (text (show phi)) _ -> text $ show phi instance Show Ter where show = render . showTer showTer :: Ter -> Doc showTer v = case v of U -> char 'U' App e0 e1 -> showTer e0 <+> showTer1 e1 Pi e0 -> text "Pi" <+> showTer e0 Lam x t e -> char '\\' <> parens (text x <+> colon <+> showTer t) <+> text "->" <+> showTer e Fst e -> showTer1 e <> text ".1" Snd e -> showTer1 e <> text ".2" Sigma e0 -> text "Sigma" <+> showTer1 e0 Pair e0 e1 -> parens (showTer e0 <> comma <> showTer e1) Where e d -> showTer e <+> text "where" <+> showDecls d Var x -> text x Con c es -> text c <+> showTers es PCon c a es phis -> text c <+> braces (showTer a) <+> showTers es <+> hsep (map ((char '@' <+>) . showFormula) phis) Split f _ _ _ -> text f Sum _ n _ -> text n HSum _ n _ -> text n Undef{} -> text "undefined" Hole{} -> text "?" IdP e0 e1 e2 -> text "IdP" <+> showTers [e0,e1,e2] Path i e -> char '<' <> text (show i) <> char '>' <+> showTer e AppFormula e phi -> showTer1 e <+> char '@' <+> showFormula phi Comp e t ts -> text "comp" <+> showTers [e,t] <+> text (showSystem ts) Fill e t ts -> text "fill" <+> showTers [e,t] <+> text (showSystem ts) Glue a ts -> text "glue" <+> showTer1 a <+> text (showSystem ts) GlueElem a ts -> text "glueElem" <+> showTer1 a <+> text (showSystem ts) showTers :: [Ter] -> Doc showTers = hsep . map showTer1 showTer1 :: Ter -> Doc showTer1 t = case t of U -> char 'U' Con c [] -> text c Var{} -> showTer t Undef{} -> showTer t Hole{} -> showTer t Split{} -> showTer t Sum{} -> showTer t HSum{} -> showTer t Fst{} -> showTer t Snd{} -> showTer t _ -> parens (showTer t) showDecls :: [Decl] -> Doc showDecls defs = hsep $ punctuate comma [ text x <+> equals <+> showTer d | (x,(_,d)) <- defs ] instance Show Val where show = render . showVal showVal :: Val -> Doc showVal v = case v of VU -> char 'U' Ter t@Sum{} rho -> showTer t <+> showEnv False rho Ter t@HSum{} rho -> showTer t <+> showEnv False rho Ter t@Split{} rho -> showTer t <+> showEnv False rho Ter t rho -> showTer1 t <+> showEnv True rho VCon c us -> text c <+> showVals us VPCon c a us phis -> text c <+> braces (showVal a) <+> showVals us <+> hsep (map ((char '@' <+>) . showFormula) phis) VHComp v0 v1 vs -> text "hComp" <+> showVals [v0,v1] <+> text (showSystem vs) VPi a l@(VLam x t b) | "_" `isPrefixOf` x -> showVal a <+> text "->" <+> showVal1 b | otherwise -> char '(' <> showLam v VPi a b -> text "Pi" <+> showVals [a,b] VPair u v -> parens (showVal u <> comma <> showVal v) VSigma u v -> text "Sigma" <+> showVals [u,v] VApp u v -> showVal u <+> showVal1 v VLam{} -> text "\\(" <> showLam v VPath{} -> char '<' <> showPath v VSplit u v -> showVal u <+> showVal1 v VVar x _ -> text x VFst u -> showVal1 u <> text ".1" VSnd u -> showVal1 u <> text ".2" VUnGlueElem v b hs -> text "unGlueElem" <+> showVals [v,b] <+> text (showSystem hs) VIdP v0 v1 v2 -> text "IdP" <+> showVals [v0,v1,v2] VAppFormula v phi -> showVal v <+> char '@' <+> showFormula phi VComp v0 v1 vs -> text "comp" <+> showVals [v0,v1] <+> text (showSystem vs) VGlue a ts -> text "glue" <+> showVal1 a <+> text (showSystem ts) VGlueElem a ts -> text "glueElem" <+> showVal1 a <+> text (showSystem ts) showPath :: Val -> Doc showPath e = case e of VPath i a@VPath{} -> text (show i) <+> showPath a VPath i a -> text (show i) <> char '>' <+> showVal a _ -> showVal e -- Merge lambdas of the same type showLam :: Val -> Doc showLam e = case e of VLam x t a@(VLam _ t' _) | t == t' -> text x <+> showLam a | otherwise -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal a VPi _ (VLam x t a@(VPi _ (VLam _ t' _))) | t == t' -> text x <+> showLam a | otherwise -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal a VLam x t e -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal e VPi _ (VLam x t e) -> text x <+> colon <+> showVal t <> char ')' <+> text "->" <+> showVal e _ -> showVal e showVal1 :: Val -> Doc showVal1 v = case v of VU -> showVal v VCon c [] -> showVal v VVar{} -> showVal v VFst{} -> showVal v VSnd{} -> showVal v _ -> parens (showVal v) showVals :: [Val] -> Doc showVals = hsep . map showVal1
hansbugge/cubicaltt
CTT.hs
mit
13,647
0
17
4,242
5,664
2,912
2,752
320
25
{-# htermination intersectFM :: Ord a => FiniteMap a b -> FiniteMap a b -> FiniteMap a b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_intersectFM_1.hs
mit
110
0
3
21
5
3
2
1
0
module Inference.Ast where import NameResolution.Ast import GlobalAst (SourceRange(..), TSize(..), BinOp(..), UnOp(..), TerminatorType(..), location, Source, Inline(..)) import qualified Data.Map as M type CallableDef = CallableDefT TypeKey CompoundAccess Literal data CallableDefT t a l = FuncDef { callableName :: String , finalType :: t , intypes :: [t] , outtype :: t , inargs :: [Resolved] , outarg :: Resolved , callableBody :: StatementT t a l , callableRange :: SourceRange } | ProcDef { callableName :: String , finalType :: t , intypes :: [t] , outtypes :: [t] , inargs :: [Resolved] , outargs :: [Resolved] , callableBody :: StatementT t a l , callableRange :: SourceRange } type Statement = StatementT TypeKey CompoundAccess Literal data StatementT t a l = ProcCall Inline (ExpressionT t a l) [ExpressionT t a l] [Either (StatementT t a l) (ExpressionT t a l)] SourceRange | Defer (StatementT t a l) SourceRange | ShallowCopy (ExpressionT t a l) (ExpressionT t a l) SourceRange | If (ExpressionT t a l) (StatementT t a l) (Maybe (StatementT t a l)) SourceRange | While (ExpressionT t a l) (StatementT t a l) SourceRange | Scope [StatementT t a l] SourceRange | Terminator TerminatorType SourceRange | VarInit Bool Resolved (ExpressionT t a l) SourceRange type Expression = ExpressionT TypeKey CompoundAccess Literal data ExpressionT t a l = Bin BinOp (ExpressionT t a l) (ExpressionT t a l) SourceRange | Un UnOp (ExpressionT t a l) SourceRange | CompoundAccess (ExpressionT t a l) a SourceRange | Variable Resolved t SourceRange | FuncCall Inline (ExpressionT t a l) [ExpressionT t a l] t SourceRange | ExprLit l deriving Show data Default = Default | External deriving (Show, Eq) type RepMap = M.Map Resolved (Default, Expression) data CompoundAccess = Expanded RepMap (Maybe Expression) Expression | ExpandedMember String | ExpandedSubscript Expression data Literal = ILit Integer TypeKey SourceRange | FLit Double TypeKey SourceRange | BLit Bool SourceRange | Null TypeKey SourceRange | Undef TypeKey SourceRange | Zero TypeKey SourceRange | StructLit [Expression] TypeKey SourceRange bool :: TypeKey bool = TypeKey 0 newtype TypeKey = TypeKey { representation :: Int } deriving (Eq, Ord, Show) data FlatType = IntT TSize | UIntT TSize | FloatT TSize | BoolT | PointerT TypeKey | StructT [(String, TypeKey)] | FuncT [TypeKey] TypeKey | ProcT [TypeKey] [TypeKey] deriving (Show, Eq, Ord) instance Source (CallableDefT t a l) where location = callableRange
elegios/datalang
src/Inference/Ast.hs
mit
3,458
0
10
1,381
891
512
379
66
1
{-# LANGUAGE CPP #-} {- | Module : $Header$ Description : run hets as server Copyright : (c) Christian Maeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable (via imports) -} module PGIP.Server (hetsServer) where import PGIP.Query as Query import Driver.Options import Driver.ReadFn #ifdef OLDSERVER import Network.Wai.Handler.SimpleServer import Control.Monad.Trans (lift) #else import Network.Wai.Handler.Warp import Network.HTTP.Types (Status, status200, status400, status403, status405) import Control.Monad.Trans (lift, liftIO) import qualified Data.Text as T #endif import Network.Wai import Network.Wai.Parse import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.ByteString.Char8 as B8 import Static.AnalysisLibrary import Static.ApplyChanges import Static.ComputeTheory import Static.DevGraph import Static.DgUtils import Static.DotGraph import Static.FromXml import Static.GTheory import Static.PrintDevGraph import Static.ToXml as ToXml import Syntax.ToXml import Interfaces.Command import Interfaces.CmdAction import Comorphisms.LogicGraph import Logic.Prover import Logic.Grothendieck import Logic.Comorphism import Logic.Logic import Proofs.AbstractState import Text.XML.Light import Text.XML.Light.Cursor hiding (findChild) import Common.Doc import Common.DocUtils (Pretty, pretty, showGlobalDoc, showDoc) import Common.ExtSign (ExtSign (..)) import Common.GtkGoal import Common.LibName import Common.PrintLaTeX import Common.Result import Common.ResultT import Common.ToXml import Common.Utils import Common.XUpdate import Control.Monad import qualified Data.IntMap as IntMap import qualified Data.Map as Map import qualified Data.Set as Set import Data.Char import Data.IORef import Data.List import Data.Ord import Data.Graph.Inductive.Graph (lab) import Data.Time.Clock import System.Random import System.Process import System.Directory import System.Exit import System.FilePath import System.IO data Session = Session { sessLibEnv :: LibEnv , sessLibName :: LibName , _previousKeys :: [Int] , _sessStart :: UTCTime } randomKey :: IO Int randomKey = randomRIO (100000000, 999999999) sessGraph :: DGQuery -> Session -> Maybe (LibName, DGraph) sessGraph dgQ (Session le ln _ _) = case dgQ of DGQuery _ (Just path) -> find (\ (n, _) -> show (getLibId n) == path) $ Map.toList le _ -> fmap (\ dg -> (ln, dg)) $ Map.lookup ln le hetsServer :: HetcatsOpts -> IO () hetsServer opts1 = do tempDir <- getTemporaryDirectory let tempHetsLib = tempDir </> "MyHetsLib" permFile = tempDir </> "empty.txt" opts = opts1 { libdirs = tempHetsLib : libdirs opts1 } createDirectoryIfMissing False tempHetsLib writeFile permFile "" sessRef <- newIORef IntMap.empty run 8000 $ \ re -> do let (query, splitQuery) = queryToString $ queryString re rhost = shows (remoteHost re) "\n" bots = ["crawl", "ffff:66.249."] #ifdef OLDSERVER queryToString s = let r = B8.unpack s in (r, map ((\ l -> case l of [] -> error "queryToString" [x] -> (x, Nothing) x : t -> (x, Just $ intercalate "=" t)) . splitOn '=') . concatMap (splitOn ';') . splitOn '&' . dropWhile (== '?') $ filter (not . isSpace) r) path = dropWhile (== '/') . B8.unpack $ pathInfo re pathBits = splitOn '/' path liftRun = id #else queryToString s = let r = map (\ (bs, ms) -> (B8.unpack bs, fmap B8.unpack ms)) s in (('?' :) . intercalate "&" $ map (\ (x, ms) -> x ++ maybe "" ('=' :) ms) r, r) pathBits = map T.unpack $ pathInfo re path = intercalate "/" pathBits liftRun = liftIO #endif liftRun $ do time <- getCurrentTime createDirectoryIfMissing False tempHetsLib m <- readIORef sessRef appendFile permFile $ shows time " sessions: " ++ shows (IntMap.size m) "\n" appendFile permFile rhost appendFile permFile $ shows (requestHeaders re) "\n" -- better try to read hosts to exclude from a file if any (`isInfixOf` rhost) bots then return $ mkResponse status403 "" else let -- extract params from query for later use mNot f = maybe Nothing f format = mNot id $ lookup "format" splitQuery session = mNot (mNot readMaybe) $ lookup "session" splitQuery library = mNot (mNot (Just . decodeQueryCode)) $ lookup "library" splitQuery dgQ = case (session, library) of (Just i, _) -> DGQuery i library (_, Just l) -> NewDGQuery l _ -> undefined -- TODO proper error code! -- TODO use Common.Iri to parse and use Iris correctly!! in case B8.unpack (requestMethod re) of "GET" -> liftRun $ case pathBits of "menues" : [] -> mkMenuResponse "dir" : r -> getHetsLibContent opts (intercalate "/" r) query >>= mkHtmlPage path "hets-lib" : r -> let file = intercalate "/" r in getHetsResponse' opts [] sessRef $ Query (NewDGQuery file) $ DisplayQuery format "libraries" : libIri : "development_graph" : [] -> let libnm = decodeQueryCode libIri in getHetsResponse' opts [] sessRef $ Query (NewDGQuery libnm) $ DisplayQuery format "sessions" : sessIri : [] -> case readMaybe $ decodeQueryCode sessIri of Just i -> getHetsResponse' opts [] sessRef $ Query (DGQuery i Nothing) $ DisplayQuery format Nothing -> undefined -- TODO what kind of error message "nodes" : nodeIri : cmd -> let i = (\ s -> if isNat s then Left (read s) else Right s) $ decodeQueryCode nodeIri in getHetsResponse' opts [] sessRef $ Query dgQ $ NodeQuery i $ case cmd of ["theory"] -> NcCmd Query.Theory _ -> NcCmd Query.Info "edges" : edgeIri : [] -> let i = EdgeId $ maybe (-1) id $ readMaybe $ decodeQueryCode edgeIri in getHetsResponse' opts [] sessRef $ Query dgQ $ EdgeQuery i "edge" -- default case if query doesn't comply with RESTFullInterface _ -> if query == "?menus" then mkMenuResponse else do dirs@(_ : cs) <- getHetsLibContent opts path query if null cs then getHetsResponse opts [] sessRef pathBits splitQuery else mkHtmlPage path dirs -- TODO continue implementing restfull interface responses here m | m == "PUT" || m == "POST" -> do (params, files) <- parseRequestBody tempFileSink re liftRun $ print params mTmpFile <- liftRun $ case lookup "content" $ map (\ (a, b) -> (B8.unpack a, b)) params of Nothing -> return Nothing Just areatext -> let content = B8.unpack areatext in if all isSpace content then return Nothing else do tmpFile <- getTempFile content "temp.het" copyPermissions permFile tmpFile return $ Just tmpFile let res tmpFile = getHetsResponse opts [] sessRef [tmpFile] splitQuery mRes = maybe (return $ mkResponse status400 "nothing submitted") res mTmpFile liftRun $ case files of [] -> if isPrefixOf "?prove=" query then getHetsResponse opts [] sessRef pathBits $ splitQuery ++ map (\ (a, b) -> (B8.unpack a, Just $ B8.unpack b)) params else mRes [(_, f)] | query /= "?update" -> do let fn = takeFileName $ B8.unpack $ fileName f if any isAlphaNum fn then do let tmpFile = tempHetsLib </> fn snkFile = fileContent f copyPermissions permFile snkFile copyFile snkFile tmpFile maybe (res tmpFile) res mTmpFile else mRes _ -> getHetsResponse opts (map snd files) sessRef pathBits splitQuery _ -> return $ mkResponse status405 "" mkMenuResponse :: IO Response mkMenuResponse = return $ mkOkResponse $ ppTopElement $ unode "menus" mkMenus mkMenus :: [Element] mkMenus = menuTriple "" "Get menu triples" "menus" : menuTriple "/DGraph" "update" "update" : map (\ (c, _) -> menuTriple "/" (menuTextGlobCmd c) $ cmdlGlobCmd c) allGlobLibAct ++ map (\ nc -> menuTriple "/DGraph/DGNode" ("Show " ++ nc) nc) nodeCommands ++ [menuTriple "/DGraph/DGLink" "Show edge info" "edge"] menuTriple :: String -> String -> String -> Element menuTriple q d c = unode "triple" [ unode "xquery" q , unode "displayname" d , unode "command" c ] mkHtmlString :: FilePath -> [Element] -> String mkHtmlString path dirs = htmlHead ++ mkHtmlElem ("Listing of" ++ if null path then " repository" else ": " ++ path) (headElems path ++ [unode "ul" dirs]) mkHtmlElem :: String -> [Element] -> String mkHtmlElem title body = ppElement $ unode "html" [ unode "head" $ unode "title" title, unode "body" body ] -- include a script within page (manual tags to avoid encoding) mkHtmlElemScript :: String -> String -> [Element] -> String mkHtmlElemScript title scr body = "<html>\n<head>\n" ++ ppElement (unode "title" title) ++ "\n<script type=text/javascript>" ++ scr ++ "</script>\n</head>\n" ++ ppElement (unode "body" body) ++ "</html>" mkHtmlPage :: FilePath -> [Element] -> IO Response mkHtmlPage path = return . mkOkResponse . mkHtmlString path mkResponse :: Status -> String -> Response mkResponse st = #ifdef OLDSERVER Response st [] . ResponseLBS #else responseLBS st [] #endif . BS.pack mkOkResponse :: String -> Response mkOkResponse = mkResponse status200 addNewSess :: IORef (IntMap.IntMap Session) -> Session -> IO Int addNewSess sessRef sess = do k <- randomKey atomicModifyIORef sessRef (\ m -> (IntMap.insert k sess m, k)) nextSess :: IORef (IntMap.IntMap Session) -> LibEnv -> Int -> IO Session nextSess sessRef newLib k = atomicModifyIORef sessRef (\ m -> case IntMap.lookup k m of Nothing -> error "nextSess" Just s -> let newSess = s { sessLibEnv = newLib } in (IntMap.insert k newSess m, newSess)) ppDGraph :: DGraph -> Maybe PrettyType -> ResultT IO String ppDGraph dg mt = let ga = globalAnnos dg in case optLibDefn dg of Nothing -> fail "parsed LIB-DEFN not avaible" Just ld -> let latex = renderLatex Nothing (toLatex ga $ pretty ld) in case mt of Just pty -> case pty of PrettyXml -> return $ ppTopElement $ xmlLibDefn ga ld PrettyAscii -> return $ showGlobalDoc ga ld "\n" PrettyHtml -> return $ htmlHead ++ renderHtml ga (pretty ld) PrettyLatex -> return latex Nothing -> lift $ do tmpDir <- getTemporaryDirectory tmpFile <- writeTempFile (latexHeader ++ latex ++ latexFooter) tmpDir "temp.tex" copyPermissions (tmpDir </> "empty.txt") tmpFile mapM_ (\ s -> do let sty = (</> "hetcasl.sty") f = sty s ex <- doesFileExist f when ex $ copyFile f $ sty tmpDir) [ "utils", "Hets/utils" , "/home/www.informatik.uni-bremen.de/cofi/hets-tmp" ] withinDirectory tmpDir $ do (ex1, out1, err1) <- readProcessWithExitCode "pdflatex" [tmpFile] "" (ex2, out2, err2) <- readProcessWithExitCode "pdflatex" [tmpFile] "" let pdfFile = replaceExtension tmpFile "pdf" pdf <- doesFileExist pdfFile if ex1 == ExitSuccess && ex2 == ExitSuccess && pdf then do pdfHdl <- openBinaryFile pdfFile ReadMode str <- hGetContents pdfHdl when (length str < 0) $ putStrLn "pdf file too large" hClose pdfHdl return str else return $ "could not create pdf:\n" ++ unlines [out1, err1, out2, err2] getDGraph :: HetcatsOpts -> IORef (IntMap.IntMap Session) -> DGQuery -> ResultT IO (Session, Int) getDGraph opts sessRef dgQ = case dgQ of NewDGQuery file -> do (ln, le) <- case guess file GuessIn of DgXml -> do mf <- lift $ findFileOfLibName opts file case mf of Just f -> readDGXmlR opts f Map.empty Nothing -> liftR $ fail "xml file not found" _ -> anaSourceFile logicGraph opts { outputToStdout = False, useLibPos = True } Set.empty emptyLibEnv emptyDG file time <- lift getCurrentTime let sess = Session le ln [] time k <- lift $ addNewSess sessRef sess return (sess, k) DGQuery k _ -> do m <- lift $ readIORef sessRef case IntMap.lookup k m of Nothing -> liftR $ fail "unknown development graph" Just sess -> return (sess, k) getSVG :: String -> String -> DGraph -> ResultT IO String getSVG title url dg = do (exCode, out, err) <- lift $ readProcessWithExitCode "dot" ["-Tsvg"] $ dotGraph title False url dg case exCode of ExitSuccess -> liftR $ extractSVG dg out _ -> fail err enrichSVG :: DGraph -> Element -> Element enrichSVG dg e = processSVG dg $ fromElement e processSVG :: DGraph -> Cursor -> Element processSVG dg c = case nextDF c of Nothing -> case toTree (root c) of Elem e -> e _ -> error "processSVG" Just c2 -> processSVG dg $ modifyContent (addSVGAttribs dg) c2 nodeAttrib :: DGNodeLab -> String nodeAttrib l = let nt = getRealDGNodeType l in (if isRefType nt then "Ref" else "") ++ (if hasSenKind (const True) l then (if isProvenNode nt then "P" else "Unp") ++ "roven" ++ if isProvenCons nt then "Cons" else "" else "LocallyEmpty") ++ (if isInternalSpec nt then "Internal" else "") ++ if labelHasHiding l then "HasIngoingHidingLink" else "" edgeAttrib :: DGLinkLab -> String edgeAttrib l = show (pretty $ dgl_type l) ++ if dglPending l then "IncompleteProofChain" else "" addSVGAttribs :: DGraph -> Content -> Content addSVGAttribs dg c = case c of Elem e -> case getAttrVal "id" e of Just istr | isNat istr -> let i = read istr in case getAttrVal "class" e of Just "node" -> case lab (dgBody dg) i of Nothing -> c Just l -> Elem $ add_attr (mkAttr "type" $ nodeAttrib l) e Just "edge" -> case getDGLinksById (EdgeId i) dg of [(_, _, l)] -> Elem $ add_attr (mkAttr "type" $ edgeAttrib l) e _ -> c _ -> c _ -> c _ -> c extractSVG :: DGraph -> String -> Result String extractSVG dg str = case parseXMLDoc str of Nothing -> fail "did not recognize svg element" Just e -> return $ showTopElement $ enrichSVG dg e cmpFilePath :: FilePath -> FilePath -> Ordering cmpFilePath f1 f2 = case comparing hasTrailingPathSeparator f2 f1 of EQ -> compare f1 f2 c -> c getHetsResponse :: HetcatsOpts -> [FileInfo FilePath] -> IORef (IntMap.IntMap Session) -> [String] -> [QueryPair] -> IO Response getHetsResponse opts updates sessRef pathBits query = do Result ds ms <- runResultT $ case anaUri pathBits query of Left err -> fail err Right q -> getHetsResult opts updates sessRef q return $ case ms of Nothing -> mkResponse status400 $ showRelDiags 1 ds Just s -> mkOkResponse s getHetsResponse' :: HetcatsOpts -> [FileInfo FilePath] -> IORef (IntMap.IntMap Session) -> Query -> IO Response getHetsResponse' opts updates sessRef query = do Result ds ms <- runResultT $ getHetsResult opts updates sessRef query return $ case ms of Nothing -> mkResponse status400 $ showRelDiags 1 ds Just s -> mkOkResponse s getHetsResult :: HetcatsOpts -> [FileInfo FilePath] -> IORef (IntMap.IntMap Session) -> Query -> ResultT IO String getHetsResult opts updates sessRef (Query dgQ qk) = do sk@(sess, k) <- getDGraph opts sessRef dgQ let libEnv = sessLibEnv sess case sessGraph dgQ sess of Nothing -> fail $ "unknown library given by: " ++ getQueryPath dgQ Just (ln, dg) -> let title = show $ getLibId ln in do svg <- getSVG title ('/' : show k) dg case qk of DisplayQuery ms -> case ms of Just "svg" -> return svg Just "xml" -> liftR $ return $ ppTopElement $ ToXml.dGraph libEnv ln dg Just "dot" -> liftR $ return $ dotGraph title False title dg Just "symbols" -> liftR $ return $ ppTopElement $ ToXml.dgSymbols dg Just "session" -> liftR $ return $ ppElement $ aRef (mkPath sess ln k) (show k) Just str | elem str ppList -> ppDGraph dg $ lookup str $ zip ppList prettyList _ -> liftR $ return $ sessAns ln svg sk GlobCmdQuery s -> case find ((s ==) . cmdlGlobCmd . fst) allGlobLibAct of Nothing -> if s == "update" then case filter ((== ".xupdate") . takeExtension . B8.unpack . fileName) updates of ch : _ -> do str <- lift $ readFile $ fileContent ch (newLn, newLib) <- dgXUpdate opts str libEnv ln dg newSess <- lift $ nextSess sessRef newLib k liftR $ return $ sessAns newLn svg (newSess, k) [] -> liftR $ return $ sessAns ln svg sk else fail "getHetsResult.GlobCmdQuery" Just (_, act) -> do newLib <- liftR $ act ln libEnv newSess <- lift $ nextSess sessRef newLib k liftR $ return $ sessAns ln svg (newSess, k) NodeQuery ein nc -> do nl@(i, dgnode) <- case ein of Right n -> case lookupNodeByName n dg of p : _ -> return p [] -> fail $ "no node name: " ++ n Left i -> case lab (dgBody dg) i of Nothing -> fail $ "no node id: " ++ show i Just dgnode -> return (i, dgnode) let fstLine = (if isDGRef dgnode then ("reference " ++) else if isInternalNode dgnode then ("internal " ++) else id) "node " ++ getDGNodeName dgnode ++ " (#" ++ show i ++ ")\n" ins = getImportNames dg i showN d = showGlobalDoc (globalAnnos dg) d "\n" case nc of NcCmd cmd | elem cmd [Query.Node, Info, Symbols] -> case cmd of Symbols -> return $ ppTopElement $ showSymbols ins (globalAnnos dg) dgnode _ -> return $ fstLine ++ showN dgnode _ -> case maybeResult $ getGlobalTheory dgnode of Nothing -> fail $ "cannot compute global theory of:\n" ++ fstLine Just gTh -> let subL = sublogicOfTh gTh in case nc of ProveNode incl mp mt tl thms -> do (newLib, sens) <- proveNode libEnv ln dg nl gTh subL incl mp mt tl thms if null sens then return "nothing to prove" else do lift $ nextSess sessRef newLib k return $ formatResults k $ unode "results" $ map (\ (n, e) -> unode "goal" [unode "name" n, unode "result" e]) sens _ -> return $ case nc of NcCmd Query.Theory -> showGlobalTh dg i gTh k fstLine NcProvers mt -> getProvers mt subL NcTranslations mp -> getComorphs mp subL _ -> error "getHetsResult.NodeQuery." EdgeQuery i _ -> case getDGLinksById i dg of [e@(_, _, l)] -> return $ showLEdge e ++ "\n" ++ showDoc l "" [] -> fail $ "no edge found with id: " ++ showEdgeId i _ -> fail $ "multiple edges found with id: " ++ showEdgeId i formatResults :: Int -> Element -> String formatResults sessId rs = let goBack = aRef ('/' : show sessId) "return to DGraph" in ppElement $ unode "html" [ unode "head" [ unode "title" "Results", (add_attr (mkAttr "type" "text/css") $ unode "style" resultStyles), goBack ], rs ] resultStyles :: String resultStyles = unlines [ "results { margin: 5px; padding:5px; display:block; }" , "goal { display:block; margin-left:15px; }" , "name { display:inline; margin:5px; padding:10px; font-weight:bold; }" , "result { display:inline; padding:30px; }" ] {- | displays the global theory for a node with the option to prove theorems and select proving options -} showGlobalTh :: DGraph -> Int -> G_theory -> Int -> String -> String showGlobalTh dg i gTh sessId fstLine = case simplifyTh gTh of sGTh@(G_theory lid (ExtSign sig _) _ thsens _) -> let ga = globalAnnos dg -- links to translations and provers xml view transBt = aRef ('/' : show sessId ++ "?translations=" ++ show i) "translations" prvsBt = aRef ('/' : show sessId ++ "?provers=" ++ show i) "provers" headr = unode "h3" fstLine thShow = renderHtml ga $ vcat $ map (print_named lid) $ toNamedList thsens sbShow = renderHtml ga $ pretty sig in case getThGoals sGTh of -- show simple view if no goals are found [] -> mkHtmlElem fstLine [ headr, transBt, prvsBt, unode "h4" "Theory" ] ++ sbShow ++ "\n<br />" ++ thShow -- else create proving functionality gs -> let -- create list of theorems, selectable for proving thmSl = map (\ (nm, bp) -> let gSt = maybe GOpen basicProofToGStatus bp in add_attrs [ mkAttr "type" "checkbox", mkAttr "name" $ escStr nm , mkAttr "goalstatus" $ showSimple gSt ] $ unode "input" $ nm ++ " (" ++ showSimple gSt ++ ")" ) gs -- create prove button and prover/comorphism selection (prSl, cmrSl, jvScr1) = showProverSelection $ sublogicOfTh gTh prBt = [ mkAttr "type" "submit", mkAttr "value" "Prove" ] `add_attrs` inputNode -- create timeout field timeout = add_attrs [mkAttr "type" "text", mkAttr "name" "timeout" , mkAttr "value" "1", mkAttr "size" "3"] $ unode "input" "Sec/Goal " -- select unproven goals by button selUnPr = add_attrs [mkAttr "type" "button", mkAttr "value" "Unproven" , mkAttr "onClick" "chkUnproven()"] inputNode -- select or deselect all theorems by button selAll = add_attrs [mkAttr "type" "button", mkAttr "value" "All" , mkAttr "onClick" "chkAll(true)"] inputNode deSelAll = add_attrs [mkAttr "type" "button", mkAttr "value" "None" , mkAttr "onClick" "chkAll(false)"] inputNode -- hidden param field hidStr = add_attrs [ mkAttr "name" "prove" , mkAttr "type" "hidden", mkAttr "style" "display:none;" , mkAttr "value" $ show i ] inputNode -- combine elements within a form thmMenu = let br = unode "br " () in add_attrs [mkAttr "name" "thmSel", mkAttr "method" "get"] $ unode "form" $ [hidStr, prSl, cmrSl, br, selAll, deSelAll, selUnPr, timeout] ++ intersperse br (prBt : thmSl) goBack = aRef ('/' : show sessId) "return to DGraph" -- javascript features jvScr = unlines [ jvScr1 -- select unproven goals by button , "\nfunction chkUnproven() {" , " var e = document.forms[0].elements;" , " for (i = 0; i < e.length; i++) {" , " if( e[i].type == 'checkbox' )" , " e[i].checked = e[i].getAttribute('goalstatus') != 'Proved';" , " }" -- select or deselect all theorems by button , "}\nfunction chkAll(b) {" , " var e = document.forms[0].elements;" , " for (i = 0; i < e.length; i++) {" , " if( e[i].type == 'checkbox' ) e[i].checked = b;" , " }" -- autoselect SPASS if possible , "}\nwindow.onload = function() {" , " prSel = document.forms[0].elements.namedItem('prover');" , " prs = prSel.getElementsByTagName('option');" , " for ( i=0; i<prs.length; i++ ) {" , " if( prs[i].value == 'SPASS' ) {" , " prs[i].selected = 'selected';" , " updCmSel('SPASS');" , " return;" , " }" , " }" -- if SPASS unable, select first one in list , " prs[0].selected = 'selected';" , " updCmSel( prs[0].value );" , "}" ] in mkHtmlElemScript fstLine jvScr [ headr, transBt, prvsBt, plain " ", goBack, unode "h4" "Theorems", thmMenu, unode "h4" "Theory" ] ++ sbShow ++ "\n<br />" ++ thShow -- | create prover and comorphism menu and combine them using javascript showProverSelection :: G_sublogics -> (Element, Element, String) showProverSelection subL = let jvScr = unlines -- the chosen prover is passed as param [ "\nfunction updCmSel(pr) {" , " var cmrSl = document.forms[0].elements.namedItem('translation');" -- then, all selectable comorphisms are gathered and iterated , " var opts = cmrSl.getElementsByTagName('option');" -- try to keep current comorph-selection , " var selAccept = false;" , " for( var i = opts.length-1; i >= 0; i-- ) {" , " var cmr = opts.item( i );" -- the list of supported provers is extracted , " var prs = cmr.getAttribute('4prover').split(';');" , " var pFit = false;" , " for( var j = 0; ! pFit && j < prs.length; j++ ) {" , " pFit = prs[j] == pr;" , " }" -- if prover is supported, remove disabled attribute , " if( pFit ) {" , " cmr.removeAttribute('disabled');" , " selAccept = selAccept || cmr.selected;" -- else create and append a disabled attribute , " } else {" , " var ds = document.createAttribute('disabled');" , " ds.value = 'disabled';" , " cmr.setAttributeNode(ds);" , " }" , " }" -- check if selected comorphism fits, and select fst. in list otherwise , " if( ! selAccept ) {" , " for( i = 0; i < opts.length; i++ ) {" , " if( ! opts.item(i).disabled ) {" , " opts.item(i).selected = 'selected';" , " return;" , " }" , " }" , " }" , "}" ] allPrCm = getProversAux Nothing subL -- create prover selection (drop-down) prs = add_attr (mkAttr "name" "prover") $ unode "select" $ map (\ p -> add_attrs [mkAttr "value" p, mkAttr "onClick" $ "updCmSel('" ++ p ++ "')"] $ unode "option" p) $ showProversOnly allPrCm -- create comorphism selection (drop-down) cmrs = add_attr (mkAttr "name" "translation") $ unode "select" $ map (\ (cm, ps) -> let c = showComorph cm in add_attrs [mkAttr "value" c, mkAttr "4prover" $ intercalate ";" ps] $ unode "option" c) allPrCm in (prs, cmrs, jvScr) getAllAutomaticProvers :: G_sublogics -> [(G_prover, AnyComorphism)] getAllAutomaticProvers subL = getAllProvers ProveCMDLautomatic subL logicGraph filterByProver :: Maybe String -> [(G_prover, AnyComorphism)] -> [(G_prover, AnyComorphism)] filterByProver mp = case mp of Nothing -> id Just p -> filter ((== p) . getWebProverName . fst) filterByComorph :: Maybe String -> [(G_prover, AnyComorphism)] -> [(G_prover, AnyComorphism)] filterByComorph mt = case mt of Nothing -> id Just c -> filter ((== c) . showComorph . snd) getProverAndComorph :: Maybe String -> Maybe String -> G_sublogics -> [(G_prover, AnyComorphism)] getProverAndComorph mp mc subL = let ps = filterByComorph mc $ getAllAutomaticProvers subL spps = case filterByProver (Just "SPASS") ps of [] -> ps fps -> fps in case mp of Nothing -> spps _ -> case filterByProver mp ps of [] -> spps mps -> mps showComorph :: AnyComorphism -> String showComorph (Comorphism cid) = removeFunnyChars . drop 1 . dropWhile (/= ':') . map (\ c -> if c == ';' then ':' else c) $ language_name cid removeFunnyChars :: String -> String removeFunnyChars = filter (\ c -> isAlphaNum c || elem c "_.-") getWebProverName :: G_prover -> String getWebProverName = removeFunnyChars . getProverName getProvers :: Maybe String -> G_sublogics -> String getProvers mt subL = ppTopElement . unode "provers" $ map (unode "prover") $ showProversOnly $ getProversAux mt subL showProversOnly :: [(AnyComorphism, [String])] -> [String] showProversOnly = nubOrd . concatMap snd {- | gather provers and comoprhisms and resort them to (comorhism, supported provers) while not changing orig comorphism order -} getProversAux :: Maybe String -> G_sublogics -> [(AnyComorphism, [String])] getProversAux mt subL = foldl insertCmL [] $ filterByComorph mt $ getAllAutomaticProvers subL where insertCmL [] (p, c) = [(c, [getWebProverName p])] insertCmL ((c', pL) : r) (p, c) | c' == c = (c, getWebProverName p : pL) : r | otherwise = (c', pL) : insertCmL r (p, c) getComorphs :: Maybe String -> G_sublogics -> String getComorphs mp subL = ppTopElement . unode "translations" . map (unode "comorphism") . nubOrd . map (showComorph . snd) . filterByProver mp $ getAllAutomaticProvers subL proveNode :: LibEnv -> LibName -> DGraph -> (Int, DGNodeLab) -> G_theory -> G_sublogics -> Bool -> Maybe String -> Maybe String -> Maybe Int -> [String] -> ResultT IO (LibEnv, [(String, String)]) proveNode le ln dg nl gTh subL useTh mp mt tl thms = case getProverAndComorph mp mt subL of [] -> fail "no prover found" cp : _ -> do let ks = map fst $ getThGoals gTh diffs = Set.difference (Set.fromList thms) $ Set.fromList ks unless (Set.null diffs) $ fail $ "unknown theorems: " ++ show diffs (res, prfs) <- lift $ autoProofAtNode useTh (maybe 1 (max 1) tl) thms gTh cp case prfs of Nothing -> fail "proving failed" Just sens -> if null sens then return (le, sens) else case res of Nothing -> error "proveNode" Just nTh -> return (Map.insert ln (updateLabelTheory le dg nl nTh) le, sens) mkPath :: Session -> LibName -> Int -> String mkPath sess l k = '/' : concat [ show (getLibId l) ++ "?session=" | l /= sessLibName sess ] ++ show k extPath :: Session -> LibName -> Int -> String extPath sess l k = mkPath sess l k ++ if l /= sessLibName sess then "&" else "?" sessAns :: LibName -> String -> (Session, Int) -> String sessAns libName svg (sess, k) = let libEnv = sessLibEnv sess ln = show $ getLibId libName libref l = aRef (mkPath sess l k) (show $ getLibId l) : map (\ d -> aRef (extPath sess l k ++ d) d) displayTypes libPath = extPath sess libName k ref d = aRef (libPath ++ d) d {- the html quicklinks to nodes and edges have been removed with R.16827 -} in htmlHead ++ mkHtmlElem ('(' : shows k ")" ++ ln) (bold ("library " ++ ln) : map ref displayTypes ++ menuElement : loadXUpdate (libPath ++ "update") : [plain "commands:"] ++ [mkUnorderedList $ map ref globalCommands] ++ [plain "imported libraries:"] ++ [mkUnorderedList $ map libref $ Map.keys libEnv] ) ++ svg getHetsLibContent :: HetcatsOpts -> String -> String -> IO [Element] getHetsLibContent opts dir query = do let hlibs = libdirs opts ds <- if null dir then return hlibs else filterM doesDirectoryExist $ map (</> dir) hlibs fs <- fmap (sortBy cmpFilePath . filter (not . isPrefixOf ".") . concat) $ mapM getDirContents ds return $ map (mkHtmlRef query) $ getParent dir : fs getParent :: String -> String getParent = addTrailingPathSeparator . ("/" </>) . takeDirectory . dropTrailingPathSeparator -- | a variant that adds a trailing slash getDirContents :: FilePath -> IO [FilePath] getDirContents d = do fs <- getDirectoryContents d mapM (\ f -> doesDirectoryExist (d </> f) >>= \ b -> return $ if b then addTrailingPathSeparator f else f) fs aRef :: String -> String -> Element aRef lnk txt = add_attr (mkAttr "href" lnk) $ unode "a" txt mkHtmlRef :: String -> String -> Element mkHtmlRef query entry = unode "dir" $ aRef (entry ++ query) entry mkUnorderedList :: Node t => [t] -> Element mkUnorderedList = unode "ul" . map (unode "li") italic :: String -> Element italic = unode "i" bold :: String -> Element bold = unode "b" plain :: String -> Element plain = unode "p" headElems :: String -> [Element] headElems path = let d = "default" in unode "strong" "Choose query type:" : map (\ q -> aRef (if q == d then "/" </> path else '?' : q) q) (d : displayTypes) ++ [menuElement, uploadHtml] menuElement :: Element menuElement = aRef "?menus" "menus" htmlHead :: String htmlHead = let dtd = "PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"" url = "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"" in concat ["<!DOCTYPE html ", dtd, " ", url, ">\n"] inputNode :: Element inputNode = unode "input" () loadNode :: String -> Element loadNode name = add_attrs [ mkAttr "type" "file" , mkAttr "name" name , mkAttr "size" "40"] inputNode submitNode :: Element submitNode = add_attrs [ mkAttr "type" "submit" , mkAttr "value" "submit"] inputNode mkForm :: String -> [Element] -> Element mkForm a = add_attrs [ mkAttr "action" a , mkAttr "enctype" "multipart/form-data" , mkAttr "method" "post" ] . unode "form" uploadHtml :: Element uploadHtml = mkForm "/" [ loadNode "file" , unode "p" $ add_attrs [ mkAttr "cols" "68" , mkAttr "rows" "22" , mkAttr "name" "content" ] $ unode "textarea" "" , submitNode ] loadXUpdate :: String -> Element loadXUpdate a = mkForm a [ italic "xupdate" , loadNode "xupdate" , italic "impacts" , loadNode "impacts" , submitNode ]
nevrenato/Hets_Fork
PGIP/Server.hs
gpl-2.0
34,313
0
41
9,938
10,001
5,036
4,965
716
29
module BWLib where -- ======================================================= -- Some important and useful functions for general purpose -- ======================================================= -- Function composition - in case of more than 1 argument comp4 = (.) . (.) . (.) . (.) comp5 = (.) . (.) . (.) . (.) . (.) fstOf3 (a,b,c) = a fst2Of3 (a,b,c) = (a,b) sndOf3 (a,b,c) = b trdOf3 (a,b,c) = c fstOf5 (a,b,c,d,e) = a sndOf5 (a,b,c,d,e) = b trdOf5 (a,b,c,d,e) = c frthOf5 (a,b,c,d,e) = d fvthOf5 (a,b,c,d,e) = e -- Checks if all elements of the list are equall allEq :: (Eq a) => [a] -> Bool allEq ls = all ((head ls) ==) ls --zip4 [] _ _ _ = [] --zip4 (a:as) (b:bs) (c:cs) (d:ds) = (a,b,c,d):zip4 as bs cs ds --zip5 [] _ _ _ _ = [] --zip5 (a:as) (b:bs) (c:cs) (d:ds) (e:es) = (a,b,c,d,e):zip5 as bs cs ds es --zip8 [] _ _ _ _ _ _ _ = [] --zip8 (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) (h:hs) = -- (a,b,c,d,e,f,g,h):zip8 as bs cs ds es fs gs hs zip9 (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs) (h:hs) (i:is) = (a,b,c,d,e,f,g,h,i) : zip9 as bs cs ds es fs gs hs is zip9 _ _ _ _ _ _ _ _ _ = [] unzip9 = foldr (\(a,b,c,d,e,f,g,h,i) ~(as,bs,cs,ds,es,fs,gs,hs,is) -> (a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs,h:hs,i:is)) ([],[],[],[],[],[],[],[],[])
bartoszw/elca
BWLib.hs
gpl-2.0
1,394
0
9
358
651
391
260
20
1
module HayooBot.Types where import Data.ByteString.Char8 data MsgType = ChanMsg ByteString | PrivMsg ByteString data Msg = Msg { msgType :: !MsgType, msgBody :: !ByteString } data IrcConn = IrcConn { serverIP :: !ByteString, serverPort :: !Int, nickName :: !ByteString, realName :: !ByteString, channelList :: ![ByteString] }
petercommand/HayooBot
src/HayooBot/Types.hs
gpl-2.0
489
0
10
209
96
56
40
24
0
{-# LANGUAGE OverloadedStrings #-} module Sling.Proposal ( Proposal (..) , ProposalStatus (..) , ServerId (..) , MergeType (..) , ProposalType (..) , Prefix (..) , prefixFromText , prefixToText , toBranchName , fromBranchName , formatProposal , parseProposal ) where import Data.Text (Text) import qualified Data.Text as T import qualified Sling.Git as Git import Sling.Lib (Email (..), NatInt, formatSepEmail, fromNatInt, fromNonEmptyText, Hash, fromHash, hash, natInt, nonEmptyText, singleMatch, NonEmptyText, someText) import Control.Monad (void) import Control.Applicative ((<|>)) import Data.Monoid ((<>)) import Turtle (Pattern, alphaNum, char, decimal, eof, hexDigit, notChar, oneOf, some, text) newtype ServerId = ServerId { fromServerId :: Text } deriving (Show, Eq, Ord) data ProposalStatus = ProposalProposed | ProposalInProgress { _proposalInProgressServerId :: ServerId } | ProposalRejected deriving (Show, Eq, Ord) emailPat :: Text -> Pattern Email emailPat sep = do user <- nonEmptyText . T.pack <$> some (alphaNum <|> oneOf ".-_+") _ <- text sep domain <- nonEmptyText . T.pack <$> some (alphaNum <|> oneOf ".-") return $ Email user domain newtype Prefix = Prefix { fromPrefix :: NonEmptyText } deriving (Show, Eq) prefixToText :: Prefix -> Text prefixToText = fromNonEmptyText . fromPrefix prefixFromText :: Text -> Prefix prefixFromText = Prefix . nonEmptyText data MergeType = MergeTypeFlat | MergeTypeKeepMerges deriving (Show, Eq, Ord) data ProposalType = ProposalTypeRebase { _ptBranchToRebase :: Git.BranchName } | ProposalTypeMerge { _ptMergeType :: MergeType, _ptBase :: Hash } deriving (Show, Eq, Ord) data Proposal = Proposal { proposalEmail :: Email , proposalName :: Git.BranchName -- not really a branch, but it will be used as a branch name , proposalType :: ProposalType , proposalBranchOnto :: Git.BranchName , proposalQueueIndex :: NatInt , proposalStatus :: ProposalStatus , proposalDryRun :: Bool , proposalPrefix :: Maybe Prefix } deriving (Show, Eq) ontoPrefix :: Text ontoPrefix = "onto" dryRunOntoPrefix :: Text dryRunOntoPrefix = "dry-run-onto" proposalPrefixPrefix :: Text proposalPrefixPrefix = "prefix-" slashEscape :: Text slashEscape = "," formatBranchName :: Git.BranchName -> Text formatBranchName = T.replace "/" slashEscape . Git.fromBranchName branchNamePat :: Pattern Git.BranchName branchNamePat = Git.mkBranchName . T.replace slashEscape "/" . T.pack <$> some (notChar '#') proposalTypeMergePrefix :: Text proposalTypeMergePrefix = "base" proposalTypeRebasePrefix :: Text proposalTypeRebasePrefix = "rebase" mergeTypePrefix :: MergeType -> Text mergeTypePrefix MergeTypeKeepMerges = "-keep" mergeTypePrefix MergeTypeFlat = "" formatProposalType :: ProposalType -> Text formatProposalType (ProposalTypeMerge mergeType ref) = proposalTypeMergePrefix <> mergeTypePrefix mergeType <> "/" <> fromHash ref formatProposalType (ProposalTypeRebase name) = proposalTypeRebasePrefix <> "/" <> (formatBranchName name) toBranchName :: Proposal -> Git.BranchName toBranchName = Git.mkBranchName . formatProposal formatProposal :: Proposal -> Text formatProposal p = "sling/" <> prefix <> "/" <> suffix where prefix = maybe T.empty (\x -> (proposalPrefixPrefix <> prefixToText x) <> "/") (proposalPrefix p) <> case proposalStatus p of ProposalProposed -> proposedPrefix ProposalInProgress serverId -> inProgressPrefix <> "/" <> fromServerId serverId ProposalRejected -> rejectBranchPrefix suffix = T.pack (show . fromNatInt . proposalQueueIndex $ p) <> "/" <> formatBranchName (proposalName p) <> "/" <> formatProposalType (proposalType p) <> "/" <> (if proposalDryRun p then dryRunOntoPrefix else ontoPrefix) <> "/" <> formatBranchName (proposalBranchOnto p) <> "/user/" <> formatSepEmail "-at-" (proposalEmail p) hashPat :: Pattern Hash hashPat = hash . T.pack <$> some hexDigit formatRef :: Git.Ref -> Text formatRef (Git.RefParent r n) = (T.pack . show $ fromNatInt n) <> "#" <> formatRef r formatRef (Git.RefBranch (Git.RemoteBranch r n)) = "R-" <> fromNonEmptyText (Git.remoteName r) <> "/" <> formatBranchName n formatRef r@(Git.RefBranch (Git.LocalBranch{})) = "L-" <> Git.refName r formatRef r = Git.refName r fieldSep :: Pattern () fieldSep = void $ char '/' mergeTypePat :: Pattern MergeType mergeTypePat = (text (mergeTypePrefix MergeTypeKeepMerges) *> pure MergeTypeKeepMerges) <|> (pure MergeTypeFlat) movePat :: Pattern ProposalType movePat = (text proposalTypeMergePrefix *> (ProposalTypeMerge <$> mergeTypePat <*> (fieldSep *> hashPat))) <|> (text proposalTypeRebasePrefix *> fieldSep *> (ProposalTypeRebase <$> branchNamePat)) proposalPat :: Pattern Proposal proposalPat = do _ <- text slingPrefix prefix <- (text ("/" <> proposalPrefixPrefix) *> (Just . Prefix . nonEmptyText <$> (someText <* fieldSep))) <|> (fieldSep *> pure Nothing) ps <- (text proposedPrefix *> pure ProposalProposed) <|> (text rejectBranchPrefix *> pure ProposalRejected) <|> (text inProgressPrefix *> fieldSep *> (ProposalInProgress . ServerId <$> someText)) fieldSep index <- natInt <$> decimal fieldSep name <- branchNamePat fieldSep moveBranch <- movePat fieldSep isDryRun <- (text ontoPrefix *> pure False) <|> (text dryRunOntoPrefix *> pure True) fieldSep ontoRef <- branchNamePat fieldSep _ <- text "user" fieldSep email <- emailPat "-at-" _ <- eof return $ Proposal email name moveBranch ontoRef index ps isDryRun prefix parseProposal :: Text -> Maybe Proposal parseProposal = singleMatch proposalPat fromBranchName :: Git.BranchName -> Maybe Proposal fromBranchName = parseProposal . Git.fromBranchName slingPrefix :: Text slingPrefix = "sling" rejectBranchPrefix :: Text rejectBranchPrefix = "rejected" proposedPrefix :: Text proposedPrefix = "proposed" inProgressPrefix :: Text inProgressPrefix = "in-progress"
Elastifile/git-sling
server/src/Sling/Proposal.hs
gpl-2.0
6,567
0
21
1,575
1,766
943
823
151
4
module Lamdu.Sugar.Convert.Hole ( convert ) where import qualified Control.Lens.Extended as Lens import Control.Monad.Transaction (MonadTransaction(..)) import Data.Typeable (Typeable) import Hyper import Hyper.Recurse (wrap) import Hyper.Syntax (FuncType(..)) import Hyper.Syntax.Row (freExtends, freRest) import Hyper.Type.Prune (Prune(..)) import qualified Lamdu.Builtins.Anchors as Builtins import Lamdu.Calc.Definition (depsNominals) import qualified Lamdu.Calc.Term as V import qualified Lamdu.Calc.Type as T import qualified Lamdu.Expr.IRef as ExprIRef import qualified Lamdu.Expr.Load as Load import qualified Lamdu.I18N.Code as Texts import Lamdu.Sugar.Convert.Expression.Actions (addActions) import qualified Lamdu.Sugar.Convert.Input as Input import Lamdu.Sugar.Convert.Monad (ConvertM) import qualified Lamdu.Sugar.Convert.Monad as ConvertM import Lamdu.Sugar.Convert.Option import Lamdu.Sugar.Internal import Lamdu.Sugar.Types import qualified Revision.Deltum.Transaction as Transaction import Lamdu.Prelude type T = Transaction.Transaction convert :: (Monad m, Monoid a, Typeable m) => ConvertM.PositionInfo -> Input.Payload m a # V.Term -> ConvertM m (ExpressionU EvalPrep m a) convert posInfo holePl = do forType <- makeForType (holePl ^. Input.inferredType) & transaction let filtForType = filter (\x -> x ^. rExpr `notElem` (forType <&> (^. rExpr))) ResultGroups { gSyntax = makeResultsSyntax posInfo & transaction <&> filtForType , gDefs = makeGlobals makeGetDef , gLocals = makeLocals (const pure) (holePl ^. Input.inferScope) , gInjects = makeTagRes "'" ((^. hPlain) . (`V.BAppP` V.BLeafP V.LRecEmpty) . V.BLeafP . V.LInject) <&> filtForType , gToNoms = makeNoms [] "" makeToNoms , gFromNoms = makeNoms [] "." (\_ x -> pure [Result mempty (_Pure . V._BLeaf . V._LFromNom # x) mempty]) <&> filtForType , gForType = pure forType , gGetFields = makeTagRes "." (Pure . V.BLeaf . V.LGetField) , gWrapInRecs = pure [] -- Only used in fragments } <&> (>>= traverse (makeOption holePl . fmap (\x -> [((), wrap (const (Ann ExprIRef.WriteNew)) x)]))) & traverse ConvertM.convertOnce <&> filterResults const -- The call to convertOnce makes the result expressions consistent. -- If we remove all calls to convertOnce (replacing with "fmap pure"), -- they would flicker when editing the search term. & ConvertM.convertOnce <&> BodyLeaf . LeafHole . Hole >>= addActions (Const ()) holePl <&> annotation . pActions . delete .~ CannotDelete <&> annotation . pActions . mApply .~ Nothing makeToNoms :: Monad m => Pure # T.Type -> NominalId -> T m [Result (Pure # V.Term)] makeToNoms t tid = case t ^. _Pure of -- Many nominals (like Maybe, List) wrap a sum type, suggest their various injections T.TVariant r | Lens.has (freRest . _Pure . T._REmpty) f -> f ^@.. freExtends . Lens.itraversed & traverse mkVariant where f = r ^. T.flatRow mkVariant (tag, typ) = Result mempty <$> (suggestVal typ <&> (_Pure . V._BApp #) . V.App (_Pure . V._BLeaf . V._LInject # tag)) <*> (ExprIRef.readTagData tag <&> tagTexts <&> Lens.mapped %~ (>>= injTexts)) _ -> suggestVal t <&> (:[]) . (Result mempty ?? mempty) <&> traverse . rExpr %~ Pure . V.BToNom . V.ToNom tid where -- "t" will be prefix for "Bool 'true" too, -- so that one doesn't have to type the "'" prefix injTexts x = [x, "'" <> x] makeResultsSyntax :: Monad m => ConvertM.PositionInfo -> T m [Result (Pure # V.Term)] makeResultsSyntax posInfo = sequenceA [ genLamVar <&> \v -> r lamTexts (V.BLamP v Pruned (V.BLeafP V.LHole)) , r recTexts (V.BLeafP V.LRecEmpty) & pure , r caseTexts (V.BLeafP V.LAbsurd) & pure ] <> sequenceA [ genLamVar <&> \v -> r (^.. qCodeTexts . Texts.let_) (V.BLamP v Pruned (V.BLeafP V.LHole) `V.BAppP` V.BLeafP V.LHole) | posInfo == ConvertM.BinderPos ] <> do -- Suggest if-else only if bool is in the stdlib (otherwise tests fail) deps <- Load.nominal Builtins.boolTid <&> \(Right x) -> mempty & depsNominals . Lens.at Builtins.boolTid ?~ x if Lens.has (depsNominals . Lens.ix Builtins.boolTid) deps then do t <- genLamVar f <- genLamVar pure [Result { _rTexts = ifTexts , _rExpr = ( V.BLeafP V.LAbsurd & V.BCaseP Builtins.falseTag (V.BLamP f Pruned (V.BLeafP V.LHole)) & V.BCaseP Builtins.trueTag (V.BLamP t Pruned (V.BLeafP V.LHole)) ) `V.BAppP` (V.BLeafP (V.LFromNom Builtins.boolTid) `V.BAppP` V.BLeafP V.LHole) ^. hPlain , _rDeps = deps }] else pure [] where r f t = Result mempty (t ^. hPlain) f makeGetDef :: Monad m => V.Var -> Pure # T.Type -> T m (Maybe (Pure # V.Term)) makeGetDef v t = case t of Pure (T.TFun (FuncType a _)) -- Avoid filling in params for open records | Lens.nullOf (_Pure . T._TRecord . T.flatRow . freRest . _Pure . T._RVar) a -> suggestVal a <&> Pure . V.BApp . V.App base _ -> pure base <&> Just where base = _Pure . V._BLeaf . V._LVar # v
Peaker/lamdu
src/Lamdu/Sugar/Convert/Hole.hs
gpl-3.0
5,809
0
37
1,777
1,771
954
817
-1
-1
module Main where lista = 1 : 2 : prox lista where prox (x:t@(y:resto)) = (x+y):prox t main ::IO() main = do print ( sum [x| x <- (takeWhile (< 4000001) lista),x`mod`2==0])
llscm0202/BIGDATA2017
ATIVIDADE1/exerciciosListas/ex4.hs
gpl-3.0
187
2
12
46
120
66
54
6
1
module Problem042 (answer) where import Data.List.Split (splitOn) import Data.Char (ord) answer :: IO Int answer = do content <- readFile "./data/42.txt" let words = map (tail . init) (splitOn "," content) return $ length (filter isTriangleWord words) wordValue :: String -> Int wordValue w = sum $ map (\c -> ord c - ord 'A' + 1) w isInt x = x == fromInteger (round x) isTriangleWord w = isInt ((-1 + sqrt (1 + 8 * s)) / 2) where s = fromIntegral (wordValue w)
geekingfrog/project-euler
Problem042.hs
gpl-3.0
475
0
13
99
226
115
111
13
1
module Pictikz.Config where import qualified Data.DescriLo as D import Data.Char import Pictikz.Elements import System.Directory import System.Environment import Pictikz.Parser -- | Searches for the file in the following directories: -- 1. Current directory. -- 2. $XDG_CONFIG_HOME/pictikz -- 3. $HOME/.pictikz -- 4. /usr/share/pictikz -- | If the file is not found in any of these directories, the same path is returned. findFileConfig fl = do xdg <- getXdgDirectory XdgConfig "pictikz" app <- getAppUserDataDirectory "pictikz" exists <- doesFileExist fl if exists then return fl else findFileDirs fl [xdg, app, "/usr/share/paphragen"] findFileDirs fl dirs = do let dirsFl = map ( ++ ('/':fl)) dirs dirsE <- mapM doesFileExist $ dirsFl let results = dropWhile (\(fl,e) -> not e) $ zip dirsFl dirsE return $ if null results then fl else fst $ head results loadConfig fl = do fl' <- findFileConfig fl D.loadDescriptionFile fl' "heuristics" loadColors str = map (getColor . words) $ lines str where getColor (name:space:value) | (map toLower space) == "rgb" = let (r,g,b) = parseValue value 255 255 255 in (RGB r g b, name) | (map toLower space) == "hsl" = let (h,s,l) = parseValue value 359 100 100 in (fromHSL (fromIntegral h) (fromIntegral s / 100) (fromIntegral l / 100), name) parseValue (('#':hex):_) _ _ _ = readHexa hex parseValue (x:y:z:_) mx my mz = let [x1,y1,z1] = zipWith parseNumber [x, y, z] [mx, my, mz] in (x1, y1, z1) parseNumber x mx | '.' `elem` x = round $ (read x) * mx | otherwise = read x :: Int
mgmillani/pictikz
src/Pictikz/Config.hs
gpl-3.0
1,680
2
14
415
618
317
301
35
2
{-# LANGUAGE MultiParamTypeClasses #-} module Main where import Prelude hiding (read) import Control.Concurrent hiding (yield) import Data.Sequence import Data.Int import System.TimeIt import Control.Concurrent.MVar import Control.Monad.Except import Pipes readVar :: MVar a -> Producer a (ExceptT String IO) () readVar v = do x <- liftIO $ takeMVar v yield x writeVar :: Show a => MVar String -> Consumer a (ExceptT String IO) () writeVar v = do x <- show <$> await liftIO $ putMVar v x class Filter input state where filter_ :: input -> state -> input data Input = Start | Pause | Stop | Restart data State = Running | Waiting data Status = Status { statusError :: Bool , statusState :: State } instance Filter Input Status where filter_ Restart _ = Restart filter_ i s = case statusError s of True -> Pause False -> i data Do what data Done what data Cmd = Run | Wait type Request a = Do a type Response a = Done a class Monad s => Server s where request :: Request a -> s (Response a) main :: IO () main = pure ()
wowofbob/scratch
app/Loop/Main.hs
gpl-3.0
1,106
0
10
278
394
209
185
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Content.Orders.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists the orders in your Merchant Center account. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.orders.list@. module Network.Google.Resource.Content.Orders.List ( -- * REST Resource OrdersListResource -- * Creating a Request , ordersList , OrdersList -- * Request Lenses , ollXgafv , ollPlacedDateEnd , ollMerchantId , ollUploadProtocol , ollOrderBy , ollAccessToken , ollUploadType , ollAcknowledged , ollStatuses , ollPageToken , ollPlacedDateStart , ollMaxResults , ollCallback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.orders.list@ method which the -- 'OrdersList' request conforms to. type OrdersListResource = "content" :> "v2.1" :> Capture "merchantId" (Textual Word64) :> "orders" :> QueryParam "$.xgafv" Xgafv :> QueryParam "placedDateEnd" Text :> QueryParam "upload_protocol" Text :> QueryParam "orderBy" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "acknowledged" Bool :> QueryParams "statuses" OrdersListStatuses :> QueryParam "pageToken" Text :> QueryParam "placedDateStart" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] OrdersListResponse -- | Lists the orders in your Merchant Center account. -- -- /See:/ 'ordersList' smart constructor. data OrdersList = OrdersList' { _ollXgafv :: !(Maybe Xgafv) , _ollPlacedDateEnd :: !(Maybe Text) , _ollMerchantId :: !(Textual Word64) , _ollUploadProtocol :: !(Maybe Text) , _ollOrderBy :: !(Maybe Text) , _ollAccessToken :: !(Maybe Text) , _ollUploadType :: !(Maybe Text) , _ollAcknowledged :: !(Maybe Bool) , _ollStatuses :: !(Maybe [OrdersListStatuses]) , _ollPageToken :: !(Maybe Text) , _ollPlacedDateStart :: !(Maybe Text) , _ollMaxResults :: !(Maybe (Textual Word32)) , _ollCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrdersList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ollXgafv' -- -- * 'ollPlacedDateEnd' -- -- * 'ollMerchantId' -- -- * 'ollUploadProtocol' -- -- * 'ollOrderBy' -- -- * 'ollAccessToken' -- -- * 'ollUploadType' -- -- * 'ollAcknowledged' -- -- * 'ollStatuses' -- -- * 'ollPageToken' -- -- * 'ollPlacedDateStart' -- -- * 'ollMaxResults' -- -- * 'ollCallback' ordersList :: Word64 -- ^ 'ollMerchantId' -> OrdersList ordersList pOllMerchantId_ = OrdersList' { _ollXgafv = Nothing , _ollPlacedDateEnd = Nothing , _ollMerchantId = _Coerce # pOllMerchantId_ , _ollUploadProtocol = Nothing , _ollOrderBy = Nothing , _ollAccessToken = Nothing , _ollUploadType = Nothing , _ollAcknowledged = Nothing , _ollStatuses = Nothing , _ollPageToken = Nothing , _ollPlacedDateStart = Nothing , _ollMaxResults = Nothing , _ollCallback = Nothing } -- | V1 error format. ollXgafv :: Lens' OrdersList (Maybe Xgafv) ollXgafv = lens _ollXgafv (\ s a -> s{_ollXgafv = a}) -- | Obtains orders placed before this date (exclusively), in ISO 8601 -- format. ollPlacedDateEnd :: Lens' OrdersList (Maybe Text) ollPlacedDateEnd = lens _ollPlacedDateEnd (\ s a -> s{_ollPlacedDateEnd = a}) -- | The ID of the account that manages the order. This cannot be a -- multi-client account. ollMerchantId :: Lens' OrdersList Word64 ollMerchantId = lens _ollMerchantId (\ s a -> s{_ollMerchantId = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ollUploadProtocol :: Lens' OrdersList (Maybe Text) ollUploadProtocol = lens _ollUploadProtocol (\ s a -> s{_ollUploadProtocol = a}) -- | Order results by placement date in descending or ascending order. -- Acceptable values are: - placedDateAsc - placedDateDesc ollOrderBy :: Lens' OrdersList (Maybe Text) ollOrderBy = lens _ollOrderBy (\ s a -> s{_ollOrderBy = a}) -- | OAuth access token. ollAccessToken :: Lens' OrdersList (Maybe Text) ollAccessToken = lens _ollAccessToken (\ s a -> s{_ollAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ollUploadType :: Lens' OrdersList (Maybe Text) ollUploadType = lens _ollUploadType (\ s a -> s{_ollUploadType = a}) -- | Obtains orders that match the acknowledgement status. When set to true, -- obtains orders that have been acknowledged. When false, obtains orders -- that have not been acknowledged. We recommend using this filter set to -- \`false\`, in conjunction with the \`acknowledge\` call, such that only -- un-acknowledged orders are returned. ollAcknowledged :: Lens' OrdersList (Maybe Bool) ollAcknowledged = lens _ollAcknowledged (\ s a -> s{_ollAcknowledged = a}) -- | Obtains orders that match any of the specified statuses. Please note -- that \`active\` is a shortcut for \`pendingShipment\` and -- \`partiallyShipped\`, and \`completed\` is a shortcut for \`shipped\`, -- \`partiallyDelivered\`, \`delivered\`, \`partiallyReturned\`, -- \`returned\`, and \`canceled\`. ollStatuses :: Lens' OrdersList [OrdersListStatuses] ollStatuses = lens _ollStatuses (\ s a -> s{_ollStatuses = a}) . _Default . _Coerce -- | The token returned by the previous request. ollPageToken :: Lens' OrdersList (Maybe Text) ollPageToken = lens _ollPageToken (\ s a -> s{_ollPageToken = a}) -- | Obtains orders placed after this date (inclusively), in ISO 8601 format. ollPlacedDateStart :: Lens' OrdersList (Maybe Text) ollPlacedDateStart = lens _ollPlacedDateStart (\ s a -> s{_ollPlacedDateStart = a}) -- | The maximum number of orders to return in the response, used for paging. -- The default value is 25 orders per page, and the maximum allowed value -- is 250 orders per page. ollMaxResults :: Lens' OrdersList (Maybe Word32) ollMaxResults = lens _ollMaxResults (\ s a -> s{_ollMaxResults = a}) . mapping _Coerce -- | JSONP ollCallback :: Lens' OrdersList (Maybe Text) ollCallback = lens _ollCallback (\ s a -> s{_ollCallback = a}) instance GoogleRequest OrdersList where type Rs OrdersList = OrdersListResponse type Scopes OrdersList = '["https://www.googleapis.com/auth/content"] requestClient OrdersList'{..} = go _ollMerchantId _ollXgafv _ollPlacedDateEnd _ollUploadProtocol _ollOrderBy _ollAccessToken _ollUploadType _ollAcknowledged (_ollStatuses ^. _Default) _ollPageToken _ollPlacedDateStart _ollMaxResults _ollCallback (Just AltJSON) shoppingContentService where go = buildClient (Proxy :: Proxy OrdersListResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Orders/List.hs
mpl-2.0
8,192
0
24
2,038
1,329
765
564
182
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.GamesManagement.Achievements.ResetAll -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Resets all achievements for the currently authenticated player for your -- application. This method is only accessible to whitelisted tester -- accounts for your application. -- -- /See:/ <https://developers.google.com/games/ Google Play Game Management Reference> for @gamesManagement.achievements.resetAll@. module Network.Google.Resource.GamesManagement.Achievements.ResetAll ( -- * REST Resource AchievementsResetAllResource -- * Creating a Request , achievementsResetAll , AchievementsResetAll -- * Request Lenses , araXgafv , araUploadProtocol , araAccessToken , araUploadType , araCallback ) where import Network.Google.GamesManagement.Types import Network.Google.Prelude -- | A resource alias for @gamesManagement.achievements.resetAll@ method which the -- 'AchievementsResetAll' request conforms to. type AchievementsResetAllResource = "games" :> "v1management" :> "achievements" :> "reset" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Post '[JSON] AchievementResetAllResponse -- | Resets all achievements for the currently authenticated player for your -- application. This method is only accessible to whitelisted tester -- accounts for your application. -- -- /See:/ 'achievementsResetAll' smart constructor. data AchievementsResetAll = AchievementsResetAll' { _araXgafv :: !(Maybe Xgafv) , _araUploadProtocol :: !(Maybe Text) , _araAccessToken :: !(Maybe Text) , _araUploadType :: !(Maybe Text) , _araCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementsResetAll' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'araXgafv' -- -- * 'araUploadProtocol' -- -- * 'araAccessToken' -- -- * 'araUploadType' -- -- * 'araCallback' achievementsResetAll :: AchievementsResetAll achievementsResetAll = AchievementsResetAll' { _araXgafv = Nothing , _araUploadProtocol = Nothing , _araAccessToken = Nothing , _araUploadType = Nothing , _araCallback = Nothing } -- | V1 error format. araXgafv :: Lens' AchievementsResetAll (Maybe Xgafv) araXgafv = lens _araXgafv (\ s a -> s{_araXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). araUploadProtocol :: Lens' AchievementsResetAll (Maybe Text) araUploadProtocol = lens _araUploadProtocol (\ s a -> s{_araUploadProtocol = a}) -- | OAuth access token. araAccessToken :: Lens' AchievementsResetAll (Maybe Text) araAccessToken = lens _araAccessToken (\ s a -> s{_araAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). araUploadType :: Lens' AchievementsResetAll (Maybe Text) araUploadType = lens _araUploadType (\ s a -> s{_araUploadType = a}) -- | JSONP araCallback :: Lens' AchievementsResetAll (Maybe Text) araCallback = lens _araCallback (\ s a -> s{_araCallback = a}) instance GoogleRequest AchievementsResetAll where type Rs AchievementsResetAll = AchievementResetAllResponse type Scopes AchievementsResetAll = '["https://www.googleapis.com/auth/games"] requestClient AchievementsResetAll'{..} = go _araXgafv _araUploadProtocol _araAccessToken _araUploadType _araCallback (Just AltJSON) gamesManagementService where go = buildClient (Proxy :: Proxy AchievementsResetAllResource) mempty
brendanhay/gogol
gogol-games-management/gen/Network/Google/Resource/GamesManagement/Achievements/ResetAll.hs
mpl-2.0
4,675
0
17
1,071
634
372
262
95
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.Cloudbuild.Projects.Triggers.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns information about a \`BuildTrigger\`. This API is experimental. -- -- /See:/ <https://cloud.google.com/cloud-build/docs/ Cloud Build API Reference> for @cloudbuild.projects.triggers.get@. module Network.Google.Resource.Cloudbuild.Projects.Triggers.Get ( -- * REST Resource ProjectsTriggersGetResource -- * Creating a Request , projectsTriggersGet , ProjectsTriggersGet -- * Request Lenses , ptgXgafv , ptgUploadProtocol , ptgTriggerId , ptgAccessToken , ptgUploadType , ptgName , ptgProjectId , ptgCallback ) where import Network.Google.ContainerBuilder.Types import Network.Google.Prelude -- | A resource alias for @cloudbuild.projects.triggers.get@ method which the -- 'ProjectsTriggersGet' request conforms to. type ProjectsTriggersGetResource = "v1" :> "projects" :> Capture "projectId" Text :> "triggers" :> Capture "triggerId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "name" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] BuildTrigger -- | Returns information about a \`BuildTrigger\`. This API is experimental. -- -- /See:/ 'projectsTriggersGet' smart constructor. data ProjectsTriggersGet = ProjectsTriggersGet' { _ptgXgafv :: !(Maybe Xgafv) , _ptgUploadProtocol :: !(Maybe Text) , _ptgTriggerId :: !Text , _ptgAccessToken :: !(Maybe Text) , _ptgUploadType :: !(Maybe Text) , _ptgName :: !(Maybe Text) , _ptgProjectId :: !Text , _ptgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsTriggersGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptgXgafv' -- -- * 'ptgUploadProtocol' -- -- * 'ptgTriggerId' -- -- * 'ptgAccessToken' -- -- * 'ptgUploadType' -- -- * 'ptgName' -- -- * 'ptgProjectId' -- -- * 'ptgCallback' projectsTriggersGet :: Text -- ^ 'ptgTriggerId' -> Text -- ^ 'ptgProjectId' -> ProjectsTriggersGet projectsTriggersGet pPtgTriggerId_ pPtgProjectId_ = ProjectsTriggersGet' { _ptgXgafv = Nothing , _ptgUploadProtocol = Nothing , _ptgTriggerId = pPtgTriggerId_ , _ptgAccessToken = Nothing , _ptgUploadType = Nothing , _ptgName = Nothing , _ptgProjectId = pPtgProjectId_ , _ptgCallback = Nothing } -- | V1 error format. ptgXgafv :: Lens' ProjectsTriggersGet (Maybe Xgafv) ptgXgafv = lens _ptgXgafv (\ s a -> s{_ptgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ptgUploadProtocol :: Lens' ProjectsTriggersGet (Maybe Text) ptgUploadProtocol = lens _ptgUploadProtocol (\ s a -> s{_ptgUploadProtocol = a}) -- | Required. Identifier (\`id\` or \`name\`) of the \`BuildTrigger\` to -- get. ptgTriggerId :: Lens' ProjectsTriggersGet Text ptgTriggerId = lens _ptgTriggerId (\ s a -> s{_ptgTriggerId = a}) -- | OAuth access token. ptgAccessToken :: Lens' ProjectsTriggersGet (Maybe Text) ptgAccessToken = lens _ptgAccessToken (\ s a -> s{_ptgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ptgUploadType :: Lens' ProjectsTriggersGet (Maybe Text) ptgUploadType = lens _ptgUploadType (\ s a -> s{_ptgUploadType = a}) -- | The name of the \`Trigger\` to retrieve. Format: -- \`projects\/{project}\/locations\/{location}\/triggers\/{trigger}\` ptgName :: Lens' ProjectsTriggersGet (Maybe Text) ptgName = lens _ptgName (\ s a -> s{_ptgName = a}) -- | Required. ID of the project that owns the trigger. ptgProjectId :: Lens' ProjectsTriggersGet Text ptgProjectId = lens _ptgProjectId (\ s a -> s{_ptgProjectId = a}) -- | JSONP ptgCallback :: Lens' ProjectsTriggersGet (Maybe Text) ptgCallback = lens _ptgCallback (\ s a -> s{_ptgCallback = a}) instance GoogleRequest ProjectsTriggersGet where type Rs ProjectsTriggersGet = BuildTrigger type Scopes ProjectsTriggersGet = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsTriggersGet'{..} = go _ptgProjectId _ptgTriggerId _ptgXgafv _ptgUploadProtocol _ptgAccessToken _ptgUploadType _ptgName _ptgCallback (Just AltJSON) containerBuilderService where go = buildClient (Proxy :: Proxy ProjectsTriggersGetResource) mempty
brendanhay/gogol
gogol-containerbuilder/gen/Network/Google/Resource/Cloudbuild/Projects/Triggers/Get.hs
mpl-2.0
5,549
0
19
1,298
860
500
360
123
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeSynonymInstances #-} module Tetris.Orientation where import Control.Monad import Data.Eq import Data.Maybe import GHC.Show import Tetris.Block.Dir import Tetris.Coord -- | Orientation on the board, used to move from one cell to another data Orientation = North | South | East | West deriving (Eq,Show) instance DirToFun Right Orientation Coord where toF Right North = predColumn toF Right South = succColumn toF Right East = predRow toF Right West = succRow instance DirToFun Down Orientation Coord where toF Down North = predRow toF Down South = succRow toF Down East = succColumn toF Down West = predColumn instance DirToFun RightUp Orientation Coord where toF RightUp North c = predColumn c >>= succRow toF RightUp South c = succColumn c >>= predRow toF RightUp East c = predRow c >>= predColumn toF RightUp West c = succRow c >>= succColumn -- only two ways to rotate a block, clockwise and counterwise -- -- please note that the rotations are reversed because the board is upside down, -- ie row Digit Zero is the one at the top of the screen and Twentyone the one -- at the bottom data Rotation = Clockwise | Counterwise deriving (Eq,Show) -- implementation of the rotation on the orientation (note that counterwise and -- clockwise are reversed) clockwise,counterwise :: Orientation -> Orientation counterwise North = East counterwise East = South counterwise South = West counterwise West = North clockwise North = West clockwise West = South clockwise South = East clockwise East = North -- conversion from the declarative form to the function rotationToFun :: Rotation -> Orientation -> Orientation rotationToFun Clockwise = clockwise rotationToFun Counterwise = counterwise -- implementation of the rotation on the head (note that counterwise and -- clockwise are reversed) clockwiseHeadShift,counterwiseHeadShift :: Orientation -> Coord -> Maybe Coord clockwiseHeadShift North c = succColumn c >>= succColumn clockwiseHeadShift East c = succRow c >>= succRow clockwiseHeadShift South c = predColumn c >>= predColumn clockwiseHeadShift West c = predRow c >>= predRow counterwiseHeadShift North c = succRow c >>= succRow counterwiseHeadShift East c = predColumn c >>= predColumn counterwiseHeadShift South c = predRow c >>= predRow counterwiseHeadShift West c = succColumn c >>= succColumn rotationToShift :: Rotation -> Orientation -> Coord -> Maybe Coord rotationToShift Clockwise = clockwiseHeadShift rotationToShift Counterwise = counterwiseHeadShift
melrief/tetris
src/Tetris/Orientation.hs
apache-2.0
2,680
0
8
479
586
306
280
54
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Spark.Core.PruningSpec where import Test.Hspec import qualified Data.Text as T import Data.List(sort) import Spark.Core.Context import Spark.Core.Types import Spark.Core.Row import Spark.Core.Functions import Spark.Core.Column import Spark.Core.IntegrationUtilities import Spark.Core.CollectSpec(run) run2 :: T.Text -> IO () -> SpecWith (Arg (IO ())) run2 s f = it (T.unpack s) $ do createSparkSessionDef $ defaultConf { confRequestedSessionName = s, confUseNodePrunning = True } f -- This is horribly not robust to any sort of failure, but it will do for now -- TODO(kps) make more robust closeSparkSessionDef return () spec :: Spec spec = do describe "Integration test - pruning" $ do run2 "running_twice" $ do let ds = dataset [1::Int,2] l2 <- exec1Def $ collect (asCol ds) l2' <- exec1Def $ collect (asCol ds) l2 `shouldBe` l2'
krapsh/kraps-haskell
test-integration/Spark/Core/PruningSpec.hs
apache-2.0
973
0
17
190
278
150
128
29
1
module Connection where import DSL.Execute import Control.Exception withConnection :: (ConnectionObject -> IO a) -> IO a withConnection f = bracket (newConnection "localhost" 9200) closeConnection f
edgarklerks/document-indexer
Connection.hs
bsd-2-clause
202
0
8
28
59
31
28
5
1
-- -- Copyright 2014, NICTA -- -- This software may be distributed and modified according to the terms of -- the BSD 2-Clause license. Note that NO WARRANTY is provided. -- See "LICENSE_BSD2.txt" for details. -- -- @TAG(NICTA_BSD) -- module CapDL.Parser where import CapDL.AST import CapDL.Model import CapDL.ParserUtils import Text.ParserCombinators.Parsec import qualified Text.ParserCombinators.Parsec.Token as PT import Text.ParserCombinators.Parsec.Language import Data.Word import Data.Set (fromList) obj_decl_or_ref :: MapParser (Either KODecl NameRef) obj_decl_or_ref = (try $ do d <- obj_decl (comma <|> return "") return $ Left d) <|> (do n <- name_ref (comma <|> return "") return $ Right n) opt_obj_decls :: MapParser [Either KODecl NameRef] opt_obj_decls = braces (many obj_decl_or_ref) <|> return [] object :: MapParser KO object = do typ <- object_type params <- object_params decls <- opt_obj_decls return (Obj typ params decls) obj_decl :: MapParser KODecl obj_decl = do qname <- qname symbol "=" obj <- CapDL.Parser.object return (KODecl qname obj) obj_decls :: MapParser [Decl] obj_decls = do reserved "objects" decls <- braces $ many obj_decl return $ map ObjDecl decls cap_mapping :: Maybe Word -> Maybe NameRef -> MapParser CapMapping cap_mapping sl nm = do obj <- name_ref params <- cap_params parent <- maybe_parent return $ CapMapping sl nm obj params parent cap_name_ref :: Maybe Word -> Maybe NameRef -> MapParser CapMapping cap_name_ref sl nm = do symbol "<" name <- name_ref symbol ">" params <- cap_params parent <- maybe_parent return $ CopyOf sl nm name params parent maybe_name :: MapParser (Maybe NameRef) maybe_name = optionMaybe $ try $ do n <- name_ref symbol "=" return n cap_mapping_or_ref :: MapParser CapMapping cap_mapping_or_ref = do sl <- maybe_slot nm <- maybe_name cap_mapping sl nm <|> cap_name_ref sl nm cap_decl :: MapParser Decl cap_decl = do n <- name_ref ms <- braces (sepEndBy cap_mapping_or_ref opt_semi) return $ CapDecl n ms cap_name_decl :: MapParser Decl cap_name_decl = do n <- name symbol "=" symbol "(" ref <- name_ref symbol "," slot <- parse_slot symbol ")" return $ CapNameDecl n ref slot cap_decls :: MapParser [Decl] cap_decls = do reserved "caps" braces $ many (try cap_name_decl <|> try cap_decl) decl_section :: MapParser [Decl] decl_section = obj_decls <|> cap_decls <|> irq_decls <|> cdt_decls capDLModule :: MapParser Module capDLModule = do whiteSpace arch <- parse_arch decls <- many1 decl_section eof return (Module arch (concat decls))
smaccm/capDL-tool
CapDL/Parser.hs
bsd-2-clause
2,802
0
12
670
845
403
442
91
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QComboBox.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:24 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QComboBox ( QqComboBox(..) ,autoCompletion ,autoCompletionCaseSensitivity ,clearEditText ,duplicatesEnabled ,QfindData(..) ,QfindText(..) ,insertPolicy ,QitemData(..), QitemData_nf(..) ,maxCount ,maxVisibleItems ,minimumContentsLength ,rootModelIndex ,setAutoCompletion ,setAutoCompletionCaseSensitivity ,setDuplicatesEnabled ,setEditText ,setInsertPolicy ,QsetItemData(..) ,setMaxCount ,setMaxVisibleItems ,setMinimumContentsLength ,setRootModelIndex ,setSizeAdjustPolicy ,setView ,sizeAdjustPolicy ,view ,qComboBox_delete ,qComboBox_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QComboBox 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 (QComboBox ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QComboBox_userMethod" qtc_QComboBox_userMethod :: Ptr (TQComboBox a) -> CInt -> IO () instance QuserMethod (QComboBoxSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QComboBox ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QComboBox_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QComboBox_userMethodVariant" qtc_QComboBox_userMethodVariant :: Ptr (TQComboBox a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QComboBoxSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QComboBox_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqComboBox x1 where qComboBox :: x1 -> IO (QComboBox ()) instance QqComboBox (()) where qComboBox () = withQComboBoxResult $ qtc_QComboBox foreign import ccall "qtc_QComboBox" qtc_QComboBox :: IO (Ptr (TQComboBox ())) instance QqComboBox ((QWidget t1)) where qComboBox (x1) = withQComboBoxResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox1 cobj_x1 foreign import ccall "qtc_QComboBox1" qtc_QComboBox1 :: Ptr (TQWidget t1) -> IO (Ptr (TQComboBox ())) instance QaddItem (QComboBox a) ((QIcon t1, String)) (IO ()) where addItem x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QComboBox_addItem2 cobj_x0 cobj_x1 cstr_x2 foreign import ccall "qtc_QComboBox_addItem2" qtc_QComboBox_addItem2 :: Ptr (TQComboBox a) -> Ptr (TQIcon t1) -> CWString -> IO () instance QaddItem (QComboBox a) ((QIcon t1, String, QVariant t3)) (IO ()) where addItem x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QComboBox_addItem3 cobj_x0 cobj_x1 cstr_x2 cobj_x3 foreign import ccall "qtc_QComboBox_addItem3" qtc_QComboBox_addItem3 :: Ptr (TQComboBox a) -> Ptr (TQIcon t1) -> CWString -> Ptr (TQVariant t3) -> IO () instance QaddItem (QComboBox a) ((String)) (IO ()) where addItem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_addItem cobj_x0 cstr_x1 foreign import ccall "qtc_QComboBox_addItem" qtc_QComboBox_addItem :: Ptr (TQComboBox a) -> CWString -> IO () instance QaddItem (QComboBox a) ((String, QVariant t2)) (IO ()) where addItem x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_addItem1 cobj_x0 cstr_x1 cobj_x2 foreign import ccall "qtc_QComboBox_addItem1" qtc_QComboBox_addItem1 :: Ptr (TQComboBox a) -> CWString -> Ptr (TQVariant t2) -> IO () instance QaddItems (QComboBox a) (([String])) where addItems x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withQListString x1 $ \cqlistlen_x1 cqliststr_x1 -> qtc_QComboBox_addItems cobj_x0 cqlistlen_x1 cqliststr_x1 foreign import ccall "qtc_QComboBox_addItems" qtc_QComboBox_addItems :: Ptr (TQComboBox a) -> CInt -> Ptr (Ptr CWchar) -> IO () autoCompletion :: QComboBox a -> (()) -> IO (Bool) autoCompletion x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_autoCompletion cobj_x0 foreign import ccall "qtc_QComboBox_autoCompletion" qtc_QComboBox_autoCompletion :: Ptr (TQComboBox a) -> IO CBool autoCompletionCaseSensitivity :: QComboBox a -> (()) -> IO (CaseSensitivity) autoCompletionCaseSensitivity x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_autoCompletionCaseSensitivity cobj_x0 foreign import ccall "qtc_QComboBox_autoCompletionCaseSensitivity" qtc_QComboBox_autoCompletionCaseSensitivity :: Ptr (TQComboBox a) -> IO CLong instance QchangeEvent (QComboBox ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_changeEvent_h" qtc_QComboBox_changeEvent_h :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QComboBoxSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_changeEvent_h cobj_x0 cobj_x1 instance Qclear (QComboBox a) (()) where clear x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_clear cobj_x0 foreign import ccall "qtc_QComboBox_clear" qtc_QComboBox_clear :: Ptr (TQComboBox a) -> IO () clearEditText :: QComboBox a -> (()) -> IO () clearEditText x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_clearEditText cobj_x0 foreign import ccall "qtc_QComboBox_clearEditText" qtc_QComboBox_clearEditText :: Ptr (TQComboBox a) -> IO () instance Qcompleter (QComboBox a) (()) where completer x0 () = withQCompleterResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_completer cobj_x0 foreign import ccall "qtc_QComboBox_completer" qtc_QComboBox_completer :: Ptr (TQComboBox a) -> IO (Ptr (TQCompleter ())) instance QcontextMenuEvent (QComboBox ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_contextMenuEvent_h" qtc_QComboBox_contextMenuEvent_h :: Ptr (TQComboBox a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QComboBoxSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_contextMenuEvent_h cobj_x0 cobj_x1 instance Qcount (QComboBox a) (()) where count x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_count cobj_x0 foreign import ccall "qtc_QComboBox_count" qtc_QComboBox_count :: Ptr (TQComboBox a) -> IO CInt instance QcurrentIndex (QComboBox a) (()) (IO (Int)) where currentIndex x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_currentIndex cobj_x0 foreign import ccall "qtc_QComboBox_currentIndex" qtc_QComboBox_currentIndex :: Ptr (TQComboBox a) -> IO CInt instance QcurrentText (QComboBox a) (()) where currentText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_currentText cobj_x0 foreign import ccall "qtc_QComboBox_currentText" qtc_QComboBox_currentText :: Ptr (TQComboBox a) -> IO (Ptr (TQString ())) duplicatesEnabled :: QComboBox a -> (()) -> IO (Bool) duplicatesEnabled x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_duplicatesEnabled cobj_x0 foreign import ccall "qtc_QComboBox_duplicatesEnabled" qtc_QComboBox_duplicatesEnabled :: Ptr (TQComboBox a) -> IO CBool instance Qevent (QComboBox ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_event_h" qtc_QComboBox_event_h :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QComboBoxSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_event_h cobj_x0 cobj_x1 class QfindData x1 where findData :: QComboBox a -> x1 -> IO (Int) instance QfindData ((QVariant t1)) where findData x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_findData cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_findData" qtc_QComboBox_findData :: Ptr (TQComboBox a) -> Ptr (TQVariant t1) -> IO CInt instance QfindData ((QVariant t1, Int)) where findData x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_findData1 cobj_x0 cobj_x1 (toCInt x2) foreign import ccall "qtc_QComboBox_findData1" qtc_QComboBox_findData1 :: Ptr (TQComboBox a) -> Ptr (TQVariant t1) -> CInt -> IO CInt instance QfindData ((QVariant t1, Int, MatchFlags)) where findData x0 (x1, x2, x3) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_findData2 cobj_x0 cobj_x1 (toCInt x2) (toCLong $ qFlags_toInt x3) foreign import ccall "qtc_QComboBox_findData2" qtc_QComboBox_findData2 :: Ptr (TQComboBox a) -> Ptr (TQVariant t1) -> CInt -> CLong -> IO CInt class QfindText x1 where findText :: QComboBox a -> x1 -> IO (Int) instance QfindText ((String)) where findText x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_findText cobj_x0 cstr_x1 foreign import ccall "qtc_QComboBox_findText" qtc_QComboBox_findText :: Ptr (TQComboBox a) -> CWString -> IO CInt instance QfindText ((String, MatchFlags)) where findText x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_findText1 cobj_x0 cstr_x1 (toCLong $ qFlags_toInt x2) foreign import ccall "qtc_QComboBox_findText1" qtc_QComboBox_findText1 :: Ptr (TQComboBox a) -> CWString -> CLong -> IO CInt instance QfocusInEvent (QComboBox ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_focusInEvent_h" qtc_QComboBox_focusInEvent_h :: Ptr (TQComboBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QComboBoxSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusInEvent_h cobj_x0 cobj_x1 instance QfocusOutEvent (QComboBox ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_focusOutEvent_h" qtc_QComboBox_focusOutEvent_h :: Ptr (TQComboBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QComboBoxSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusOutEvent_h cobj_x0 cobj_x1 instance QhasFrame (QComboBox a) (()) where hasFrame x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_hasFrame cobj_x0 foreign import ccall "qtc_QComboBox_hasFrame" qtc_QComboBox_hasFrame :: Ptr (TQComboBox a) -> IO CBool instance QhideEvent (QComboBox ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_hideEvent_h" qtc_QComboBox_hideEvent_h :: Ptr (TQComboBox a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QComboBoxSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_hideEvent_h cobj_x0 cobj_x1 instance QhidePopup (QComboBox ()) (()) where hidePopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_hidePopup_h cobj_x0 foreign import ccall "qtc_QComboBox_hidePopup_h" qtc_QComboBox_hidePopup_h :: Ptr (TQComboBox a) -> IO () instance QhidePopup (QComboBoxSc a) (()) where hidePopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_hidePopup_h cobj_x0 instance QqiconSize (QComboBox a) (()) where qiconSize x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_iconSize cobj_x0 foreign import ccall "qtc_QComboBox_iconSize" qtc_QComboBox_iconSize :: Ptr (TQComboBox a) -> IO (Ptr (TQSize ())) instance QiconSize (QComboBox a) (()) where iconSize x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_iconSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QComboBox_iconSize_qth" qtc_QComboBox_iconSize_qth :: Ptr (TQComboBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QinitStyleOption (QComboBox ()) ((QStyleOptionComboBox t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_initStyleOption cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_initStyleOption" qtc_QComboBox_initStyleOption :: Ptr (TQComboBox a) -> Ptr (TQStyleOptionComboBox t1) -> IO () instance QinitStyleOption (QComboBoxSc a) ((QStyleOptionComboBox t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_initStyleOption cobj_x0 cobj_x1 instance QinputMethodEvent (QComboBox ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_inputMethodEvent" qtc_QComboBox_inputMethodEvent :: Ptr (TQComboBox a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QComboBoxSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QComboBox ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QComboBox_inputMethodQuery" qtc_QComboBox_inputMethodQuery :: Ptr (TQComboBox a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QComboBoxSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QinsertItem (QComboBox a) ((Int, QIcon t2, String)) (IO ()) where insertItem x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> withCWString x3 $ \cstr_x3 -> qtc_QComboBox_insertItem2 cobj_x0 (toCInt x1) cobj_x2 cstr_x3 foreign import ccall "qtc_QComboBox_insertItem2" qtc_QComboBox_insertItem2 :: Ptr (TQComboBox a) -> CInt -> Ptr (TQIcon t2) -> CWString -> IO () instance QinsertItem (QComboBox a) ((Int, QIcon t2, String, QVariant t4)) (IO ()) where insertItem x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> withCWString x3 $ \cstr_x3 -> withObjectPtr x4 $ \cobj_x4 -> qtc_QComboBox_insertItem3 cobj_x0 (toCInt x1) cobj_x2 cstr_x3 cobj_x4 foreign import ccall "qtc_QComboBox_insertItem3" qtc_QComboBox_insertItem3 :: Ptr (TQComboBox a) -> CInt -> Ptr (TQIcon t2) -> CWString -> Ptr (TQVariant t4) -> IO () instance QinsertItem (QComboBox a) ((Int, String)) (IO ()) where insertItem x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCWString x2 $ \cstr_x2 -> qtc_QComboBox_insertItem cobj_x0 (toCInt x1) cstr_x2 foreign import ccall "qtc_QComboBox_insertItem" qtc_QComboBox_insertItem :: Ptr (TQComboBox a) -> CInt -> CWString -> IO () instance QinsertItem (QComboBox a) ((Int, String, QVariant t3)) (IO ()) where insertItem x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QComboBox_insertItem1 cobj_x0 (toCInt x1) cstr_x2 cobj_x3 foreign import ccall "qtc_QComboBox_insertItem1" qtc_QComboBox_insertItem1 :: Ptr (TQComboBox a) -> CInt -> CWString -> Ptr (TQVariant t3) -> IO () instance QinsertItems (QComboBox a) ((Int, [String])) where insertItems x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withQListString x2 $ \cqlistlen_x2 cqliststr_x2 -> qtc_QComboBox_insertItems cobj_x0 (toCInt x1) cqlistlen_x2 cqliststr_x2 foreign import ccall "qtc_QComboBox_insertItems" qtc_QComboBox_insertItems :: Ptr (TQComboBox a) -> CInt -> CInt -> Ptr (Ptr CWchar) -> IO () insertPolicy :: QComboBox a -> (()) -> IO (InsertPolicy) insertPolicy x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_insertPolicy cobj_x0 foreign import ccall "qtc_QComboBox_insertPolicy" qtc_QComboBox_insertPolicy :: Ptr (TQComboBox a) -> IO CLong instance QisEditable (QComboBox a) (()) where isEditable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_isEditable cobj_x0 foreign import ccall "qtc_QComboBox_isEditable" qtc_QComboBox_isEditable :: Ptr (TQComboBox a) -> IO CBool class QitemData x0 x1 where itemData :: x0 -> x1 -> IO (QVariant ()) class QitemData_nf x0 x1 where itemData_nf :: x0 -> x1 -> IO (QVariant ()) instance QitemData (QComboBox ()) ((Int)) where itemData x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_itemData" qtc_QComboBox_itemData :: Ptr (TQComboBox a) -> CInt -> IO (Ptr (TQVariant ())) instance QitemData (QComboBoxSc a) ((Int)) where itemData x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData cobj_x0 (toCInt x1) instance QitemData_nf (QComboBox ()) ((Int)) where itemData_nf x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData cobj_x0 (toCInt x1) instance QitemData_nf (QComboBoxSc a) ((Int)) where itemData_nf x0 (x1) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData cobj_x0 (toCInt x1) instance QitemData (QComboBox ()) ((Int, Int)) where itemData x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QComboBox_itemData1" qtc_QComboBox_itemData1 :: Ptr (TQComboBox a) -> CInt -> CInt -> IO (Ptr (TQVariant ())) instance QitemData (QComboBoxSc a) ((Int, Int)) where itemData x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData1 cobj_x0 (toCInt x1) (toCInt x2) instance QitemData_nf (QComboBox ()) ((Int, Int)) where itemData_nf x0 (x1, x2) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData1 cobj_x0 (toCInt x1) (toCInt x2) instance QitemData_nf (QComboBoxSc a) ((Int, Int)) where itemData_nf x0 (x1, x2) = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemData1 cobj_x0 (toCInt x1) (toCInt x2) instance QitemDelegate (QComboBox a) (()) where itemDelegate x0 () = withQAbstractItemDelegateResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemDelegate cobj_x0 foreign import ccall "qtc_QComboBox_itemDelegate" qtc_QComboBox_itemDelegate :: Ptr (TQComboBox a) -> IO (Ptr (TQAbstractItemDelegate ())) instance QitemIcon (QComboBox a) ((Int)) where itemIcon x0 (x1) = withQIconResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemIcon cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_itemIcon" qtc_QComboBox_itemIcon :: Ptr (TQComboBox a) -> CInt -> IO (Ptr (TQIcon ())) instance QitemText (QComboBox a) ((Int)) where itemText x0 (x1) = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_itemText cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_itemText" qtc_QComboBox_itemText :: Ptr (TQComboBox a) -> CInt -> IO (Ptr (TQString ())) instance QkeyPressEvent (QComboBox ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_keyPressEvent_h" qtc_QComboBox_keyPressEvent_h :: Ptr (TQComboBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QComboBoxSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyPressEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QComboBox ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_keyReleaseEvent_h" qtc_QComboBox_keyReleaseEvent_h :: Ptr (TQComboBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QComboBoxSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlineEdit (QComboBox a) (()) where lineEdit x0 () = withQLineEditResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_lineEdit cobj_x0 foreign import ccall "qtc_QComboBox_lineEdit" qtc_QComboBox_lineEdit :: Ptr (TQComboBox a) -> IO (Ptr (TQLineEdit ())) maxCount :: QComboBox a -> (()) -> IO (Int) maxCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_maxCount cobj_x0 foreign import ccall "qtc_QComboBox_maxCount" qtc_QComboBox_maxCount :: Ptr (TQComboBox a) -> IO CInt maxVisibleItems :: QComboBox a -> (()) -> IO (Int) maxVisibleItems x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_maxVisibleItems cobj_x0 foreign import ccall "qtc_QComboBox_maxVisibleItems" qtc_QComboBox_maxVisibleItems :: Ptr (TQComboBox a) -> IO CInt minimumContentsLength :: QComboBox a -> (()) -> IO (Int) minimumContentsLength x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumContentsLength cobj_x0 foreign import ccall "qtc_QComboBox_minimumContentsLength" qtc_QComboBox_minimumContentsLength :: Ptr (TQComboBox a) -> IO CInt instance QqminimumSizeHint (QComboBox ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QComboBox_minimumSizeHint_h" qtc_QComboBox_minimumSizeHint_h :: Ptr (TQComboBox a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QComboBoxSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QComboBox ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QComboBox_minimumSizeHint_qth_h" qtc_QComboBox_minimumSizeHint_qth_h :: Ptr (TQComboBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QComboBoxSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance Qmodel (QComboBox a) (()) (IO (QAbstractItemModel ())) where model x0 () = withQAbstractItemModelResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_model cobj_x0 foreign import ccall "qtc_QComboBox_model" qtc_QComboBox_model :: Ptr (TQComboBox a) -> IO (Ptr (TQAbstractItemModel ())) instance QmodelColumn (QComboBox a) (()) where modelColumn x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_modelColumn cobj_x0 foreign import ccall "qtc_QComboBox_modelColumn" qtc_QComboBox_modelColumn :: Ptr (TQComboBox a) -> IO CInt instance QmousePressEvent (QComboBox ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mousePressEvent_h" qtc_QComboBox_mousePressEvent_h :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QComboBoxSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QComboBox ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mouseReleaseEvent_h" qtc_QComboBox_mouseReleaseEvent_h :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QComboBoxSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseReleaseEvent_h cobj_x0 cobj_x1 instance QpaintEvent (QComboBox ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_paintEvent_h" qtc_QComboBox_paintEvent_h :: Ptr (TQComboBox a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QComboBoxSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_paintEvent_h cobj_x0 cobj_x1 instance QremoveItem (QComboBox a) ((Int)) where removeItem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_removeItem cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_removeItem" qtc_QComboBox_removeItem :: Ptr (TQComboBox a) -> CInt -> IO () instance QresizeEvent (QComboBox ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_resizeEvent_h" qtc_QComboBox_resizeEvent_h :: Ptr (TQComboBox a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QComboBoxSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_resizeEvent_h cobj_x0 cobj_x1 rootModelIndex :: QComboBox a -> (()) -> IO (QModelIndex ()) rootModelIndex x0 () = withQModelIndexResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_rootModelIndex cobj_x0 foreign import ccall "qtc_QComboBox_rootModelIndex" qtc_QComboBox_rootModelIndex :: Ptr (TQComboBox a) -> IO (Ptr (TQModelIndex ())) setAutoCompletion :: QComboBox a -> ((Bool)) -> IO () setAutoCompletion x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setAutoCompletion cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_setAutoCompletion" qtc_QComboBox_setAutoCompletion :: Ptr (TQComboBox a) -> CBool -> IO () setAutoCompletionCaseSensitivity :: QComboBox a -> ((CaseSensitivity)) -> IO () setAutoCompletionCaseSensitivity x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setAutoCompletionCaseSensitivity cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QComboBox_setAutoCompletionCaseSensitivity" qtc_QComboBox_setAutoCompletionCaseSensitivity :: Ptr (TQComboBox a) -> CLong -> IO () instance QsetCompleter (QComboBox a) ((QCompleter t1)) where setCompleter x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setCompleter cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setCompleter" qtc_QComboBox_setCompleter :: Ptr (TQComboBox a) -> Ptr (TQCompleter t1) -> IO () instance QsetCurrentIndex (QComboBox a) ((Int)) where setCurrentIndex x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setCurrentIndex cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_setCurrentIndex" qtc_QComboBox_setCurrentIndex :: Ptr (TQComboBox a) -> CInt -> IO () setDuplicatesEnabled :: QComboBox a -> ((Bool)) -> IO () setDuplicatesEnabled x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setDuplicatesEnabled cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_setDuplicatesEnabled" qtc_QComboBox_setDuplicatesEnabled :: Ptr (TQComboBox a) -> CBool -> IO () setEditText :: QComboBox a -> ((String)) -> IO () setEditText x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_setEditText cobj_x0 cstr_x1 foreign import ccall "qtc_QComboBox_setEditText" qtc_QComboBox_setEditText :: Ptr (TQComboBox a) -> CWString -> IO () instance QsetEditable (QComboBox a) ((Bool)) where setEditable x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setEditable cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_setEditable" qtc_QComboBox_setEditable :: Ptr (TQComboBox a) -> CBool -> IO () instance QsetFrame (QComboBox a) ((Bool)) where setFrame x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setFrame cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_setFrame" qtc_QComboBox_setFrame :: Ptr (TQComboBox a) -> CBool -> IO () instance QqsetIconSize (QComboBox a) ((QSize t1)) where qsetIconSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setIconSize cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setIconSize" qtc_QComboBox_setIconSize :: Ptr (TQComboBox a) -> Ptr (TQSize t1) -> IO () instance QsetIconSize (QComboBox a) ((Size)) where setIconSize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QComboBox_setIconSize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QComboBox_setIconSize_qth" qtc_QComboBox_setIconSize_qth :: Ptr (TQComboBox a) -> CInt -> CInt -> IO () setInsertPolicy :: QComboBox a -> ((InsertPolicy)) -> IO () setInsertPolicy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setInsertPolicy cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QComboBox_setInsertPolicy" qtc_QComboBox_setInsertPolicy :: Ptr (TQComboBox a) -> CLong -> IO () class QsetItemData x1 where setItemData :: QComboBox a -> x1 -> IO () instance QsetItemData ((Int, QVariant t2)) where setItemData x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_setItemData cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QComboBox_setItemData" qtc_QComboBox_setItemData :: Ptr (TQComboBox a) -> CInt -> Ptr (TQVariant t2) -> IO () instance QsetItemData ((Int, QVariant t2, Int)) where setItemData x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_setItemData1 cobj_x0 (toCInt x1) cobj_x2 (toCInt x3) foreign import ccall "qtc_QComboBox_setItemData1" qtc_QComboBox_setItemData1 :: Ptr (TQComboBox a) -> CInt -> Ptr (TQVariant t2) -> CInt -> IO () instance QsetItemDelegate (QComboBox a) ((QAbstractItemDelegate t1)) where setItemDelegate x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setItemDelegate cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setItemDelegate" qtc_QComboBox_setItemDelegate :: Ptr (TQComboBox a) -> Ptr (TQAbstractItemDelegate t1) -> IO () instance QsetItemIcon (QComboBox a) ((Int, QIcon t2)) where setItemIcon x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_setItemIcon cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QComboBox_setItemIcon" qtc_QComboBox_setItemIcon :: Ptr (TQComboBox a) -> CInt -> Ptr (TQIcon t2) -> IO () instance QsetItemText (QComboBox a) ((Int, String)) where setItemText x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCWString x2 $ \cstr_x2 -> qtc_QComboBox_setItemText cobj_x0 (toCInt x1) cstr_x2 foreign import ccall "qtc_QComboBox_setItemText" qtc_QComboBox_setItemText :: Ptr (TQComboBox a) -> CInt -> CWString -> IO () instance QsetLineEdit (QComboBox a) ((QLineEdit t1)) where setLineEdit x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setLineEdit cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setLineEdit" qtc_QComboBox_setLineEdit :: Ptr (TQComboBox a) -> Ptr (TQLineEdit t1) -> IO () setMaxCount :: QComboBox a -> ((Int)) -> IO () setMaxCount x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setMaxCount cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_setMaxCount" qtc_QComboBox_setMaxCount :: Ptr (TQComboBox a) -> CInt -> IO () setMaxVisibleItems :: QComboBox a -> ((Int)) -> IO () setMaxVisibleItems x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setMaxVisibleItems cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_setMaxVisibleItems" qtc_QComboBox_setMaxVisibleItems :: Ptr (TQComboBox a) -> CInt -> IO () setMinimumContentsLength :: QComboBox a -> ((Int)) -> IO () setMinimumContentsLength x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setMinimumContentsLength cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_setMinimumContentsLength" qtc_QComboBox_setMinimumContentsLength :: Ptr (TQComboBox a) -> CInt -> IO () instance QsetModel (QComboBox a) ((QAbstractItemModel t1)) where setModel x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setModel cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setModel" qtc_QComboBox_setModel :: Ptr (TQComboBox a) -> Ptr (TQAbstractItemModel t1) -> IO () instance QsetModelColumn (QComboBox a) ((Int)) where setModelColumn x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setModelColumn cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_setModelColumn" qtc_QComboBox_setModelColumn :: Ptr (TQComboBox a) -> CInt -> IO () setRootModelIndex :: QComboBox a -> ((QModelIndex t1)) -> IO () setRootModelIndex x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setRootModelIndex cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setRootModelIndex" qtc_QComboBox_setRootModelIndex :: Ptr (TQComboBox a) -> Ptr (TQModelIndex t1) -> IO () setSizeAdjustPolicy :: QComboBox a -> ((SizeAdjustPolicy)) -> IO () setSizeAdjustPolicy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setSizeAdjustPolicy cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QComboBox_setSizeAdjustPolicy" qtc_QComboBox_setSizeAdjustPolicy :: Ptr (TQComboBox a) -> CLong -> IO () instance QsetValidator (QComboBox a) ((QValidator t1)) where setValidator x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setValidator cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setValidator" qtc_QComboBox_setValidator :: Ptr (TQComboBox a) -> Ptr (TQValidator t1) -> IO () setView :: QComboBox a -> ((QAbstractItemView t1)) -> IO () setView x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setView cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setView" qtc_QComboBox_setView :: Ptr (TQComboBox a) -> Ptr (TQAbstractItemView t1) -> IO () instance QshowEvent (QComboBox ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_showEvent_h" qtc_QComboBox_showEvent_h :: Ptr (TQComboBox a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QComboBoxSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_showEvent_h cobj_x0 cobj_x1 instance QshowPopup (QComboBox ()) (()) where showPopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_showPopup_h cobj_x0 foreign import ccall "qtc_QComboBox_showPopup_h" qtc_QComboBox_showPopup_h :: Ptr (TQComboBox a) -> IO () instance QshowPopup (QComboBoxSc a) (()) where showPopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_showPopup_h cobj_x0 sizeAdjustPolicy :: QComboBox a -> (()) -> IO (SizeAdjustPolicy) sizeAdjustPolicy x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeAdjustPolicy cobj_x0 foreign import ccall "qtc_QComboBox_sizeAdjustPolicy" qtc_QComboBox_sizeAdjustPolicy :: Ptr (TQComboBox a) -> IO CLong instance QqsizeHint (QComboBox ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint_h cobj_x0 foreign import ccall "qtc_QComboBox_sizeHint_h" qtc_QComboBox_sizeHint_h :: Ptr (TQComboBox a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QComboBoxSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint_h cobj_x0 instance QsizeHint (QComboBox ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QComboBox_sizeHint_qth_h" qtc_QComboBox_sizeHint_qth_h :: Ptr (TQComboBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QComboBoxSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance Qvalidator (QComboBox a) (()) where validator x0 () = withQValidatorResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_validator cobj_x0 foreign import ccall "qtc_QComboBox_validator" qtc_QComboBox_validator :: Ptr (TQComboBox a) -> IO (Ptr (TQValidator ())) view :: QComboBox a -> (()) -> IO (QAbstractItemView ()) view x0 () = withQAbstractItemViewResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_view cobj_x0 foreign import ccall "qtc_QComboBox_view" qtc_QComboBox_view :: Ptr (TQComboBox a) -> IO (Ptr (TQAbstractItemView ())) instance QwheelEvent (QComboBox ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_wheelEvent_h" qtc_QComboBox_wheelEvent_h :: Ptr (TQComboBox a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QComboBoxSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_wheelEvent_h cobj_x0 cobj_x1 qComboBox_delete :: QComboBox a -> IO () qComboBox_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_delete cobj_x0 foreign import ccall "qtc_QComboBox_delete" qtc_QComboBox_delete :: Ptr (TQComboBox a) -> IO () qComboBox_deleteLater :: QComboBox a -> IO () qComboBox_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_deleteLater cobj_x0 foreign import ccall "qtc_QComboBox_deleteLater" qtc_QComboBox_deleteLater :: Ptr (TQComboBox a) -> IO () instance QactionEvent (QComboBox ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_actionEvent_h" qtc_QComboBox_actionEvent_h :: Ptr (TQComboBox a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QComboBoxSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QComboBox ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_addAction" qtc_QComboBox_addAction :: Ptr (TQComboBox a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QComboBoxSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_addAction cobj_x0 cobj_x1 instance QcloseEvent (QComboBox ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_closeEvent_h" qtc_QComboBox_closeEvent_h :: Ptr (TQComboBox a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QComboBoxSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_closeEvent_h cobj_x0 cobj_x1 instance Qcreate (QComboBox ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_create cobj_x0 foreign import ccall "qtc_QComboBox_create" qtc_QComboBox_create :: Ptr (TQComboBox a) -> IO () instance Qcreate (QComboBoxSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_create cobj_x0 instance Qcreate (QComboBox ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_create1" qtc_QComboBox_create1 :: Ptr (TQComboBox a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QComboBoxSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_create1 cobj_x0 cobj_x1 instance Qcreate (QComboBox ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QComboBox_create2" qtc_QComboBox_create2 :: Ptr (TQComboBox a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QComboBoxSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QComboBox ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QComboBox_create3" qtc_QComboBox_create3 :: Ptr (TQComboBox a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QComboBoxSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QComboBox ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_destroy cobj_x0 foreign import ccall "qtc_QComboBox_destroy" qtc_QComboBox_destroy :: Ptr (TQComboBox a) -> IO () instance Qdestroy (QComboBoxSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_destroy cobj_x0 instance Qdestroy (QComboBox ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_destroy1" qtc_QComboBox_destroy1 :: Ptr (TQComboBox a) -> CBool -> IO () instance Qdestroy (QComboBoxSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QComboBox ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QComboBox_destroy2" qtc_QComboBox_destroy2 :: Ptr (TQComboBox a) -> CBool -> CBool -> IO () instance Qdestroy (QComboBoxSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QComboBox ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_devType_h cobj_x0 foreign import ccall "qtc_QComboBox_devType_h" qtc_QComboBox_devType_h :: Ptr (TQComboBox a) -> IO CInt instance QdevType (QComboBoxSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_devType_h cobj_x0 instance QdragEnterEvent (QComboBox ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dragEnterEvent_h" qtc_QComboBox_dragEnterEvent_h :: Ptr (TQComboBox a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QComboBoxSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QComboBox ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dragLeaveEvent_h" qtc_QComboBox_dragLeaveEvent_h :: Ptr (TQComboBox a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QComboBoxSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QComboBox ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dragMoveEvent_h" qtc_QComboBox_dragMoveEvent_h :: Ptr (TQComboBox a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QComboBoxSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QComboBox ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dropEvent_h" qtc_QComboBox_dropEvent_h :: Ptr (TQComboBox a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QComboBoxSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dropEvent_h cobj_x0 cobj_x1 instance QenabledChange (QComboBox ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_enabledChange" qtc_QComboBox_enabledChange :: Ptr (TQComboBox a) -> CBool -> IO () instance QenabledChange (QComboBoxSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QComboBox ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_enterEvent_h" qtc_QComboBox_enterEvent_h :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QComboBoxSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_enterEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QComboBox ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_focusNextChild cobj_x0 foreign import ccall "qtc_QComboBox_focusNextChild" qtc_QComboBox_focusNextChild :: Ptr (TQComboBox a) -> IO CBool instance QfocusNextChild (QComboBoxSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_focusNextChild cobj_x0 instance QfocusNextPrevChild (QComboBox ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_focusNextPrevChild" qtc_QComboBox_focusNextPrevChild :: Ptr (TQComboBox a) -> CBool -> IO CBool instance QfocusNextPrevChild (QComboBoxSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusPreviousChild (QComboBox ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_focusPreviousChild cobj_x0 foreign import ccall "qtc_QComboBox_focusPreviousChild" qtc_QComboBox_focusPreviousChild :: Ptr (TQComboBox a) -> IO CBool instance QfocusPreviousChild (QComboBoxSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_focusPreviousChild cobj_x0 instance QfontChange (QComboBox ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_fontChange" qtc_QComboBox_fontChange :: Ptr (TQComboBox a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QComboBoxSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QComboBox ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_heightForWidth_h" qtc_QComboBox_heightForWidth_h :: Ptr (TQComboBox a) -> CInt -> IO CInt instance QheightForWidth (QComboBoxSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_heightForWidth_h cobj_x0 (toCInt x1) instance QlanguageChange (QComboBox ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_languageChange cobj_x0 foreign import ccall "qtc_QComboBox_languageChange" qtc_QComboBox_languageChange :: Ptr (TQComboBox a) -> IO () instance QlanguageChange (QComboBoxSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_languageChange cobj_x0 instance QleaveEvent (QComboBox ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_leaveEvent_h" qtc_QComboBox_leaveEvent_h :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QComboBoxSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QComboBox ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QComboBox_metric" qtc_QComboBox_metric :: Ptr (TQComboBox a) -> CLong -> IO CInt instance Qmetric (QComboBoxSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance QmouseDoubleClickEvent (QComboBox ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mouseDoubleClickEvent_h" qtc_QComboBox_mouseDoubleClickEvent_h :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QComboBoxSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QComboBox ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mouseMoveEvent_h" qtc_QComboBox_mouseMoveEvent_h :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QComboBoxSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseMoveEvent_h cobj_x0 cobj_x1 instance Qmove (QComboBox ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QComboBox_move1" qtc_QComboBox_move1 :: Ptr (TQComboBox a) -> CInt -> CInt -> IO () instance Qmove (QComboBoxSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QComboBox ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QComboBox_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QComboBox_move_qth" qtc_QComboBox_move_qth :: Ptr (TQComboBox a) -> CInt -> CInt -> IO () instance Qmove (QComboBoxSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QComboBox_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QComboBox ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_move cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_move" qtc_QComboBox_move :: Ptr (TQComboBox a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QComboBoxSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_move cobj_x0 cobj_x1 instance QmoveEvent (QComboBox ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_moveEvent_h" qtc_QComboBox_moveEvent_h :: Ptr (TQComboBox a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QComboBoxSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QComboBox ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_paintEngine_h cobj_x0 foreign import ccall "qtc_QComboBox_paintEngine_h" qtc_QComboBox_paintEngine_h :: Ptr (TQComboBox a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QComboBoxSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_paintEngine_h cobj_x0 instance QpaletteChange (QComboBox ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_paletteChange" qtc_QComboBox_paletteChange :: Ptr (TQComboBox a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QComboBoxSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QComboBox ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_repaint cobj_x0 foreign import ccall "qtc_QComboBox_repaint" qtc_QComboBox_repaint :: Ptr (TQComboBox a) -> IO () instance Qrepaint (QComboBoxSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_repaint cobj_x0 instance Qrepaint (QComboBox ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QComboBox_repaint2" qtc_QComboBox_repaint2 :: Ptr (TQComboBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QComboBoxSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QComboBox ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_repaint1" qtc_QComboBox_repaint1 :: Ptr (TQComboBox a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QComboBoxSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QComboBox ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_resetInputContext cobj_x0 foreign import ccall "qtc_QComboBox_resetInputContext" qtc_QComboBox_resetInputContext :: Ptr (TQComboBox a) -> IO () instance QresetInputContext (QComboBoxSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_resetInputContext cobj_x0 instance Qresize (QComboBox ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QComboBox_resize1" qtc_QComboBox_resize1 :: Ptr (TQComboBox a) -> CInt -> CInt -> IO () instance Qresize (QComboBoxSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QComboBox ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_resize" qtc_QComboBox_resize :: Ptr (TQComboBox a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QComboBoxSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_resize cobj_x0 cobj_x1 instance Qresize (QComboBox ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QComboBox_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QComboBox_resize_qth" qtc_QComboBox_resize_qth :: Ptr (TQComboBox a) -> CInt -> CInt -> IO () instance Qresize (QComboBoxSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QComboBox_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QComboBox ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QComboBox_setGeometry1" qtc_QComboBox_setGeometry1 :: Ptr (TQComboBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QComboBoxSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QComboBox ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_setGeometry" qtc_QComboBox_setGeometry :: Ptr (TQComboBox a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QComboBoxSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QComboBox ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QComboBox_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QComboBox_setGeometry_qth" qtc_QComboBox_setGeometry_qth :: Ptr (TQComboBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QComboBoxSc 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_QComboBox_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QComboBox ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_setMouseTracking" qtc_QComboBox_setMouseTracking :: Ptr (TQComboBox a) -> CBool -> IO () instance QsetMouseTracking (QComboBoxSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QComboBox ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_setVisible_h" qtc_QComboBox_setVisible_h :: Ptr (TQComboBox a) -> CBool -> IO () instance QsetVisible (QComboBoxSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setVisible_h cobj_x0 (toCBool x1) instance QtabletEvent (QComboBox ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_tabletEvent_h" qtc_QComboBox_tabletEvent_h :: Ptr (TQComboBox a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QComboBoxSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QComboBox ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_updateMicroFocus cobj_x0 foreign import ccall "qtc_QComboBox_updateMicroFocus" qtc_QComboBox_updateMicroFocus :: Ptr (TQComboBox a) -> IO () instance QupdateMicroFocus (QComboBoxSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_updateMicroFocus cobj_x0 instance QwindowActivationChange (QComboBox ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_windowActivationChange" qtc_QComboBox_windowActivationChange :: Ptr (TQComboBox a) -> CBool -> IO () instance QwindowActivationChange (QComboBoxSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QComboBox ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_childEvent" qtc_QComboBox_childEvent :: Ptr (TQComboBox a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QComboBoxSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QComboBox ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QComboBox_connectNotify" qtc_QComboBox_connectNotify :: Ptr (TQComboBox a) -> CWString -> IO () instance QconnectNotify (QComboBoxSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QComboBox ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_customEvent" qtc_QComboBox_customEvent :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QComboBoxSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QComboBox ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QComboBox_disconnectNotify" qtc_QComboBox_disconnectNotify :: Ptr (TQComboBox a) -> CWString -> IO () instance QdisconnectNotify (QComboBoxSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_disconnectNotify cobj_x0 cstr_x1 instance QeventFilter (QComboBox ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QComboBox_eventFilter_h" qtc_QComboBox_eventFilter_h :: Ptr (TQComboBox a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QComboBoxSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QComboBox ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QComboBox_receivers" qtc_QComboBox_receivers :: Ptr (TQComboBox a) -> CWString -> IO CInt instance Qreceivers (QComboBoxSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QComboBox_receivers cobj_x0 cstr_x1 instance Qsender (QComboBox ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sender cobj_x0 foreign import ccall "qtc_QComboBox_sender" qtc_QComboBox_sender :: Ptr (TQComboBox a) -> IO (Ptr (TQObject ())) instance Qsender (QComboBoxSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sender cobj_x0 instance QtimerEvent (QComboBox ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_timerEvent" qtc_QComboBox_timerEvent :: Ptr (TQComboBox a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QComboBoxSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_timerEvent cobj_x0 cobj_x1
uduki/hsQt
Qtc/Gui/QComboBox.hs
bsd-2-clause
68,475
0
16
11,279
22,832
11,583
11,249
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} -- | Converting between pixel-centric and ray-centric models. module Ray.Image where import Ray.Types import Ray.Imports import Codec.Picture import Codec.Picture.Types import Data.Array import Data.Word -- clamp :: Double -> Double clamp :: (Num a, Ord a) => a -> a clamp x | x > 1 = 1 clamp x | x < 0 = 0 clamp x = x bit8 :: Float -> Word8 bit8 px = round (255 * px) bit16 :: Float -> Word16 bit16 px = round (65535 * px) to8Bit :: Image PixelF -> Image Pixel8 to8Bit = pixelMap bit8 to16Bit :: Image PixelF -> Image Pixel16 to16Bit = pixelMap bit16 toJpg :: Image PixelF -> Image PixelYCbCr8 toJpg = convertImage . (promoteImage :: Image Pixel8 -> Image PixelRGB8) . to8Bit -- saveJpeg :: FilePath -> Image PixelF -> IO () -- saveJpeg fp img = BS.writeFile fp . encodeJpeg . toJpg $ img -- TODO add other options for handling gamut -- | Take colors with luminance in [0,1] and adjust to the non-linear -- sRGB space, clamping if they are out of gamut. toSRGB :: V3D -> RGB toSRGB = fmap clamp asImg :: V2 Int -> Array2D RGB -> Image PixelRGBF asImg (V2 xres yres) arr = generateImage lookup xres yres where lookup x y = asRGB . toSRGB $ arr ! V2 x y asRGB :: V3D -> PixelRGBF asRGB (V3 r g b) = PixelRGBF (r2f r) (r2f g) (r2f b) asRGB8 :: PixelRGBF -> PixelRGB8 asRGB8 (PixelRGBF r g b) = PixelRGB8 (bit8 r) (bit8 g) (bit8 b) asRGB16 :: PixelRGBF -> PixelRGB16 asRGB16 (PixelRGBF r g b) = PixelRGB16 (bit16 r) (bit16 g) (bit16 b)
bergey/panther
src/Ray/Image.hs
bsd-3-clause
1,487
0
9
299
506
259
247
33
1
module Ntha ( module Ntha.Core.Ast , module Ntha.Runtime.Value , module Ntha.Type.Type , module Ntha.Type.TypeScope , module Ntha.Type.Refined , module Ntha.Runtime.Eval , module Ntha.Type.Infer , module Ntha.Core.Prelude , module Ntha.Parser.Parser ) where import Ntha.Core.Ast import Ntha.Runtime.Value(ValueScope(..), Value(..)) import Ntha.Type.Type import Ntha.Type.TypeScope import Ntha.Type.Refined import Ntha.Runtime.Eval import Ntha.Type.Infer import Ntha.Core.Prelude import Ntha.Parser.Parser
zjhmale/Ntha
src/Ntha.hs
bsd-3-clause
546
0
6
91
139
96
43
19
0
{-# LANGUAGE Rank2Types #-} ----------------------------------------------------------- -- | -- Module : Database.HaskellDB.Connect.HDBC -- Copyright : Kei Hibino 2012 -- License : BSD-style -- -- Maintainer : ex8k.hibino@gmail.com -- Stability : experimental -- Portability : portable -- -- Bracketed session for HaskellDB with HDBC -- ----------------------------------------------------------- module Database.HaskellDB.Connect.HDBC ( -- * Bracketed session -- $bracketedSession makeHDBCSession ) where import Database.HDBC (IConnection, handleSqlError) import qualified Database.HDBC as HDBC import Database.HaskellDB.Database (Database (..)) import Database.HaskellDB.Sql.Generate (SqlGenerator) import Database.HaskellDB.Connect.HDBC.Internal (mkDatabase) {- $bracketedSession This module provides a base function to call close correctly against opend DB connection. Bracket function implementation is provided by several packages, so this package provides base implementation which requires bracket function and corresponding lift function. -} -- | Run an action on a HDBC IConnection and close the connection. makeHDBCSession :: (Monad m, IConnection conn) => (m conn -> (conn -> m ()) -> (conn -> m a) -> m a) -- ^ bracket -> (forall b. IO b -> m b) -- ^ lift -> SqlGenerator -> IO conn -- ^ Connect action -> (conn -> Database -> m a) -- ^ Transaction body -> m a makeHDBCSession bracket lift gen connect action = bracket (lift $ handleSqlError connect) (lift . handleSqlError . HDBC.disconnect) (\conn -> do x <- action conn (mkDatabase gen conn) -- Do rollback independent from driver default behavior when disconnect. lift $ HDBC.rollback conn return x)
khibino/haskelldb-connect-hdbc
src/Database/HaskellDB/Connect/HDBC.hs
bsd-3-clause
1,949
0
14
511
310
177
133
25
1
{-# LANGUAGE TupleSections #-} module Database.Firebase( module Database.Firebase.Types, query, key, get, put, post, patch, delete, sendMessage, getRules, setRules ) where import Database.Firebase.Types import Control.Applicative ((<$>)) import Control.Lens (view) import Control.Monad.Except (MonadError) import Control.Monad.Reader (MonadReader) import Control.Monad.Trans (MonadIO) import Data.Aeson (FromJSON, ToJSON, encode) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as BL import Data.List (intercalate) import Data.Maybe (catMaybes) import Network.HTTP.Nano import Network.HTTP.Types.URI (urlEncode) query :: Query query = Query Nothing Nothing Nothing Nothing key :: ToJSON a => a -> Key key = Key get :: (FbHttpM m e r, HasFirebase r, FromJSON a) => Location -> Maybe Query -> m a get loc mq = httpJSON =<< fbReq GET loc NoRequestData mq put :: (FbHttpM m e r, HasFirebase r, ToJSON a) => Location -> a -> m () put loc dta = http' =<< fbReq PUT loc (mkJSONData dta) Nothing post :: (FbHttpM m e r, HasFirebase r, ToJSON a) => Location -> a -> m FBID post loc dta = unName <$> (httpJSON =<< fbReq POST loc (mkJSONData dta) Nothing) patch :: (FbHttpM m e r, HasFirebase r, ToJSON a) => Location -> a -> m () patch loc dta = http' =<< fbReq (CustomMethod "PATCH") loc (mkJSONData dta) Nothing delete :: (FbHttpM m e r, HasFirebase r) => Location -> m () delete loc = http' =<< fbReq DELETE loc NoRequestData Nothing sendMessage :: (FbHttpM m e r, HasFirebase r, ToJSON a) => Message a -> m () sendMessage msg = do req <- buildReq POST googleCloudEndpoint (mkJSONData msg) apiKey <- view firebaseToken let req' = addHeaders [json, auth apiKey] req http' req' where json = ("Content-Type", "application/json") auth t = ("Authorization", "key=" ++ t) googleCloudEndpoint = "https://fcm.googleapis.com/fcm/send" getRules :: (FbHttpM m e r, HasFirebase r, FromJSON a) => m a getRules = httpJSON =<< fbReq GET ".settings/rules" NoRequestData Nothing setRules :: (FbHttpM m e r, HasFirebase r, ToJSON a) => a -> m () setRules dta = http' =<< fbReq PUT ".settings/rules" (mkJSONData dta) Nothing fbReq :: (FbHttpM m e r, HasFirebase r) => HttpMethod -> Location -> RequestData -> Maybe Query -> m Request fbReq mthd loc dta mq = do baseURL <- view firebaseURL token <- view firebaseToken let qstr = maybe "" buildQuery mq let url = baseURL ++ loc ++ ".json?auth=" ++ token ++ "&" ++ qstr buildReq mthd url dta buildQuery :: Query -> String buildQuery q = intercalate "&" . fmap (uncurry toParam) $ catMaybes [orderByQ, startAtQ, endAtQ, limitQ $ limit q] where orderByQ = ("orderBy",) . show <$> orderBy q startAtQ = ("startAt",) . encodeK <$> startAt q endAtQ = ("endAt",) . encodeK <$> endAt q limitQ Nothing = Nothing limitQ (Just (LimitToFirst l)) = Just ("limitToFirst", show l) limitQ (Just (LimitToLast l)) = Just ("limitToLast", show l) encodeK :: Key -> String encodeK (Key a) = BL.unpack $ encode a toParam :: String -> String -> String toParam k v = k ++ "=" ++ (B.unpack . urlEncode False $ B.pack v)
collegevine/firebase
src/Database/Firebase.hs
bsd-3-clause
3,209
0
14
648
1,242
650
592
72
3
module ParseBEST where import Text.Parsec import BEST parensParse :: Parser a -> Parser a parensParse = between (lexeme (char '(') <?> "Open Paren") (lexeme (char ')') <?> "Close Paren") eol :: Parser Char eol = lexeme endOfLine lexeme :: Parser a -> Parser a lexeme = (<* many (char ' ')) lexString :: String -> Parser () lexString = (pure () <*) . lexeme . string declaration :: Parser Expression declaration = choice [varIDExpression ,dataTypeDeclaration ,classDeclaration ,instanceDeclaration ,try valueDeclaration ,typeSignatureDeclaration ] <?> "Declaration" varIDExpression :: Parser Expression varIDExpression = VariableExpression <$> varID varID :: Parser VarID varID = VarID <$> typeSynonymDeclaration :: Parser Declaration typeSynonymDeclaration = TypeSynonymDeclaration <$> (lexString "type" *> varName) <*> many varName <* lexString "=" <*> typeExpression <?> "Type Synonym Declaration"
Lazersmoke/rhc
src/Old/ParseBEST.hs
bsd-3-clause
946
0
12
170
276
144
132
-1
-1
{-# language QuasiQuotes #-} module Bespoke.Utils ( marshalUtils , hasObjectTypeClass ) where import Prettyprinter import Foreign.C.Types import Foreign.Ptr import Polysemy import Polysemy.Input import Relude import Text.InterpolatedString.Perl6.Unindented import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import Foreign.Marshal.Array import Foreign.Marshal.Utils import Foreign.Storable import GHC.TypeNats import Error import Foreign.Marshal.Alloc ( callocBytes ) import Haskell.Name import Render.Element import Spec.Name ( CName(CName) ) hasObjectTypeClass :: (HasErr r, HasRenderParams r) => Sem r RenderElement hasObjectTypeClass = genRe "HasObjectType class" $ do RenderParams {..} <- input tellExport (EClass (TyConName "HasObjectType")) tellExplicitModule =<< mkModuleName ["Core10", "APIConstants"] tellImport ''Word64 tellNotReexportable let objectType = mkTyName (CName $ camelPrefix <> "ObjectType") tellImport objectType tellDoc $ "class HasObjectType a where" <> line <> indent 2 ("objectTypeAndHandle :: a ->" <+> tupled [pretty objectType, "Word64"]) marshalUtils :: (HasErr r, HasRenderParams r) => Sem r RenderElement marshalUtils = genRe "marshal utils" $ do tellExplicitModule =<< mkModuleName ["CStruct", "Utils"] tellNotReexportable traverseV_ tellImportWithAll [''Proxy, ''CChar] traverseV_ tellImport [ ''Word8 , ''BS.ByteString , 'BS.take , 'BS.unpack , 'BS.packCString , 'BS.packCStringLen , 'BS.unsafeUseAsCString , ''V.Vector , 'V.ifoldr , 'allocaArray , 'copyBytes , ''Ptr , 'castPtr , ''Storable , 'pokeElemOff , 'peekElemOff , 'natVal , ''KnownNat , ''(<=) , 'natVal , 'plusPtr , ''Nat , ''Type , 'callocBytes , 'sizeOf ] traverseV_ tellQualImport [ 'V.length , 'VG.length , 'VG.take , 'VG.replicate , 'VG.fromList , ''VG.Vector , '(VG.++) , 'VG.snoc , 'VG.empty , 'BS.length ] traverseV_ (tellExport . ETerm . TermName) [ "pokeFixedLengthByteString" , "pokeFixedLengthNullTerminatedByteString" , "peekByteStringFromSizedVectorPtr" , "callocFixedArray" , "lowerArrayPtr" , "advancePtrBytes" ] tellExport (EType (TyConName "FixedArray")) tellDoc [qi| -- | An unpopulated type intended to be used as in @'Ptr' (FixedArray n a)@ to -- indicate that the pointer points to an array of @n@ @a@s data FixedArray (n :: Nat) (a :: Type) -- | Store a 'ByteString' in a fixed amount of space inserting a null -- character at the end and truncating if necessary. -- -- If the 'ByteString' is not long enough to fill the space the remaining -- bytes are unchanged -- -- Note that if the 'ByteString' is exactly long enough the last byte will -- still be replaced with 0 pokeFixedLengthNullTerminatedByteString :: forall n . KnownNat n => Ptr (FixedArray n CChar) -> ByteString -> IO () pokeFixedLengthNullTerminatedByteString to bs = unsafeUseAsCString bs $ \from -> do let maxLength = fromIntegral (natVal (Proxy @n)) len = min maxLength (Data.ByteString.length bs) end = min (maxLength - 1) len -- Copy the entire string into the buffer copyBytes (lowerArrayPtr to) from len -- Make the last byte (the one following the string, or the -- one at the end of the buffer) pokeElemOff (lowerArrayPtr to) end 0 -- | Store a 'ByteString' in a fixed amount of space, truncating if necessary. -- -- If the 'ByteString' is not long enough to fill the space the remaining -- bytes are unchanged pokeFixedLengthByteString :: forall n . KnownNat n => Ptr (FixedArray n Word8) -> ByteString -> IO () pokeFixedLengthByteString to bs = unsafeUseAsCString bs $ \from -> do let maxLength = fromIntegral (natVal (Proxy @n)) len = min maxLength (Data.ByteString.length bs) copyBytes (lowerArrayPtr to) (castPtr @CChar @Word8 from) len -- | Peek a 'ByteString' from a fixed sized array of bytes peekByteStringFromSizedVectorPtr :: forall n . KnownNat n => Ptr (FixedArray n Word8) -> IO ByteString peekByteStringFromSizedVectorPtr p = packCStringLen (castPtr p, fromIntegral (natVal (Proxy @n))) -- | Allocate a zero array with the size specified by the 'FixedArray' -- return type. Make sure to release the memory with 'free' callocFixedArray :: forall n a . (KnownNat n, Storable a) => IO (Ptr (FixedArray n a)) callocFixedArray = callocBytes ( sizeOf (error "sizeOf evaluated its argument" :: a) * fromIntegral (natVal (Proxy @n)) ) -- | Get the pointer to the first element in the array lowerArrayPtr :: forall a n . Ptr (FixedArray n a) -> Ptr a lowerArrayPtr = castPtr -- | A type restricted 'plusPtr' advancePtrBytes :: Ptr a -> Int -> Ptr a advancePtrBytes = plusPtr |]
expipiplus1/vulkan
generate-new/src/Bespoke/Utils.hs
bsd-3-clause
5,458
0
14
1,536
649
377
272
-1
-1
module State.ChannelScroll ( channelScrollToTop , channelScrollToBottom , channelScrollUp , channelScrollDown , channelPageUp , channelPageDown , loadMoreMessages ) where import Prelude () import Prelude.MH import Brick.Main import Constants import State.Messages import Types channelPageUp :: MH () channelPageUp = do cId <- use csCurrentChannelId mh $ vScrollBy (viewportScroll (ChannelMessages cId)) (-1 * pageAmount) channelPageDown :: MH () channelPageDown = do cId <- use csCurrentChannelId mh $ vScrollBy (viewportScroll (ChannelMessages cId)) pageAmount channelScrollUp :: MH () channelScrollUp = do cId <- use csCurrentChannelId mh $ vScrollBy (viewportScroll (ChannelMessages cId)) (-1) channelScrollDown :: MH () channelScrollDown = do cId <- use csCurrentChannelId mh $ vScrollBy (viewportScroll (ChannelMessages cId)) 1 channelScrollToTop :: MH () channelScrollToTop = do cId <- use csCurrentChannelId mh $ vScrollToBeginning (viewportScroll (ChannelMessages cId)) channelScrollToBottom :: MH () channelScrollToBottom = do cId <- use csCurrentChannelId mh $ vScrollToEnd (viewportScroll (ChannelMessages cId)) loadMoreMessages :: MH () loadMoreMessages = whenMode ChannelScroll asyncFetchMoreMessages
aisamanra/matterhorn
src/State/ChannelScroll.hs
bsd-3-clause
1,354
0
12
288
380
190
190
41
1
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-} module LogMan.Filters (applyFilters ) where import Control.Monad.State import Data.ByteString.Lazy (ByteString) import Data.Text.Lazy (Text, replace, unpack) import Data.Time.Clock import LogMan.LogEntry import LogMan.Options import LogMan.Utils startTimeFilter :: (MonadState Options m) => [LogData] -> m [LogData] startTimeFilter es = do o <- get case optStartTime o of Nothing -> return es Just startTime -> return $ filter (\(e, r) -> isAfterTime e startTime) es endTimeFilter :: (MonadState Options m) => [LogData] -> m [LogData] endTimeFilter es = do o <- get case optEndTime o of Nothing -> return es Just endTime -> return $ filter (\(e, r) -> isBeforeTime e endTime) es usernameFilter :: (MonadState Options m) => [LogData] -> m [LogData] usernameFilter es = do o <- get case optUsername o of Nothing -> return es f -> return $ filter (\(e, r) -> (logUsername e) == f) es sessionFilter :: (MonadState Options m) => [LogData] -> m [LogData] sessionFilter es = do o <- get case optSessionId o of Nothing -> return es f -> return $ filter (\(e, r) -> (logSessionId e) == f) es applyFilters :: (MonadState Options m) => [LogData] -> m [LogData] applyFilters es = sessionFilter es >>= usernameFilter >>= startTimeFilter >>= endTimeFilter
cwmunn/logman
src/LogMan/Filters.hs
bsd-3-clause
1,406
0
16
312
523
274
249
36
2
module EFA.Flow.Sequence.Variable ( Any, Signal, RecordSignal, signal, Scalar, RecordScalar, scalar, Var.Index, Var.Type, Var.index, Var.FormatIndex, Var.checkedLookup, ) where import qualified EFA.Flow.SequenceState.Variable as Var import qualified EFA.Flow.SequenceState.Index as Idx import qualified EFA.Equation.RecordIndex as RecIdx import qualified EFA.Equation.Record as Record type Any = Var.Any Idx.Section signal :: Signal node -> Any node signal = Var.Signal scalar :: Scalar node -> Any node scalar = Var.Scalar type Signal = Var.Signal Idx.Section type RecordSignal rec node = RecIdx.Record (Record.ToIndex rec) (Signal node) type Scalar = Var.Scalar Idx.Section type RecordScalar rec node = RecIdx.Record (Record.ToIndex rec) (Scalar node)
energyflowanalysis/efa-2.1
src/EFA/Flow/Sequence/Variable.hs
bsd-3-clause
804
0
8
142
236
142
94
22
1
{-# LANGUAGE TemplateHaskell #-} module Graphics.GridView.Scroller(Scroller(..), empty, iteration, sImageIndex, sPixelOffset, sMovementDelta) where import Control.Applicative ((<$>), (<*>)) import Control.Lens (_1, (^.), (%~), (.~), (&), makeLenses) import Data.Vector.Vector2 (Vector2(..)) data Scroller = Scroller { gridItemSize :: Int , _sImageIndex :: Int , _sPixelOffset :: Int , _sMovementDelta :: Int } deriving (Show) makeLenses ''Scroller empty :: Int -> Scroller empty gis = Scroller gis 0 0 0 ceilDiv :: Integral a => a -> a -> a ceilDiv x y = (x + y - 1) `div` y align :: Integral a => a -> a -> a align x boundary = (x `ceilDiv` boundary) * boundary iteration :: Int -> Vector2 Int -> Scroller -> (Scroller, (Vector2 Int, [Vector2 Int])) iteration imgCount (Vector2 winWidth winHeight) s = ( s & sImageIndex .~ resultImageIndex & sPixelOffset .~ resultPixelOffset , ( Vector2 xCount yCount , gridPositions ) ) where gridPositions = map ((_1 %~ subtract (s ^. sPixelOffset)) . fmap ((gridItemSize s *) . fromIntegral)) $ Vector2 <$> [0::Int ..] <*> [0..yCount-1] imageIndex = s ^. sImageIndex pixelOffset = s ^. sPixelOffset movement = s ^. sMovementDelta yCount = winHeight `div` gridItemSize s xCount = 1 + (winWidth `ceilDiv` gridItemSize s) (resultImageIndex, resultPixelOffset) | newPosIndex < 0 = (0, 0) | newPosIndex >= rightMost && m+winWidth >= gridItemSize s = (imageIndex, pixelOffset) | otherwise = (newPosIndex, m) where newPosIndex = imageIndex + (d * yCount) columns = imgCount `ceilDiv` yCount rightMost = (1 + columns - (xCount-1)) `align` yCount (d, m) = (pixelOffset + movement) `divMod` gridItemSize s
Peaker/gridview
src/Graphics/GridView/Scroller.hs
bsd-3-clause
1,781
0
17
402
659
375
284
42
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-} -- Load information on package sources module Stack.Build.Source ( loadSourceMap , SourceMap , PackageSource (..) , localFlags , getLocalPackageViews , loadLocalPackage , parseTargetsFromBuildOpts , addUnlistedToBuildCache , getPackageConfig ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception (assert, catch) import Control.Monad import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import "cryptohash" Crypto.Hash (Digest, SHA256) import Crypto.Hash.Conduit (sinkHash) import qualified Data.ByteString as S import Data.Byteable (toBytes) import Data.Conduit (($$), ZipSink (..)) import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import Data.Either import Data.Function import qualified Data.HashSet as HashSet import Data.List import qualified Data.Map as Map import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Distribution.Package (pkgName, pkgVersion) import Distribution.PackageDescription (GenericPackageDescription, package, packageDescription) import qualified Distribution.PackageDescription as C import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Path.IO import Prelude import Stack.Build.Cache import Stack.Build.Target import Stack.BuildPlan (loadMiniBuildPlan, shadowMiniBuildPlan, parseCustomMiniBuildPlan) import Stack.Constants (wiredInPackages) import Stack.Package import Stack.Types import qualified System.Directory as D import System.IO (withBinaryFile, IOMode (ReadMode)) import System.IO.Error (isDoesNotExistError) loadSourceMap :: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m, HasEnvConfig env) => NeedTargets -> BuildOpts -> m ( Map PackageName SimpleTarget , MiniBuildPlan , [LocalPackage] , Set PackageName -- non-local targets , SourceMap ) loadSourceMap needTargets bopts = do bconfig <- asks getBuildConfig rawLocals <- getLocalPackageViews (mbp0, cliExtraDeps, targets) <- parseTargetsFromBuildOpts needTargets bopts let latestVersion = Map.fromListWith max $ map toTuple $ Map.keys (bcPackageCaches bconfig) -- Extend extra-deps to encompass targets requested on the command line -- that are not in the snapshot. extraDeps0 <- extendExtraDeps (bcExtraDeps bconfig) cliExtraDeps (Map.keysSet $ Map.filter (== STUnknown) targets) latestVersion locals <- mapM (loadLocalPackage bopts targets) $ Map.toList rawLocals checkFlagsUsed bopts locals extraDeps0 (mbpPackages mbp0) checkComponentsBuildable locals let -- loadLocals returns PackageName (foo) and PackageIdentifier (bar-1.2.3) targets separately; -- here we combine them into nonLocalTargets. This is one of the -- return values of this function. nonLocalTargets :: Set PackageName nonLocalTargets = Map.keysSet $ Map.filter (not . isLocal) targets where isLocal (STLocalComps _) = True isLocal STLocalAll = True isLocal STUnknown = False isLocal STNonLocal = False shadowed = Map.keysSet rawLocals <> Map.keysSet extraDeps0 (mbp, extraDeps1) = shadowMiniBuildPlan mbp0 shadowed -- Add the extra deps from the stack.yaml file to the deps grabbed from -- the snapshot extraDeps2 = Map.union (Map.map (\v -> (v, Map.empty)) extraDeps0) (Map.map (mpiVersion &&& mpiFlags) extraDeps1) -- Overwrite any flag settings with those from the config file extraDeps3 = Map.mapWithKey (\n (v, f) -> PSUpstream v Local $ case ( Map.lookup (Just n) $ boptsFlags bopts , Map.lookup Nothing $ boptsFlags bopts , Map.lookup n $ bcFlags bconfig ) of -- Didn't have any flag overrides, fall back to the flags -- defined in the snapshot. (Nothing, Nothing, Nothing) -> f -- Either command line flag for this package, general -- command line flag, or flag in stack.yaml is defined. -- Take all of those and ignore the snapshot flags. (x, y, z) -> Map.unions [ fromMaybe Map.empty x , fromMaybe Map.empty y , fromMaybe Map.empty z ]) extraDeps2 let sourceMap = Map.unions [ Map.fromList $ flip map locals $ \lp -> let p = lpPackage lp in (packageName p, PSLocal lp) , extraDeps3 , flip fmap (mbpPackages mbp) $ \mpi -> PSUpstream (mpiVersion mpi) Snap (mpiFlags mpi) ] `Map.difference` Map.fromList (map (, ()) (HashSet.toList wiredInPackages)) return (targets, mbp, locals, nonLocalTargets, sourceMap) -- | Use the build options and environment to parse targets. parseTargetsFromBuildOpts :: (MonadIO m, MonadCatch m, MonadReader env m, HasBuildConfig env, MonadBaseControl IO m, HasHttpManager env, MonadLogger m, HasEnvConfig env) => NeedTargets -> BuildOpts -> m (MiniBuildPlan, M.Map PackageName Version, M.Map PackageName SimpleTarget) parseTargetsFromBuildOpts needTargets bopts = do bconfig <- asks getBuildConfig mbp0 <- case bcResolver bconfig of ResolverSnapshot snapName -> do $logDebug $ "Checking resolver: " <> renderSnapName snapName loadMiniBuildPlan snapName ResolverCompiler _ -> do -- We ignore the resolver version, as it might be -- GhcMajorVersion, and we want the exact version -- we're using. version <- asks (envConfigCompilerVersion . getEnvConfig) return MiniBuildPlan { mbpCompilerVersion = version , mbpPackages = Map.empty } ResolverCustom _ url -> do stackYamlFP <- asks $ bcStackYaml . getBuildConfig parseCustomMiniBuildPlan stackYamlFP url rawLocals <- getLocalPackageViews workingDir <- getCurrentDir let snapshot = mpiVersion <$> mbpPackages mbp0 flagExtraDeps <- convertSnapshotToExtra snapshot (bcExtraDeps bconfig) rawLocals (catMaybes $ Map.keys $ boptsFlags bopts) (cliExtraDeps, targets) <- parseTargets needTargets (bcImplicitGlobal bconfig) snapshot (flagExtraDeps <> bcExtraDeps bconfig) (fst <$> rawLocals) workingDir (boptsTargets bopts) return (mbp0, cliExtraDeps <> flagExtraDeps, targets) -- | For every package in the snapshot which is referenced by a flag, give the -- user a warning and then add it to extra-deps. convertSnapshotToExtra :: MonadLogger m => Map PackageName Version -- ^ snapshot -> Map PackageName Version -- ^ extra-deps -> Map PackageName a -- ^ locals -> [PackageName] -- ^ packages referenced by a flag -> m (Map PackageName Version) convertSnapshotToExtra snapshot extra0 locals = go Map.empty where go !extra [] = return extra go extra (flag:flags) | Just _ <- Map.lookup flag extra0 = go extra flags | flag `Map.member` locals = go extra flags | otherwise = case Map.lookup flag snapshot of Nothing -> go extra flags Just version -> do $logWarn $ T.concat [ "- Implicitly adding " , T.pack $ packageNameString flag , " to extra-deps based on command line flag" ] go (Map.insert flag version extra) flags -- | Parse out the local package views for the current project getLocalPackageViews :: (MonadThrow m, MonadIO m, MonadReader env m, HasEnvConfig env, MonadLogger m) => m (Map PackageName (LocalPackageView, GenericPackageDescription)) getLocalPackageViews = do econfig <- asks getEnvConfig locals <- forM (Map.toList $ envConfigPackages econfig) $ \(dir, validWanted) -> do cabalfp <- findOrGenerateCabalFile dir (warnings,gpkg) <- readPackageUnresolved cabalfp mapM_ (printCabalFileWarning cabalfp) warnings let cabalID = package $ packageDescription gpkg name = fromCabalPackageName $ pkgName cabalID checkCabalFileName name cabalfp let lpv = LocalPackageView { lpvVersion = fromCabalVersion $ pkgVersion cabalID , lpvRoot = dir , lpvCabalFP = cabalfp , lpvExtraDep = not validWanted , lpvComponents = getNamedComponents gpkg } return (name, (lpv, gpkg)) checkDuplicateNames locals return $ Map.fromList locals where getNamedComponents gpkg = Set.fromList $ concat [ maybe [] (const [CLib]) (C.condLibrary gpkg) , go CExe C.condExecutables , go CTest C.condTestSuites , go CBench C.condBenchmarks ] where go wrapper f = map (wrapper . T.pack . fst) $ f gpkg -- | Check if there are any duplicate package names and, if so, throw an -- exception. checkDuplicateNames :: MonadThrow m => [(PackageName, (LocalPackageView, gpd))] -> m () checkDuplicateNames locals = case filter hasMultiples $ Map.toList $ Map.fromListWith (++) $ map toPair locals of [] -> return () x -> throwM $ DuplicateLocalPackageNames x where toPair (pn, (lpv, _)) = (pn, [lpvRoot lpv]) hasMultiples (_, _:_:_) = True hasMultiples _ = False splitComponents :: [NamedComponent] -> (Set Text, Set Text, Set Text) splitComponents = go id id id where go a b c [] = (Set.fromList $ a [], Set.fromList $ b [], Set.fromList $ c []) go a b c (CLib:xs) = go a b c xs go a b c (CExe x:xs) = go (a . (x:)) b c xs go a b c (CTest x:xs) = go a (b . (x:)) c xs go a b c (CBench x:xs) = go a b (c . (x:)) xs -- | Upgrade the initial local package info to a full-blown @LocalPackage@ -- based on the selected components loadLocalPackage :: forall m env. (MonadReader env m, HasEnvConfig env, MonadCatch m, MonadLogger m, MonadIO m) => BuildOpts -> Map PackageName SimpleTarget -> (PackageName, (LocalPackageView, GenericPackageDescription)) -> m LocalPackage loadLocalPackage bopts targets (name, (lpv, gpkg)) = do config <- getPackageConfig bopts name let pkg = resolvePackage config gpkg mtarget = Map.lookup name targets (exes, tests, benches) = case mtarget of Just (STLocalComps comps) -> splitComponents $ Set.toList comps Just STLocalAll -> ( packageExes pkg , if boptsTests bopts then Map.keysSet (packageTests pkg) else Set.empty , if boptsBenchmarks bopts then packageBenchmarks pkg else Set.empty ) Just STNonLocal -> assert False mempty Just STUnknown -> assert False mempty Nothing -> mempty toComponents e t b = Set.unions [ Set.map CExe e , Set.map CTest t , Set.map CBench b ] btconfig = config { packageConfigEnableTests = not $ Set.null tests , packageConfigEnableBenchmarks = not $ Set.null benches } testconfig = config { packageConfigEnableTests = True , packageConfigEnableBenchmarks = False } benchconfig = config { packageConfigEnableTests = False , packageConfigEnableBenchmarks = True } btpkg | Set.null tests && Set.null benches = Nothing | otherwise = Just (resolvePackage btconfig gpkg) testpkg = resolvePackage testconfig gpkg benchpkg = resolvePackage benchconfig gpkg mbuildCache <- tryGetBuildCache $ lpvRoot lpv (files,_) <- getPackageFilesSimple pkg (lpvCabalFP lpv) -- Filter out the cabal_macros file to avoid spurious recompilations let filteredFiles = Set.filter ((/= $(mkRelFile "cabal_macros.h")) . filename) files (dirtyFiles, newBuildCache) <- checkBuildCache (fromMaybe Map.empty mbuildCache) (map toFilePath $ Set.toList filteredFiles) return LocalPackage { lpPackage = pkg , lpTestDeps = packageDeps testpkg , lpBenchDeps = packageDeps benchpkg , lpTestBench = btpkg , lpFiles = files , lpForceDirty = boptsForceDirty bopts , lpDirtyFiles = if not (Set.null dirtyFiles) then let tryStripPrefix y = fromMaybe y (stripPrefix (toFilePath $ lpvRoot lpv) y) in Just $ Set.map tryStripPrefix dirtyFiles else Nothing , lpNewBuildCache = newBuildCache , lpCabalFile = lpvCabalFP lpv , lpDir = lpvRoot lpv , lpWanted = isJust mtarget , lpComponents = toComponents exes tests benches -- TODO: refactor this so that it's easier to be sure that these -- components are indeed unbuildable. -- -- The reasoning here is that if the STLocalComps specification -- made it through component parsing, but the components aren't -- present, then they must not be buildable. , lpUnbuildable = toComponents (exes `Set.difference` packageExes pkg) (tests `Set.difference` Map.keysSet (packageTests pkg)) (benches `Set.difference` packageBenchmarks pkg) } -- | Ensure that the flags specified in the stack.yaml file and on the command -- line are used. checkFlagsUsed :: (MonadThrow m, MonadReader env m, HasBuildConfig env) => BuildOpts -> [LocalPackage] -> Map PackageName extraDeps -- ^ extra deps -> Map PackageName snapshot -- ^ snapshot, for error messages -> m () checkFlagsUsed bopts lps extraDeps snapshot = do bconfig <- asks getBuildConfig -- Check if flags specified in stack.yaml and the command line are -- used, see https://github.com/commercialhaskell/stack/issues/617 let flags = map (, FSCommandLine) [(k, v) | (Just k, v) <- Map.toList $ boptsFlags bopts] ++ map (, FSStackYaml) (Map.toList $ bcFlags bconfig) localNameMap = Map.fromList $ map (packageName . lpPackage &&& lpPackage) lps checkFlagUsed ((name, userFlags), source) = case Map.lookup name localNameMap of -- Package is not available locally Nothing -> case Map.lookup name extraDeps of -- Also not in extra-deps, it's an error Nothing -> case Map.lookup name snapshot of Nothing -> Just $ UFNoPackage source name Just _ -> Just $ UFSnapshot name -- We don't check for flag presence for extra deps Just _ -> Nothing -- Package exists locally, let's check if the flags are defined Just pkg -> let unused = Set.difference (Map.keysSet userFlags) (packageDefinedFlags pkg) in if Set.null unused -- All flags are defined, nothing to do then Nothing -- Error about the undefined flags else Just $ UFFlagsNotDefined source pkg unused unusedFlags = mapMaybe checkFlagUsed flags unless (null unusedFlags) $ throwM $ InvalidFlagSpecification $ Set.fromList unusedFlags -- | All flags for a local package localFlags :: Map (Maybe PackageName) (Map FlagName Bool) -> BuildConfig -> PackageName -> Map FlagName Bool localFlags boptsflags bconfig name = Map.unions [ Map.findWithDefault Map.empty (Just name) boptsflags , Map.findWithDefault Map.empty Nothing boptsflags , Map.findWithDefault Map.empty name (bcFlags bconfig) ] -- | Add in necessary packages to extra dependencies -- -- Originally part of https://github.com/commercialhaskell/stack/issues/272, -- this was then superseded by -- https://github.com/commercialhaskell/stack/issues/651 extendExtraDeps :: (MonadThrow m, MonadReader env m, HasBuildConfig env) => Map PackageName Version -- ^ original extra deps -> Map PackageName Version -- ^ package identifiers from the command line -> Set PackageName -- ^ all packages added on the command line -> Map PackageName Version -- ^ latest versions in indices -> m (Map PackageName Version) -- ^ new extradeps extendExtraDeps extraDeps0 cliExtraDeps unknowns latestVersion | null errs = return $ Map.unions $ extraDeps1 : unknowns' | otherwise = do bconfig <- asks getBuildConfig throwM $ UnknownTargets (Set.fromList errs) Map.empty -- TODO check the cliExtraDeps for presence in index (bcStackYaml bconfig) where extraDeps1 = Map.union extraDeps0 cliExtraDeps (errs, unknowns') = partitionEithers $ map addUnknown $ Set.toList unknowns addUnknown pn = case Map.lookup pn extraDeps1 of Just _ -> Right Map.empty Nothing -> case Map.lookup pn latestVersion of Just v -> Right $ Map.singleton pn v Nothing -> Left pn -- | Compare the current filesystem state to the cached information, and -- determine (1) if the files are dirty, and (2) the new cache values. checkBuildCache :: MonadIO m => Map FilePath FileCacheInfo -- ^ old cache -> [FilePath] -- ^ files in package -> m (Set FilePath, Map FilePath FileCacheInfo) checkBuildCache oldCache files = liftIO $ do (dirtyFiles, m) <- mconcat <$> mapM go files return (dirtyFiles, m) where go fp = do mmodTime <- getModTimeMaybe fp case mmodTime of Nothing -> return (Set.empty, Map.empty) Just modTime' -> do (isDirty, newFci) <- case Map.lookup fp oldCache of Just fci | fciModTime fci == modTime' -> return (False, fci) | otherwise -> do newFci <- calcFci modTime' fp let isDirty = fciSize fci /= fciSize newFci || fciHash fci /= fciHash newFci return (isDirty, newFci) Nothing -> do newFci <- calcFci modTime' fp return (True, newFci) return (if isDirty then Set.singleton fp else Set.empty, Map.singleton fp newFci) -- | Returns entries to add to the build cache for any newly found unlisted modules addUnlistedToBuildCache :: (MonadIO m, MonadReader env m, MonadCatch m, MonadLogger m, HasEnvConfig env) => ModTime -> Package -> Path Abs File -> Map FilePath a -> m ([Map FilePath FileCacheInfo], [PackageWarning]) addUnlistedToBuildCache preBuildTime pkg cabalFP buildCache = do (files,warnings) <- getPackageFilesSimple pkg cabalFP let newFiles = Set.toList $ Set.map toFilePath files `Set.difference` Map.keysSet buildCache addBuildCache <- mapM addFileToCache newFiles return (addBuildCache, warnings) where addFileToCache fp = do mmodTime <- getModTimeMaybe fp case mmodTime of Nothing -> return Map.empty Just modTime' -> if modTime' < preBuildTime then do newFci <- calcFci modTime' fp return (Map.singleton fp newFci) else return Map.empty -- | Gets list of Paths for files in a package getPackageFilesSimple :: (MonadIO m, MonadReader env m, MonadCatch m, MonadLogger m, HasEnvConfig env) => Package -> Path Abs File -> m (Set (Path Abs File), [PackageWarning]) getPackageFilesSimple pkg cabalFP = do (_,compFiles,cabalFiles,warnings) <- getPackageFiles (packageFiles pkg) cabalFP return ( Set.map dotCabalGetPath (mconcat (M.elems compFiles)) <> cabalFiles , warnings) -- | Get file modification time, if it exists. getModTimeMaybe :: MonadIO m => FilePath -> m (Maybe ModTime) getModTimeMaybe fp = liftIO (catch (liftM (Just . modTime) (D.getModificationTime fp)) (\e -> if isDoesNotExistError e then return Nothing else throwM e)) -- | Create FileCacheInfo for a file. calcFci :: MonadIO m => ModTime -> FilePath -> m FileCacheInfo calcFci modTime' fp = liftIO $ withBinaryFile fp ReadMode $ \h -> do (size, digest) <- CB.sourceHandle h $$ getZipSink ((,) <$> ZipSink (CL.fold (\x y -> x + fromIntegral (S.length y)) 0) <*> ZipSink sinkHash) return FileCacheInfo { fciModTime = modTime' , fciSize = size , fciHash = toBytes (digest :: Digest SHA256) } checkComponentsBuildable :: MonadThrow m => [LocalPackage] -> m () checkComponentsBuildable lps = unless (null unbuildable) $ throwM $ SomeTargetsNotBuildable unbuildable where unbuildable = [ (packageName (lpPackage lp), c) | lp <- lps , c <- Set.toList (lpUnbuildable lp) ] -- | Get 'PackageConfig' for package given its name. getPackageConfig :: (MonadIO m, MonadThrow m, MonadCatch m, MonadLogger m, MonadReader env m, HasEnvConfig env) => BuildOpts -> PackageName -> m PackageConfig getPackageConfig bopts name = do econfig <- asks getEnvConfig bconfig <- asks getBuildConfig return PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = localFlags (boptsFlags bopts) bconfig name , packageConfigCompilerVersion = envConfigCompilerVersion econfig , packageConfigPlatform = configPlatform $ getConfig bconfig }
luigy/stack
src/Stack/Build/Source.hs
bsd-3-clause
24,048
0
27
7,904
5,607
2,899
2,708
-1
-1
module Web.Zenfolio.Categories ( getCategories ) where import Web.Zenfolio.Monad (ZM) import Web.Zenfolio.RPC (zfRemote) import Web.Zenfolio.Types (CategoryInfo) getCategories :: ZM [CategoryInfo] getCategories = zfRemote "GetCategories"
md5/hs-zenfolio
Web/Zenfolio/Categories.hs
bsd-3-clause
244
0
6
29
64
39
25
7
1
module Onedrive.User (me) where import Control.Monad.Catch (MonadThrow) import Control.Monad.IO.Class (MonadIO) import Network.HTTP.Simple (parseRequest) import Onedrive.Internal.Response (json) import Onedrive.Session (Session) import Onedrive.Types.UserInfo (UserInfo) me :: (MonadThrow m, MonadIO m) => Session -> m UserInfo me session = do initReq <- parseRequest "https://apis.live.net/v5.0/me" json session initReq
asvyazin/hs-onedrive
src/Onedrive/User.hs
bsd-3-clause
429
0
8
52
130
74
56
11
1
-- -- SPI.hs --- SPI peripheral -- -- Copyright (C) 2014, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32.Peripheral.SPI ( module Ivory.BSP.STM32.Peripheral.SPI.Regs , module Ivory.BSP.STM32.Peripheral.SPI.RegTypes , module Ivory.BSP.STM32.Peripheral.SPI.Peripheral ) where import Ivory.BSP.STM32.Peripheral.SPI.Regs import Ivory.BSP.STM32.Peripheral.SPI.RegTypes import Ivory.BSP.STM32.Peripheral.SPI.Peripheral
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/SPI.hs
bsd-3-clause
438
0
5
47
74
59
15
7
0
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE FlexibleInstances #-} module PID where import Ivory.Compile.C.CmdlineFrontend import Ivory.Language [ivory| struct PID { pid_mv :: Stored IFloat ; pid_i :: Stored IFloat ; pid_err :: Stored IFloat } |] type SP = IFloat -- Set point type PV = IFloat -- Process (measured) value type Time = IFloat {- void pid_update(struct PID * pid, sp_t sp, pv_t pv, timeinc_t dt ) { float err = sp - pv; float i = pid->i + err*dt; float d = (err - pid->err) / dt; pid->i = ki*i; pid->mv = kp*err + pid->i + kd*d; pid->err = err; return; } -} kp, ki, kd :: IFloat kp = 1.0 ki = 0.1 kd = 0.1 pidUpdate :: Def ('[ Ref s (Struct "PID") , SP , PV , Time ] :-> IFloat) pidUpdate = proc "pid_update" $ \ pid sp pv dt -> -- These are made up requires/ensures for testing purposes. requires (checkStored (pid ~> pid_err) (\err -> err <? 1)) $ ensures (\res -> checkStored (pid ~> pid_err) (\err -> err <? res)) $ body $ do err <- assign (sp - pv) i <- deref $ pid ~> pid_i i' <- assign $ ki * (i + err*dt) prevErr <- deref $ pid ~> pid_err d <- assign $ (err - prevErr) / dt store (pid ~> pid_i) i' store (pid ~> pid_mv) (kp*err + i' + kd*d) store (pid ~> pid_err) err ret err foo :: Def ('[ Ref s (Array 3 (Stored Uint32)) , Ref s (Array 3 (Stored Uint32)) ] :-> ()) foo = proc "foo" $ \a b -> -- requires (*a!0 < *b!0) requires (checkStored (a ! 0) (\v -> (checkStored (b ! 0) (\v1 -> v <? v1)))) $ body $ do retVoid runPID :: IO () runPID = runCompiler [cmodule] [] initialOpts { outDir = Nothing, bitShiftCheck = True, divZero = True } cmodule :: Module cmodule = package "PID" $ do incl foobar -- defStruct (Proxy :: Proxy "PID") -- incl pidUpdate -- incl alloc_test foobar :: Def ('[Uint8] :-> Uint8) foobar = proc "foobar" $ \x -> body $ do ret (x `iShiftR` (3 `iDiv` 2)) alloc_test :: Def ('[] :-> IFloat) alloc_test = proc "alloc_test" $ body $ do pid <- local (istruct [pid_i .= ival 1]) ret =<< deref (pid ~> pid_i)
Hodapp87/ivory
ivory-examples/examples/PID.hs
bsd-3-clause
2,384
0
18
744
742
399
343
57
1
{-# LANGUAGE RecordWildCards #-} module Main (main) where import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Control.Monad.Trans import Criterion.Config import Criterion.Main import Criterion.Monad import Data.IORef import System.IO.Unsafe data Lock a b = Lock { lockMake :: IO (a b) , lockPut :: (a b) -> b -> IO () , lockTake :: (a b) -> IO b } lockMVar :: Lock MVar a lockMVar = Lock newEmptyMVar putMVar takeMVar lockTMVar :: Lock TMVar a lockTMVar = Lock newEmptyTMVarIO (\lock x -> atomically $ putTMVar lock x) (atomically . takeTMVar) forkJoin :: Lock a () -> IO () forkJoin Lock{..} = do lock <- lockMake _ <- forkIO (lockPut lock ()) lockTake lock cfg :: Config cfg = defaultConfig -- Always GC between runs. { cfgPerformGC = ljust True , cfgTemplate = ljust "report.tpl" , cfgReport = ljust "report.html" } prepare :: Criterion () prepare = liftIO $ do _ <- forkIO $ forever $ do () <- readChan theChan putMVar theLock () _ <- forkIO $ forever $ do () <- atomically (readTChan theTChan) putMVar theLock () _ <- forkIO $ forever $ do () <- takeMVar theMVar putMVar theLock () _ <- forkIO $ forever $ do () <- atomically $ takeTMVar theTMVar putMVar theLock () return () theChan :: Chan () theChan = unsafePerformIO newChan theTChan :: TChan () theTChan = unsafePerformIO newTChanIO theMVar :: MVar () theMVar = unsafePerformIO newEmptyMVar theTMVar :: TMVar () theTMVar = unsafePerformIO newEmptyTMVarIO theLock :: MVar () theLock = unsafePerformIO newEmptyMVar theTMVarLock :: TMVar () theTMVarLock = unsafePerformIO newEmptyTMVarIO theTVar :: TVar () theTVar = unsafePerformIO $ newTVarIO () theIORef :: IORef () theIORef = unsafePerformIO $ newIORef () main :: IO () main = defaultMainWith cfg prepare [ bgroup "write-read" [ bench "IORef" $ writeIORef theIORef () >> readIORef theIORef , bench "MVar" $ putMVar theLock () >> takeMVar theLock , bench "TVar" $ atomically (writeTVar theTVar ()) >> atomically (readTVar theTVar) , bench "TMVar" $ do atomically $ putTMVar theTMVarLock () atomically $ takeTMVar theTMVarLock ] , bgroup "forkIO-join" [ bench "MVar" $ forkJoin lockMVar , bench "TMVar" $ forkJoin lockTMVar ] , bgroup "send-join" [ bench "MVar" $ do putMVar theMVar () takeMVar theLock , bench "Chan" $ do writeChan theChan () takeMVar theLock , bench "TMVar" $ do atomically $ putTMVar theTMVar () takeMVar theLock , bench "TChan" $ do atomically $ writeTChan theTChan () takeMVar theLock ] ]
informatikr/concurrency-cost
Main.hs
bsd-3-clause
2,981
0
15
929
949
462
487
87
1
module Graphics.UI.Oak.Widgets ( Identifier(..) , MessageCode(..) , WidgetBehavior(..) , LayoutItem(..) , Widget(..) , WidgetState(..) , SizePolicy(..) , acceptsFocus , isBox , boxItems , sizePolicy , compact , hexpand , vexpand , vbox , hbox , table , vcenter , hcenter , center , margin , header , dialog ) where import Data.Maybe (fromMaybe) import Graphics.UI.Oak.Basics class (Eq a, Show a) => Identifier a where unused :: a btnBack :: a data MessageCode = Ok | Yes | No | Cancel deriving (Eq, Show) data WidgetState = Normal | Focused deriving (Eq, Show) data LayoutItem i m = LayoutItem { name :: i , widget :: Widget i m , rect :: Rect } deriving (Eq, Show) data (Monad m) => WidgetBehavior m = WidgetBehavior { accFocusFcn :: Bool , sizePcyFcn :: Orientation -> (SizePolicy, SizePolicy) , sizeHintFcn :: Orientation -> m Size , renderFcn :: WidgetState -> Rect -> m () } instance Show (WidgetBehavior m) where show _ = "<#behavior>" instance Eq (WidgetBehavior m) where _ == _ = False data Widget i m = VBox [LayoutItem i m] | HBox [LayoutItem i m] | Table [[LayoutItem i m]] | Label String | Button String | Edit String Int | Stretch | Space Int | Line Int | Adjustable (Maybe (SizePolicy, SizePolicy)) (Maybe (SizePolicy, SizePolicy)) (Widget i m) | Margin (Int, Int, Int, Int) (Widget i m) | Custom (WidgetBehavior m) deriving (Eq, Show) data SizePolicy = Fixed | Minimum | Expanding deriving (Eq, Show) compact :: Widget i m -> Widget i m compact = Adjustable c c where c = Just (Minimum, Minimum) hexpand :: Widget i m -> Widget i m hexpand = Adjustable Nothing $ Just (Expanding, Expanding) vexpand :: Widget i m -> Widget i m vexpand = Adjustable (Just (Expanding, Expanding)) Nothing vbox :: [(i, Widget i m)] -> Widget i m vbox ws = VBox $ items ws hbox :: [(i, Widget i m)] -> Widget i m hbox ws = HBox $ items ws table :: [[(i, Widget i m)]] -> Widget i m table wss = Table $ map items wss items :: [(i, Widget i m)] -> [LayoutItem i m] items = map (\(i, w) -> LayoutItem i w (Rect 0 0 (Size 0 0))) margin :: Identifier i => Int -> (i, Widget i m) -> Widget i m margin m (_, w) = Margin (m, m, m, m) w vcenter :: Identifier i => (i, Widget i m) -> Widget i m vcenter p = vbox [ (unused, Stretch) , p , (unused, Stretch) ] hcenter :: Identifier i => (i, Widget i m) -> Widget i m hcenter p = hbox [(unused, Stretch), p, (unused, Stretch)] center :: Identifier i => (i, Widget i m) -> Widget i m center p = vcenter (unused, hcenter p) header :: Identifier i => String -> Widget i m header s = compact $ vbox [ (unused, Label s) , (unused, Line 3) ] dialog :: Identifier i => String -> [(i, Widget i m)] -> (i, Widget i m) -> Widget i m dialog title buttons contents = margin 20 (unused, vbox [ (unused, header title) , (unused, margin 10 contents) , (unused, hbox $ buttons ++ [(unused, Stretch)]) ] ) isBox :: Widget i m -> Bool isBox (HBox _) = True isBox (VBox _) = True isBox (Table _) = True isBox (Adjustable _ _ _) = True isBox (Margin _ _) = True isBox _ = False boxItems :: Widget i m -> [LayoutItem i m] boxItems (HBox is) = is boxItems (VBox is) = is boxItems (Table iss) = concat iss boxItems (Adjustable _ _ w) = boxItems w boxItems (Margin _ w) = boxItems w boxItems _ = [] acceptsFocus :: Monad m => Widget i m -> Bool acceptsFocus (Button _) = True acceptsFocus (Edit _ _) = True acceptsFocus (Custom bh) = accFocusFcn bh acceptsFocus _ = False -- Returns a (vertical, horizontal) size policies sizePolicy :: Monad m => Orientation -> Widget i m -> (SizePolicy, SizePolicy) sizePolicy _ (VBox _) = (Expanding, Minimum) sizePolicy _ (HBox _) = (Minimum, Expanding) sizePolicy _ (Table _) = (Expanding, Expanding) sizePolicy _ (Label _) = (Minimum, Minimum) sizePolicy _ (Button _) = (Minimum, Minimum) sizePolicy _ (Edit _ _ ) = (Minimum, Expanding) sizePolicy o (Space _) = flexiblePolicy o sizePolicy o (Line _) = flexiblePolicy o sizePolicy _ Stretch = (Expanding, Expanding) sizePolicy o (Margin _ w) = sizePolicy o w sizePolicy o (Custom bh) = sizePcyFcn bh o sizePolicy o (Adjustable v h w) | o == Vertical = fromMaybe orig v | o == Horizontal = fromMaybe orig h where orig = sizePolicy o w flexiblePolicy :: Orientation -> (SizePolicy, SizePolicy) flexiblePolicy o | o == Vertical = (Fixed, Expanding) | o == Horizontal = (Expanding, Fixed)
dmatveev/oak
Graphics/UI/Oak/Widgets.hs
bsd-3-clause
5,308
0
12
1,835
2,020
1,086
934
142
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE UndecidableInstances #-} module Data.Time.ValidGregorian ( gregorian , Gregorian(..) , ValidGregorian ) where import Data.Proxy (Proxy (..)) import Data.Time.Calendar (Day, fromGregorian) import Data.Type.Bool import Data.Type.Equality import GHC.TypeLits gregorian :: forall year month day. ( KnownNat year , KnownNat month , KnownNat day , ValidGregorian year month day ) => Gregorian year month day -> Day gregorian _ = fromGregorian year (fromInteger month) (fromInteger day) where year = natVal (Proxy :: Proxy year) month = natVal (Proxy :: Proxy month) day = natVal (Proxy :: Proxy day) data Gregorian (year :: Nat) (month :: Nat) (day :: Nat) = Gregorian type ValidGregorian year month day = IsValidGregorian year month day ~ 'True type family IsValidGregorian (year :: Nat) (month :: Nat) (day :: Nat) where IsValidGregorian year 01 day = 1 <=? day && day <=? 31 IsValidGregorian year 02 29 = IsLeapYear year IsValidGregorian year 02 day = 1 <=? day && day <=? 28 IsValidGregorian year 03 day = 1 <=? day && day <=? 31 IsValidGregorian year 04 day = 1 <=? day && day <=? 30 IsValidGregorian year 05 day = 1 <=? day && day <=? 31 IsValidGregorian year 06 day = 1 <=? day && day <=? 30 IsValidGregorian year 07 day = 1 <=? day && day <=? 31 IsValidGregorian year 08 day = 1 <=? day && day <=? 31 IsValidGregorian year 09 day = 1 <=? day && day <=? 30 IsValidGregorian year 10 day = 1 <=? day && day <=? 31 IsValidGregorian year 11 day = 1 <=? day && day <=? 30 IsValidGregorian year 12 day = 1 <=? day && day <=? 31 type family IsLeapYear (n :: Nat) where IsLeapYear 0 = 'True IsLeapYear n = (DivisibleBy 4 n) && (Not (DivisibleBy 100 n)) || (DivisibleBy 400 n) -- | Checks whether `n` divides by `a` type family DivisibleBy (a :: Nat) (n :: Nat) where DivisibleBy 0 n = 'False -- Nothing divides by 0 DivisibleBy a 0 = 'True -- 0 divides by anything DivisibleBy a n = If (CmpNat a n == 'GT) 'False (DivisibleBy a (n - a))
zudov/time-checker
src/Data/Time/ValidGregorian.hs
bsd-3-clause
2,482
0
11
598
756
417
339
54
1
{-- | An opaque handle to a keystore, used to read and write 'EncryptedSecretKey' from/to disk. NOTE: This module aims to provide a stable interface with a concrete implementation concealed by the user of this module. The internal operations are currently quite inefficient, as they have to work around the legacy 'UserSecret' storage. --} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Cardano.Wallet.Kernel.Keystore ( Keystore -- opaque , DeletePolicy(..) , ReplaceResult(..) -- * Constructing a keystore , bracketKeystore , bracketLegacyKeystore , readWalletSecret -- * Inserting values , insert -- * Replacing values, atomically , compareAndReplace -- * Deleting values , delete -- * Queries on a keystore , getKeys , lookup -- * Tests handy functions , bracketTestKeystore ) where import Universum import qualified Data.List import System.Directory (getTemporaryDirectory, removeFile) import System.IO (hClose, openTempFile) import Pos.Core.NetworkMagic (NetworkMagic) import Pos.Crypto (EncryptedSecretKey, hash) import Pos.Util.Trace (fromTypeclassWlog) import Pos.Util.UserSecret (UserSecret, getUSPath, isEmptyUserSecret, readUserSecret, takeUserSecret, usKeys, usWallet, writeRaw, writeUserSecretRelease, _wusRootKey) import Pos.Util.Wlog (addLoggerName) import Cardano.Wallet.Kernel.DB.HdWallet (eskToHdRootId) import Cardano.Wallet.Kernel.Types (WalletId (..)) import qualified Cardano.Wallet.Kernel.Util.Strict as Strict -- Internal storage necessary to smooth out the legacy 'UserSecret' API. data InternalStorage = InternalStorage !UserSecret -- | We are not really interested in fully-forcing the 'UserSecret'. We are -- happy here with the operations on the keystore being applied not lazily. instance NFData InternalStorage where rnf x = x `seq` () -- A 'Keystore'. data Keystore = Keystore (Strict.MVar InternalStorage) -- | A 'DeletePolicy' is a preference the user can express on how to release -- the 'Keystore' during its teardown. data DeletePolicy = RemoveKeystoreIfEmpty -- ^ Completely obliterate the 'Keystore' if is empty, including the -- file on disk. | KeepKeystoreIfEmpty -- ^ Release the 'Keystore' without touching its file on disk, even -- if the latter is empty. {------------------------------------------------------------------------------- Creating a keystore -------------------------------------------------------------------------------} -- FIXME [CBR-316] Due to the current, legacy 'InternalStorage' being -- used, the 'Keystore' does not persist the in-memory content on disk after -- every destructive operations, which means that in case of a node crash or -- another catastrophic behaviour (e.g. power loss, etc) the in-memory content -- not yet written in memory will be forever lost. -- | Creates a 'Keystore' using a 'bracket' pattern, where the -- initalisation and teardown of the resource are wrapped in 'bracket'. bracketKeystore :: DeletePolicy -- ^ What to do if the keystore is empty -> FilePath -- ^ The path to the file which will be used for the 'Keystore' -> (Keystore -> IO a) -- ^ An action on the 'Keystore'. -> IO a bracketKeystore deletePolicy fp withKeystore = bracket (newKeystore fp) (releaseKeystore deletePolicy) withKeystore -- | Creates a new keystore. newKeystore :: FilePath -> IO Keystore newKeystore fp = do us <- takeUserSecret fromTypeclassWlog fp Keystore <$> Strict.newMVar (InternalStorage us) -- | Reads the legacy root key stored in the specified keystore. This is -- useful only for importing a wallet using the legacy '.key' format. readWalletSecret :: FilePath -- ^ The path to the file which will be used for the 'Keystore' -> IO (Maybe EncryptedSecretKey) readWalletSecret fp = addLoggerName "KeyStore" $ importKeystore >>= lookupLegacyRootKey where lookupLegacyRootKey :: Keystore -> IO (Maybe EncryptedSecretKey) lookupLegacyRootKey (Keystore ks) = Strict.withMVar ks $ \(InternalStorage us) -> case us ^. usWallet of Nothing -> return Nothing Just w -> return (Just $ _wusRootKey w) importKeystore :: IO Keystore importKeystore = do us <- readUserSecret fromTypeclassWlog fp Keystore <$> Strict.newMVar (InternalStorage us) -- | Creates a legacy 'Keystore' by reading the 'UserSecret' from a 'NodeContext'. -- Hopefully this function will go in the near future. newLegacyKeystore :: UserSecret -> IO Keystore newLegacyKeystore us = Keystore <$> Strict.newMVar (InternalStorage us) -- | Creates a legacy 'Keystore' using a 'bracket' pattern, where the -- initalisation and teardown of the resource are wrapped in 'bracket'. -- For a legacy 'Keystore' users do not get to specify a 'DeletePolicy', as -- the release of the keystore is left for the node and the legacy code -- themselves. bracketLegacyKeystore :: UserSecret -> (Keystore -> IO a) -> IO a bracketLegacyKeystore us withKeystore = bracket (newLegacyKeystore us) (\_ -> return ()) -- Leave teardown to the legacy wallet withKeystore bracketTestKeystore :: (Keystore -> IO a) -> IO a bracketTestKeystore withKeystore = bracket newTestKeystore (releaseKeystore RemoveKeystoreIfEmpty) withKeystore -- | Creates a 'Keystore' out of a randomly generated temporary file (i.e. -- inside your $TMPDIR of choice). -- We don't offer a 'bracket' style here as the teardown is irrelevant, as -- the file is disposed automatically from being created into the -- OS' temporary directory. -- NOTE: This 'Keystore', as its name implies, shouldn't be using in -- production, but only for testing, as it can even possibly contain data -- races due to the fact its underlying file is stored in the OS' temporary -- directory. newTestKeystore :: IO Keystore newTestKeystore = do tempDir <- getTemporaryDirectory (tempFile, hdl) <- openTempFile tempDir "keystore.key" hClose hdl us <- takeUserSecret fromTypeclassWlog tempFile Keystore <$> Strict.newMVar (InternalStorage us) -- | Release the resources associated with this 'Keystore'. releaseKeystore :: DeletePolicy -> Keystore -> IO () releaseKeystore dp (Keystore ks) = -- We are not modifying the 'MVar' content, because this function is -- not exported and called exactly once from the bracket de-allocation. Strict.withMVar ks $ \internalStorage@(InternalStorage us) -> do fp <- release internalStorage case dp of KeepKeystoreIfEmpty -> return () RemoveKeystoreIfEmpty -> when (isEmptyUserSecret us) $ removeFile fp -- | Releases the underlying 'InternalStorage' and returns the updated -- 'InternalStorage' and the file on disk this storage lives in. -- 'FilePath'. release :: InternalStorage -> IO FilePath release (InternalStorage us) = do let fp = getUSPath us writeUserSecretRelease us return fp {------------------------------------------------------------------------------- Modifying the Keystore We wrap each operation which modifies the underlying `InternalStorage` into a combinator which also writes the updated `UserSecret` to file. -------------------------------------------------------------------------------} -- | Modifies the 'Keystore' by applying the transformation 'f' on the -- underlying 'UserSecret'. modifyKeystore_ :: Keystore -> (UserSecret -> UserSecret) -> IO () modifyKeystore_ ks f = let f' us = (f us, ()) in modifyKeystore ks f' -- | Like 'modifyKeystore_', but it returns a result at the end. modifyKeystore :: Keystore -> (UserSecret -> (UserSecret, a)) -> IO a modifyKeystore (Keystore ks) f = Strict.modifyMVar ks $ \(InternalStorage us) -> do let (us', a) = f us -- This is a safe operation to be because we acquired the exclusive -- lock on this file when we initialised the keystore, and as we are -- using 'bracket', we are the sole owner of this lock. writeRaw us' return (InternalStorage us', a) {------------------------------------------------------------------------------- Inserting things inside a keystore -------------------------------------------------------------------------------} -- | Insert a new 'EncryptedSecretKey' indexed by the input 'WalletId'. insert :: WalletId -> EncryptedSecretKey -> Keystore -> IO () insert _walletId esk ks = modifyKeystore_ ks (insertKey esk) -- | Insert a new 'EncryptedSecretKey' directly inside the 'UserSecret'. insertKey :: EncryptedSecretKey -> UserSecret -> UserSecret insertKey esk us = if view usKeys us `contains` esk then us else us & over usKeys (esk :) where -- Comparator taken from the old code which needs to hash -- all the 'EncryptedSecretKey' in order to compare them. contains :: [EncryptedSecretKey] -> EncryptedSecretKey -> Bool contains ls k = hash k `elem` map hash ls -- | An enumeration data ReplaceResult = Replaced | OldKeyLookupFailed | PredicateFailed -- ^ The supplied predicate failed. deriving (Show, Eq) -- | Replace an old 'EncryptedSecretKey' with a new one, -- verifying a pre-condition on the previously stored key. compareAndReplace :: NetworkMagic -> WalletId -> (EncryptedSecretKey -> Bool) -> EncryptedSecretKey -> Keystore -> IO ReplaceResult compareAndReplace nm walletId predicateOnOldKey newKey ks = modifyKeystore ks $ \us -> let mbOldKey = lookupKey nm us walletId in case predicateOnOldKey <$> mbOldKey of Nothing -> (us, OldKeyLookupFailed) Just False -> (us, PredicateFailed) Just True -> (insertKey newKey . deleteKey nm walletId $ us, Replaced) {------------------------------------------------------------------------------- Looking up things inside a keystore -------------------------------------------------------------------------------} -- | Lookup an 'EncryptedSecretKey' associated to the input 'HdRootId'. lookup :: NetworkMagic -> WalletId -> Keystore -> IO (Maybe EncryptedSecretKey) lookup nm wId (Keystore ks) = Strict.withMVar ks $ \(InternalStorage us) -> return $ lookupKey nm us wId -- | Lookup a key directly inside the 'UserSecret'. lookupKey :: NetworkMagic -> UserSecret -> WalletId -> Maybe EncryptedSecretKey lookupKey nm us (WalletIdHdRnd walletId) = Data.List.find (\k -> eskToHdRootId nm k == walletId) (us ^. usKeys) -- | Return all Keystore 'usKeys' getKeys :: Keystore -> IO [EncryptedSecretKey] getKeys (Keystore ks) = Strict.withMVar ks $ \(InternalStorage us) -> return $ us ^. usKeys {------------------------------------------------------------------------------- Deleting things from the keystore -------------------------------------------------------------------------------} -- | Deletes an element from the 'Keystore'. This is an idempotent operation -- as in case a key was not present, no error would be thrown. delete :: NetworkMagic -> WalletId -> Keystore -> IO () delete nm walletId ks = modifyKeystore_ ks (deleteKey nm walletId) -- | Delete a key directly inside the 'UserSecret'. deleteKey :: NetworkMagic -> WalletId -> UserSecret -> UserSecret deleteKey nm walletId us = let mbEsk = lookupKey nm us walletId erase = Data.List.deleteBy (\a b -> hash a == hash b) in maybe us (\esk -> us & over usKeys (erase esk)) mbEsk
input-output-hk/pos-haskell-prototype
wallet/src/Cardano/Wallet/Kernel/Keystore.hs
mit
11,941
0
15
2,647
1,850
993
857
153
3
{-# LANGUAGE CPP #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Yesod.Auth ( -- * Subsite Auth , AuthRoute , Route (..) , AuthPlugin (..) , getAuth , YesodAuth (..) , YesodAuthPersist (..) -- * Plugin interface , Creds (..) , setCreds , setCredsRedirect , clearCreds , loginErrorMessage , loginErrorMessageI -- * User functions , AuthenticationResult (..) , defaultMaybeAuthId , defaultLoginHandler , maybeAuthPair , maybeAuth , requireAuthId , requireAuthPair , requireAuth -- * Exception , AuthException (..) -- * Helper , MonadAuthHandler , AuthHandler -- * Internal , credsKey , provideJsonMessage , messageJson401 , asHtml ) where import Control.Monad (when) import Control.Monad.Trans.Maybe import UnliftIO (withRunInIO, MonadUnliftIO) import Yesod.Auth.Routes import Data.Aeson hiding (json) import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Data.Text (Text) import qualified Data.Text as T import qualified Data.HashMap.Lazy as Map import Data.Monoid (Endo) import Network.HTTP.Client (Manager, Request, withResponse, Response, BodyReader) import Network.HTTP.Client.TLS (getGlobalManager) import qualified Network.Wai as W import Yesod.Core import Yesod.Persist import Yesod.Auth.Message (AuthMessage, defaultMessage) import qualified Yesod.Auth.Message as Msg import Yesod.Form (FormMessage) import Data.Typeable (Typeable) import Control.Exception (Exception) import Network.HTTP.Types (Status, internalServerError500, unauthorized401) import qualified Control.Monad.Trans.Writer as Writer import Control.Monad (void) type AuthRoute = Route Auth type MonadAuthHandler master m = (MonadHandler m, YesodAuth master, master ~ HandlerSite m, Auth ~ SubHandlerSite m, MonadUnliftIO m) type AuthHandler master a = forall m. MonadAuthHandler master m => m a type Method = Text type Piece = Text -- | The result of an authentication based on credentials -- -- @since 1.4.4 data AuthenticationResult master = Authenticated (AuthId master) -- ^ Authenticated successfully | UserError AuthMessage -- ^ Invalid credentials provided by user | ServerError Text -- ^ Some other error data AuthPlugin master = AuthPlugin { apName :: Text , apDispatch :: Method -> [Piece] -> AuthHandler master TypedContent , apLogin :: (Route Auth -> Route master) -> WidgetFor master () } getAuth :: a -> Auth getAuth = const Auth -- | User credentials data Creds master = Creds { credsPlugin :: Text -- ^ How the user was authenticated , credsIdent :: Text -- ^ Identifier. Exact meaning depends on plugin. , credsExtra :: [(Text, Text)] } deriving (Show) class (Yesod master, PathPiece (AuthId master), RenderMessage master FormMessage) => YesodAuth master where type AuthId master -- | specify the layout. Uses defaultLayout by default authLayout :: (MonadHandler m, HandlerSite m ~ master) => WidgetFor master () -> m Html authLayout = liftHandler . defaultLayout -- | Default destination on successful login, if no other -- destination exists. loginDest :: master -> Route master -- | Default destination on successful logout, if no other -- destination exists. logoutDest :: master -> Route master -- | Perform authentication based on the given credentials. -- -- Default implementation is in terms of @'getAuthId'@ -- -- @since: 1.4.4 authenticate :: (MonadHandler m, HandlerSite m ~ master) => Creds master -> m (AuthenticationResult master) authenticate creds = do muid <- getAuthId creds return $ maybe (UserError Msg.InvalidLogin) Authenticated muid -- | Determine the ID associated with the set of credentials. -- -- Default implementation is in terms of @'authenticate'@ -- getAuthId :: (MonadHandler m, HandlerSite m ~ master) => Creds master -> m (Maybe (AuthId master)) getAuthId creds = do auth <- authenticate creds return $ case auth of Authenticated auid -> Just auid _ -> Nothing -- | Which authentication backends to use. authPlugins :: master -> [AuthPlugin master] -- | What to show on the login page. -- -- By default this calls 'defaultLoginHandler', which concatenates -- plugin widgets and wraps the result in 'authLayout'. Override if -- you need fancy widget containers, additional functionality, or an -- entirely custom page. For example, in some applications you may -- want to prevent the login page being displayed for a user who is -- already logged in, even if the URL is visited explicitly; this can -- be done by overriding 'loginHandler' in your instance declaration -- with something like: -- -- > instance YesodAuth App where -- > ... -- > loginHandler = do -- > ma <- lift maybeAuthId -- > when (isJust ma) $ -- > lift $ redirect HomeR -- or any other Handler code you want -- > defaultLoginHandler -- loginHandler :: AuthHandler master Html loginHandler = defaultLoginHandler -- | Used for i18n of messages provided by this package. renderAuthMessage :: master -> [Text] -- ^ languages -> AuthMessage -> Text renderAuthMessage _ _ = defaultMessage -- | After login and logout, redirect to the referring page, instead of -- 'loginDest' and 'logoutDest'. Default is 'False'. redirectToReferer :: master -> Bool redirectToReferer _ = False -- | When being redirected to the login page should the current page -- be set to redirect back to. Default is 'True'. -- -- @since 1.4.21 redirectToCurrent :: master -> Bool redirectToCurrent _ = True -- | Return an HTTP connection manager that is stored in the foundation -- type. This allows backends to reuse persistent connections. If none of -- the backends you're using use HTTP connections, you can safely return -- @error \"authHttpManager\"@ here. authHttpManager :: (MonadHandler m, HandlerSite m ~ master) => m Manager authHttpManager = liftIO getGlobalManager -- | Called on a successful login. By default, calls -- @addMessageI "success" NowLoggedIn@. onLogin :: (MonadHandler m, master ~ HandlerSite m) => m () onLogin = addMessageI "success" Msg.NowLoggedIn -- | Called on logout. By default, does nothing onLogout :: (MonadHandler m, master ~ HandlerSite m) => m () onLogout = return () -- | Retrieves user credentials, if user is authenticated. -- -- By default, this calls 'defaultMaybeAuthId' to get the user ID from the -- session. This can be overridden to allow authentication via other means, -- such as checking for a special token in a request header. This is -- especially useful for creating an API to be accessed via some means -- other than a browser. -- -- @since 1.2.0 maybeAuthId :: (MonadHandler m, master ~ HandlerSite m) => m (Maybe (AuthId master)) default maybeAuthId :: (MonadHandler m, master ~ HandlerSite m, YesodAuthPersist master, Typeable (AuthEntity master)) => m (Maybe (AuthId master)) maybeAuthId = defaultMaybeAuthId -- | Called on login error for HTTP requests. By default, calls -- @addMessage@ with "error" as status and redirects to @dest@. onErrorHtml :: (MonadHandler m, HandlerSite m ~ master) => Route master -> Text -> m Html onErrorHtml dest msg = do addMessage "error" $ toHtml msg fmap asHtml $ redirect dest -- | runHttpRequest gives you a chance to handle an HttpException and retry -- The default behavior is to simply execute the request which will throw an exception on failure -- -- The HTTP 'Request' is given in case it is useful to change behavior based on inspecting the request. -- This is an experimental API that is not broadly used throughout the yesod-auth code base runHttpRequest :: (MonadHandler m, HandlerSite m ~ master, MonadUnliftIO m) => Request -> (Response BodyReader -> m a) -> m a runHttpRequest req inner = do man <- authHttpManager withRunInIO $ \run -> withResponse req man $ run . inner {-# MINIMAL loginDest, logoutDest, (authenticate | getAuthId), authPlugins #-} {-# DEPRECATED getAuthId "Define 'authenticate' instead; 'getAuthId' will be removed in the next major version" #-} -- | Internal session key used to hold the authentication information. -- -- @since 1.2.3 credsKey :: Text credsKey = "_ID" -- | Retrieves user credentials from the session, if user is authenticated. -- -- This function does /not/ confirm that the credentials are valid, see -- 'maybeAuthIdRaw' for more information. The first call in a request -- does a database request to make sure that the account is still in the database. -- -- @since 1.1.2 defaultMaybeAuthId :: (MonadHandler m, HandlerSite m ~ master, YesodAuthPersist master, Typeable (AuthEntity master)) => m (Maybe (AuthId master)) defaultMaybeAuthId = runMaybeT $ do s <- MaybeT $ lookupSession credsKey aid <- MaybeT $ return $ fromPathPiece s _ <- MaybeT $ cachedAuth aid return aid cachedAuth :: ( MonadHandler m , YesodAuthPersist master , Typeable (AuthEntity master) , HandlerSite m ~ master ) => AuthId master -> m (Maybe (AuthEntity master)) cachedAuth = fmap unCachedMaybeAuth . cached . fmap CachedMaybeAuth . getAuthEntity -- | Default handler to show the login page. -- -- This is the default 'loginHandler'. It concatenates plugin widgets and -- wraps the result in 'authLayout'. See 'loginHandler' for more details. -- -- @since 1.4.9 defaultLoginHandler :: AuthHandler master Html defaultLoginHandler = do tp <- getRouteToParent authLayout $ do setTitleI Msg.LoginTitle master <- getYesod mapM_ (flip apLogin tp) (authPlugins master) loginErrorMessageI :: Route Auth -> AuthMessage -> AuthHandler master TypedContent loginErrorMessageI dest msg = do toParent <- getRouteToParent loginErrorMessageMasterI (toParent dest) msg loginErrorMessageMasterI :: (MonadHandler m, HandlerSite m ~ master, YesodAuth master) => Route master -> AuthMessage -> m TypedContent loginErrorMessageMasterI dest msg = do mr <- getMessageRender loginErrorMessage dest (mr msg) -- | For HTML, set the message and redirect to the route. -- For JSON, send the message and a 401 status loginErrorMessage :: (MonadHandler m, YesodAuth (HandlerSite m)) => Route (HandlerSite m) -> Text -> m TypedContent loginErrorMessage dest msg = messageJson401 msg (onErrorHtml dest msg) messageJson401 :: MonadHandler m => Text -> m Html -> m TypedContent messageJson401 = messageJsonStatus unauthorized401 messageJson500 :: MonadHandler m => Text -> m Html -> m TypedContent messageJson500 = messageJsonStatus internalServerError500 messageJsonStatus :: MonadHandler m => Status -> Text -> m Html -> m TypedContent messageJsonStatus status msg html = selectRep $ do provideRep html provideRep $ do let obj = object ["message" .= msg] void $ sendResponseStatus status obj return obj provideJsonMessage :: Monad m => Text -> Writer.Writer (Endo [ProvidedRep m]) () provideJsonMessage msg = provideRep $ return $ object ["message" .= msg] setCredsRedirect :: (MonadHandler m, YesodAuth (HandlerSite m)) => Creds (HandlerSite m) -- ^ new credentials -> m TypedContent setCredsRedirect creds = do y <- getYesod auth <- authenticate creds case auth of Authenticated aid -> do setSession credsKey $ toPathPiece aid onLogin res <- selectRep $ do provideRepType typeHtml $ fmap asHtml $ redirectUltDest $ loginDest y provideJsonMessage "Login Successful" sendResponse res UserError msg -> case authRoute y of Nothing -> do msg' <- renderMessage' msg messageJson401 msg' $ authLayout $ -- TODO toWidget [whamlet|<h1>_{msg}|] Just ar -> loginErrorMessageMasterI ar msg ServerError msg -> do $(logError) msg case authRoute y of Nothing -> do msg' <- renderMessage' Msg.AuthError messageJson500 msg' $ authLayout $ toWidget [whamlet|<h1>_{Msg.AuthError}|] Just ar -> loginErrorMessageMasterI ar Msg.AuthError where renderMessage' msg = do langs <- languages master <- getYesod return $ renderAuthMessage master langs msg -- | Sets user credentials for the session after checking them with authentication backends. setCreds :: (MonadHandler m, YesodAuth (HandlerSite m)) => Bool -- ^ if HTTP redirects should be done -> Creds (HandlerSite m) -- ^ new credentials -> m () setCreds doRedirects creds = if doRedirects then void $ setCredsRedirect creds else do auth <- authenticate creds case auth of Authenticated aid -> setSession credsKey $ toPathPiece aid _ -> return () -- | same as defaultLayoutJson, but uses authLayout authLayoutJson :: (ToJSON j, MonadAuthHandler master m) => WidgetFor master () -- ^ HTML -> m j -- ^ JSON -> m TypedContent authLayoutJson w json = selectRep $ do provideRep $ authLayout w provideRep $ fmap toJSON json -- | Clears current user credentials for the session. -- -- @since 1.1.7 clearCreds :: (MonadHandler m, YesodAuth (HandlerSite m)) => Bool -- ^ if HTTP redirect to 'logoutDest' should be done -> m () clearCreds doRedirects = do y <- getYesod onLogout deleteSession credsKey when doRedirects $ do redirectUltDest $ logoutDest y getCheckR :: AuthHandler master TypedContent getCheckR = do creds <- maybeAuthId authLayoutJson (do setTitle "Authentication Status" toWidget $ html' creds) (return $ jsonCreds creds) where html' creds = [shamlet| $newline never <h1>Authentication Status $maybe _ <- creds <p>Logged in. $nothing <p>Not logged in. |] jsonCreds creds = Object $ Map.fromList [ (T.pack "logged_in", Bool $ maybe False (const True) creds) ] setUltDestReferer' :: (MonadHandler m, YesodAuth (HandlerSite m)) => m () setUltDestReferer' = do master <- getYesod when (redirectToReferer master) setUltDestReferer getLoginR :: AuthHandler master Html getLoginR = setUltDestReferer' >> loginHandler getLogoutR :: AuthHandler master () getLogoutR = do tp <- getRouteToParent setUltDestReferer' >> redirectToPost (tp LogoutR) postLogoutR :: AuthHandler master () postLogoutR = clearCreds True handlePluginR :: Text -> [Text] -> AuthHandler master TypedContent handlePluginR plugin pieces = do master <- getYesod env <- waiRequest let method = decodeUtf8With lenientDecode $ W.requestMethod env case filter (\x -> apName x == plugin) (authPlugins master) of [] -> notFound ap:_ -> apDispatch ap method pieces -- | Similar to 'maybeAuthId', but additionally look up the value associated -- with the user\'s database identifier to get the value in the database. This -- assumes that you are using a Persistent database. -- -- @since 1.1.0 maybeAuth :: ( YesodAuthPersist master , val ~ AuthEntity master , Key val ~ AuthId master , PersistEntity val , Typeable val , MonadHandler m , HandlerSite m ~ master ) => m (Maybe (Entity val)) maybeAuth = fmap (fmap (uncurry Entity)) maybeAuthPair -- | Similar to 'maybeAuth', but doesn’t assume that you are using a -- Persistent database. -- -- @since 1.4.0 maybeAuthPair :: ( YesodAuthPersist master , Typeable (AuthEntity master) , MonadHandler m , HandlerSite m ~ master ) => m (Maybe (AuthId master, AuthEntity master)) maybeAuthPair = runMaybeT $ do aid <- MaybeT maybeAuthId ae <- MaybeT $ cachedAuth aid return (aid, ae) newtype CachedMaybeAuth val = CachedMaybeAuth { unCachedMaybeAuth :: Maybe val } deriving Typeable -- | Class which states that the given site is an instance of @YesodAuth@ -- and that its @AuthId@ is a lookup key for the full user information in -- a @YesodPersist@ database. -- -- The default implementation of @getAuthEntity@ assumes that the @AuthId@ -- for the @YesodAuth@ superclass is in fact a persistent @Key@ for the -- given value. This is the common case in Yesod, and means that you can -- easily look up the full information on a given user. -- -- @since 1.4.0 class (YesodAuth master, YesodPersist master) => YesodAuthPersist master where -- | If the @AuthId@ for a given site is a persistent ID, this will give the -- value for that entity. E.g.: -- -- > type AuthId MySite = UserId -- > AuthEntity MySite ~ User -- -- @since 1.2.0 type AuthEntity master :: * type AuthEntity master = KeyEntity (AuthId master) getAuthEntity :: (MonadHandler m, HandlerSite m ~ master) => AuthId master -> m (Maybe (AuthEntity master)) default getAuthEntity :: ( YesodPersistBackend master ~ backend , PersistRecordBackend (AuthEntity master) backend , Key (AuthEntity master) ~ AuthId master , PersistStore backend , MonadHandler m , HandlerSite m ~ master ) => AuthId master -> m (Maybe (AuthEntity master)) getAuthEntity = liftHandler . runDB . get type family KeyEntity key type instance KeyEntity (Key x) = x -- | Similar to 'maybeAuthId', but redirects to a login page if user is not -- authenticated or responds with error 401 if this is an API client (expecting JSON). -- -- @since 1.1.0 requireAuthId :: (MonadHandler m, YesodAuth (HandlerSite m)) => m (AuthId (HandlerSite m)) requireAuthId = maybeAuthId >>= maybe handleAuthLack return -- | Similar to 'maybeAuth', but redirects to a login page if user is not -- authenticated or responds with error 401 if this is an API client (expecting JSON). -- -- @since 1.1.0 requireAuth :: ( YesodAuthPersist master , val ~ AuthEntity master , Key val ~ AuthId master , PersistEntity val , Typeable val , MonadHandler m , HandlerSite m ~ master ) => m (Entity val) requireAuth = maybeAuth >>= maybe handleAuthLack return -- | Similar to 'requireAuth', but not tied to Persistent's 'Entity' type. -- Instead, the 'AuthId' and 'AuthEntity' are returned in a tuple. -- -- @since 1.4.0 requireAuthPair :: ( YesodAuthPersist master , Typeable (AuthEntity master) , MonadHandler m , HandlerSite m ~ master ) => m (AuthId master, AuthEntity master) requireAuthPair = maybeAuthPair >>= maybe handleAuthLack return handleAuthLack :: (YesodAuth (HandlerSite m), MonadHandler m) => m a handleAuthLack = do aj <- acceptsJson if aj then notAuthenticated else redirectLogin redirectLogin :: (YesodAuth (HandlerSite m), MonadHandler m) => m a redirectLogin = do y <- getYesod when (redirectToCurrent y) setUltDestCurrent case authRoute y of Just z -> redirect z Nothing -> permissionDenied "Please configure authRoute" instance YesodAuth master => RenderMessage master AuthMessage where renderMessage = renderAuthMessage data AuthException = InvalidFacebookResponse deriving (Show, Typeable) instance Exception AuthException instance YesodAuth master => YesodSubDispatch Auth master where yesodSubDispatch = $(mkYesodSubDispatch resourcesAuth) asHtml :: Html -> Html asHtml = id
s9gf4ult/yesod
yesod-auth/Yesod/Auth.hs
mit
20,698
0
19
5,155
4,168
2,188
1,980
381
5
----------------------------------------------------------------------- -- -- Haskell: The Craft of Functional Programming -- Simon Thompson -- (c) Addison-Wesley, 1996-2011. -- -- Chapter 18 -- ----------------------------------------------------------------------- module Chapter18 where import Prelude hiding (lookup) import System.IO import Control.Monad.Identity import Chapter8 (getInt) import Data.Time import System.Locale import System.IO.Unsafe (unsafePerformIO) -- Programming with monads -- ^^^^^^^^^^^^^^^^^^^^^^^ -- The basics of input/output -- ^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Reading input is done by getLine and getChar: see Prelude for details. -- getLine :: IO String -- getChar :: IO Char -- Text strings are written using -- -- putStr :: String -> IO () -- putStrLn :: String -> IO () -- A hello, world program helloWorld :: IO () helloWorld = putStr "Hello, World!" -- Simple examples readWrite :: IO () readWrite = do getLine putStrLn "one line read" readEcho :: IO () readEcho = do line <-getLine putStrLn ("line read: " ++ line) -- Adding a sequence of integers from the input sumInts :: Integer -> IO Integer sumInts s = do n <- getInt if n==0 then return s else sumInts (s+n) -- Adding a list of integers, using an accumulator sumAcc :: Integer -> [Integer] -> Integer sumAcc s [] = s sumAcc s (n:ns) = if n==0 then s else sumAcc (s+n) ns -- Addiing a sequence of integers, courteously. sumInteract :: IO () sumInteract = do putStrLn "Enter integers one per line" putStrLn "These will be summed until zero is entered" sum <- sumInts 0 putStr "The sum is " print sum -- Further I/O -- ^^^^^^^^^^^ -- Interaction at the terminal copyInteract :: IO () copyInteract = do hSetBuffering stdin LineBuffering copyEOF hSetBuffering stdin NoBuffering copyEOF :: IO () copyEOF = do eof <- isEOF if eof then return () else do line <- getLine putStrLn line copyEOF -- Input and output as lazy lists -- Reverse all the lines in the input. listIOprog :: String -> String listIOprog = unlines . map reverse . lines -- Generating random numbers randomInt :: Integer -> IO Integer randomInt n = do time <- getCurrentTime return ( (`rem` n) $ read $ take 6 $ formatTime defaultTimeLocale "%q" time) randInt :: Integer -> Integer randInt = unsafePerformIO . randomInt -- The calculator -- ^^^^^^^^^^^^^^ -- This is available separately in the Calculator directory. -- The do notation revisited -- ^^^^^^^^^^^^^^^^^^^^^^^^^ addOneInt :: IO () addOneInt = do line <- getLine putStrLn (show (1 + read line :: Int)) addOneInt' = getLine >>= \line -> putStrLn (show (1 + read line :: Int)) -- Monads for Functional Programming -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- The definition of the Monad class -- class Monad m where -- (>>=) :: m a -> (a -> m b) -> m b -- return :: a -> m a -- fail :: String -> m a -- Kelisli composition for monadic functions. -- (>@>) :: Monad m => (a -> m b) -> -- (b -> m c) -> -- (a -> m c) -- f >@> g = \ x -> (f x) >>= g -- Some examples of monads -- ^^^^^^^^^^^^^^^^^^^^^^^ -- Some examples from the standard prelude. -- The list monad -- instance Monad [] where -- xs >>= f = concat (map f xs) -- return x = [x] -- zero = [] -- The Maybe monad -- instance Monad Maybe where -- (Just x) >>= k = k x -- Nothing >>= k = Nothing -- return = Just -- The parsing monad -- data SParse a b = SParse (Parse a b) -- instance Monad (SParse a) where -- return x = SParse (succeed x) -- zero = SParse fail -- (SParse pr) >>= f -- = SParse (\s -> concat [ sparse (f x) rest | (x,rest) <- pr st ]) -- sparse :: SParse a b -> Parse a b -- sparse (SParse pr) = pr -- A state monad (the state need not be a table; this example is designed -- to support the example discussed below.) type Table a = [a] data State a b = State (Table a -> (Table a , b)) instance Monad (State a) where return x = State (\tab -> (tab,x)) (State st) >>= f = State (\tab -> let (newTab,y) = st tab (State trans) = f y in trans newTab) -- Example: Monadic computation over trees -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- A type of binary trees. data Tree a = Nil | Node a (Tree a) (Tree a) deriving (Eq,Ord,Show) -- Summing a tree of integers -- A direct solution: sTree :: Tree Integer -> Integer sTree Nil = 0 sTree (Node n t1 t2) = n + sTree t1 + sTree t2 -- A monadic solution: first giving a value of type Identity Int ... sumTree :: Tree Integer -> Identity Integer sumTree Nil = return 0 sumTree (Node n t1 t2) = do num <- return n s1 <- sumTree t1 s2 <- sumTree t2 return (num + s1 + s2) -- ... then adapted to give an Int solution sTree' :: Tree Integer -> Integer sTree' = identity . sumTree identity :: Identity a -> a identity (Identity x) = x -- Using a state monad in a tree calculation -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- The top level function ... numTree :: Eq a => Tree a -> Tree Integer -- ... and the function which does all the work: numberTree :: Eq a => Tree a -> State a (Tree Integer) -- Its structure mirrors exactly the structure of the earlier program to -- sum the tree. numberTree Nil = return Nil numberTree (Node x t1 t2) = do num <- numberNode x nt1 <- numberTree t1 nt2 <- numberTree t2 return (Node num nt1 nt2) -- The work of the algorithm is done node by node, hence the function numberNode :: Eq a => a -> State a Integer numberNode x = State (nNode x) -- -- Looking up a value in the table; will side-effect the table if the value -- is not present. nNode :: Eq a => a -> (Table a -> (Table a , Integer)) nNode x table | elem x table = (table , lookup x table) | otherwise = (table++[x] , integerLength table) where integerLength = toInteger.length -- Looking up a value in the table when known to be present lookup :: Eq a => a -> Table a -> Integer lookup x tab = locate 0 tab where locate n (y:ys) = if x==y then n else locate (n+1) ys -- Extracting a value froma state monad. runST :: State a b -> b runST (State st) = snd (st []) -- The top-level function defined eventually. numTree = runST . numberTree -- Example tree egTree :: Tree String egTree = Node "Moon" (Node "Ahmet" Nil Nil) (Node "Dweezil" (Node "Ahmet" Nil Nil) (Node "Moon" Nil Nil))
c089/haskell-craft3e
Chapter18.hs
mit
6,948
0
14
1,983
1,509
797
712
124
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} module CO4.Example.QueensSelfContained where import Prelude (Int,Show (..),(-),(>>=),IO,($)) import qualified Data.Maybe as M import Language.Haskell.TH (runIO) import qualified Satchmo.Core.SAT.Minisat import qualified Satchmo.Core.Decode import CO4 $( [d| data Bool = False | True deriving Show data Nat = Z | S Nat deriving Show data List a = Nil | Cons a (List a) deriving Show type Board = List Nat constraint :: Board -> Bool constraint board = let n = length board in and2 (all (\q -> less q n) board) (allSafe board) allSafe :: Board -> Bool allSafe board = case board of Nil -> True Cons q qs -> and2 (safe q qs (S Z)) (allSafe qs) safe :: Nat -> Board -> Nat -> Bool safe q board delta = case board of Nil -> True Cons x xs -> and2 (noAttack q x delta) (safe q xs (S delta)) noAttack :: Nat -> Nat -> Nat -> Bool noAttack x y delta = and2 (noStraightAttack x y) (noDiagonalAttack x y delta) noStraightAttack :: Nat -> Nat -> Bool noStraightAttack x y = not (equal x y) noDiagonalAttack :: Nat -> Nat -> Nat -> Bool noDiagonalAttack x y delta = and2 (not (equal x (add y delta))) (not (equal y (add x delta))) length :: List a -> Nat length xs = case xs of Nil -> Z Cons _ ys -> S (length ys) all :: (a -> Bool) -> List a -> Bool all f xs = case xs of Nil -> True Cons y ys -> and2 (f y) (all f ys) add :: Nat -> Nat -> Nat add x y = case x of Z -> y S x' -> S (add x' y) equal :: Nat -> Nat -> Bool equal x y = case x of Z -> case y of Z -> True _ -> False S x' -> case y of S y' -> equal x' y' _ -> False less :: Nat -> Nat -> Bool less x y = case x of Z -> case y of Z -> False _ -> True S x' -> case y of S y' -> less x' y' _ -> False not :: Bool -> Bool not x = case x of False -> True True -> False and2 :: Bool -> Bool -> Bool and2 x y = case x of False -> False True -> y |] >>= compile [Cache] ) natAllocator 0 = knownZ natAllocator i = union knownZ $ knownS $ natAllocator $ i-1 listAllocator 0 _ = knownNil listAllocator i a = knownCons a (listAllocator (i-1) a) result :: Int -> IO (M.Maybe Board) result i = solveAndTest (listAllocator i (natAllocator i)) encConstraint constraint
apunktbau/co4
test/CO4/Example/QueensSelfContained.hs
gpl-3.0
3,083
0
9
1,306
226
132
94
79
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.ElasticBeanstalk.TerminateEnvironment -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Terminates the specified environment. -- -- /See:/ <http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_TerminateEnvironment.html AWS API Reference> for TerminateEnvironment. module Network.AWS.ElasticBeanstalk.TerminateEnvironment ( -- * Creating a Request terminateEnvironment , TerminateEnvironment -- * Request Lenses , teTerminateResources , teEnvironmentName , teEnvironmentId -- * Destructuring the Response , environmentDescription , EnvironmentDescription -- * Response Lenses , eStatus , eCNAME , eTemplateName , eAbortableOperationInProgress , eEndpointURL , eResources , eDateUpdated , eDateCreated , eHealth , eVersionLabel , eTier , eEnvironmentName , eApplicationName , eSolutionStackName , eEnvironmentId , eHealthStatus , eDescription ) where import Network.AWS.ElasticBeanstalk.Types import Network.AWS.ElasticBeanstalk.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | This documentation target is not reported in the API reference. -- -- /See:/ 'terminateEnvironment' smart constructor. data TerminateEnvironment = TerminateEnvironment' { _teTerminateResources :: !(Maybe Bool) , _teEnvironmentName :: !(Maybe Text) , _teEnvironmentId :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'TerminateEnvironment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'teTerminateResources' -- -- * 'teEnvironmentName' -- -- * 'teEnvironmentId' terminateEnvironment :: TerminateEnvironment terminateEnvironment = TerminateEnvironment' { _teTerminateResources = Nothing , _teEnvironmentName = Nothing , _teEnvironmentId = Nothing } -- | Indicates whether the associated AWS resources should shut down when the -- environment is terminated: -- -- 'true': (default) The user AWS resources (for example, the Auto Scaling -- group, LoadBalancer, etc.) are terminated along with the environment. -- -- 'false': The environment is removed from the AWS Elastic Beanstalk but -- the AWS resources continue to operate. -- -- - 'true': The specified environment as well as the associated AWS -- resources, such as Auto Scaling group and LoadBalancer, are -- terminated. -- - 'false': AWS Elastic Beanstalk resource management is removed from -- the environment, but the AWS resources continue to operate. -- -- For more information, see the -- <http://docs.aws.amazon.com/elasticbeanstalk/latest/ug/ AWS Elastic Beanstalk User Guide.> -- -- Default: 'true' -- -- Valid Values: 'true' | 'false' teTerminateResources :: Lens' TerminateEnvironment (Maybe Bool) teTerminateResources = lens _teTerminateResources (\ s a -> s{_teTerminateResources = a}); -- | The name of the environment to terminate. -- -- Condition: You must specify either this or an EnvironmentId, or both. If -- you do not specify either, AWS Elastic Beanstalk returns -- 'MissingRequiredParameter' error. teEnvironmentName :: Lens' TerminateEnvironment (Maybe Text) teEnvironmentName = lens _teEnvironmentName (\ s a -> s{_teEnvironmentName = a}); -- | The ID of the environment to terminate. -- -- Condition: You must specify either this or an EnvironmentName, or both. -- If you do not specify either, AWS Elastic Beanstalk returns -- 'MissingRequiredParameter' error. teEnvironmentId :: Lens' TerminateEnvironment (Maybe Text) teEnvironmentId = lens _teEnvironmentId (\ s a -> s{_teEnvironmentId = a}); instance AWSRequest TerminateEnvironment where type Rs TerminateEnvironment = EnvironmentDescription request = postQuery elasticBeanstalk response = receiveXMLWrapper "TerminateEnvironmentResult" (\ s h x -> parseXML x) instance ToHeaders TerminateEnvironment where toHeaders = const mempty instance ToPath TerminateEnvironment where toPath = const "/" instance ToQuery TerminateEnvironment where toQuery TerminateEnvironment'{..} = mconcat ["Action" =: ("TerminateEnvironment" :: ByteString), "Version" =: ("2010-12-01" :: ByteString), "TerminateResources" =: _teTerminateResources, "EnvironmentName" =: _teEnvironmentName, "EnvironmentId" =: _teEnvironmentId]
olorin/amazonka
amazonka-elasticbeanstalk/gen/Network/AWS/ElasticBeanstalk/TerminateEnvironment.hs
mpl-2.0
5,208
0
11
1,033
576
361
215
81
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.OpsWorks.UpdateLayer -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates a specified layer. -- -- __Required Permissions__: To use this action, an IAM user must have a -- Manage permissions level for the stack, or an attached policy that -- explicitly grants permissions. For more information on user permissions, -- see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_UpdateLayer.html AWS API Reference> for UpdateLayer. module Network.AWS.OpsWorks.UpdateLayer ( -- * Creating a Request updateLayer , UpdateLayer -- * Request Lenses , ulCustomInstanceProfileARN , ulCustomSecurityGroupIds , ulInstallUpdatesOnBoot , ulLifecycleEventConfiguration , ulShortname , ulCustomRecipes , ulCustomJSON , ulVolumeConfigurations , ulEnableAutoHealing , ulPackages , ulAttributes , ulName , ulAutoAssignPublicIPs , ulUseEBSOptimizedInstances , ulAutoAssignElasticIPs , ulLayerId -- * Destructuring the Response , updateLayerResponse , UpdateLayerResponse ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'updateLayer' smart constructor. data UpdateLayer = UpdateLayer' { _ulCustomInstanceProfileARN :: !(Maybe Text) , _ulCustomSecurityGroupIds :: !(Maybe [Text]) , _ulInstallUpdatesOnBoot :: !(Maybe Bool) , _ulLifecycleEventConfiguration :: !(Maybe LifecycleEventConfiguration) , _ulShortname :: !(Maybe Text) , _ulCustomRecipes :: !(Maybe Recipes) , _ulCustomJSON :: !(Maybe Text) , _ulVolumeConfigurations :: !(Maybe [VolumeConfiguration]) , _ulEnableAutoHealing :: !(Maybe Bool) , _ulPackages :: !(Maybe [Text]) , _ulAttributes :: !(Maybe (Map LayerAttributesKeys Text)) , _ulName :: !(Maybe Text) , _ulAutoAssignPublicIPs :: !(Maybe Bool) , _ulUseEBSOptimizedInstances :: !(Maybe Bool) , _ulAutoAssignElasticIPs :: !(Maybe Bool) , _ulLayerId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateLayer' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ulCustomInstanceProfileARN' -- -- * 'ulCustomSecurityGroupIds' -- -- * 'ulInstallUpdatesOnBoot' -- -- * 'ulLifecycleEventConfiguration' -- -- * 'ulShortname' -- -- * 'ulCustomRecipes' -- -- * 'ulCustomJSON' -- -- * 'ulVolumeConfigurations' -- -- * 'ulEnableAutoHealing' -- -- * 'ulPackages' -- -- * 'ulAttributes' -- -- * 'ulName' -- -- * 'ulAutoAssignPublicIPs' -- -- * 'ulUseEBSOptimizedInstances' -- -- * 'ulAutoAssignElasticIPs' -- -- * 'ulLayerId' updateLayer :: Text -- ^ 'ulLayerId' -> UpdateLayer updateLayer pLayerId_ = UpdateLayer' { _ulCustomInstanceProfileARN = Nothing , _ulCustomSecurityGroupIds = Nothing , _ulInstallUpdatesOnBoot = Nothing , _ulLifecycleEventConfiguration = Nothing , _ulShortname = Nothing , _ulCustomRecipes = Nothing , _ulCustomJSON = Nothing , _ulVolumeConfigurations = Nothing , _ulEnableAutoHealing = Nothing , _ulPackages = Nothing , _ulAttributes = Nothing , _ulName = Nothing , _ulAutoAssignPublicIPs = Nothing , _ulUseEBSOptimizedInstances = Nothing , _ulAutoAssignElasticIPs = Nothing , _ulLayerId = pLayerId_ } -- | The ARN of an IAM profile to be used for all of the layer\'s EC2 -- instances. For more information about IAM ARNs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html Using Identifiers>. ulCustomInstanceProfileARN :: Lens' UpdateLayer (Maybe Text) ulCustomInstanceProfileARN = lens _ulCustomInstanceProfileARN (\ s a -> s{_ulCustomInstanceProfileARN = a}); -- | An array containing the layer\'s custom security group IDs. ulCustomSecurityGroupIds :: Lens' UpdateLayer [Text] ulCustomSecurityGroupIds = lens _ulCustomSecurityGroupIds (\ s a -> s{_ulCustomSecurityGroupIds = a}) . _Default . _Coerce; -- | Whether to install operating system and package updates when the -- instance boots. The default value is 'true'. To control when updates are -- installed, set this value to 'false'. You must then update your -- instances manually by using CreateDeployment to run the -- 'update_dependencies' stack command or manually running 'yum' (Amazon -- Linux) or 'apt-get' (Ubuntu) on the instances. -- -- We strongly recommend using the default value of 'true', to ensure that -- your instances have the latest security updates. ulInstallUpdatesOnBoot :: Lens' UpdateLayer (Maybe Bool) ulInstallUpdatesOnBoot = lens _ulInstallUpdatesOnBoot (\ s a -> s{_ulInstallUpdatesOnBoot = a}); -- | ulLifecycleEventConfiguration :: Lens' UpdateLayer (Maybe LifecycleEventConfiguration) ulLifecycleEventConfiguration = lens _ulLifecycleEventConfiguration (\ s a -> s{_ulLifecycleEventConfiguration = a}); -- | For custom layers only, use this parameter to specify the layer\'s short -- name, which is used internally by AWS OpsWorksand by Chef. The short -- name is also used as the name for the directory where your app files are -- installed. It can have a maximum of 200 characters and must be in the -- following format: \/\\A[a-z0-9\\-\\_\\.]+\\Z\/. -- -- The built-in layers\' short names are defined by AWS OpsWorks. For more -- information, see the -- <http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html Layer Reference> ulShortname :: Lens' UpdateLayer (Maybe Text) ulShortname = lens _ulShortname (\ s a -> s{_ulShortname = a}); -- | A 'LayerCustomRecipes' object that specifies the layer\'s custom -- recipes. ulCustomRecipes :: Lens' UpdateLayer (Maybe Recipes) ulCustomRecipes = lens _ulCustomRecipes (\ s a -> s{_ulCustomRecipes = a}); -- | A JSON-formatted string containing custom stack configuration and -- deployment attributes to be installed on the layer\'s instances. For -- more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-json-override.html Using Custom JSON>. ulCustomJSON :: Lens' UpdateLayer (Maybe Text) ulCustomJSON = lens _ulCustomJSON (\ s a -> s{_ulCustomJSON = a}); -- | A 'VolumeConfigurations' object that describes the layer\'s Amazon EBS -- volumes. ulVolumeConfigurations :: Lens' UpdateLayer [VolumeConfiguration] ulVolumeConfigurations = lens _ulVolumeConfigurations (\ s a -> s{_ulVolumeConfigurations = a}) . _Default . _Coerce; -- | Whether to disable auto healing for the layer. ulEnableAutoHealing :: Lens' UpdateLayer (Maybe Bool) ulEnableAutoHealing = lens _ulEnableAutoHealing (\ s a -> s{_ulEnableAutoHealing = a}); -- | An array of 'Package' objects that describe the layer\'s packages. ulPackages :: Lens' UpdateLayer [Text] ulPackages = lens _ulPackages (\ s a -> s{_ulPackages = a}) . _Default . _Coerce; -- | One or more user-defined key\/value pairs to be added to the stack -- attributes. ulAttributes :: Lens' UpdateLayer (HashMap LayerAttributesKeys Text) ulAttributes = lens _ulAttributes (\ s a -> s{_ulAttributes = a}) . _Default . _Map; -- | The layer name, which is used by the console. ulName :: Lens' UpdateLayer (Maybe Text) ulName = lens _ulName (\ s a -> s{_ulName = a}); -- | For stacks that are running in a VPC, whether to automatically assign a -- public IP address to the layer\'s instances. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-edit.html How to Edit a Layer>. ulAutoAssignPublicIPs :: Lens' UpdateLayer (Maybe Bool) ulAutoAssignPublicIPs = lens _ulAutoAssignPublicIPs (\ s a -> s{_ulAutoAssignPublicIPs = a}); -- | Whether to use Amazon EBS-optimized instances. ulUseEBSOptimizedInstances :: Lens' UpdateLayer (Maybe Bool) ulUseEBSOptimizedInstances = lens _ulUseEBSOptimizedInstances (\ s a -> s{_ulUseEBSOptimizedInstances = a}); -- | Whether to automatically assign an -- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html Elastic IP address> -- to the layer\'s instances. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-basics-edit.html How to Edit a Layer>. ulAutoAssignElasticIPs :: Lens' UpdateLayer (Maybe Bool) ulAutoAssignElasticIPs = lens _ulAutoAssignElasticIPs (\ s a -> s{_ulAutoAssignElasticIPs = a}); -- | The layer ID. ulLayerId :: Lens' UpdateLayer Text ulLayerId = lens _ulLayerId (\ s a -> s{_ulLayerId = a}); instance AWSRequest UpdateLayer where type Rs UpdateLayer = UpdateLayerResponse request = postJSON opsWorks response = receiveNull UpdateLayerResponse' instance ToHeaders UpdateLayer where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.UpdateLayer" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON UpdateLayer where toJSON UpdateLayer'{..} = object (catMaybes [("CustomInstanceProfileArn" .=) <$> _ulCustomInstanceProfileARN, ("CustomSecurityGroupIds" .=) <$> _ulCustomSecurityGroupIds, ("InstallUpdatesOnBoot" .=) <$> _ulInstallUpdatesOnBoot, ("LifecycleEventConfiguration" .=) <$> _ulLifecycleEventConfiguration, ("Shortname" .=) <$> _ulShortname, ("CustomRecipes" .=) <$> _ulCustomRecipes, ("CustomJson" .=) <$> _ulCustomJSON, ("VolumeConfigurations" .=) <$> _ulVolumeConfigurations, ("EnableAutoHealing" .=) <$> _ulEnableAutoHealing, ("Packages" .=) <$> _ulPackages, ("Attributes" .=) <$> _ulAttributes, ("Name" .=) <$> _ulName, ("AutoAssignPublicIps" .=) <$> _ulAutoAssignPublicIPs, ("UseEbsOptimizedInstances" .=) <$> _ulUseEBSOptimizedInstances, ("AutoAssignElasticIps" .=) <$> _ulAutoAssignElasticIPs, Just ("LayerId" .= _ulLayerId)]) instance ToPath UpdateLayer where toPath = const "/" instance ToQuery UpdateLayer where toQuery = const mempty -- | /See:/ 'updateLayerResponse' smart constructor. data UpdateLayerResponse = UpdateLayerResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateLayerResponse' with the minimum fields required to make a request. -- updateLayerResponse :: UpdateLayerResponse updateLayerResponse = UpdateLayerResponse'
fmapfmapfmap/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/UpdateLayer.hs
mpl-2.0
11,723
0
13
2,482
1,692
1,018
674
188
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} module Brick.Types.Common ( Location(..) , locL , origin , Edges(..) , eTopL, eBottomL, eRightL, eLeftL ) where import Brick.Types.TH (suffixLenses) import qualified Data.Semigroup as Sem import GHC.Generics import Control.DeepSeq import Lens.Micro (_1, _2) import Lens.Micro.Internal (Field1, Field2) -- | A terminal screen location. data Location = Location { loc :: (Int, Int) -- ^ (Column, Row) } deriving (Show, Eq, Ord, Read, Generic, NFData) suffixLenses ''Location instance Field1 Location Location Int Int where _1 = locL._1 instance Field2 Location Location Int Int where _2 = locL._2 -- | The origin (upper-left corner). origin :: Location origin = Location (0, 0) instance Sem.Semigroup Location where (Location (w1, h1)) <> (Location (w2, h2)) = Location (w1+w2, h1+h2) instance Monoid Location where mempty = origin mappend = (Sem.<>) data Edges a = Edges { eTop, eBottom, eLeft, eRight :: a } deriving (Eq, Ord, Read, Show, Functor, Generic, NFData) suffixLenses ''Edges instance Applicative Edges where pure a = Edges a a a a Edges ft fb fl fr <*> Edges vt vb vl vr = Edges (ft vt) (fb vb) (fl vl) (fr vr) instance Monad Edges where Edges vt vb vl vr >>= f = Edges (eTop (f vt)) (eBottom (f vb)) (eLeft (f vl)) (eRight (f vr))
sjakobi/brick
src/Brick/Types/Common.hs
bsd-3-clause
1,581
0
10
398
539
298
241
44
1
{-# LANGUAGE ScopedTypeVariables #-} module Ivory.Language.Float where import Ivory.Language.IBool import Ivory.Language.Proxy import Ivory.Language.Ref import Ivory.Language.Type import qualified Ivory.Language.Syntax as I -- | NaN testing. isnan :: forall a. (IvoryVar a, Floating a) => a -> IBool isnan a = wrapExpr (I.ExpOp (I.ExpIsNan ty) [unwrapExpr a]) where ty = ivoryType (Proxy :: Proxy a) -- | Infinite testing. isinf :: forall a. (IvoryVar a, Floating a) => a -> IBool isinf a = wrapExpr (I.ExpOp (I.ExpIsInf ty) [unwrapExpr a]) where ty = ivoryType (Proxy :: Proxy a) -- Floating Point -------------------------------------------------------------- newtype IFloat = IFloat { getIFloat :: I.Expr } ifloat :: Float -> IFloat ifloat = IFloat . I.ExpLit . I.LitFloat instance IvoryType IFloat where ivoryType _ = I.TyFloat instance IvoryVar IFloat where wrapVar = wrapVarExpr unwrapExpr = getIFloat instance IvoryExpr IFloat where wrapExpr = IFloat instance IvoryEq IFloat instance IvoryOrd IFloat instance IvoryStore IFloat instance Num IFloat where (*) = exprBinop (*) (+) = exprBinop (+) (-) = exprBinop (-) abs = exprUnary abs signum = exprUnary signum negate = exprUnary negate fromInteger = ifloat . fromInteger instance Fractional IFloat where (/) = exprBinop (/) recip = exprUnary recip fromRational = ifloat . fromRational instance Floating IFloat where pi = ifloat pi exp = exprUnary exp sqrt = exprUnary sqrt log = exprUnary log (**) = exprBinop (**) logBase = exprBinop (logBase) sin = exprUnary sin tan = exprUnary tan cos = exprUnary cos asin = exprUnary asin atan = exprUnary atan acos = exprUnary acos sinh = exprUnary sinh tanh = exprUnary tanh cosh = exprUnary cosh asinh = exprUnary asinh atanh = exprUnary atanh acosh = exprUnary acosh -- Double Precision ------------------------------------------------------------ newtype IDouble = IDouble { getIDouble :: I.Expr } idouble :: Double -> IDouble idouble = IDouble . I.ExpLit . I.LitDouble instance Fractional IDouble where (/) = exprBinop (/) recip = exprUnary recip fromRational = idouble . fromRational instance IvoryType IDouble where ivoryType _ = I.TyDouble instance IvoryVar IDouble where wrapVar = wrapVarExpr unwrapExpr = getIDouble instance IvoryExpr IDouble where wrapExpr = IDouble instance IvoryEq IDouble instance IvoryOrd IDouble instance IvoryStore IDouble instance Num IDouble where (*) = exprBinop (*) (+) = exprBinop (+) (-) = exprBinop (-) abs = exprUnary abs signum = exprUnary signum negate = exprUnary negate fromInteger = idouble . fromInteger instance Floating IDouble where pi = idouble pi exp = exprUnary exp sqrt = exprUnary sqrt log = exprUnary log (**) = exprBinop (**) logBase = exprBinop (logBase) sin = exprUnary sin tan = exprUnary tan cos = exprUnary cos asin = exprUnary asin atan = exprUnary atan acos = exprUnary acos sinh = exprUnary sinh tanh = exprUnary tanh cosh = exprUnary cosh asinh = exprUnary asinh atanh = exprUnary atanh acosh = exprUnary acosh -- Rounding -------------------------------------------------------------------- -- XXX do not export primRound :: IvoryExpr a => I.ExpOp -> a -> a primRound op a = wrapExpr (I.ExpOp op [unwrapExpr a]) class (Floating a, IvoryExpr a) => IvoryFloat a where -- | Round a floating point number. roundF :: a -> a roundF = primRound I.ExpRoundF -- | Take the ceiling of a floating point number. ceilF :: a -> a ceilF = primRound I.ExpCeilF -- | Take the floor of a floating point number. floorF :: a -> a floorF = primRound I.ExpFloorF -- | The arctangent function of two arguments. atan2F :: a -> a -> a atan2F y x = wrapExpr (I.ExpOp I.ExpFAtan2 [unwrapExpr y, unwrapExpr x]) instance IvoryFloat IFloat instance IvoryFloat IDouble
Hodapp87/ivory
ivory/src/Ivory/Language/Float.hs
bsd-3-clause
4,137
0
11
1,014
1,181
637
544
114
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Typechecking class declarations -} {-# LANGUAGE CPP #-} module TcClassDcl ( tcClassSigs, tcClassDecl2, findMethodBind, instantiateMethod, tcInstanceMethodBody, tcClassMinimalDef, HsSigFun, mkHsSigFun, lookupHsSig, emptyHsSigs, tcMkDeclCtxt, tcAddDeclCtxt, badMethodErr ) where #include "HsVersions.h" import HsSyn import TcEnv import TcPat( addInlinePrags ) import TcEvidence( HsWrapper, idHsWrapper ) import TcBinds import TcUnify import TcHsType import TcMType import Type ( getClassPredTys_maybe ) import TcType import TcRnMonad import BuildTyCl( TcMethInfo ) import Class import Id import Name import NameEnv import NameSet import Var import Outputable import SrcLoc import Maybes import BasicTypes import Bag import FastString import BooleanFormula import Util import Control.Monad {- Dictionary handling ~~~~~~~~~~~~~~~~~~~ Every class implicitly declares a new data type, corresponding to dictionaries of that class. So, for example: class (D a) => C a where op1 :: a -> a op2 :: forall b. Ord b => a -> b -> b would implicitly declare data CDict a = CDict (D a) (a -> a) (forall b. Ord b => a -> b -> b) (We could use a record decl, but that means changing more of the existing apparatus. One step at at time!) For classes with just one superclass+method, we use a newtype decl instead: class C a where op :: forallb. a -> b -> b generates newtype CDict a = CDict (forall b. a -> b -> b) Now DictTy in Type is just a form of type synomym: DictTy c t = TyConTy CDict `AppTy` t Death to "ExpandingDicts". ************************************************************************ * * Type-checking the class op signatures * * ************************************************************************ -} tcClassSigs :: Name -- Name of the class -> [LSig Name] -> LHsBinds Name -> TcM ([TcMethInfo], -- Exactly one for each method NameEnv Type) -- Types of the generic-default methods tcClassSigs clas sigs def_methods = do { traceTc "tcClassSigs 1" (ppr clas) ; gen_dm_prs <- concat <$> mapM (addLocM tc_gen_sig) gen_sigs ; let gen_dm_env = mkNameEnv gen_dm_prs ; op_info <- concat <$> mapM (addLocM (tc_sig gen_dm_env)) vanilla_sigs ; let op_names = mkNameSet [ n | (n,_,_) <- op_info ] ; sequence_ [ failWithTc (badMethodErr clas n) | n <- dm_bind_names, not (n `elemNameSet` op_names) ] -- Value binding for non class-method (ie no TypeSig) ; sequence_ [ failWithTc (badGenericMethod clas n) | (n,_) <- gen_dm_prs, not (n `elem` dm_bind_names) ] -- Generic signature without value binding ; traceTc "tcClassSigs 2" (ppr clas) ; return (op_info, gen_dm_env) } where vanilla_sigs = [L loc (nm,ty) | L loc (TypeSig nm ty _) <- sigs] gen_sigs = [L loc (nm,ty) | L loc (GenericSig nm ty) <- sigs] dm_bind_names :: [Name] -- These ones have a value binding in the class decl dm_bind_names = [op | L _ (FunBind {fun_id = L _ op}) <- bagToList def_methods] tc_sig genop_env (op_names, op_hs_ty) = do { traceTc "ClsSig 1" (ppr op_names) ; op_ty <- tcClassSigType op_hs_ty -- Class tyvars already in scope ; traceTc "ClsSig 2" (ppr op_names) ; return [ (op_name, f op_name, op_ty) | L _ op_name <- op_names ] } where f nm | nm `elemNameEnv` genop_env = GenericDM | nm `elem` dm_bind_names = VanillaDM | otherwise = NoDM tc_gen_sig (op_names, gen_hs_ty) = do { gen_op_ty <- tcClassSigType gen_hs_ty ; return [ (op_name, gen_op_ty) | L _ op_name <- op_names ] } {- ************************************************************************ * * Class Declarations * * ************************************************************************ -} tcClassDecl2 :: LTyClDecl Name -- The class declaration -> TcM (LHsBinds Id) tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs, tcdMeths = default_binds})) = recoverM (return emptyLHsBinds) $ setSrcSpan loc $ do { clas <- tcLookupLocatedClass class_name -- We make a separate binding for each default method. -- At one time I used a single AbsBinds for all of them, thus -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... } -- But that desugars into -- ds = \d -> (..., ..., ...) -- dm1 = \d -> case ds d of (a,b,c) -> a -- And since ds is big, it doesn't get inlined, so we don't get good -- default methods. Better to make separate AbsBinds for each ; let (tyvars, _, _, op_items) = classBigSig clas prag_fn = mkPragFun sigs default_binds sig_fn = mkHsSigFun sigs clas_tyvars = snd (tcSuperSkolTyVars tyvars) pred = mkClassPred clas (mkTyVarTys clas_tyvars) ; this_dict <- newEvVar pred ; traceTc "TIM2" (ppr sigs) ; let tc_dm = tcDefMeth clas clas_tyvars this_dict default_binds sig_fn prag_fn ; dm_binds <- tcExtendTyVarEnv clas_tyvars $ mapM tc_dm op_items ; return (unionManyBags dm_binds) } tcClassDecl2 d = pprPanic "tcClassDecl2" (ppr d) tcDefMeth :: Class -> [TyVar] -> EvVar -> LHsBinds Name -> HsSigFun -> PragFun -> ClassOpItem -> TcM (LHsBinds TcId) -- Generate code for polymorphic default methods only (hence DefMeth) -- (Generic default methods have turned into instance decls by now.) -- This is incompatible with Hugs, which expects a polymorphic -- default method for every class op, regardless of whether or not -- the programmer supplied an explicit default decl for the class. -- (If necessary we can fix that, but we don't have a convenient Id to hand.) tcDefMeth clas tyvars this_dict binds_in hs_sig_fn prag_fn (sel_id, dm_info) = case dm_info of NoDefMeth -> do { mapM_ (addLocM (badDmPrag sel_id)) prags ; return emptyBag } DefMeth dm_name -> tc_dm dm_name GenDefMeth dm_name -> tc_dm dm_name where sel_name = idName sel_id prags = prag_fn sel_name (dm_bind,bndr_loc) = findMethodBind sel_name binds_in `orElse` pprPanic "tcDefMeth" (ppr sel_id) -- Eg. class C a where -- op :: forall b. Eq b => a -> [b] -> a -- gen_op :: a -> a -- generic gen_op :: D a => a -> a -- The "local_dm_ty" is precisely the type in the above -- type signatures, ie with no "forall a. C a =>" prefix tc_dm dm_name = do { dm_id <- tcLookupId dm_name ; local_dm_name <- setSrcSpan bndr_loc (newLocalName sel_name) -- Base the local_dm_name on the selector name, because -- type errors from tcInstanceMethodBody come from here ; dm_id_w_inline <- addInlinePrags dm_id prags ; spec_prags <- tcSpecPrags dm_id prags ; let local_dm_ty = instantiateMethod clas dm_id (mkTyVarTys tyvars) hs_ty = lookupHsSig hs_sig_fn sel_name `orElse` pprPanic "tc_dm" (ppr sel_name) ; local_dm_sig <- instTcTySig hs_ty local_dm_ty Nothing [] local_dm_name ; warnTc (not (null spec_prags)) (ptext (sLit "Ignoring SPECIALISE pragmas on default method") <+> quotes (ppr sel_name)) ; tc_bind <- tcInstanceMethodBody (ClsSkol clas) tyvars [this_dict] dm_id_w_inline local_dm_sig idHsWrapper IsDefaultMethod dm_bind ; return (unitBag tc_bind) } --------------- tcInstanceMethodBody :: SkolemInfo -> [TcTyVar] -> [EvVar] -> Id -> TcSigInfo -> HsWrapper -- See Note [Instance method signatures] in TcInstDcls -> TcSpecPrags -> LHsBind Name -> TcM (LHsBind Id) tcInstanceMethodBody skol_info tyvars dfun_ev_vars meth_id local_meth_sig wrapper specs (L loc bind) = do { let local_meth_id = case local_meth_sig of TcSigInfo{ sig_id = meth_id } -> meth_id _ -> pprPanic "tcInstanceMethodBody" (ppr local_meth_sig) lm_bind = L loc (bind { fun_id = L loc (idName local_meth_id) }) -- Substitute the local_meth_name for the binder -- NB: the binding is always a FunBind ; (ev_binds, (tc_bind, _, _)) <- checkConstraints skol_info tyvars dfun_ev_vars $ tcPolyCheck NonRecursive no_prag_fn local_meth_sig lm_bind ; let export = ABE { abe_wrap = wrapper, abe_poly = meth_id , abe_mono = local_meth_id, abe_prags = specs } full_bind = AbsBinds { abs_tvs = tyvars , abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = ev_binds , abs_binds = tc_bind } ; return (L loc full_bind) } where no_prag_fn _ = [] -- No pragmas for local_meth_id; -- they are all for meth_id --------------- tcClassMinimalDef :: Name -> [LSig Name] -> [TcMethInfo] -> TcM ClassMinimalDef tcClassMinimalDef _clas sigs op_info = case findMinimalDef sigs of Nothing -> return defMindef Just mindef -> do -- Warn if the given mindef does not imply the default one -- That is, the given mindef should at least ensure that the -- class ops without default methods are required, since we -- have no way to fill them in otherwise whenIsJust (isUnsatisfied (mindef `impliesAtom`) defMindef) $ (\bf -> addWarnTc (warningMinimalDefIncomplete bf)) return mindef where -- By default require all methods without a default -- implementation whose names don't start with '_' defMindef :: ClassMinimalDef defMindef = mkAnd [ mkVar name | (name, NoDM, _) <- op_info , not (startsWithUnderscore (getOccName name)) ] instantiateMethod :: Class -> Id -> [TcType] -> TcType -- Take a class operation, say -- op :: forall ab. C a => forall c. Ix c => (b,c) -> a -- Instantiate it at [ty1,ty2] -- Return the "local method type": -- forall c. Ix x => (ty2,c) -> ty1 instantiateMethod clas sel_id inst_tys = ASSERT( ok_first_pred ) local_meth_ty where (sel_tyvars,sel_rho) = tcSplitForAllTys (idType sel_id) rho_ty = ASSERT( length sel_tyvars == length inst_tys ) substTyWith sel_tyvars inst_tys sel_rho (first_pred, local_meth_ty) = tcSplitPredFunTy_maybe rho_ty `orElse` pprPanic "tcInstanceMethod" (ppr sel_id) ok_first_pred = case getClassPredTys_maybe first_pred of Just (clas1, _tys) -> clas == clas1 Nothing -> False -- The first predicate should be of form (C a b) -- where C is the class in question --------------------------- type HsSigFun = NameEnv (LHsType Name) emptyHsSigs :: HsSigFun emptyHsSigs = emptyNameEnv mkHsSigFun :: [LSig Name] -> HsSigFun mkHsSigFun sigs = mkNameEnv [(n, hs_ty) | L _ (TypeSig ns hs_ty _) <- sigs , L _ n <- ns ] lookupHsSig :: HsSigFun -> Name -> Maybe (LHsType Name) lookupHsSig = lookupNameEnv --------------------------- findMethodBind :: Name -- Selector name -> LHsBinds Name -- A group of bindings -> Maybe (LHsBind Name, SrcSpan) -- Returns the binding, and the binding -- site of the method binder findMethodBind sel_name binds = foldlBag mplus Nothing (mapBag f binds) where f bind@(L _ (FunBind { fun_id = L bndr_loc op_name })) | op_name == sel_name = Just (bind, bndr_loc) f _other = Nothing --------------------------- findMinimalDef :: [LSig Name] -> Maybe ClassMinimalDef findMinimalDef = firstJusts . map toMinimalDef where toMinimalDef :: LSig Name -> Maybe ClassMinimalDef toMinimalDef (L _ (MinimalSig _ bf)) = Just (fmap unLoc bf) toMinimalDef _ = Nothing {- Note [Polymorphic methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class Foo a where op :: forall b. Ord b => a -> b -> b -> b instance Foo c => Foo [c] where op = e When typechecking the binding 'op = e', we'll have a meth_id for op whose type is op :: forall c. Foo c => forall b. Ord b => [c] -> b -> b -> b So tcPolyBinds must be capable of dealing with nested polytypes; and so it is. See TcBinds.tcMonoBinds (with type-sig case). Note [Silly default-method bind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we pass the default method binding to the type checker, it must look like op2 = e not $dmop2 = e otherwise the "$dm" stuff comes out error messages. But we want the "$dm" to come out in the interface file. So we typecheck the former, and wrap it in a let, thus $dmop2 = let op2 = e in op2 This makes the error messages right. ************************************************************************ * * Error messages * * ************************************************************************ -} tcMkDeclCtxt :: TyClDecl Name -> SDoc tcMkDeclCtxt decl = hsep [ptext (sLit "In the"), pprTyClDeclFlavour decl, ptext (sLit "declaration for"), quotes (ppr (tcdName decl))] tcAddDeclCtxt :: TyClDecl Name -> TcM a -> TcM a tcAddDeclCtxt decl thing_inside = addErrCtxt (tcMkDeclCtxt decl) thing_inside badMethodErr :: Outputable a => a -> Name -> SDoc badMethodErr clas op = hsep [ptext (sLit "Class"), quotes (ppr clas), ptext (sLit "does not have a method"), quotes (ppr op)] badGenericMethod :: Outputable a => a -> Name -> SDoc badGenericMethod clas op = hsep [ptext (sLit "Class"), quotes (ppr clas), ptext (sLit "has a generic-default signature without a binding"), quotes (ppr op)] {- badGenericInstanceType :: LHsBinds Name -> SDoc badGenericInstanceType binds = vcat [ptext (sLit "Illegal type pattern in the generic bindings"), nest 2 (ppr binds)] missingGenericInstances :: [Name] -> SDoc missingGenericInstances missing = ptext (sLit "Missing type patterns for") <+> pprQuotedList missing dupGenericInsts :: [(TyCon, InstInfo a)] -> SDoc dupGenericInsts tc_inst_infos = vcat [ptext (sLit "More than one type pattern for a single generic type constructor:"), nest 2 (vcat (map ppr_inst_ty tc_inst_infos)), ptext (sLit "All the type patterns for a generic type constructor must be identical") ] where ppr_inst_ty (_,inst) = ppr (simpleInstInfoTy inst) -} badDmPrag :: Id -> Sig Name -> TcM () badDmPrag sel_id prag = addErrTc (ptext (sLit "The") <+> hsSigDoc prag <+> ptext (sLit "for default method") <+> quotes (ppr sel_id) <+> ptext (sLit "lacks an accompanying binding")) warningMinimalDefIncomplete :: ClassMinimalDef -> SDoc warningMinimalDefIncomplete mindef = vcat [ ptext (sLit "The MINIMAL pragma does not require:") , nest 2 (pprBooleanFormulaNice mindef) , ptext (sLit "but there is no default implementation.") ]
forked-upstream-packages-for-ghcjs/ghc
compiler/typecheck/TcClassDcl.hs
bsd-3-clause
16,614
0
16
5,351
2,917
1,529
1,388
210
3
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Sandbox.Timestamp -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- Timestamp file handling (for add-source dependencies). ----------------------------------------------------------------------------- module Distribution.Client.Sandbox.Timestamp ( AddSourceTimestamp, withAddTimestamps, withUpdateTimestamps, maybeAddCompilerTimestampRecord, listModifiedDeps, removeTimestamps, ) where import Control.Exception (IOException) import Control.Monad (filterM, forM, when) import Data.Char (isSpace) import Data.List (partition) import System.Directory (renameFile) import System.FilePath ((<.>), (</>)) import qualified Data.Map as M import Distribution.Compiler (CompilerId) import Distribution.Package (packageName) import Distribution.PackageDescription.Configuration (flattenPackageDescription) import Distribution.PackageDescription.Parse (readPackageDescription) import Distribution.Simple.Setup (Flag (..), SDistFlags (..), defaultSDistFlags, sdistCommand) import Distribution.Simple.Utils (debug, die, warn) import Distribution.System (Platform) import Distribution.Text (display) import Distribution.Verbosity (Verbosity, lessVerbose, normal) import Distribution.Version (Version (..), orLaterVersion) import Distribution.Client.Sandbox.Index (ListIgnoredBuildTreeRefs (ListIgnored), RefTypesToList(OnlyLinks) ,listBuildTreeRefs) import Distribution.Client.SetupWrapper (SetupScriptOptions (..), defaultSetupScriptOptions, setupWrapper) import Distribution.Client.Utils (inDir, removeExistingFile, tryCanonicalizePath, tryFindAddSourcePackageDesc) import Distribution.Compat.Exception (catchIO) import Distribution.Client.Compat.Time (EpochTime, getCurTime, getModTime) -- | Timestamp of an add-source dependency. type AddSourceTimestamp = (FilePath, EpochTime) -- | Timestamp file record - a string identifying the compiler & platform plus a -- list of add-source timestamps. type TimestampFileRecord = (String, [AddSourceTimestamp]) timestampRecordKey :: CompilerId -> Platform -> String timestampRecordKey compId platform = display platform ++ "-" ++ display compId -- | The 'add-source-timestamps' file keeps the timestamps of all add-source -- dependencies. It is initially populated by 'sandbox add-source' and kept -- current by 'reinstallAddSourceDeps' and 'configure -w'. The user can install -- add-source deps manually with 'cabal install' after having edited them, so we -- can err on the side of caution sometimes. -- FIXME: We should keep this info in the index file, together with build tree -- refs. timestampFileName :: FilePath timestampFileName = "add-source-timestamps" -- | Read the timestamp file. Exits with error if the timestamp file is -- corrupted. Returns an empty list if the file doesn't exist. readTimestampFile :: FilePath -> IO [TimestampFileRecord] readTimestampFile timestampFile = do timestampString <- readFile timestampFile `catchIO` \_ -> return "[]" case reads timestampString of [(timestamps, s)] | all isSpace s -> return timestamps _ -> die $ "The timestamps file is corrupted. " ++ "Please delete & recreate the sandbox." -- | Write the timestamp file, atomically. writeTimestampFile :: FilePath -> [TimestampFileRecord] -> IO () writeTimestampFile timestampFile timestamps = do writeFile timestampTmpFile (show timestamps) renameFile timestampTmpFile timestampFile where timestampTmpFile = timestampFile <.> "tmp" -- | Read, process and write the timestamp file in one go. withTimestampFile :: FilePath -> ([TimestampFileRecord] -> IO [TimestampFileRecord]) -> IO () withTimestampFile sandboxDir process = do let timestampFile = sandboxDir </> timestampFileName timestampRecords <- readTimestampFile timestampFile >>= process writeTimestampFile timestampFile timestampRecords -- | Given a list of 'AddSourceTimestamp's, a list of paths to add-source deps -- we've added and an initial timestamp, add an 'AddSourceTimestamp' to the list -- for each path. If a timestamp for a given path already exists in the list, -- update it. addTimestamps :: EpochTime -> [AddSourceTimestamp] -> [FilePath] -> [AddSourceTimestamp] addTimestamps initial timestamps newPaths = [ (p, initial) | p <- newPaths ] ++ oldTimestamps where (oldTimestamps, _toBeUpdated) = partition (\(path, _) -> path `notElem` newPaths) timestamps -- | Given a list of 'AddSourceTimestamp's, a list of paths to add-source deps -- we've reinstalled and a new timestamp value, update the timestamp value for -- the deps in the list. If there are new paths in the list, ignore them. updateTimestamps :: [AddSourceTimestamp] -> [FilePath] -> EpochTime -> [AddSourceTimestamp] updateTimestamps timestamps pathsToUpdate newTimestamp = foldr updateTimestamp [] timestamps where updateTimestamp t@(path, _oldTimestamp) rest | path `elem` pathsToUpdate = (path, newTimestamp) : rest | otherwise = t : rest -- | Given a list of 'TimestampFileRecord's and a list of paths to add-source -- deps we've removed, remove those deps from the list. removeTimestamps' :: [AddSourceTimestamp] -> [FilePath] -> [AddSourceTimestamp] removeTimestamps' l pathsToRemove = foldr removeTimestamp [] l where removeTimestamp t@(path, _oldTimestamp) rest = if path `elem` pathsToRemove then rest else t : rest -- | If a timestamp record for this compiler doesn't exist, add a new one. maybeAddCompilerTimestampRecord :: Verbosity -> FilePath -> FilePath -> CompilerId -> Platform -> IO () maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile compId platform = do let key = timestampRecordKey compId platform withTimestampFile sandboxDir $ \timestampRecords -> do case lookup key timestampRecords of Just _ -> return timestampRecords Nothing -> do buildTreeRefs <- listBuildTreeRefs verbosity ListIgnored OnlyLinks indexFile now <- getCurTime let timestamps = map (\p -> (p, now)) buildTreeRefs return $ (key, timestamps):timestampRecords -- | Given an IO action that returns a list of build tree refs, add those -- build tree refs to the timestamps file (for all compilers). withAddTimestamps :: FilePath -> IO [FilePath] -> IO () withAddTimestamps sandboxDir act = do let initialTimestamp = 0 withActionOnAllTimestamps (addTimestamps initialTimestamp) sandboxDir act -- | Given a list of build tree refs, remove those -- build tree refs from the timestamps file (for all compilers). removeTimestamps :: FilePath -> [FilePath] -> IO () removeTimestamps idxFile = withActionOnAllTimestamps removeTimestamps' idxFile . return -- | Given an IO action that returns a list of build tree refs, update the -- timestamps of the returned build tree refs to the current time (only for the -- given compiler & platform). withUpdateTimestamps :: FilePath -> CompilerId -> Platform ->([AddSourceTimestamp] -> IO [FilePath]) -> IO () withUpdateTimestamps = withActionOnCompilerTimestamps updateTimestamps -- | Helper for implementing 'withAddTimestamps' and -- 'withRemoveTimestamps'. Runs a given action on the list of -- 'AddSourceTimestamp's for all compilers, applies 'f' to the result and then -- updates the timestamp file. The IO action is run only once. withActionOnAllTimestamps :: ([AddSourceTimestamp] -> [FilePath] -> [AddSourceTimestamp]) -> FilePath -> IO [FilePath] -> IO () withActionOnAllTimestamps f sandboxDir act = withTimestampFile sandboxDir $ \timestampRecords -> do paths <- act return [(key, f timestamps paths) | (key, timestamps) <- timestampRecords] -- | Helper for implementing 'withUpdateTimestamps'. Runs a given action on the -- list of 'AddSourceTimestamp's for this compiler, applies 'f' to the result -- and then updates the timestamp file record. The IO action is run only once. withActionOnCompilerTimestamps :: ([AddSourceTimestamp] -> [FilePath] -> EpochTime -> [AddSourceTimestamp]) -> FilePath -> CompilerId -> Platform -> ([AddSourceTimestamp] -> IO [FilePath]) -> IO () withActionOnCompilerTimestamps f sandboxDir compId platform act = do let needle = timestampRecordKey compId platform withTimestampFile sandboxDir $ \timestampRecords -> do timestampRecords' <- forM timestampRecords $ \r@(key, timestamps) -> if key == needle then do paths <- act timestamps now <- getCurTime return (key, f timestamps paths now) else return r return timestampRecords' -- | List all source files of a given add-source dependency. Exits with error if -- something is wrong (e.g. there is no .cabal file in the given directory). -- FIXME: This function is not thread-safe because of 'inDir'. allPackageSourceFiles :: Verbosity -> FilePath -> IO [FilePath] allPackageSourceFiles verbosity packageDir = inDir (Just packageDir) $ do pkg <- do let err = "Error reading source files of add-source dependency." desc <- tryFindAddSourcePackageDesc packageDir err flattenPackageDescription `fmap` readPackageDescription verbosity desc let file = "cabal-sdist-list-sources" flags = defaultSDistFlags { sDistVerbosity = Flag $ if verbosity == normal then lessVerbose verbosity else verbosity, sDistListSources = Flag file } setupOpts = defaultSetupScriptOptions { -- 'sdist --list-sources' was introduced in Cabal 1.18. useCabalVersion = orLaterVersion $ Version [1,18,0] [] } doListSources :: IO [FilePath] doListSources = do setupWrapper verbosity setupOpts (Just pkg) sdistCommand (const flags) [] srcs <- fmap lines . readFile $ file mapM tryCanonicalizePath srcs onFailedListSources :: IOException -> IO () onFailedListSources e = do warn verbosity $ "Could not list sources of the add-source dependency '" ++ display (packageName pkg) ++ "'. Skipping the timestamp check." debug verbosity $ "Exception was: " ++ show e -- Run setup sdist --list-sources=TMPFILE ret <- doListSources `catchIO` (\e -> onFailedListSources e >> return []) removeExistingFile file return ret -- | Has this dependency been modified since we have last looked at it? isDepModified :: Verbosity -> EpochTime -> AddSourceTimestamp -> IO Bool isDepModified verbosity now (packageDir, timestamp) = do debug verbosity ("Checking whether the dependency is modified: " ++ packageDir) depSources <- allPackageSourceFiles verbosity packageDir go depSources where go [] = return False go (dep:rest) = do -- FIXME: What if the clock jumps backwards at any point? For now we only -- print a warning. modTime <- getModTime dep when (modTime > now) $ warn verbosity $ "File '" ++ dep ++ "' has a modification time that is in the future." if modTime >= timestamp then do debug verbosity ("Dependency has a modified source file: " ++ dep) return True else go rest -- | List all modified dependencies. listModifiedDeps :: Verbosity -> FilePath -> CompilerId -> Platform -> M.Map FilePath a -- ^ The set of all installed add-source deps. -> IO [FilePath] listModifiedDeps verbosity sandboxDir compId platform installedDepsMap = do timestampRecords <- readTimestampFile (sandboxDir </> timestampFileName) let needle = timestampRecordKey compId platform timestamps <- maybe noTimestampRecord return (lookup needle timestampRecords) now <- getCurTime fmap (map fst) . filterM (isDepModified verbosity now) . filter (\ts -> fst ts `M.member` installedDepsMap) $ timestamps where noTimestampRecord = die $ "Сouldn't find a timestamp record for the given " ++ "compiler/platform pair. " ++ "Please report this on the Cabal bug tracker: " ++ "https://github.com/haskell/cabal/issues/new ."
randen/cabal
cabal-install/Distribution/Client/Sandbox/Timestamp.hs
bsd-3-clause
13,731
0
22
3,854
2,359
1,263
1,096
199
3
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="hi-IN"> <title>FuzzDB Files</title> <maps> <homeID>fuzzdb</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/fuzzdb/src/main/javahelp/help_hi_IN/helpset_hi_IN.hs
apache-2.0
960
77
66
156
407
206
201
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="id-ID"> <title>Directory List v2.3</title> <maps> <homeID>directorylistv2_3</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/directorylistv2_3/src/main/javahelp/help_id_ID/helpset_id_ID.hs
apache-2.0
978
78
66
157
412
209
203
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sq-AL"> <title>MacOS WebDrivers</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/webdrivers/webdrivermacos/src/main/javahelp/org/zaproxy/zap/extension/webdrivermacos/resources/help_sq_AL/helpset_sq_AL.hs
apache-2.0
961
77
66
156
407
206
201
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ar-SA"> <title>Forced Browse Add-On</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>بحث</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/bruteforce/src/main/javahelp/org/zaproxy/zap/extension/bruteforce/resources/help_ar_SA/helpset_ar_SA.hs
apache-2.0
965
79
66
157
411
208
203
-1
-1
module Text.Parsec.String.Combinator where {- Wrappers for the Text.Parsec.Combinator module with the types fixed to 'Text.Parsec.String.Parser a', i.e. the stream is String, no user state, Identity monad. -} import qualified Text.Parsec.Combinator as C import Text.Parsec.String (Parser) choice :: [Parser a] -> Parser a choice = C.choice count :: Int -> Parser a -> Parser [a] count = C.count between :: Parser open -> Parser close -> Parser a -> Parser a between = C.between option :: a -> Parser a -> Parser a option = C.option optionMaybe :: Parser a -> Parser (Maybe a) optionMaybe = C.optionMaybe optional :: Parser a -> Parser () optional = C.optional skipMany1 :: Parser a -> Parser () skipMany1 = C.skipMany1 many1 :: Parser a -> Parser [a] many1 = C.many1 sepBy :: Parser a -> Parser sep -> Parser [a] sepBy = C.sepBy sepBy1 :: Parser a -> Parser sep -> Parser [a] sepBy1 = C.sepBy1 endBy :: Parser a -> Parser sep -> Parser [a] endBy = C.endBy endBy1 :: Parser a -> Parser sep -> Parser [a] endBy1 = C.endBy1 sepEndBy :: Parser a -> Parser sep -> Parser [a] sepEndBy = C.sepEndBy sepEndBy1 :: Parser a -> Parser sep -> Parser [a] sepEndBy1 = C.sepEndBy1 chainl :: Parser a -> Parser (a -> a -> a) -> a -> Parser a chainl = C.chainl chainl1 :: Parser a -> Parser (a -> a -> a) -> Parser a chainl1 = C.chainl1 chainr :: Parser a -> Parser (a -> a -> a) -> a -> Parser a chainr = C.chainr chainr1 :: Parser a -> Parser (a -> a -> a) -> Parser a chainr1 = C.chainr1 eof :: Parser () eof = C.eof notFollowedBy :: Show a => Parser a -> Parser () notFollowedBy = C.notFollowedBy manyTill :: Parser a -> Parser end -> Parser [a] manyTill = C.manyTill lookAhead :: Parser a -> Parser a lookAhead = C.lookAhead anyToken :: Parser Char anyToken = C.anyToken
EliuX/AdHocParser
src/Text/Parsec/String/Combinator.hs
bsd-3-clause
1,789
0
10
356
723
369
354
49
1
-- $Id: TypeCheck.hs,v 1.39 2001/09/29 00:08:23 diatchki Exp $ module TypeCheck where import TypeGenerics import Monad(mapM, foldM) import HsName import HsTypeStruct import Syntax import InferenceMonad import List(nub, find, intersect, (\\), lookup, union) import ST import SCC(bindingGroups) import qualified Scope import SyntaxUtil(getTyName) ------------------------------------------------------ infix 9 |-> infixr 3 +: type Kind a = GT K Sort (STRef a) type Type a = GT T (Kind a) (STRef a) type NGV a = [(HsName, Type a)] type Env a = [(HsName, Scheme a)] type Constrs a = [Pred a] type Ref a = (Int,STRef a (Maybe(Type a))) type Ptr2 a = STRef a (Maybe(Type a)) type Genfun a = String -> IM a Error HsName type KindEnv a = [(HsName, GT K Sort (STRef a))] data Pred a = IsIn HsName [Type a] data Scheme a = Sch [Kind a] [Pred a] (Type a) data Qual a x = [Pred a] :=> x data Assump name a = name :>: Scheme a data Error = TCerror String instance Show Error where show (TCerror s) = s fails :: String -> IM a Error x fails s = raise (TCerror s) unifyErr x y z = fails ((show x) ++"error in unification " ++ (show y)++", "++(show z)) instance Show (STRef a b) where show x = "?" -------------------------------------------------------- newGensym :: IM a Error (Genfun a) newGensym = do { seed <- newRef (1::Int) ; let gensym s = do { n <- readVar seed ; writeVar seed (n+1) ; return (UnQual (s ++ (show n))) } in return gensym } {-gensym s = do { n <- nextN ; return (UnQual (s ++ (show n))) } -} ------------------ Kind inference ----------------------- data Sort = Sort deriving Eq kindA :: A K Sort () (STRef a) (IM a Error) kindA = A { sameVarA = refEq , writeVarA = writeVar , readVarA = readVar , newVarA = newRef , nextA = nextN , zeroA = () , unionA = const () , genErrA = unifyErr , seqA = seqK , mapA = mapK , accA f = flip (accK f) , matchA = matchK , kindofA = const(return Sort) , samekindA = (==) } refEq :: STRef a b -> STRef a b -> Bool refEq x y = x==y eqK :: Kind a -> Kind a -> Bool B{ unifyGT = unifyKind , equalGT = eqK , freshGT = newVarK , pruneGT = pruneK , substGT = substK , genGT = genK } = makeUnify kindA star = S Kstar arrowK x y = S(Kfun x y) predicate = S Kpred instance Eq (Kind a) where (==) = eqK -- Works on HSTypes while inferK2 works on (Type a) inferK :: [(HsName,Kind a)] -> Kind a -> HsType -> IM a Error (Kind a) inferK kenv k t = do { let f (nm,k) = do { v <- newVar k; return (nm,v)} h :: [(HsName,Type a)] -> HsType -> Type a h pairs (Typ (HsTyVar x)) = look pairs x h pairs (Typ x) = S(mapT (h pairs) x) ; pairs <- mapM f kenv ; inferK2 kenv k (h pairs t) } inferK2 :: [(HsName, Kind a)] -> Kind a -> (Type a) -> IM a Error (Kind a) inferK2 env hint t = do { t' <- prune t ; case t' of (TVar r k) -> return k (TGen n) -> return hint (S typ) -> case typ of (HsTyFun x y) -> do { x' <- inferK2 env star x ; y' <- inferK2 env star y ; unifyKind hint star ; return hint } (HsTyTuple ts) -> do { sequence (map (inferK2 env star) ts) ; unifyKind hint star ; return star } (HsTyApp f x) -> do { a <- newVarK Sort ; inferK2 env (S(Kfun a hint)) f ; inferK2 env a x ; return hint } (HsTyVar nm) -> do { unifyKind hint (lookUpEnv env nm) ; return hint } (HsTyCon nm) -> do { unifyKind hint (lookUpEnv env nm) ; return hint } } kindOf2 :: [(HsName,Kind a)] -> Type a -> IM a Error (Kind a) kindOf2 envf x = do { hint <- newVarK Sort ; inferK2 envf hint x ; (ks,ts,x') <- genK (\ x -> return True) hint ; k' <- substK (repeat star) x' ; return k' } getkind :: Type a -> IM a Error (Kind a) getkind t = kindOf2 kenv0 t -------------------------------------------------------------- typeA :: A T (Kind c) [Pred c] (STRef c) (IM c Error) typeA = A { sameVarA = refEq , writeVarA = writeVar , readVarA = readVar , newVarA = newRef , nextA = nextN , zeroA = [] , unionA = concat , genErrA = unifyErr , seqA = seqT , mapA = mapT , accA = accT , matchA = matchT , kindofA = getkind , samekindA = eqK } prune :: Type a -> IM a Error (Type a) unify :: Type a -> Type a -> IM a Error [Pred a] subst :: [Type a] -> Type a -> IM a Error (Type a) B{ unifyGT = unify , matchGT = matchType , equalGT = teq , freshGT = newVar , colGT = col , occursGT = occursIn , pruneGT = prune , substGT = subst , genmapGT = gen } = makeUnify typeA match :: Type a -> Type a -> IM a Error Bool match x y = (do { matchType x y; return True}) `handle` (\ _ -> return False) unifyList xs ys = if (length xs) == (length ys) then do { xss <- mapM (uncurry unify) (zip xs ys) ; return (concat xss) } else fails "Lists not same length" --------------------------------------------------------------- class Types t a where tv :: t -> IM a Error [Ref a] collapse :: t -> IM a Error t instance Types (Type a) a where tv t = do { t' <- prune t ; case t' of (TVar r k) -> return [r] (S x) -> do { sh <- seqT (mapT tv x) ; return $ nub (accT (++) sh []) } (TGen i) -> return []} collapse t = col t instance Types x a => Types [x] a where tv xs = do { xs' <- mapM tv xs; return(concat xs') } collapse ts = mapM collapse ts instance Types (Pred a) a where tv (IsIn nm xs) = tv xs collapse (IsIn nm xs) = do {xs' <- collapse xs; return(IsIn nm xs')} instance Types(Scheme a) a where tv (Sch ks ps t) = do {ps' <- tv ps; t' <- tv t; return(union ps' t')} collapse (Sch ks ps t) = do {ps' <- collapse ps; t' <- collapse t; return(Sch ks ps' t')} instance Types y a => Types (x,y) a where tv (x,y) = tv y collapse (x,y) = do {y' <- collapse y; return (x,y') } ----------------------------------------------------------------- class Instantiate x a where inst :: [Type a] -> x -> IM a Error x instance Instantiate (Pred a) a where inst ts (IsIn nm xs) = do { xs' <- mapM (inst ts) xs; return (IsIn nm xs') } instance Instantiate x a => Instantiate [x] a where inst ts xs = mapM (inst ts) xs instance Instantiate (Type a) a where inst = subst -------------------------------------------------- class Template x a where fresh :: x -> IM a Error x instance Template (Scheme a) a where fresh (Sch free cs t) = do { sub <- mapM newVar free ; t' <- inst sub t ; cs' <- sequence (map (inst sub) cs) ; return $ Sch free cs' t' } instance Template (Inst a) a where fresh (Inst free ps p) = do { sub <- mapM newVar free ; p' <- inst sub p ; ps' <- sequence (map (inst sub) ps) ; return $ Inst free ps' p' } --------------- Environment function and types -------------------------- extend f s t = (s,t) : f lambdaExt :: [(name,Scheme a)] -> name -> Type a -> [(name,Scheme a)] lambdaExt env vname vtyp = extend env vname (Sch [] [] vtyp) lambdaExtTCE env vname vtyp = extTrm vname (Sch [] [] vtyp) env envf [] s = error ("variable not found: "++(show s)++"\n") envf ((x,t):m) s = if x==s then t else envf m s -------- Type constructors and types of literal constants ------------ starKind = S(Kstar) arrowKind x y =S(Kfun x y) predKind = S Kpred tArrow x y = S(HsTyFun x y) tTuple ts = S(HsTyTuple ts) tInteger = S(HsTyCon (UnQual "Integer")) tInt = S(HsTyCon (UnQual "Int")) tChar = S(HsTyCon (UnQual "Char")) tString = tlist tChar tRational = S(HsTyCon (UnQual "Rational")) tBool = S(HsTyCon (UnQual "Bool")) tDouble = S(HsTyCon (UnQual "Double")) tStringHash = S(HsTyCon (UnQual "stringHash")) tCharHash = S(HsTyCon (UnQual "CharHash")) tIntHash = S(HsTyCon (UnQual "IntHash")) tRationalHash = S(HsTyCon (UnQual "RationalHash")) tlist x = S(HsTyApp tlistCon x) tlistCon = (S(HsTyCon (UnQual "[]"))) tcode x = S(HsTyApp tcodeCon x) tcodeCon = (S(HsTyCon (UnQual "Code"))) litTyp (HsInt _) = tInteger litTyp (HsChar _) = tChar litTyp (HsString _) = tString litTyp (HsFrac _) = tRational litTyp (HsCharPrim _) = tCharHash litTyp (HsStringPrim _) = tStringHash litTyp (HsIntPrim _) = tIntHash litTyp (HsFloatPrim _) = tRationalHash litTyp (HsDoublePrim _) = tRationalHash --------------------------------------------------- -- Kind environment stuff funkify [] env = env funkify ((a,b):rest) env = (a,b) +: (funkify rest env) hsname |-> knd = (hsname,knd) --(x,y) +: env = \t -> if x == t then y else lookUpEnv env t (x,y) +: env = (x,y) : env --emptyKEnv x = error $ "unknown kinnd variable: " ++ (show x) emptyKEnv = [] lookUpEnv env t = case List.lookup t env of Just b -> b Nothing -> error $ "Kind environment: " ++ (show t) ++ "not found!" kenv0 = (UnQual "Integer") |-> star +: (UnQual "Int") |-> star +: (UnQual "Char") |-> star +: (UnQual "Rational") |-> star +: (UnQual "Bool") |-> star +: (UnQual "Double") |-> star +: (UnQual "stringHash") |-> star +: (UnQual "CharHash") |-> star +: (UnQual "IntHash") |-> star +: (UnQual "RationalHash") |-> star +: (UnQual "[]") |-> arrowK star star +: (UnQual "Q") |-> arrowK star star +: (UnQual "X") |-> arrowK star star +: (UnQual "W") |-> arrowK star star +: (UnQual "Num") |-> arrowK star predicate +: emptyKEnv ------------------------ Predefined Class predicates ---------------- num x = IsIn (UnQual "Num") [x] monad x = IsIn (UnQual "Monad") [x] enum x = IsIn (UnQual "Enum") [x] ----------------------------------------------------------------------------- -- This mimics the "Class Environments" Section (7.2) of Typing Haskell in -- Haskell. The differences are: -- 1) Class environments are lists rather than partial functions -- 1) Many functions are in the (IM a Error) Monad instead of the Maybe Monad -- 2) instead of Inst = Qual Pred -- data INST a = INST [Kind] [Pred a] (Pred a) -- An instance is like a (Sch ks ps t), a fresh copy of an instance -- can be made by applying the method "inst". this is usefull for -- determining if we have overlapping instances. We make fresh copies, -- and then we unify. Also like Schemes, things of type (Inst a) have a -- normal form, because of this, and because (Inst a) should be TVar free -- they can be compared for equality. data Class a = Class HsName [HsName] [Inst a] data ClassEnv a = ClassEnv { classList :: [(HsName, Class a)] , defaults :: [Type a] } data Inst a = Inst [Kind a] [Pred a] (Pred a) instance Instantiate (Inst a) a where inst ts (Inst ks ps p) = do { ps' <- (inst ts ps) ; p' <- (inst ts p) ; return (Inst ks ps' p') } instance Eq (Inst a) where (Inst ks1 ps1 p1) == (Inst ks2 ps2 p2) = listEq (==) ks1 ks2 && listEq (==) ps1 ps2 && p1 == p2 instance Eq (Pred a) where (IsIn c ts) == (IsIn d xs) = c==d && listEq teq ts xs listEq eqf [] [] = True listEq eqf (x:xs) (y :ys) = eqf x y && listEq eqf xs ys listEq eqf _ _ = False ----------------------------------------------------------------------- classes :: ClassEnv a -> HsName -> Maybe (Class a) classes ce i = case find ( \ (x,y) -> x==i) (classList ce) of Just (name,cl) -> Just cl Nothing -> Nothing super :: ClassEnv a -> HsName -> [HsName] super ce i = case classes ce i of Just (Class name sup insts) -> sup insts :: ClassEnv a -> HsName -> [Inst a] insts ce i = case classes ce i of Just (Class name sup its) -> its defined :: Maybe a -> Bool defined (Just _) = True defined Nothing = False modify :: ClassEnv a -> HsName -> Class a -> ClassEnv a modify ce i c = ce {classList = (i,c) : classList ce } initialEnv :: ClassEnv a initialEnv = ClassEnv { classList = [], defaults = [tInteger,tDouble] } type EnvTransformer a = ClassEnv a -> IM a Error (ClassEnv a) infixr 5 <:> (<:>) :: EnvTransformer a -> EnvTransformer a -> EnvTransformer a (f <:> g) ce = do { ce' <- f ce; g ce' } {- ClassEnv a -> Maybe (ClassEnv a) -} addClass :: String -> [String] -> EnvTransformer a addClass i is ce | defined (classes ce (UnQual i)) = fails ("Adding class: "++(show i)++ " to class environment failed. Class already defined. ") | any (not . defined . (classes ce)) (map UnQual is) = fails("Adding class: "++(show i)++ " to class environment failed. Superclass not defined. ") | otherwise = return (modify ce (UnQual i) (Class (UnQual i) (map UnQual is) [] )) addCoreClasses :: EnvTransformer a addCoreClasses = addClass "Eq" [] <:> addClass "Ord" ["Eq"] <:> addClass "Show" [] <:> addClass "Read" [] <:> addClass "Bounded" [] <:> addClass "Enum" [] <:> addClass "Functor" [] <:> addClass "Monad" [] addNumClasses :: EnvTransformer a addNumClasses = addClass "Num" ["Eq","Show"] <:> addClass "Real" ["Num","Ord"] <:> addClass "Fractional" ["Num"] <:> addClass "Integral" ["Real","Enum"] <:> addClass "RealFract" ["Real","Fractional"] <:> addClass "Floating" ["Fractional"] <:> addClass "RealFloat" ["RealFract","Floating"] <:> addInst (Inst [] [] (IsIn (UnQual "Num") [tInteger])) ce0 = (addCoreClasses <:> addNumClasses) initialEnv ------------------------------------------------------------------ overlap :: Pred a -> Pred a -> IM a Error Bool overlap (IsIn c ts1) (IsIn d ts2) = if c==d then (do { unifyList ts1 ts2; return True}) `handle` (\ _ -> return False) else return False addInst :: Inst a -> EnvTransformer a addInst (x @ (Inst ks ps (p @ (IsIn i _)))) ce | not (defined (classes ce i)) = fails ("No class: "++(show i)++", for instance") | otherwise = do { Inst _ _ p' <- fresh x ; qs <- sequence (map getPred its) -- the predicates (without qualifiers) ; lap <- fmap or (sequence (map (overlap p') qs)) ; if lap then fails ("Overlapping instance for: "++(show i)++".") else return(modify ce i c) } where its = insts ce i -- the instances of i getPred (x @(Inst ks ps q)) = do { Inst _ _ q' <- fresh x; return q' } c = Class i (super ce i) (x:its) -- the new class with additional instance bySuper :: ClassEnv a -> Pred a -> [Pred a] bySuper ce (p @ (IsIn cname ts)) = p : concat[bySuper ce (IsIn c' ts) | c' <- super ce cname] lift :: (Type a -> Type b -> IM c Error d) -> Pred a -> Pred b -> IM c Error [d] lift m (IsIn c1 ts1) (IsIn c2 ts2) = if (c1==c2) && (length ts1) ==(length ts2) then sequence (zipWith m ts1 ts2) else fails "classes do not match" matchPred :: Pred a -> Pred a -> IM a Error Bool matchPred x y = fmap and (lift match x y) byInst :: Pred a -> Inst a -> IM a Error (Maybe [Pred a]) byInst p (x @ (Inst ks ps h)) = do { Inst _ ps' h' <- fresh x ; b <- matchPred h' p ; if b then return (Just ps') else return Nothing } reducePred :: ClassEnv a -> Pred a -> IM a Error (Maybe [Pred a]) reducePred ce (p @ (IsIn c ts)) = let instances = (insts ce c) first [] = return Nothing first (i:is) = do { m <- byInst p i ; case m of Just ps -> return(Just ps) Nothing -> first is } in first instances anyM p xs = fmap or (sequence (map p xs)) entail :: ClassEnv a -> [Pred a] -> Pred a -> IM a Error Bool entail ce ps p = do { let preconditions = (map (bySuper ce) ps) -- all possible preds => by ps alreadythere = (any (p `elem`) preconditions) ; if alreadythere then return True else do { m <- reducePred ce p ; case m of Nothing -> return False Just qs -> do { bs <- sequence (map (entail ce ps) qs) ; return (and bs) } } } inHnf (IsIn c ts) = all hnf ts where hnf (TVar _ _) = True hnf (S(HsTyApp x _)) = hnf x hnf (S _) = False hnf (TGen n) = False toHnf :: ClassEnv a -> Pred a -> IM a Error [Pred a] toHnf ce p = if inHnf p then return [p] else do { m <- reducePred ce p ; case m of Nothing -> fails "context reduction" Just ps -> toHnfs ce ps } toHnfs ce ps = fmap concat (mapM (toHnf ce) ps) simplify :: ClassEnv a -> [Pred a] -> [Pred a] -> [Pred a] simplify ce rs [] = rs simplify ce rs (p:ps) = simplify ce (p:(rs \\ qs)) (ps \\ qs) where qs = bySuper ce p rs \\ qs = [ r | r <- rs, r `notElem` qs] numClasses :: [HsName] numClasses = map UnQual ["Num","Integral","Floating","Fractional","Real","RealFloat","RealFrac"] stdClasses :: [HsName] stdClasses = map UnQual ["Eq","Ord","Show","Read","Bounded","Enum","Ix","Functor" ,"Monad","MonadPlus"] ++ numClasses defs :: ClassEnv a -> Ref a -> [Pred a] -> IM a Error [Type a] defs ce v qs = if (all (same v) ts) && (all (`elem` stdClasses) clnames) && (any (`elem` numClasses) clnames) then fmap concat(sequence (zipWith f (defaults ce) (repeat clnames))) else return [] where clnames = [ c | (IsIn c t) <- qs ] ts = [ t | (IsIn c [t]) <- qs ] -- DON"T KNOW if this translates to MPTC same (n,v) (TVar (m,u) k) = v==u same v _ = False f t [] = return [] f t (c:cs) = do { b <- entail ce [] (IsIn c [t]) ; if b then do { ts <- f t cs; return(t:ts) } else f t cs } ambig :: ClassEnv a -> [Ref a] -> [Pred a] -> IM a Error [(Ref a,[Pred a],[Type a])] ambig ce vs ps = do { psvss <- sequence(map tv ps) -- [[ vars ]] ; let psvs = concat psvss -- [ vars ] all of them in any of the ps ambigvs = psvs \\ vs -- vars in ps but not in vs getqs v [] = [] getqs v ((free,p):xs) = if elem v free then p:(getqs v xs) else getqs v xs f v = let qs = getqs v (zip psvss ps) in do { ts <- (defs ce v qs) ; ts' <- mapM collapse ts ; return (v,qs,ts') } ; sequence (map f ambigvs) } useDefaults :: String -> ClassEnv a -> [Ref a] -> [Pred a] -> IM a Error [Pred a] useDefaults names ce vs ps = do { ams <- ambig ce vs ps -- [(v,ps,ts)] "v" can be resolved to any of the "ts", which then cancels the "ps" ; let tss = [ts | (v,qs,ts) <- ams] ps' = [p | (v,qs,ts) <- ams, p <- qs] fix ((n,v),ps,ts) = writeVar v (Just (head ts)) ; if any null tss -- if any "v" can't be resolved by some "t" we have to fail then fails "ambiguity" else do { cs <- mapM fix ams ; newps <- collapse ((ps \\ ps')) ; return newps -- subtract the cancelled ps } } partitionM p xs = select xs where select [] = return ([],[]) select (x:xs) = do { (ys,zs) <- select xs ; b <- p x ; if b then return (x:ys,zs) else return (ys,x:zs) } split :: ClassEnv a -> [Ref a] -> [Pred a] -> IM a Error ([Pred a],[Pred a]) split ce fs ps = do { ps2 <- toHnfs ce ps ; let ps3 = simplify ce [] ps2 ; partitionM p ps3 } where p ps = do { free <- tv ps; return(all (`elem` fs) free) } reduce :: String -> ClassEnv a -> [Ref a] -> [Ref a] -> [Pred a] -> IM a Error ([Pred a],[Pred a]) reduce names ce fs gs ps = do { (ds,rs) <- split ce fs ps ; rs' <- useDefaults names ce (fs ++ gs) rs ; return(ds,rs') } ---------------------------------------------------------------------------- type NGVars a = [(HsName,Type a)] emptyNGVars :: NGVars a emptyNGVars = [] extendNGVars :: HsName -> Type a -> NGVars a -> NGVars a extendNGVars s t ngvars = (s,t):ngvars generic :: NGVars a -> Ref a -> IM a Error Bool generic ngvars (_,v) = do { b <- occursInList v ngvars; return (not b) } where occursInList v l = do { bools <- mapM (\ (a,b) -> occursIn v b) l ; return (or bools) } ------------------------------------------------------------------------- -- unArrow [p1,p2,p3] (t1 -> t2 -> t3 -> t4) ---> (t4,[(p1,t1),(p2,t2),(p3,t3)]) unArrow :: [HsPat] -> Type a -> IM a Error (Type a,[(HsPat,Type a)]) unArrow ps t = do { t' <- col t; flat ps t' } where flat (p:ps) (S(HsTyFun dom rng)) = do { (t,ts) <- (flat ps rng) ; return (t,(p,dom) : ts) } flat [] t = return (t,[]) flat (p:ps) t = error "Too many arguments to pattern" patExtTup [] env = return ([],[],[]) patExtTup ((p,t):m) env = do { (t1,e1,c1) <- patExt p t env ; (ts,e2,cs) <- patExtTup m env ; return(t1:ts,e1++e2,c1 ++ cs) } patExtList [] elemtyp env cs = return (tlist elemtyp,[],cs) patExtList (p:m) elemtyp env cs = do { (t1,e1,c1) <- patExt p elemtyp env ; (listOfelem,e2,cs) <- patExtList m elemtyp env c1 ; return(listOfelem,e1 ++ e2,c1++cs) } patExt :: HsPat -> Type a ->TEnv a -> IM a Error (Type a,NGV a,[Pred a]) patExt (Pat p) typ env = case p of HsPId(HsVar name) -> return (typ,[(name,typ)],[]) HsPId(HsCon name) -> case lookTrmOpt env name of Nothing -> fails $ "Data constructor " ++ (show name) ++ " not defined!!!" Just (scheme @ (Sch tvars preds typ)) -> do { newVars <- mapM (\k -> newVar k) tvars ; t' <- inst newVars typ ; ps <- mapM (inst newVars) preds ; return (t',[],ps) } (HsPLit (HsInt _)) -> do { nv <- newVar starKind ; cs <- unify nv typ ; return (nv, [], [(num nv)]++cs) } (HsPLit l) -> do { let t = litTyp l ; cs <- unify t typ ; return (t,[],cs) } (HsPNeg x) -> error "whats this?" (HsPInfixApp x n y) -> patExt (Pat(HsPApp (getHSName n) [x,y])) typ env (HsPApp nm ps) -> do { Sch _ cs1 ctyp <- fresh (lookTrm env nm) ; (t,patTypeList) <- unArrow ps ctyp ; cs2 <- unify t typ ; (ts2,env2,cs3) <- patExtTup patTypeList env ; return (t,env2,cs1 ++ cs2 ++ cs3) } (HsPTuple ps) -> do { ts <- sequence (map (\ x -> (newVar starKind)) ps) ; cs2 <- unify (tTuple ts) typ ; (ts,ngv3,cs3) <- patExtTup (zip ps ts) env ; return (tTuple ts,ngv3,cs2 ++ cs3) } (HsPList ps ) -> do { elemtyp <- newVar starKind ; (listtyp,ngv2,cs) <- patExtList ps elemtyp env [] ; cs2 <- unify listtyp (tlist elemtyp) ; cs3 <- unify typ listtyp ; return (listtyp,ngv2,cs ++ cs2++ cs3) } (HsPParen x) -> patExt x typ env (HsPRec n pairs) -> error "not yet" (HsPRecUpdate nm pairs) -> error "not yet" (HsPAsPat name x) -> do { (t,ngv1,cs1) <- patExt x typ env ; return (t,(name,t):ngv1,cs1) } (HsPWildCard) -> do { t <- newVar starKind ; cs <- unify typ t ; return (t,[],cs) } (HsPIrrPat x) -> patExt x typ env inferPats :: [HsPat] -> NGV a -> TEnv a -> IM a Error ([Type a],NGV a,TEnv a,[Pred a]) inferPats ps ngvars env = do { pairs <- sequence (map (\ p -> do { t <- newVar starKind; return (p,t) }) ps) ; (t1,ngv1,cs1) <- patExtTup pairs env ; return (t1,ngv1 ++ ngvars,g ngv1 env,cs1) } where g [] env = env g ((v,t):more) env = lambdaExtTCE (g more env) v t inferPat p ngvars env hint = do { (t,ngv1,cs1) <- patExt p hint env ; unify t hint ; return (ngv1 ++ ngvars,g ngv1 env,cs1) } where g [] env = env g ((v,t):more) env = lambdaExtTCE (g more env) v t ------------------------------------------------------------- infer :: Genfun a -> NGV a -> TEnv a -> Type a -> HsExp -> IM a Error (Type a,[Pred a]) infer gensym ngvars env hint (exp @ (Exp e)) = let check env hint x = infer gensym ngvars env hint x in case e of HsId(HsVar nm) -> do { Sch _ cs t <- fresh (lookTrm env nm) ; cs2 <- unify t hint ; return (t,cs ++ cs2) } HsId(HsCon nm) -> do { Sch _ cs t <- fresh (lookTrm env nm) ; cs2 <- unify t hint ; return (t,cs++cs2) } HsLit (HsInt _) -> do { nt <- newVar starKind ; unify nt hint ; return (nt, [num nt]) } HsLit n -> do { let t = litTyp n ; cs <- unify t hint ; return (t,cs) } HsInfixApp x (HsVar f) y -> check env hint (hsApp (hsApp (hsEVar f) x) y) HsInfixApp x (HsCon f) y -> check env hint (hsApp (hsApp (hsECon f) x) y) HsApp f x -> do { xtyp <- newVar starKind ; let ftyp = tArrow xtyp hint ; (_,cs2) <- check env xtyp x ; (_,cs3) <- check env ftyp f ; return (hint,cs2++cs3) } HsNegApp x -> do { (t,cs) <- check env hint x ; return (t,num t : cs) } HsLambda ps x -> do { (ptyps,ngv2,env2,cs) <- inferPats ps ngvars env ; result <- newVar starKind -- f [t1,t2,t3] r --> (t1 -> t2 -> t3 -> r) ; let f [] rng = rng f (t:ts) rng = tArrow t (f ts rng) ans = f ptyps result ; (_,cs2) <- infer gensym ngv2 env2 result x ; cs3 <- unify ans hint ; return (ans,cs ++ cs2 ++ cs3) } HsLet ds e -> do { (ngv2,env2,cs2) <- inferDs gensym ngvars env ds ; (etyp,cs3) <- infer gensym ngv2 env2 hint e ; return (etyp,cs2++cs3) } HsIf x y z -> do { t <- newVar starKind ; (_,cs1) <- check env tBool x ; (_,cs2) <- check env t y ; (_,cs3) <- check env t z ; unify t hint ; return (t,cs1 ++ cs2 ++ cs3) } {- HsCase e alts -> do { argtyp <- newVar starKind ; (ptyp,cs1) <- check env argtyp e ; csAll <- mapM (inferAlt gensym ngvars env ptyp hint) alts ; return (hint, cs1 ++ concat csAll) } -} HsDo stmt -> do { mtyp <- newVar (arrowKind starKind starKind) ; let m x = (S(HsTyApp mtyp x)) ; a <- newVar starKind ; cs2 <- unify hint (m a) ; cs3 <- inferStmt gensym ngvars env mtyp (m a) False stmt ; return (hint,(monad mtyp) : cs2 ++ cs3) } HsTuple xs -> do { pairs <- sequence (map (\ x -> do { t <- newVar starKind; return (t,x) }) xs) ; let tupletyp = tTuple(map fst pairs) ; cs1 <- unify hint tupletyp ; ts <- mapM (uncurry (check env)) pairs ; return (hint,foldr (\ (t,c) cs -> c ++ cs) cs1 ts) } HsList xs -> do { elemtyp <- newVar starKind ; cs1 <- unify hint (tlist elemtyp) ; pairs <- mapM (check env elemtyp) xs ; return (hint,foldr (\ (t,c) cs -> c ++ cs) cs1 pairs) } HsParen x -> check env hint x HsRightSection op arg -> -- i.e. (+ 3) } do { ltyp <- newVar starKind ; rtyp <- newVar starKind ; anstyp <- newVar starKind ; cs1 <- unify (tArrow ltyp anstyp) hint ; (_,cs2) <- check env (tArrow ltyp (tArrow rtyp anstyp)) (hsId op) ; (_,cs3) <- check env rtyp arg ; return (hint,cs1 ++ cs2 ++ cs3) } HsLeftSection arg op -> -- i.e. (3 +) do { ltyp <- newVar starKind ; rtyp <- newVar starKind ; anstyp <- newVar starKind ; cs1 <- unify (tArrow rtyp anstyp) hint ; (_,cs2) <- check env (tArrow ltyp (tArrow rtyp anstyp)) (hsId op) ; (_,cs3) <- check env ltyp arg ; return (hint,cs1 ++ cs2 ++ cs3) } HsRecConstr name fields -> error "not yet" HsRecUpdate arg fields -> error "not yet" HsEnumFrom x -> -- [x ..] :: Enum a => [a] do { a <- newVar starKind ; cs1 <- unify hint (tlist a) ; (_,cs2) <- check env a x ; return (hint,(enum a) : cs1 ++ cs2) } HsEnumFromTo x y -> -- [x .. y] :: Enum a => a -> a -> [a] do { a <- newVar starKind ; cs0 <- unify hint (tlist a) ; (_,cs1) <- check env a x ; (_,cs2) <- check env a y ; return (hint,(enum a) : cs0 ++ cs1 ++ cs2) } HsEnumFromThen x y -> -- [x, y ..] : Enum a => a -> a -> [a] do { a <- newVar starKind ; cs0 <- unify hint (tlist a) ; (_,cs1) <- check env a x ; (_,cs2) <- check env a y ; return (hint,(enum a) : cs0 ++ cs1 ++ cs2) } HsEnumFromThenTo x y z -> -- [x,y .. z] :: Enum a => a -> a -> a -> [a] do { a <- newVar starKind ; cs0 <- unify hint (tlist a) ; (_,cs1) <- check env a x ; (_,cs2) <- check env a y ; (_,cs3) <- check env a z ; return (hint,(enum a) : cs0 ++ cs1 ++ cs2 ++ cs3) } HsListComp stmt -> do { let mtyp = tlistCon ; let m x = (S(HsTyApp mtyp x)) ; a <- newVar starKind ; cs2 <- unify hint (m a) ; cs3 <- inferStmt gensym ngvars env mtyp a True stmt ; return (hint,cs2 ++ cs3) } HsExpTypeSig loc e qt -> do { Sch _ cs1 typ <- hsQual2freshSch qt ; cs2 <- unify typ hint ; (_,cs3) <- check env typ e ; return (typ,cs1 ++ cs2 ++ cs3) } HsAsPat nm e -> error "pattern only" HsWildCard -> error "pattern only" HsIrrPat e -> error "pattern only" {- HsMetaBracket e -> -- MetaHUGS extension <<| exp |> do { a <- newVar starKind ; cs1 <- unify hint (tcode a) ; (_,cs2) <- check env a e ; return (hint,cs1 ++ cs2) } HsMetaEscape e -> -- MetaHUGS extansion ^exp do { (_,cs1) <- check env (tcode hint) e ; return (hint,cs1) } -} isValueDecl (Dec d) = case d of HsPatBind _ _ _ _ -> True HsFunBind _ _ -> True _ -> False isTypeDecl (Dec d) = case d of HsTypeDecl _ _ _ -> True HsDataDecl _ _ _ _ _ -> True HsPrimitiveTypeDecl _ _ _ -> True _ -> False isClassInstDecl (Dec d) = case d of HsClassDecl _ _ _ _ -> True HsInstDecl _ _ _ _ -> True HsDefaultDecl _ _ -> True _ -> False -------------------------------------------------------------------- -- InferDs, first breaks the [HsDecl] into strongly connected binding -- groups, then types each set separately using inferBG inferDs :: Genfun a -> NGV a -> TEnv a -> [HsDecl] -> IM a Error (NGV a,TEnv a, Constrs a) inferDs gensym ngv env ds = let valueDs = filter isValueDecl ds typeDs = filter isTypeDecl ds (groups,_) = bindingGroups valueDs (typeGroups,cyclicSynonyms) = bindingGroups typeDs f (ngv,env,cs) ds = do { (n,e,c) <- inferBG gensym ngv env ds; return(n,e,c++cs)} g (env) ds = do { env' <- inferDataTypes gensym env ds ; return env' } in do { if cyclicSynonyms then fails "Cyclic type synonyms" else return () ; e <- (foldM g env typeGroups) ; foldM f (ngv,e,[]) groups } ------------------------------------------------------------------ -- Section 4.5.2 of the Haskell report states that all constraints -- resulting from typing a single binding group are collected together -- to form the context of the type for each name bound in the binding -- group. Thus given a binding group we should construct a delta env -- with a binding for each name, and a common set of contraints. pr2 s x = do { x' <- x; pr s x'} dataTypeName sloc (Typ t) = case t of HsTyVar n -> return n HsTyApp a b -> dataTypeName sloc a HsTyCon n -> return n _ -> fails $ show sloc ++ "Error in type pattern: ill formed. " dataTypeArgs sloc (Typ t) = case t of HsTyVar n -> return [n] HsTyApp a b -> dataTypeArgs sloc b HsTyCon _ -> return [] _ -> fails $ show sloc ++ "Error in type pattern: ill formed. " inferDataTypes gensym env [] = return env inferDataTypes gensym env ds = do { let (freef, envf) = Scope.freeD ds freeVars = freef [] ; vs <- mapM (\_ -> newVarK Sort) freeVars ; pr "In binding group; type constructors" freeVars ; env' <- return $ foldr (.) id (zipWith extTconstr freeVars vs) env0 ; r <- mapM (inferDataType gensym env') ds ; return (foldr (+|+) env r ) } -- data (Q x, P y) => T x y = C x y | D [y] x -- tpat = T x y -- ctxt = [Q x,P y] -- C :: Sch [*,*] (Q #0,P #1) (#0 -> #1 -> T #0 #1) -- D :: Sch [*,*] (Q #1,P #0) ([#0] -> #1 -> T #1 #0) inferDataType gensym env (Dec d) = case d of HsDataDecl sloc ctxt (tcon:targs) consdecls derivs -> do { pr "In Infer Data with " ((show tcon)++" -- "++(show targs)) ; let { tpat = foldl hsTyApp tcon targs } ; pairs <- mapM (\ nm -> do { k <- newVarK Sort; return(nm,k)}) (map getTyName targs) ; pr "pairs" pairs ; envd <- return $ (foldr (.) id (map (\ (nm,k) -> extTconstr nm k ) pairs)) env ; let kindCheck k x = (pr "in kindcheck " (show x)) >> inferK (getKindEnv envd) k x constrs (HsConDecl sloc consname btypes) = do { let types = (map unBang btypes) ; pr "constr is " ((show consname) ++" with "++(show (length types))) ; pr ("constr arity for" ++ (show consname)++": ") (length types) ; mapM (kindCheck star) types ; return (consname, foldr hsTyFun tpat types) } ; kindCheck star tpat ; mapM_ (kindCheck predicate) ctxt ; delta <- mapM constrs consdecls ; pr "delta" delta ; let delta2 = foldr (.) id (map (\ (nm,sch) -> extTrm nm sch) (map (hsType2Scheme (lookTconstr envd) ctxt) delta)) env0 ; return (delta2 +|+ env) } HsTypeDecl sloc (constr : args) body -> return(env) other -> error "not implemented yet" hsType2Scheme kenvd ps (nm,t) = let free (Typ (HsTyVar nm)) ans = union [nm] ans free (Typ t) ans = accT free t ans vars = free t [] sigma = zipWith (\ n nm -> (nm,TGen n)) [0..] vars t' = rebuild sigma t ps' = map (type2pred (rebuild sigma)) ps in (nm,Sch (map kenvd vars) ps' t') unBang (HsBangedType a) = a unBang (HsUnBangedType a) =a ------------------------------------------------------------------------------ extBGmono :: [HsDecl] -> IM a Error (NGV a,TEnv a,Constrs a,[(Type a,HsDecl)]) extBGmono ds = foldM extB ([],env0,[],[]) ds where extB (ngvars,env,cs,tds) (dec @ (Dec d)) = case d of HsPatBind s pat e ds -> do { ptype <- newVar starKind ; (ngv2,env2,cs2) <- inferPat pat ngvars env ptype ; return(ngv2,env2,cs2++cs,(ptype,dec):tds) } HsFunBind s matches -> do { let getname ((HsMatch sloc name ps rhs ds):_) = name name = getname matches ; ftype <- newVar starKind ; let env2 = lambdaExtTCE env name ftype ; return((name,ftype):ngvars,env2,cs,(ftype,dec):tds) } inferBG :: Genfun a -> NGV a -> TEnv a -> [HsDecl] -> IM a Error (NGV a,TEnv a, Constrs a) inferBG gensym ngv env [] = return(ngv,env,[]) inferBG gensym ngv env ds = do { (ngvDelta,envDelta,cs,tds) <- extBGmono ds ; let names = showl (map show (map fst ngvDelta)) "" ; cs2 <- foldM (inferEach gensym (ngvDelta++ngv) (envDelta +|+ env)) cs tds ; ps' <- sequence (map collapse cs2) ; ts' <- mapM collapse (map snd ( ngvDelta)) ; fs <- fmap concat (sequence (map (\ (name,t) -> tv t) ngv)) ; vss <- mapM tv ts' ; let inEveryT = foldr1 intersect vss gs = (foldr List.union [] vss) \\ fs -- In infered types, but not env -- at this point ps' holds all the constraints resulting from typing -- the whole binding group. envDelta holds an env with monomorphic types for -- just the names bound by the binding group, and ngvDelta pairs just those -- names with their types. ; ce <- ce0 ; (deferred,retained) <- reduce names ce fs inEveryT ps' ; let generic x = return True --(x `elem` gs) genSch (name,t) = do { sch <- quant generic (retained :=> t) ; return (name,sch) } getngv (x,Sch ks ps t) = (x,t) ; d2 <- mapM genSch ngvDelta ; delta2 <- return $ (foldr (.) id (map (uncurry extTrm) d2) (E [] [] [])) ; return (map getngv (getTermEnv delta2) ++ ngv,delta2 +|+ env,deferred) } quant :: (Ptr2 a -> IM a Error Bool) -> Qual a (Type a) -> IM a Error (Scheme a) quant generic (x @ (preds :=> typ)) = do { free <- newRef [] ; z <- col typ ; let genPred (IsIn c ts) = do {ts' <- mapM (gen generic free) ts ; return (IsIn c ts') } ; typ' <- gen generic free typ ; preds' <- mapM genPred preds ; theta <- readVar free ; x <- col typ' ; return $ Sch (map (\ (t,_,k) -> k) (reverse theta)) preds' x } inferEach gensym ngv env cs (t,Dec d) = do { case d of HsPatBind s pat rhs ds -> do { (ngv1,env1,cs1) <- inferDs gensym ngv env ds ; cs2 <- inferRhs ngv1 env1 t rhs ; return(cs1++cs2) } HsFunBind s matches -> foldM (infermatch t) cs matches other -> error "Only PatBind and FunBind allowed in inferEach" } where inferRhs ngv env hint (HsGuard gs) = foldM (inferGuard ngv env hint) cs gs inferRhs ngv env hint (HsBody e) = do { (etyp,cs2) <- infer gensym ngv env hint e ; return(cs2++cs) } inferGuard ngv env hint cs (srloc,guard,body) = do { (_,cs2) <- infer gensym ngv env tBool guard ; (_,cs3) <- infer gensym ngv env hint body ; return (cs3++cs2++cs) } infermatch hint cs (HsMatch sloc name ps rhs ds) = do { (ts,ngv1,env1,cs1) <- inferPats ps ngv env ; (ngv2,env2,cs2) <- inferDs gensym ngv1 env1 ds ; range <- newVar starKind ; cs3 <- unify hint (foldr tArrow range ts) ; cs4 <- inferRhs ngv2 env2 range rhs ; return(cs4++cs3++cs2++cs1++cs) } ------------------------------------------------------------------ ---------------------------------------------------------------------------------- -- inferStmt is used to infer the type of both Do stmts and list comprehensions -- [ A | p <- e ; f ] has the same structure as (do { P <- e; f ; A }) -- but the type rules differ slightly for both "A" and "f". We've parameterized -- inferStmt to handle this inferStmt :: Genfun a -> NGV a -> TEnv a -> Type a -> Type a -> Bool -> HsStmtR -> IM a Error [Pred a] inferStmt gensym ngvars env mtyp lasttyp isListComp stmt = let m x = (S(HsTyApp mtyp x)) in case stmt of HsGenerator p e next -> -- p <- e ; next do { ptyp <- newVar starKind ; (_,cs2) <- infer gensym ngvars env (m ptyp) e ; (ngv2,env2,cs3) <- inferPat p ngvars env ptyp ; cs4 <- inferStmt gensym ngv2 env2 mtyp lasttyp isListComp next ; return (cs2 ++ cs3 ++ cs4) } HsQualifier e next -> -- e ; next do { typ <- if isListComp then return tBool else fmap m (newVar starKind) ; (_,cs2) <- infer gensym ngvars env typ e ; return cs2 } HsLetStmt ds next -> -- let ds ; next do { (ngv2,env2,cs2) <- inferDs gensym ngvars env ds ; cs3 <- inferStmt gensym ngv2 env2 mtyp lasttyp isListComp next ; return (cs2 ++ cs3) } HsLast e -> do { (_,cs) <- infer gensym ngvars env lasttyp e; return cs } --------------------------------------------------------------------- -- The Parser produces HsQualType data structures, we must turn these -- into Scheme data structures, while doing to we should kind-check -- all the type information. hstype2Type :: HsType -> Type a hstype2Type (Typ x) = S(mapT hstype2Type x) -- Takes [ HsType ] representing qualifying predicates and a (HsType) -- and produces fresh Scheme for that annotation. used like -- ( x :: (P,Q) => t ) hsQual2freshSch:: HsTypeId HsType [HsType] -> IM a Error (Scheme a) hsQual2freshSch x = f (preds x) (types x) where preds (TypeQual ps x) = ps preds (TypeUnQual x) = [] types (TypeQual ps x) = x types (TypeUnQual x) = x f preds x = do { let names = freeNames [] x ; let g x = do { v <- newVar starKind; return(x,v) } ; sub <- mapM g names ; let x' = rebuild sub x preds' = map (type2pred (rebuild sub)) preds ; return(Sch [] preds' x') } ----------------------------------------------------------------- -- Helper functions for turning HsType into (Type a) and (Pred a) type2pred :: (HsType -> Type a) -> HsType -> Pred a type2pred g (Typ(HsTyApp (Typ(HsTyVar f)) x)) = IsIn f [g x] type2pred g (Typ(HsTyApp (Typ(HsTyCon f)) x)) = IsIn f [g x] type2pred g (Typ(HsTyApp f x)) = IsIn h ((g x): ys) where IsIn h ys = type2pred g f type2pred g x = error ("type2pred dies: " ++(show x)) freeNames :: [HsName] -> HsType -> [HsName] freeNames bound (Typ x) = case x of HsTyVar n -> if elem n bound then [] else [n] x -> accT f x [] where f x ans = union (freeNames bound x) ans rebuild :: [(HsName,Type a)] -> HsType -> Type a rebuild sub (Typ x) = case x of HsTyVar n -> case find (\ (x,y) -> x==n) sub of Just(_,v) -> v Nothing -> error "unknown type variable in signature" x -> S(mapT (rebuild sub) x) look ((y, e):ys) x = if x == y then e else look ys x look [] x = error "empty list in look" --------- Show Instances ---------------------------------- instance Show(Type a) where showsPrec n (S x) = shows x showsPrec n (TGen m) = showString "%" . shows m showsPrec n (TVar (m,r) k) = showString ("("++(show m)++",?)") instance Show(Pred a) where showsPrec m (IsIn n ts) = showString "(" . showsPrec m n . showString " " . shl ts . showString ")" shl [] ss = ss shl [x] ss = (showsPrec 0 x . showString " ") ss shl (x:xs) ss = showsPrec 0 x ( showString ", " (shl xs ss)) showl [] ss = ss showl [x] ss = showString (x++" ") ss showl (x:xs) ss = showString (x++", ") (showl xs ss) instance Show (Scheme a) where --show (Sch x p t) = "(all " ++ (showString (showList (nums x)"") "") ++"." ++ (show p) ++ " => " ++ (show t) ++ ")" showsPrec n (Sch x p t) = showString "(all " . showl (nums x) . showString "." . showsPrec n p . showString " => " . showsPrec n t . showString ")" where nums xs = ["%"++(show n) | n <- [0 .. (length xs - 1)]] toVis map (S x) = VS(map (toVis map) x) toVis map (TGen n) = VN("v" ++ (show n)) toVis map (TVar _ _) = VN "?" visKind = toVis mapK visType = toVis mapT data Vis s = VS (s (Vis s)) | VN String instance Show (Vis T) where show (VN gen) = gen show (VS tstruct) = show tstruct instance Show (Vis K) where show (VN gen) = gen show (VS tstruct) = show tstruct instance Show (Kind a) where show t = show(visKind t) --------------------------------------------- a:b:c:d:_ = [ TGen i | i <- [0..] ] simpleEnv = [(UnQual "+",Sch[star] [num a] (tArrow a (tArrow a a))) ,(UnQual "*",Sch[star] [num a] (tArrow a (tArrow a a))) ,(UnQual "-",Sch[star] [num a] (tArrow a (tArrow a a))) ,(UnQual ":",Sch[star,star] [] (tArrow a (tArrow (tlist a) (tlist a)))) ,(UnQual "True",Sch[] [] tBool) ,(UnQual "False",Sch[] [] tBool) ] --------------------------------------------------------------- -- a declaration like -- type T a b = (a,b -> Int) -- is stored in an environment with type [(HsName,([HsName],HsType))] -- e.g. (T,([a,b],(a,b -> Int))) :: more -- expandType walks over a type. At every application it tests if that application -- matches some fully applied instance of (T a b). Suppose it does and looks like -- (T Int String). Then we build a substitution [(a,Int),(b,String)] and apply -- it to (a,b -> Int). If it doesn't, we just recursively expand the sub-types. expandType :: [(HsName,([HsName],HsType))] -> HsType -> Type a expandType env (x @ (Typ(HsTyApp f a))) = case matchApp env x of Nothing -> S(HsTyApp (expandType env f) (expandType env a)) expandType env (Typ x) = S(mapT (expandType env) x) matchApp :: [(HsName,([HsName],HsType))] -> HsType -> Maybe (Type a) matchApp env t = walkSpine t [] where walkSpine (Typ(HsTyApp x y)) ts = walkSpine x (expandType env y : ts) walkSpine (Typ(HsTyCon nm)) ts = applySub nm env ts walkSpine _ ts = Nothing applySub nm env ts = case lookup nm env of Nothing -> Nothing Just(vs,t) -> if length vs == length ts then Just(rebuild (zip vs ts) t) else Nothing -------------------------------------------------------- class TCEnv env where extTconstr :: HsName -> GT K Sort (STRef a) -> env a -> env a extTySyn :: HsName -> [HsName] -> Type a -> env a -> env a extTrm :: HsName -> Scheme a -> env a -> env a lookTconstr :: env a -> HsName -> GT K Sort (STRef a) lookTySyn :: env a -> HsName -> ([HsName],Type a) lookTrm :: env a -> HsName -> Scheme a lookTconstrOpt :: env a -> HsName -> Maybe (GT K Sort (STRef a)) lookTySynOpt :: env a -> HsName -> Maybe ([HsName],Type a) lookTrmOpt :: env a -> HsName -> Maybe (Scheme a) getKindEnv :: env a -> [(HsName, GT K Sort (STRef a))] getTermEnv :: env a -> [(HsName, Scheme a)] env0 :: env a data TEnv a = E { typeSyns :: [(HsName, ([HsName], Type a))] , termEnv :: [(HsName, Scheme a)] , kindEnv :: [(HsName,GT K Sort (STRef a))] } deriving Show (E a b c) +|+ (E d e f) = E (a++d) (b++e) (c++f) instance TCEnv TEnv where env0 = E [] [] [] extTconstr n t env = env { kindEnv = (n,t) : kindEnv env } extTySyn n ns t env = env { typeSyns = (n, (ns,t)) : typeSyns env } extTrm n sch env = env { termEnv = (n,sch) : termEnv env} lookTconstr env n = case lookup n (kindEnv env) of Just x -> x Nothing -> error $ "Not found: "++(show n) lookTySyn env n = case lookup n (typeSyns env) of Just x -> x Nothing -> error $ "Not found: type synonym " ++ (show n) lookTrm env n = case lookup n (termEnv env) of Just x -> x Nothing -> error $ "Not found: no type for " ++ (show n) getKindEnv env = kindEnv env getTermEnv env = termEnv env ---------------------------------------------------------
forste/haReFork
tools/base/TC/TypeCheck.hs
bsd-3-clause
48,711
124
72
15,843
19,219
9,904
9,315
-1
-1
{-# LANGUAGE Unsafe #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign -- Copyright : (c) The FFI task force 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : portable -- -- A collection of data types, classes, and functions for interfacing -- with another programming language. -- ----------------------------------------------------------------------------- module Foreign ( module Data.Bits , module Data.Int , module Data.Word , module Foreign.Ptr , module Foreign.ForeignPtr , module Foreign.StablePtr , module Foreign.Storable , module Foreign.Marshal ) where import Data.Bits import Data.Int import Data.Word import Foreign.Ptr import Foreign.ForeignPtr import Foreign.StablePtr import Foreign.Storable import Foreign.Marshal
frantisekfarka/ghc-dsi
libraries/base/Foreign.hs
bsd-3-clause
1,016
0
5
205
110
76
34
19
0
module Definition where seven :: Int seven = 7
charleso/intellij-haskforce
tests/gold/codeInsight/QualifiedImport_QualifierResolvesMultipleCons_Cons2/Definition.hs
apache-2.0
47
0
4
9
14
9
5
3
1
module Unused.UtilSpec ( main , spec ) where import Test.Hspec import Unused.Util data Person = Person { pName :: String , pAge :: Int } deriving (Eq, Show) main :: IO () main = hspec spec spec :: Spec spec = parallel $ do describe "groupBy" $ do it "groups by the result of a function" $ do let numbers = [1 .. 10] :: [Int] groupBy ((0 ==) . flip mod 2) numbers `shouldBe` [(False, [1, 3, 5, 7, 9]), (True, [2, 4, 6, 8, 10])] it "handles records" $ do let people = [Person "Jane" 10, Person "Jane" 20, Person "John" 20] groupBy pName people `shouldBe` [("Jane", [Person "Jane" 10, Person "Jane" 20]), ("John", [Person "John" 20])] groupBy pAge people `shouldBe` [(10, [Person "Jane" 10]), (20, [Person "Jane" 20, Person "John" 20])] describe "stringToInt" $ it "converts a String value to Maybe Int" $ do stringToInt "12345678" `shouldBe` Just 12345678 stringToInt "0" `shouldBe` Just 0 stringToInt "10591" `shouldBe` Just 10591 stringToInt "bad" `shouldBe` Nothing
joshuaclayton/unused
test/Unused/UtilSpec.hs
mit
1,255
0
18
454
436
235
201
31
1
{-# LANGUAGE RankNTypes #-} module Yabi.Engine ( run , initWorld ) where import Control.Monad.Trans import Data.ByteString import Control.Lens import System.IO (stdin, stdout) import Data.Word import Prelude hiding (null, head) import qualified Data.Stream as S import Yabi.Types initWorld :: World initWorld = World (S.repeat 0) 0 (S.repeat 0) run :: [Inst] -> VM () run [] = return () run (x:xs) = inst x >> run xs shift :: Lens' World (S.Stream Word8) -> VM Word8 shift g = g %%= \(S.Cons x xs) -> (x, xs) unshift :: Word8 -> Lens' World (S.Stream Word8) -> VM () unshift x g = g %= S.Cons x inst :: Inst -> VM () inst Next = do c <- use here r <- shift right unshift c left here .= r inst Prev = do c <- use here l <- shift left unshift c right here .= l inst Incr = here += 1 inst Decr = here -= 1 inst GetC = do bs <- liftIO $ hGet stdin 1 here .= if null bs then -1 else head bs inst PutC = do c <- use here liftIO $ hPut stdout (pack [c]) inst (Loop blk) = do c <- use here if c == 0 then return () else run blk >> inst (Loop blk)
L8D/yabi
lib/Yabi/Engine.hs
mit
1,130
0
11
308
542
270
272
43
3
{-# LANGUAGE RecordWildCards #-} module Control.FRPNow.Vty.Widgets where import Control.FRPNow.Vty.Core import Control.FRPNow import Graphics.Vty hiding (Event) import Control.Applicative import Data.Monoid data Widget = Widget { widgetLocation :: (Int,Int) , widgetChildrean :: [Widget] , widgetImage :: Image , widgetRegion :: DisplayRegion , widgetVisible :: Bool } type MakeWidget = Behavior DisplayRegion -> Behavior Bool -> Behavior (Behavior Widget) originWidget = Widget (0,0) makeWidget :: Behavior DisplayRegion -> Behavior Bool -> MakeWidget -> Behavior (Behavior Widget) makeWidget bD bVis w = w bD bVis drawWidget :: Widget -> Picture drawWidget = picForLayers . helper where helper Widget{..} | widgetVisible = map (uncurry translate (widgetLocation)) $ widgetImage : concatMap helper widgetChildrean | otherwise = [] keyToQuit :: Key -> EvStream VEvent -> Behavior DisplayRegion -> MakeWidget -> Behavior (Behavior Widget) keyToQuit k eEv bDis mW = next (filterEs (isKey k) eEv) >>= mW bDis . flip (cstep True) False runWidget :: (EvStream VEvent -> Behavior Double -> Behavior DisplayRegion -> Now (Behavior Widget)) -> IO () runWidget f = runVTY $ \eEv bT bD -> do masterWidget <- f eEv bT bD endEv <- sampleNow $ when $ (not . widgetVisible) <$> masterWidget return (endEv, drawWidget <$> masterWidget) tabbingWidget :: EvStream a -> EvStream b -> [MakeWidget] -> MakeWidget tabbingWidget eUp eDown ws bDis bVis = do let sz = length ws eNum <- fmap (\x -> mod x sz) <$> foldEs (+) 0 ((1 <$ eDown) <> ((-1) <$ eUp)) children <- sequence $ zipWith (\f n -> f bDis ((== n) <$> eNum)) ws [0..] return $ originWidget <$> sequence children <*> pure mempty <*> bDis <*> bVis horzPane :: Int -> MakeWidget -> MakeWidget -> MakeWidget horzPane = paneWidget (\d (x,y) -> (x+d,y)) vertPane :: Int -> MakeWidget -> MakeWidget -> MakeWidget vertPane = paneWidget (\d (x,y) -> (x,y+d)) paneWidget :: (Int -> (Int,Int) -> (Int,Int) ) -> Int -> MakeWidget -> MakeWidget -> MakeWidget paneWidget fTran n w1 w2 bDis bVis = do c1 <- makeWidget bDis bVis w1 c2 <- fmap (\w -> w {widgetLocation = fTran n (widgetLocation w)}) <$> makeWidget bDis bVis w2 return $ originWidget <$> sequence [c1,c2] <*> pure mempty <*> bDis <*> bVis simpleWidget :: Image -> MakeWidget simpleWidget i bDis bVis = return $ Widget (0,0) [] i <$> bDis <*> bVis
edwardwas/FRPNow-Vty
src/Lib/Control/FRPNow/Vty/Widgets.hs
mit
2,475
0
16
518
974
505
469
47
1
module Main where import qualified LLVM.General.Module as M import LLVM.General.Context import LLVM.General.PrettyPrint import LLVM.General.Pretty (ppllvm) import Control.Monad (filterM) import Control.Monad.Except import Data.Functor import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as T import System.IO import System.Exit import System.Directory import System.FilePath import System.Environment ------------------------------------------------------------------------------- -- Harness ------------------------------------------------------------------------------- readir :: FilePath -> IO () readir fname = do putStrLn $ "Test: " ++ fname putStrLn $ replicate 80 '=' putStrLn fname putStrLn $ replicate 80 '=' str <- readFile fname withContext $ \ctx -> do res <- runExceptT $ M.withModuleFromLLVMAssembly ctx str $ \mod -> do ast <- M.moduleAST mod putStrLn $ showPretty ast let str = ppllvm ast T.putStrLn str trip <- runExceptT $ M.withModuleFromLLVMAssembly ctx (T.unpack str) (const $ return ()) case trip of Left err -> do print err exitFailure Right ast -> putStrLn "Round Tripped!" case res of Left err -> print err Right _ -> return () main :: IO () main = do putStrLn "Running test suite:" files <- getArgs case files of [] -> do dircontents <- map (combine "tests") <$> getDirectoryContents "tests" dirfiles <- filterM doesFileExist dircontents mapM readir dirfiles _ -> mapM readir files putStrLn "All good." return ()
sdiehl/llvm-pp
Main.hs
mit
1,610
0
22
347
479
235
244
49
3
{-# LANGUAGE TupleSections #-} module ProjectEuler.Problem82 ( problem ) where import Control.Monad import Petbox import qualified Data.Array.ST as A import qualified Data.Array.Unboxed as A import qualified Data.Text as T import ProjectEuler.GetData problem :: Problem problem = pureProblemWithData "p082_matrix.txt" 82 Solved compute getMat :: T.Text -> A.UArray (Int,Int) Int getMat raw = A.array ((1,1), (rowN,colN)) genPairs where raws = map parseLine . lines . T.unpack $ raw parseLine s = read ("[" ++ s ++ "]") :: [Int] colN = length (head raws) rowN = length raws genPairs = concat $ add2DCoords 1 1 raws pathSum :: A.UArray (Int,Int) Int -> A.UArray (Int,Int) Int pathSum mat = A.runSTUArray $ do mary <- A.newArray bd 0 -- initialize the first col forM_ [1..rowN] $ \row -> A.writeArray mary (row,1) (mat A.! (row,1)) forM_ [2..colN-1] $ \col -> do -- update from previous col forM_ [1..rowN] $ \row -> do v <- A.readArray mary (row,col-1) A.writeArray mary (row,col) (v + mat A.! (row,col)) -- update from ups forM_ [2..rowN] $ \row -> do vUp <- (mat A.! (row,col) +) <$> A.readArray mary (row-1,col) v <- A.readArray mary (row,col) A.writeArray mary (row,col) (min v vUp) -- update from downs forM_ [rowN-1,rowN-2..1] $ \row -> do vDn <- (mat A.! (row,col) +) <$> A.readArray mary (row+1,col) v <- A.readArray mary (row,col) A.writeArray mary (row,col) (min v vDn) -- the last col forM_ [1..rowN] $ \row -> ((mat A.! (row,colN) +) <$> A.readArray mary (row,colN-1)) >>= A.writeArray mary (row,colN) pure mary where bd@(_,(rowN,colN)) = A.bounds mat compute :: T.Text -> Int compute = getResult . pathSum . getMat where getResult arr = minimum (map ((arr A.!). (,colN) ) [1..rowN]) where (_,(rowN,colN)) = A.bounds arr
Javran/Project-Euler
src/ProjectEuler/Problem82.hs
mit
1,992
0
20
539
874
473
401
44
1
module Language.Meta.C.Parser {- ( TheParser, -- TODO: make it generic blank, blanks, lx, symbol, parens, braces, angles, keyword, eitherP, comma, colon, semicolon, equal, -- TODO: move them to more common module nonEmptyListP, -- TODO: amend this ugly utility nonEmptyListFollowedByP, nonEmptyCommaListP, nonEmptyOptionalCommaListP, negligibleP, idP, literalP, enumerationConstantP ) -} where import Text.Parsec import Text.Parsec.Combinator (manyTill) import Control.Applicative hiding ((<|>), many, optionMaybe, optional) import Control.Monad.Identity (Identity) import qualified Language.Meta.SExpr as S import Language.Meta.C.Literal import Language.Meta.C.AST import Language.Meta.SExpr import qualified Data.Set as Set -- the type of parser type TheParser = ParsecT String () Identity blank :: TheParser Char blank = space -- oneOf "  \t\r\n" blanks :: TheParser () blanks= skipMany blank >> pure () lx :: TheParser a -> TheParser a lx p = p <* blanks symbol :: String -> TheParser String symbol = try . lx . string parens :: TheParser a -> TheParser a parens = between (symbol "(") (symbol ")") braces :: TheParser a -> TheParser a braces = between (symbol "{") (symbol "}") angles :: TheParser a -> TheParser a angles = between (symbol "[") (symbol "]") keyword :: String -> TheParser String keyword s = try (lx $ string s <* notFollowedBy (alphaNum <|> char '_')) -- type NonEmptyList a = (a, [a]) nonEmptyListP :: TheParser a -> TheParser (NonEmptyList a) nonEmptyListP p = NonEmptyList <$> ((,) <$> (try p) <*> many (try p)) nonEmptyListFollowedByP :: TheParser a -> TheParser () -> TheParser (NonEmptyList a) nonEmptyListFollowedByP ap bp = NonEmptyList <$> ((,) <$> try ap <*> many ((notFollowedBy (try bp)) >> try ap)) nonEmptyCommaListP :: TheParser a -> TheParser (NonEmptyList a) nonEmptyCommaListP p = NonEmptyList <$> ((,) <$> (try p) <*> many (try $ comma >> p)) nonEmptyOptionalCommaListP :: TheParser a -> TheParser (NonEmptyList a) nonEmptyOptionalCommaListP p = sepEndBy1 (try p) comma >>= \(car:cdr) -> pure (NonEmptyList (car, cdr)) eitherP :: TheParser a -> TheParser b -> TheParser (Either a b) eitherP a b = Left <$> try a <|> Right <$> try b comma :: TheParser () comma = symbol "," >> pure () colon :: TheParser () colon = symbol ":" >> pure () semicolon :: TheParser () semicolon = symbol ";" >> pure () equal :: TheParser () equal = symbol "=" >> pure () reservedSet :: Set.Set String reservedSet = Set.fromList [ "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", "_Bool", "_Complex", "_Imaginary"] -- cheap subset of CPP negligibleP :: TheParser Negligible negligibleP = NegligibleMacro <$> ((++) <$> string "#" <*> many (noneOf "\r\n")) <|> NegligibleComment <$> try (string "/" >> ((++) "//" <$> (string "/" >> many (noneOf "\r\n")) <|> (\s -> "/*" ++ s ++ "*/") <$> (string "*" >> manyTill anyChar (try (string "*/"))))) -- data Id = Id String idP :: TheParser Id idP = lx (try (lookAhead carSExprP >> (sExprP cdrP <?> "sExpr")) >>= \sexpr -> case sexpr of SList [(SString s)] -> Id <$> checkReserved s _ -> pure (WildId sexpr)) where checkReserved ('$':_) = parserZero checkReserved s = if Set.member s reservedSet then parserZero else pure s carSExprP = oneOf (letters ++ "_$") --carP = oneOf (letters ++ "_") cdrP = oneOf (letters ++ ['0'..'9'] ++ "_") letters = ['a'..'z'] ++ ['A'..'Z'] -- data Literal = -- LiteralInt IntegerConstant -- | LiteralChar CharConstant -- | LiteralString String -- | LiteralFloat FloatingConstant -- | LiteralEnumConst String literalP :: TheParser Literal literalP = lx . choice $ map try [ LiteralString <$> stringLiteralP, LiteralChar <$> charConstantP, LiteralFloat <$> floatingConstantP, LiteralInt <$> integerConstantP, LiteralEnumConst <$> enumerationConstantP ] enumerationConstantP :: TheParser EnumerationConstant enumerationConstantP = idP >>= \(Id str) -> pure (EnumerationConstant str) charConstantP :: TheParser CharConstant charConstantP = WideCharConstant <$> (string "L'" >> charSequenceP quote) <|> CharConstant <$> (char quote >> charSequenceP quote) where quote = '\'' stringLiteralP :: TheParser StringLiteral stringLiteralP = WideStringLiteral <$> ((foldl (++) "" <$> many1 (lx $ string "L\"" >> charSequenceP quote)) >>= pure . S.parseSExpr "wide string literal") -- TODO: is the concat right? <|> StringLiteral <$> ((foldl (++) "" <$> many1 (lx $ char quote >> charSequenceP quote)) >>= pure . S.parseSExpr "string literal") where quote = '"' charSequenceP :: Char -> TheParser String charSequenceP quote = charSequenceP' False [] where charSequenceP' :: Bool -> String -> TheParser String charSequenceP' escaping str | escaping = anyChar >>= \c -> charSequenceP' False (c:str) | otherwise = anyChar >>= \c -> case c of x | x == quote -> pure (reverse str) | otherwise -> charSequenceP' (c == '\\') (c:str) integerConstantP :: TheParser IntegerConstant integerConstantP = DecimalConstant <$> decimalConstantP <*> integerSuffixP <|> (string "0" >> (((oneOf "xX" >> (HexadecimalConstant <$> hexadecimalConstantP <*> integerSuffixP)) <|> OctalConstant <$> octalConstantP <*> integerSuffixP) <|> DecimalConstant "0" <$> integerSuffixP)) where decimalConstantP = (:) <$> natDigit <*> many digit hexadecimalConstantP = many1 hexDigit octalConstantP = many1 octDigit integerSuffixP :: TheParser [IntegerSuffix] integerSuffixP = choice [ glue <$> unsignedSuffixP <*> optionMaybe longlongSuffixP, glue <$> unsignedSuffixP <*> optionMaybe longSuffixP, glue <$> longlongSuffixP <*> optionMaybe unsignedSuffixP, glue <$> longSuffixP <*> optionMaybe unsignedSuffixP ] <|> pure [] where glue a b = a:(maybe [] pure b) longlongSuffixP = try (LongLongSuffix <$ (string "ll" <|> string "LL")) longSuffixP = LongSuffix <$ oneOf "lL" unsignedSuffixP = UnsignedSuffix <$ oneOf "uU" floatingConstantP :: TheParser FloatingConstant floatingConstantP = try (string "0" >> oneOf "xX" >> (HexadecimalFloatingConstant <$> hexadecimalFractionalConstantP <*> binaryExponentP <*> optionMaybe floatingSuffixP)) <|> DecimalFloatingConstant <$> fractionalConstantP <*> optionMaybe exponentPartP <*> optionMaybe floatingSuffixP fractionalConstantP :: TheParser FractionalConstant fractionalConstantP = many digit >>= \mantissa -> string "." >> many digit >>= \floating -> case floating of [] -> case mantissa of [] -> parserZero _ -> pure (MantissaConstant mantissa) _ -> case mantissa of [] -> pure (FractionalConstant Nothing floating) _ -> pure (FractionalConstant (Just mantissa) floating) hexadecimalFractionalConstantP :: TheParser HexadecimalFractionalConstant hexadecimalFractionalConstantP = many digit >>= \mantissa -> string "." >> many digit >>= \floating -> case floating of [] -> case mantissa of [] -> parserZero _ -> pure (HexadecimalMantissaConstant mantissa) _ -> case mantissa of [] -> pure (HexadecimalFractionalConstant Nothing floating) _ -> pure (HexadecimalFractionalConstant (Just mantissa) floating) exponentPartP :: TheParser ExponentPart exponentPartP = ExponentPart <$> (oneOf "eE" >> optionMaybe floatingConstantSignP) <*> many1 digit binaryExponentP :: TheParser BinaryExponentPart binaryExponentP = BinaryExponentPart <$> (oneOf "pP" >> optionMaybe floatingConstantSignP) <*> many1 digit floatingConstantSignP :: TheParser FloatingConstantSign floatingConstantSignP = FloatingConstantSignPlus <$ string "+" <|>FloatingConstantSignMinus <$ string "-" floatingSuffixP :: TheParser FloatingSuffix floatingSuffixP = FloatSuffix <$ oneOf "fF" <|> LongDoubleSuffix <$ oneOf "lL" natDigit :: TheParser Char natDigit = oneOf ['1'..'9']
ykst/MetaC
Language/Meta/C/Parser.hs
mit
8,434
0
19
1,733
2,530
1,305
1,225
165
4
import Control.Monad main = do line <- getLine let n = read line :: Int forM_ [0..n-1] (\i -> do putStr $ take i (repeat ' ') putStrLn $ take (2*(n-i)-1) (repeat '*'))
Voleking/ICPC
references/aoapc-book/BeginningAlgorithmContests/haskell/ch2/ex2-4.hs
mit
183
0
18
48
112
55
57
7
1
module P2 where p2 :: [a] -> Maybe a p2 [] = Nothing p2 [x] = Nothing p2 [x,_] = Just x p2 (_:xs) = p2 xs
nosoosso/nnh
src/P2.hs
mit
107
0
7
28
75
40
35
6
1
module SuperUserSpark ( spark ) where import Import import SuperUserSpark.Bake import SuperUserSpark.Check import SuperUserSpark.Compiler import SuperUserSpark.Deployer import SuperUserSpark.Diagnose import SuperUserSpark.OptParse import SuperUserSpark.Parser spark :: IO () spark = getDispatch >>= dispatch dispatch :: Dispatch -> IO () dispatch (DispatchParse pas) = parseFromArgs pas dispatch (DispatchCompile cas) = compileFromArgs cas dispatch (DispatchBake bas) = bakeFromArgs bas dispatch (DispatchDiagnose bas) = diagnoseFromArgs bas dispatch (DispatchCheck cas) = checkFromArgs cas dispatch (DispatchDeploy das) = deployFromArgs das
NorfairKing/super-user-spark
src/SuperUserSpark.hs
mit
654
0
7
85
182
94
88
19
1
module Global where -- The proportion (in length) of the area where points are generated coverage :: Float coverage = 1.0 -- 0.5 -- The relative size of the text textscale :: Float textscale = 0.005 -- The window title windowtitle = "Algebra" -- The size of the window in pixels pixelSize :: (Int,Int) pixelSize = (900,700) -- The initial position of the window in the screen windowPosition :: (Int,Int) windowPosition = (10,10) -- The model coordinates of the shown area modelSize :: Float modelSize = 10.0
alphalambda/k12math
prog/lib/alg/Global.hs
mit
516
0
5
95
90
59
31
12
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Types import Parser import Step import System.Exit import System.Environment import Control.Monad import Data.Attoparsec.ByteString.Char8 hiding (take) import qualified Data.ByteString.Char8 as B main :: IO () main = do putStrLn "GERMS!" (f:_) <- getArgs txt <- readFile f ds <- case readDefinitions txt of Left err -> putStrLn err >> exitFailure Right ds -> return ds putStrLn $ unwords ["Definitions:", show ds] g <- case defsToGame ds of Left err -> putStrLn err >> exitFailure Right g -> return g --_ <- forkIO $ do _ <- getLine -- exitSuccess loop g loop :: Game -> IO () loop g = do let g' = stepGame g b = gameBoard g b' = gameBoard g' s = unlines $ zipWith (\l r -> l ++ pad l ++ " | " ++ r) (lines $ show b) (lines $ show b') pad a = replicate (boardWidth b - length a) ' ' putStrLn s ch <- getChar when (ch == 'q') exitSuccess if b == b' then putStrLn $ unwords [ "Reached stasis after" , show $ gameSteps g , "steps." ] else loop g' readDefinitions :: String -> Either String [Definition] readDefinitions = parseOnly definitions . B.pack readGame :: String -> Either String Game readGame = parseOnly game . B.pack
schell/germs
src/Main.hs
mit
1,530
0
17
562
472
235
237
42
3
module Main where import System.Directory (createDirectoryIfMissing) import System.Environment (getArgs) import Data.List (isPrefixOf) import Arguments import Compiler import Deployer import Dispatch import Formatter import Parser import Paths import Types import Utils main :: IO () main = do checkSystemConsistency (di, config) <- getInstructions er <- runSparker config $ dispatch di case er of Left err -> die $ showError err Right _ -> return () spark :: StartingSparkReference -> Sparker () spark ssr = do cs <- parseStartingCardReference ssr fcs <- formatCards cs debug fcs dp <- compile (head cs) cs debug $ formatDeployments dp deploy dp showError :: SparkError -> String showError (ParseError err) = show err showError (CompileError err) = err showError (DeployError err) = case err of PreDeployError ss -> unlines ss DuringDeployError ss -> unlines ss PostDeployError ss -> unlines ss showError (UnpredictedError err) = "Panic: " ++ err showError (GitError err) = show err checkSystemConsistency :: IO () checkSystemConsistency = do dir <- sparkDir createDirectoryIfMissing True dir
plietar/super-user-spark
src/Main.hs
mit
1,330
0
11
397
387
188
199
43
3
module EilerGenAlg where import BitOperations import CongruentGenerator import Control.Lens import Data.Graph import Data.List import EilerGraph import GenAlgEngine import Individual import GaGraph import qualified BitStringIndRunner as BSR defaultGenAlgContext = GenAlgContext {_rndContext = simpleRndContext 100, _mutationProb = 15, _crossoverProb = 60, _maxCount = 100000, _count = 0} defaultGenAlgContext2 :: Int -> GenAlgContext defaultGenAlgContext2 token = GenAlgContext {_rndContext = simpleRndContext token, _mutationProb = 15, _crossoverProb = 60, _maxCount = 5000, _count = 0} runEilerGaFine :: Graph -> Int -> (Int,[Int]) runEilerGaFine g pop = let (count, result) = runEilerGa g pop in (count, map (+1) result) runEilerGa :: Graph -> Int -> (Int,[Int]) runEilerGa g popSize = let (count, result) = runGA defaultGenAlgContext (eilerFirstGen g popSize) (eilerPathFound g) in (count, fetchResult result) runEilerGa2 :: Graph -> Int -> (Int,[Int]) runEilerGa2 g popSize = let (count, result) = BSR.processGAPop popSize (maxEilerFitnesse g) (pathDimension g) (eilerInd g) in (count, fetchResult result) runEilerGaGen :: Graph -> Int -> (Int,[Int]) runEilerGaGen g popSize = let (count, result) = runGA defaultGenAlgContext (eilerFirstGen g popSize) (eilerPathFound g) in (count, map genome result) runEilerGaPhen :: Graph -> Int -> (Int,[[Int]]) runEilerGaPhen g popSize = let (count, result) = runGA defaultGenAlgContext (eilerFirstGen g popSize) (eilerPathFound g) in (count, map ((map (+1)).eilerPhenotype) result) runEilerGaFit :: Graph -> Int -> (Int,[Int]) runEilerGaFit g popSize = let (count, result) = runGA defaultGenAlgContext (eilerFirstGen g popSize) (eilerPathFound g) in (count, map fitnesse result) fetchResult :: [EilerGraph] -> [Int] fetchResult result = case find isEilerPath result of Nothing -> [] Just eg -> eilerPhenotype eg ---factory func eilerFirstGen :: Graph -> Int -> GenAlgContext -> ([EilerGraph], GenAlgContext) eilerFirstGen g count ctx = let (rands, newCtx) = randVector count (powOfTwo $ pathDimension g) $ ctx^.rndContext in (eilerInds g rands, ctx&rndContext.~newCtx) ---stop function eilerPathFound :: Graph -> [EilerGraph] -> Bool eilerPathFound g = maxFitnesseStop $ maxEilerFitnesse g maxEilerFitnesse :: Graph -> Int maxEilerFitnesse = edgesNum isEilerPath :: EilerGraph -> Bool isEilerPath eg = fitnesse eg == (maxEilerFitnesse $ graph eg) ---help functions eilerInds :: Graph -> [Int] -> [EilerGraph] eilerInds g = map (eilerInd g) eilerInd :: Graph -> Int -> EilerGraph eilerInd g gn = EilerGraph{graph = g, genome = gn}
salamansar/GA-cube
src/EilerGenAlg.hs
mit
2,759
0
14
539
942
512
430
58
2
{-#LANGUAGE TemplateHaskell, ScopedTypeVariables, BangPatterns, TupleSections#-} {-#OPTIONS -fllvm -optlo-mem2reg -optlc-O3 -fexcess-precision -msse2 -funbox-strict-fields#-} module Main where import Numeric.Optimization.Algorithms.DifferentialEvolution import qualified Data.Vector.Unboxed as VUB import qualified Data.Vector as V import Data.Vector.Unboxed ((!)) import Data.List import Utils.List import Control.Arrow import System.Random.MWC import System.Environment import System.Directory import Utils.File import Data.Label import Data.Monoid import Graphics.Gnuplot.Simple import qualified Data.DList as DL f4 dim = VUB.sum . VUB.map (\x -> x*x-10*cos(2*pi*x)+10) f4b dim = (VUB.replicate dim (-6) ,VUB.replicate dim (6)) fsphere :: Int -> VUB.Vector Double -> Double fsphere dim = VUB.sum . VUB.map (**2) createSeed fls = initialize (VUB.fromList fls) >>= save main = do seed <- createSeed [11..256] let params0 = (defaultParams (f4 10) (f4b 10) (DL.singleton . currentBest)) let params1 = (defaultParams (f4 10) (f4b 10) (DL.singleton . currentBest)) {destrategy = Prox1Bin 0.3 0.7} w <- de params0 seed w2 <- de params1 seed plotLists [Custom "logscale" ["y"]] $ [map fst . DL.toList $ w, map fst . DL.toList $ w2] let ds = transpose . map VUB.toList . map snd $ DL.toList w plotListsStyle [Custom "logscale" ["y"]] (map (defaultStyle{plotType = Points},) ds) --[map abs . decreasing . DL.toList $ f, DL.toList s]
alphaHeavy/differential-evolution
Test2.hs
mit
1,497
0
15
260
524
280
244
34
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Model.Types where import ClassyPrelude.Yesod hiding (show, Read) import Data.Aeson (withObject) import qualified Data.ByteString.Base64 as B64 import qualified Data.Serialize as Cereal import qualified Data.Text import Database.Persist.Sql as DB import Network.Mail.Mime (randomString) import Prelude (Show (show), Read (readsPrec)) import System.Random (Random, randomR, random) import Text.Blaze.Html (ToMarkup (..)) import Data.Data -- | A Git blob SHA in textual form. newtype BlobSHA = BlobSHA { unBlobSHA :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql BlobSHA where sqlType = sqlType . liftM unBlobSHA -- | A Git commit SHA in textual form. newtype CommitSHA = CommitSHA { unCommitSHA :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql CommitSHA where sqlType = sqlType . liftM unCommitSHA data SHAPair = SHAPair !CommitSHA !BlobSHA deriving (Show, Read, Eq) instance PersistField SHAPair where toPersistValue (SHAPair x y) = toPersistValue $ unwords [toPathPiece x, unBlobSHA y] fromPersistValue v = case fromPersistValue v of Left e -> Left e Right t | [x, y] <- words t -> Right $ SHAPair (CommitSHA x) (BlobSHA y) Right _ -> Left "Invalid SHAPair" instance PersistFieldSql SHAPair where sqlType _ = SqlString newtype Title = Title { unTitle :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql Title where sqlType = sqlType . liftM unTitle newtype UserHandle = UserHandle { unUserHandle :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql UserHandle where sqlType = sqlType . liftM unUserHandle newtype NormalizedHandle = NormalizedHandle { unNormalizedHandle :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql NormalizedHandle where sqlType = sqlType . liftM unNormalizedHandle newtype TutorialName = TutorialName { unTutorialName :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql TutorialName where sqlType = sqlType . liftM unTutorialName newtype TutorialContent = TutorialContent' { unTutorialContent :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql TutorialContent where sqlType = sqlType . liftM unTutorialContent newtype SecurityToken = SecurityToken { unSecurityToken :: Text } deriving (Show, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql SecurityToken where sqlType = sqlType . liftM unSecurityToken -- | Constant time equality to avoid timing attacks. instance Eq SecurityToken where SecurityToken x == SecurityToken y = all (uncurry (==)) (Data.Text.zip x y) && length x == length y newtype DeletionToken = DeletionToken { unDeletionToken :: Text } deriving (Eq, Show, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql DeletionToken where sqlType = sqlType . liftM unDeletionToken type TutorialNames = [TutorialName] instance PathMultiPiece TutorialNames where toPathMultiPiece = map toPathPiece fromPathMultiPiece = mapM fromPathPiece slugify :: IsSlug a => Text -> Either Text a slugify t = case normalizeHandle (UserHandle t) of Left e -> Left $ pack $ show e Right (NormalizedHandle h) -> Right $ toSlug h class IsSlug a where toSlug :: Text -> a instance IsSlug TutorialName where toSlug = TutorialName data NormalizeFailure = NFTooShort | NFInvalidCharacters instance Show NormalizeFailure where show NFTooShort = "Must be at least three characters" show NFInvalidCharacters = "Must be the letters a-z, digits, hyphens and underscores" normalizeHandle :: UserHandle -> Either NormalizeFailure NormalizedHandle normalizeHandle (UserHandle t') | length t' < 3 = Left NFTooShort | all isValid t = Right $ NormalizedHandle t | otherwise = Left NFInvalidCharacters where t = toLower t' isValid c | 'a' <= c && c <= 'z' = True | '0' <= c && c <= '9' = True | c == '-' || c == '_' || c == '.' = True | otherwise = False titleToSlug :: Title -> Text titleToSlug = minLength . intercalate "-" . words . omap valid . toLower . unTitle where minLength x = take (max 3 $ length x) $ x ++ "123" valid c | 'a' <= c && c <= 'z' = c | '0' <= c && c <= '9' = c | otherwise = ' ' instance Random SecurityToken where randomR = const random random = first (SecurityToken . pack) . randomString 15 newtype GithubAccessKey = GithubAccessKey ByteString deriving (Show, Eq, Read, Generic, PersistField) instance PersistFieldSql GithubAccessKey where sqlType = sqlType . liftM (\(GithubAccessKey v) -> v) instance ToJSON GithubAccessKey where toJSON (GithubAccessKey bs) = toJSON $ decodeUtf8 $ B64.encode bs instance FromJSON GithubAccessKey where parseJSON = fmap (GithubAccessKey . B64.decodeLenient . encodeUtf8) . parseJSON data Keymap = KeymapVim | KeymapEmacs deriving (Show, Eq, Read, Enum, Bounded, Generic) instance ToJSON Keymap instance FromJSON Keymap derivePersistField "Keymap" data SSHKeyPair = SSHKeyPair { publicKey :: !ByteString , privateKey :: !ByteString } deriving (Show, Eq, Ord, Generic) instance Cereal.Serialize SSHKeyPair instance ToJSON SSHKeyPair where toJSON (SSHKeyPair pub priv) = object [ "public" .= decodeUtf8 (B64.encode pub) , "private" .= decodeUtf8 (B64.encode priv) ] instance FromJSON SSHKeyPair where parseJSON = withObject "SSHKeyPair" $ \o -> SSHKeyPair <$> (go <$> (o .: "public")) <*> (go <$> (o .: "private")) where go = B64.decodeLenient . encodeUtf8 instance PersistField SSHKeyPair where toPersistValue = toPersistValue . Cereal.encode fromPersistValue = fromPersistValue >=> either (Left . pack) Right . Cereal.decode instance PersistFieldSql SSHKeyPair where sqlType _ = SqlBlob data SkillLevel = SLBeginner | SLAdvanced deriving (Eq, Ord, Enum, Bounded, Generic, Data, Typeable) instance Show SkillLevel where show SLBeginner = "Beginner" show SLAdvanced = "Advanced" instance Read SkillLevel where readsPrec _ s = case lookup s m of Nothing -> [] Just sl -> [(sl, "")] where m = map (show &&& id) [minBound..maxBound] instance ToJSON SkillLevel instance FromJSON SkillLevel derivePersistField "SkillLevel" -- | Access code used for viewing tutorial previews. type PreviewCode = Text newtype LowerCaseText = LowerCaseTextDoNotUse { unLowerCaseText :: Text } deriving (Show, Eq, Read, Ord, Generic, Data, Typeable, ToJSON, FromJSON, PersistField, PathPiece, ToMarkup, ToMessage) instance PersistFieldSql LowerCaseText where sqlType = sqlType . liftM unLowerCaseText mkLowerCaseText :: Text -> LowerCaseText mkLowerCaseText = LowerCaseTextDoNotUse . toLower newtype PkgSetId = PkgSetId { unPkgSetId :: Text } deriving (Eq, Read, Show, Data, Typeable, Ord, PathPiece, ToJSON, FromJSON, Generic, Hashable, PersistField) instance PersistFieldSql PkgSetId where sqlType = sqlType . liftM unPkgSetId -- | work around persistent's relative table rules type PkgSetId' = PkgSetId newtype GhcEnvId = GhcEnvId { unGhcEnvId :: Text } deriving (Eq, Read, Show, Data, Typeable, Ord, PathPiece, ToJSON, FromJSON, Generic, Hashable, PersistField) instance PersistFieldSql GhcEnvId where sqlType = sqlType . liftM unGhcEnvId type GhcEnvId' = GhcEnvId -- | Controls how Disqus comments are displayed for an individual's content. data Disqus = NoComments | FPAccount -- ^ Use FP Complete's account | UserAccount DisqusIdent deriving (Show, Generic, Eq) instance ToJSON Disqus instance FromJSON Disqus instance PersistField Disqus where toPersistValue NoComments = PersistText "nocomments" toPersistValue FPAccount = PersistText "fpaccount" toPersistValue (UserAccount di) = PersistText $ "user-" ++ unDisqusIdent di fromPersistValue pv = do t <- fromPersistValue pv case t of "nocomments" -> return NoComments "fpaccount" -> return FPAccount _ -> do di' <- maybe (Left "Invalid Disqus value") Right $ stripPrefix "user-" t either (Left . tshow) (Right . UserAccount) (mkDisqusIdent di') instance PersistFieldSql Disqus where sqlType _ = SqlString newtype DisqusIdent = DisqusIdent Text deriving (Show, Generic, Eq) unDisqusIdent :: DisqusIdent -> Text unDisqusIdent (DisqusIdent x) = x newtype DisqusException = DisqusException Text deriving (Typeable, Generic) instance Show DisqusException where show (DisqusException t) = unpack t instance Exception DisqusException instance ToJSON DisqusIdent instance FromJSON DisqusIdent where parseJSON v = do t <- parseJSON v case mkDisqusIdent t of Left e -> fail $ show e Right x -> return x -- FIXME need something more definitive mkDisqusIdent :: MonadThrow m => Text -> m DisqusIdent mkDisqusIdent "" = throwM $ DisqusException "Shortname must not be blank" mkDisqusIdent t | length t > 50 = throwM $ DisqusException "Shortname must be at most 50 characters" | length t < 3 = throwM $ DisqusException "Shortname must less at least 3 characters" | any isValid t = return $ DisqusIdent t | otherwise = throwM $ DisqusException "Your shortname must be letters, numbers, hyphens and underscores only" where isValid c = ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') || c == '-' || c == '_' -- | Token for a tutorial. newtype TutorialConcurrentToken = TutorialConcurrentToken' { unTutorialConcurrentToken :: Int32 } deriving (Eq, Show, Data, Read, Typeable, Num, Ord, Generic, ToJSON, FromJSON, Hashable, PersistField, Random) instance Default TutorialConcurrentToken where def = TutorialConcurrentToken' 1 instance PersistFieldSql TutorialConcurrentToken where sqlType = sqlType . liftM unTutorialConcurrentToken incrToken :: TutorialConcurrentToken -> TutorialConcurrentToken incrToken (TutorialConcurrentToken' x) = TutorialConcurrentToken' (x + 1)
fpco/schoolofhaskell.com
src/Model/Types.hs
mit
11,630
0
17
2,879
3,307
1,704
1,603
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-taskdefinitionplacementconstraint.html module Stratosphere.ResourceProperties.ECSTaskDefinitionTaskDefinitionPlacementConstraint where import Stratosphere.ResourceImports -- | Full data type definition for -- ECSTaskDefinitionTaskDefinitionPlacementConstraint. See -- 'ecsTaskDefinitionTaskDefinitionPlacementConstraint' for a more -- convenient constructor. data ECSTaskDefinitionTaskDefinitionPlacementConstraint = ECSTaskDefinitionTaskDefinitionPlacementConstraint { _eCSTaskDefinitionTaskDefinitionPlacementConstraintExpression :: Maybe (Val Text) , _eCSTaskDefinitionTaskDefinitionPlacementConstraintType :: Val Text } deriving (Show, Eq) instance ToJSON ECSTaskDefinitionTaskDefinitionPlacementConstraint where toJSON ECSTaskDefinitionTaskDefinitionPlacementConstraint{..} = object $ catMaybes [ fmap (("Expression",) . toJSON) _eCSTaskDefinitionTaskDefinitionPlacementConstraintExpression , (Just . ("Type",) . toJSON) _eCSTaskDefinitionTaskDefinitionPlacementConstraintType ] -- | Constructor for 'ECSTaskDefinitionTaskDefinitionPlacementConstraint' -- containing required fields as arguments. ecsTaskDefinitionTaskDefinitionPlacementConstraint :: Val Text -- ^ 'ecstdtdpcType' -> ECSTaskDefinitionTaskDefinitionPlacementConstraint ecsTaskDefinitionTaskDefinitionPlacementConstraint typearg = ECSTaskDefinitionTaskDefinitionPlacementConstraint { _eCSTaskDefinitionTaskDefinitionPlacementConstraintExpression = Nothing , _eCSTaskDefinitionTaskDefinitionPlacementConstraintType = typearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-taskdefinitionplacementconstraint.html#cfn-ecs-taskdefinition-taskdefinitionplacementconstraint-expression ecstdtdpcExpression :: Lens' ECSTaskDefinitionTaskDefinitionPlacementConstraint (Maybe (Val Text)) ecstdtdpcExpression = lens _eCSTaskDefinitionTaskDefinitionPlacementConstraintExpression (\s a -> s { _eCSTaskDefinitionTaskDefinitionPlacementConstraintExpression = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-taskdefinitionplacementconstraint.html#cfn-ecs-taskdefinition-taskdefinitionplacementconstraint-type ecstdtdpcType :: Lens' ECSTaskDefinitionTaskDefinitionPlacementConstraint (Val Text) ecstdtdpcType = lens _eCSTaskDefinitionTaskDefinitionPlacementConstraintType (\s a -> s { _eCSTaskDefinitionTaskDefinitionPlacementConstraintType = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/ECSTaskDefinitionTaskDefinitionPlacementConstraint.hs
mit
2,693
0
13
214
267
153
114
28
1
module Network.GDAX.Exceptions where import Control.Monad.Catch import Data.Text (Text) data MalformedGdaxResponse = MalformedGdaxResponse Text deriving (Show) instance Exception MalformedGdaxResponse
AndrewRademacher/gdax
lib/Network/GDAX/Exceptions.hs
mit
242
0
6
59
46
27
19
7
0
module Find where -- https://www.codewars.com/kata/find-the-middle-element import Data.List gimme :: Ord a => (a, a, a) -> Int gimme (a, b, c) | middle == a = 0 | middle == b = 1 | middle == c = 2 where middle = sort [a, b, c] !! 1
cojoj/Codewars
Haskell/Codewars.hsproj/Find.hs
mit
251
0
9
67
111
60
51
8
1
---- -- SayIt.hs -- by daniel -- -- A work in progress ---- -- Our task is to create a chainable function with the following -- behavior: -- input > sayit("Hi")(" ")("there")("!") -- output> Hi there! -- I think this might be untennable in the present language without -- writing a DSL <.< sayIt :: String -> IO () -> IO () sayIt string = \action -> do putStr string action main :: IO () main = sayIt "Hi" . sayIt " " . sayIt "there" . sayIt "!" . sayIt "\n" $ return ()
friedbrice/hemingway
SayIt/SayIt.hs
gpl-2.0
497
0
10
121
113
58
55
12
1
{- | Module : ./Common/ProverTools.hs Description : Check for availability of provers Copyright : (c) Dminik Luecke, and Uni Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : luecke@informatik.uni-bremen.de Stability : provisional Portability : portable check for provers -} module Common.ProverTools where import Common.Utils import System.Directory import System.FilePath missingExecutableInPath :: String -> IO Bool missingExecutableInPath name = do mp <- findExecutable name case mp of Nothing -> return True Just name' -> do p1 <- check4File (takeFileName name') "PATH" () p2 <- check4File (takeFileName name') "Path" () return . null $ p1 ++ p2 check4FileAux :: String -- ^ file name -> String -- ^ Environment Variable -> IO [String] check4FileAux name env = do pPath <- getEnvDef env "" let path = "" : splitPaths pPath exIT <- mapM (doesFileExist . (</> name)) path return $ map fst $ filter snd $ zip path exIT -- | Checks if a file exists in PATH checkBinary :: String -> IO (Maybe String) checkBinary name = fmap (\ l -> if null l then Just $ "missing binary in $PATH: " ++ name else Nothing) $ check4FileAux name "PATH" -- | Checks if a file exists check4File :: String -- ^ file name -> String -- ^ Environment Variable -> a -> IO [a] check4File name env a = do ex <- check4FileAux name env return [a | not $ null ex ] -- | check for java and the jar file in the directory of the variable check4jarFile :: String -- ^ environment Variable -> String -- ^ jar file name -> IO (Bool, FilePath) check4jarFile = check4jarFileWithDefault "" check4jarFileWithDefault :: String -- ^ default path -> String -- ^ environment Variable -> String -- ^ jar file name -> IO (Bool, FilePath) check4jarFileWithDefault def var jar = do pPath <- getEnvDef var def hasJar <- doesFileExist $ pPath </> jar return (hasJar, pPath) -- | environment variable for HETS_OWL_TOOLS hetsOWLenv :: String hetsOWLenv = "HETS_OWL_TOOLS" -- | check for the jar file under HETS_OWL_TOOLS check4HetsOWLjar :: String -- ^ jar file name -> IO (Bool, FilePath) check4HetsOWLjar = check4jarFileWithDefault "OWL2" hetsOWLenv checkOWLjar :: String -> IO (Maybe String) checkOWLjar name = fmap (\ (b, p) -> if b then Nothing else Just $ "missing jar ($" ++ hetsOWLenv ++ "): " ++ (p </> name)) $ check4HetsOWLjar name
spechub/Hets
Common/ProverTools.hs
gpl-2.0
2,524
0
15
608
615
314
301
57
2
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings, MultiParamTypeClasses, GeneralizedNewtypeDeriving #-} module Text.Pandoc2.Builder where import Text.Pandoc2.Definition import qualified Data.Text as T import Data.Text (Text) -- Pandoc2 builder DSL txt :: Text -> Inlines txt = single . Txt ch :: Char -> Inlines ch = single . Txt . T.singleton (<+>) :: Inlines -> Inlines -> Inlines x <+> y = x <> single Sp <> y emph :: Inlines -> Inlines emph = single . Emph strong :: Inlines -> Inlines strong = single . Strong subscript :: Inlines -> Inlines subscript = single . Subscript superscript :: Inlines -> Inlines superscript = single . Superscript strikeout :: Inlines -> Inlines strikeout = single . Strikeout link :: Inlines -> Source -> Inlines link lab src = single $ Link (Label lab) src image :: Inlines -> Source -> Inlines image lab src = single $ Image (Label lab) src verbatim :: Text -> Inlines verbatim = verbatimAttr nullAttr verbatimAttr :: Attr -> Text -> Inlines verbatimAttr attr = single . Verbatim attr singleQuoted :: Inlines -> Inlines singleQuoted = single . Quoted SingleQuoted doubleQuoted :: Inlines -> Inlines doubleQuoted = single . Quoted DoubleQuoted lineBreak :: Inlines lineBreak = single LineBreak math :: MathType -> Text -> Inlines math t = single . Math t rawInline :: Format -> Text -> Inlines rawInline f = single . RawInline f note :: Blocks -> Inlines note = single . Note para :: Inlines -> Blocks para = single . Para plain :: Inlines -> Blocks plain = single . Plain quote :: Blocks -> Blocks quote = single . Quote codeAttr :: Attr -> Text -> Blocks codeAttr attr = single . Code attr code :: Text -> Blocks code = codeAttr nullAttr list :: ListStyle -> [Blocks] -> Blocks list sty = single . List sty orderedList :: [Blocks] -> Blocks orderedList = single . List (Ordered 1 DefaultStyle DefaultDelim) bulletList :: [Blocks] -> Blocks bulletList = single . List Bullet definitions :: [(Inlines, [Blocks])] -> Blocks definitions = single . Definitions header :: Int -> Inlines -> Blocks header n = single . Header n rawBlock :: Format -> Text -> Blocks rawBlock f = single . RawBlock f hrule :: Blocks hrule = single HRule
jgm/pandoc2
Text/Pandoc2/Builder.hs
gpl-2.0
2,205
0
8
414
739
396
343
68
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE DeriveGeneric #-} module Test.QuickFuzz.Gen.Code.Lua where import Data.Default import Test.QuickCheck import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.State import Data.List import Language.Lua.Syntax import Language.Lua.PrettyPrinter import Test.QuickFuzz.Derive.Arbitrary import Test.QuickFuzz.Derive.Fixable import Test.QuickFuzz.Derive.Show import Test.QuickFuzz.Gen.FormatInfo import Test.QuickFuzz.Gen.Base.ByteString import Test.QuickFuzz.Gen.Base.String import qualified Data.ByteString.Lazy.Char8 as L8 devArbitrary ''Block luaInfo :: FormatInfo Block NoActions luaInfo = def { encode = L8.pack . show . pprint , random = arbitrary , value = show , ext = "lua" }
elopez/QuickFuzz
src/Test/QuickFuzz/Gen/Code/Lua.hs
gpl-3.0
847
0
9
114
171
113
58
27
1
module Problem034 (answer) where import NumUtil (decompose) answer :: Int answer = sum [i | i <- [3..999999], sum (map fact (decompose i)) == i] fact 0 = 1 fact n = product [1..n]
geekingfrog/project-euler
Problem034.hs
gpl-3.0
183
0
13
37
95
51
44
6
1
module TestTelnet where import Control.Applicative import Control.Monad import qualified Data.Map as Map (map) import Data.String.Utils import Test.QuickCheck import Telnet import Telnet.Utils main :: IO () main = do quickCheck prop_need_more_input quickCheck prop_erroneous_command quickCheck prop_erroneous_subnegotiation quickCheck prop_identity1 quickCheck prop_identity2 quickCheck prop_absorbing_element quickCheck prop_zero_sum quickCheck prop_edge_trigger quickCheck prop_step_function -- -- Tests of packet parse/serialize -- prop_need_more_input :: Bool prop_need_more_input = all ((Left NeedMoreInput ==) . parse) [ "\255", "\255\250", "\255\250\255", "\255\250abc", "\255\250abc\255", "\255\251", "\255\252", "\255\253", "\255\254", ""] prop_erroneous_command :: Bool prop_erroneous_command = all test ['\0'..'\239'] where test = isError . parse . ("\255" `sonc`) prop_erroneous_subnegotiation :: Bool prop_erroneous_subnegotiation = all (isError . parse) [ "\255\250\255\1", "\255\250abc\255\1"] isError result = case result of (Left (Err _)) -> True _ -> False sonc :: String -> Char -> String sonc cs c = cs ++ [c] instance Arbitrary Packet where arbitrary = oneof [ return PacketNop, return PacketDataMark, return PacketBreak, return PacketIp, return PacketAo, return PacketAyt, return PacketEc, return PacketEl, return PacketGoAhead, liftM PacketSubOption arbitrary, liftM PacketWill arbitrary, liftM PacketWont arbitrary, liftM PacketDo arbitrary, liftM PacketDont arbitrary, liftM PacketText arbitrary] parse' :: String -> [Packet] parse' str@(_:_) = packet : parse' rest where (packet, rest) = unpack $ parse str unpack (Right result ) = result unpack (Left (Err reason) ) = error reason unpack (Left NeedMoreInput) = error "Need more input" parse' _ = [] serialize' :: [Packet] -> String serialize' = concat . map serialize identity :: String -> String identity = serialize' . parse' prop_identity1 :: [Char] -> Bool prop_identity1 cs = identity quoted == quoted where quoted = quote cs quote = replace "\255" "\255\255" -- This quotes all IAC -- NOTE: Test identity for [Packet] is difficult because: -- * [PacketText ""] is serialized to "" but "" is parsed to [] rather than -- [PacketText ""]. -- * PacketText may be generated at different splits of input text. -- So the easies way to test identity is to test on serialized text. prop_identity2 :: [Packet] -> Bool prop_identity2 ps = identity cs == cs where cs = serialize' ps -- -- Tests of NvtContext -- instance Arbitrary NvtOpt where arbitrary = oneof [ liftM NvtOptBool arbitrary, liftM NvtOptAlways arbitrary, liftM NvtOptPair arbitrary, liftM NvtOptString arbitrary, return NvtOptNothing] instance Arbitrary a => Arbitrary (NvtContext a) where arbitrary = fromList <$> listOf1 arbitrary edge' = liftA2 edge alter = (alter' <$>) where alter' (NvtOptBool opt) = NvtOptBool $ not opt alter' (NvtOptAlways opt) = NvtOptAlways $ not opt alter' (NvtOptPair opt) = NvtOptPair (1 + fst opt, snd opt) alter' (NvtOptString opt) = NvtOptString (opt ++ " ") alter' NvtOptNothing = NvtOptNothing makeZero (NvtContext table) = NvtContext $ zero where zero = Map.map (\_ -> NvtOptNothing) table prop_absorbing_element :: Nvt -> Bool prop_absorbing_element nvt = nvt `edge'` zero == zero && zero `edge'` nvt == zero where zero = makeZero nvt prop_zero_sum :: Nvt -> Bool prop_zero_sum nvt = nvt `edge'` nvt == zero where zero = makeZero nvt prop_edge_trigger :: Nvt -> Bool prop_edge_trigger nvt = alter nvt `edge'` nvt == nvt && nvt `edge'` alter nvt == alter nvt -- NOTE: When receiving WONT/DONT, DONT/WONT is the only valid response? prop_step_function :: Bool prop_step_function = step nvt PacketNop == (nvt, []) && step nvt PacketDataMark == (nvt, []) && step nvt PacketBreak == (nvt, []) && step nvt PacketIp == (nvt, []) && step nvt PacketAo == (nvt, []) && step nvt PacketAyt == (nvt, []) && step nvt PacketEc == (nvt, []) && step nvt PacketEl == (nvt, []) && step nvt PacketGoAhead == (nvt, []) && step nvt (PacketWill '\0') == ( nvt, [PacketDo '\0']) && step nvt (PacketDo '\0') == ( nvt, [PacketWill '\0']) && step nvt (PacketWont '\0') == (u '\0' f nvt, [PacketDont '\0']) && step nvt (PacketDont '\0') == (u '\0' f nvt, [PacketWont '\0']) && step nvt (PacketWill '\1') == (u '\1' t nvt, [PacketDo '\1']) && step nvt (PacketDo '\1') == (u '\1' t nvt, [PacketWill '\1']) && step nvt (PacketWont '\1') == ( nvt, [PacketDont '\1']) && step nvt (PacketDont '\1') == ( nvt, [PacketWont '\1']) && step nvt (PacketWill '\3') == (nvt, [PacketDo '\3']) && step nvt (PacketDo '\3') == (nvt, [PacketWill '\3']) && step nvt (PacketWont '\3') == (nvt, [PacketDont '\3']) && step nvt (PacketDont '\3') == (nvt, [PacketWont '\3']) && step nvt' (PacketWill '\3') == (nvt', [PacketDont '\3']) && step nvt' (PacketDo '\3') == (nvt', [PacketWont '\3']) && step nvt' (PacketWont '\3') == (nvt', [PacketDont '\3']) && step nvt' (PacketDont '\3') == (nvt', [PacketWont '\3']) && step nvt (PacketWill '\31') == (nvt, [PacketDo '\31', windowSize]) && step nvt (PacketDo '\31') == (nvt, [PacketWill '\31', windowSize]) && step nvt (PacketWont '\31') == (nvt, [PacketDont '\31']) && step nvt (PacketDont '\31') == (nvt, [PacketWont '\31']) && step nvt (PacketWill '\24') == (nvt, [PacketDo '\24']) && step nvt (PacketDo '\24') == (nvt, [PacketWill '\24']) && step nvt (PacketWont '\24') == (nvt, [PacketDont '\24']) && step nvt (PacketDont '\24') == (nvt, [PacketWont '\24']) && step nvt (PacketSubOption "\24\1" ) == (nvt, [PacketSubOption "\24\0VT100"]) && True where nvt = fromList [(rfc856_BINARY_TRANSMISSION, NvtOptBool True), (rfc857_ECHO, NvtOptBool False), (rfc858_SUPPRESS_GOAHEAD, NvtOptAlways True), (rfc1073_WINDOW_SIZE, NvtOptPair (80, 24)), (rfc1091_TERMINAL_TYPE, NvtOptString "VT100")] nvt' = u '\3' (NvtOptAlways False) nvt u = update t = NvtOptBool True f = NvtOptBool False windowSize = PacketSubOption "\31\00\80\00\24"
clchiou/gwab
test/TestTelnet.hs
gpl-3.0
6,803
0
74
1,784
2,208
1,155
1,053
158
5
-- https://esolangs.org/wiki/Μ -- Build: ghc --make moo -- Usage: ./moo -- The μ syntax is underspecified. -- I'll assume that two consecutive newlines (i.e. a blank line) ends a -- definition. -- I'll assume identifiers are non-empty strings of non-whitespace characters -- excluding parentheses, but cannot be "=". -- I'll assume that definitions where the identifier being defined is within -- parentheses are defined as infix (or postfix for unary functions). -- I'll assume that expressions invoking infix functions have the function -- between the first and second arguments, with additional arguments, if any, -- following the second argument. -- I'll assume infix functions are right associative. -- Not exactly syntax, but I'll assume redefining <= is disallowed. -- Additionally, if there is an "=" token in the first line of an entry, it is -- considered a definition that can span multiple lines and is ended by a -- blank line. And if there is no "=" token in the first line, it is -- considered an expression that will be evaluated and cannot span multiple -- lines. import Data.Char(isSpace) import Data.Map(Map,empty,insert,member,toList,(!)) import qualified Data.Map import Data.Time(diffUTCTime,getCurrentTime) import System.IO(hFlush,isEOF,stdout) tokenize :: String -> [String] tokenize [] = [] tokenize (c:rest) | c == '(' || c == ')' = [c] : tokenize rest | isSpace c = tokenize rest | otherwise = let (ident,remaining) = break nonIdent rest in (c:ident) : tokenize remaining where nonIdent c = c == '(' || c == ')' || isSpace c data Token = Identifier String | Grouping [Token] | Argument Int | Implicit deriving Show data Unresolved = Unresolved Bool Int [Token] -- infix arity body deriving Show parseDef :: [String] -> Either String (String,Unresolved) parseDef tokens = parseDefName tokens where parseDefName ("(":name:")":tokens) | name `elem` ["(",")","=","<="] = Left "Bad definition" | otherwise = fmap ((,) name) (parseDefParams True tokens) parseDefName (name:tokens) | name `elem` ["(",")","=","<="] = Left "Bad definition" | otherwise = fmap ((,) name) (parseDefParams False tokens) parseDefName [] = Left "Bad definition" parseDefParams :: Bool -> [String] -> Either String Unresolved parseDefParams infixFlag (name:tokens) | name `elem` ["(",")","=","<="] = Left "Bad definition" | otherwise = parseDefAdditionalParams infixFlag name [] tokens parseDefParams infixFlag [] = Left "Bad definition" parseDefAdditionalParams :: Bool -> String -> [String] -> [String] -> Either String Unresolved parseDefAdditionalParams infixFlag implicit params (name:tokens) | name `elem` ["(",")","<="] = Left "Bad definition" | name == "=" = fmap (Unresolved infixFlag (length params)) (parseExpr (zip (reverse params) [0..]) implicit tokens) | otherwise = parseDefAdditionalParams infixFlag name (implicit:params) tokens parseDefAdditionalParams infixFlag implicit params [] = Left "Bad definition" parseExpr :: [(String,Int)] -> String -> [String] -> Either String [Token] parseExpr params implicit tokens = do (exprTokens,remainingTokens) <- parseTokens [] tokens if null remainingTokens then return exprTokens else Left "Unmatched parenthesis" where parseTokens :: [Token] -> [String] -> Either String ([Token],[String]) parseTokens parsedToks [] = return (reverse parsedToks,[]) parseTokens parsedToks toks@(")":_) = return (reverse parsedToks,toks) parseTokens parsedToks ("(":rest) = do (groupedToks,remaining) <- parseTokens [] rest case remaining of (")":rest) -> parseTokens (Grouping groupedToks:parsedToks) rest _ -> Left "Unmatched parenthesis" parseTokens parsedToks (name:rest) | name == implicit = parseTokens (Implicit:parsedToks) rest | otherwise = parseTokens (maybe (Identifier name) Argument (lookup name params):parsedToks) rest data Expr = Call (Either String Expr) [Expr] | Arg Int | Impl | LE Expr Expr resolve :: Map String Unresolved -> [Token] -> Either String Expr resolve unresolved tokens = resolveExpr tokens where isInfix :: String -> Bool isInfix name = (\ (Unresolved infixFlag _ _) -> infixFlag) (unresolved!name) arity :: String -> Int arity name = (\ (Unresolved _ a _) -> a) (unresolved!name) resolved :: Map String (Either String Expr) resolved = Data.Map.map resolveDef unresolved resolveDef :: Unresolved -> Either String Expr resolveDef (Unresolved _ _ tokens) = resolveExpr tokens resolveExpr :: [Token] -> Either String Expr resolveExpr tokens = do (exprList,remainingToks) <- resolveExprList ([],tokens) 1 False if not (null remainingToks) then Left "Resolver failure" else return (head exprList) resolveExprList :: ([Expr],[Token]) -> Int -> Bool -> Either String ([Expr],[Token]) resolveExprList (exprStack,[]) n stopOnInfix | length exprStack == n = return (reverse exprStack,[]) | otherwise = Left "Resolver failure" resolveExprList (exprStack,toks@(Identifier "<=":remainingToks)) n stopOnInfix | null exprStack = Left "Resolver failure" | stopOnInfix && length exprStack == n = return (reverse exprStack,toks) | otherwise = do (rhs,moreToks) <- resolveExprList ([],remainingToks) 1 False resolveExprList (LE (head exprStack) (head rhs):tail exprStack,moreToks) n stopOnInfix resolveExprList (exprStack,toks@(Identifier name:remainingToks)) n stopOnInfix | not (member name unresolved) = Left "Resolver failure" | (arity name == 0 || not (isInfix name) || stopOnInfix) && length exprStack == n = return (reverse exprStack,toks) | arity name == 0 = resolveExprList (Call (resolved!name) []:exprStack,remainingToks) n stopOnInfix | isInfix name && null exprStack = Left "Resolver failure" | isInfix name && arity name == 1 = resolveExprList (Call (resolved!name) [head exprStack]:tail exprStack,remainingToks) n stopOnInfix | isInfix name = do (args,moreToks) <- resolveExprList ([],remainingToks) (arity name - 1) False resolveExprList (Call (resolved!name) (head exprStack:args):tail exprStack,moreToks) n stopOnInfix | otherwise = do (args,moreToks) <- resolveExprList ([],remainingToks) (arity name) True resolveExprList (Call (resolved!name) args:exprStack,moreToks) n stopOnInfix resolveExprList (exprStack,toks@(Grouping group:remainingToks)) n stopOnInfix | length exprStack == n = return (reverse exprStack,toks) | otherwise = do expr <- resolveExpr group resolveExprList (expr:exprStack,remainingToks) n stopOnInfix resolveExprList (exprStack,toks@(Argument i:remainingToks)) n stopOnInfix | length exprStack == n = return (reverse exprStack,toks) | otherwise = resolveExprList (Arg i:exprStack,remainingToks) n stopOnInfix resolveExprList (exprStack,toks@(Implicit:remainingToks)) n stopOnInfix | length exprStack == n = return (reverse exprStack,toks) | otherwise = resolveExprList (Impl:exprStack,remainingToks) n stopOnInfix eval :: Expr -> [Either String Integer] -> Integer -> Either String Integer eval (Call (Left msg) args) params implicit = Left msg eval (Call (Right fn) args) params implicit = call 0 where evalArg arg = eval arg params implicit call i = do r <- eval fn (map evalArg args) i if r == 0 then call (i+1) else return i eval (Arg i) params implicit = params !! i eval Impl params implicit = return implicit eval (LE lhs rhs) params implicit = do l <- eval lhs params implicit if l == 0 then return 1 else if l > 1 && isLE rhs then return 0 else do r <- eval rhs params implicit return (if l <= r then 1 else 0) where isLE (LE _ _) = True isLE _ = False repl :: (Map String Unresolved,[String]) -> IO () repl (defs,tokens) = do putStr (if null tokens then "- " else "+ ") hFlush stdout eof <- isEOF if eof then return () else do line <- getLine epl (tokenize line) where epl [] | null tokens = repl (defs,[]) | otherwise = either perror addDef (parseDef tokens) epl [":q"] = return () epl [":?"] = do putStrLn ":? - print this message" putStrLn ":d - print definitions" putStrLn ":c - clear definitions" putStrLn ":l file - load definitions from file" putStrLn ":q - quit" repl (defs,[]) epl [":d"] = do mapM_ (putStrLn . showDef) (toList defs) repl (defs,[]) epl [":c"] = repl (empty,[]) epl [":l",file] = do src <- readFile file let (errors,newDefs) = load [] defs [] (lines src) mapM_ putStrLn errors repl (newDefs,[]) epl toks | not (null tokens) = repl (defs,tokens++toks) | "=" `elem` toks = repl (defs,toks) | otherwise = do start <- getCurrentTime either putStrLn print (compileEval toks) done <- getCurrentTime print [diffUTCTime done start] repl (defs,[]) perror msg = do putStrLn msg repl (defs,[]) addDef (name,def) = repl (insert name def defs,[]) compileEval toks = do tokens <- parseExpr [] "" toks expr <- resolve defs tokens eval expr [] 0 load errors defs tokens lines | null tokens && null lines = (reverse errors,defs) | null lines || null (tokenize (head lines)) = either (\ msg -> load (msg:errors) defs [] (drop 1 lines)) (\ (name,def) -> load errors (insert name def defs) [] (drop 1 lines)) (parseDef tokens) | otherwise = load errors defs (tokens ++ tokenize (head lines)) (tail lines) showDef (name,Unresolved isInfix arity body) = (if isInfix then "(" ++ name ++ ")" else name) ++ concatMap (' ':) argNames ++ " =" ++ stripSpaceAfterParen (concatMap showBody body) where argNames = take (arity+1) (filter (not . (`elem` (concatMap extractIdentifiers body))) (map (:[]) ['a'..'z'] ++ map (('a':) . show) [1..])) extractIdentifiers (Identifier ident) = [ident] extractIdentifiers (Grouping tokens) = concatMap extractIdentifiers tokens extractIdentifiers _ = [] showBody (Identifier ident) = ' ':ident showBody (Grouping tokens) = " (" ++ concatMap showBody tokens ++ ")" showBody (Argument i) = ' ':(argNames !! i) showBody Implicit = ' ':(argNames !! arity) stripSpaceAfterParen "" = "" stripSpaceAfterParen ('(':' ':s) = '(':stripSpaceAfterParen s stripSpaceAfterParen (c:s) = c:stripSpaceAfterParen s main :: IO () main = do putStrLn "μ: https://esolangs.org/wiki/Μ :? for help" repl (empty,[])
qpliu/esolang
random/moo.hs
gpl-3.0
10,927
0
17
2,538
3,915
1,974
1,941
194
17
module Parser(parse) where import Sinterp import Control.Monad import Control.Applicative hiding((<|>), many) import Text.ParserCombinators.Parsec hiding(parse) import qualified Text.ParserCombinators.Parsec as P import Prelude hiding(div, not, and, or, EQ, LT, GT) parse :: String -> Either String Expr parse str = let parsed = P.parse expr "" str in case parsed of Left err -> Left . show $ err Right e -> Right e spaces1 :: Parser () spaces1 = skipMany1 space expr :: Parser Expr expr = spaces >> (try apply <|> expr') >>= precedent1 >>= precedent0 expr' :: Parser Expr expr' = (try paren <|> term) >>= precedent0 where paren = do {spaces; char '('; e <- expr; char ')'; return e} apply :: Parser Expr apply = partialApply >>= partialApply' where partialApply = do {e0 <- expr'; spaces; return (Apply e0)} partialApply' part = (try recur <|> finalApply) where finalApply = do {en <- expr'; spaces; return (part en)} recur = do {en <- expr'; spaces; partialApply' (Apply (part en))} value :: Parser Expr value = ((choice . map try $ expressions) <|> identifier) >>= precedent1 where expressions = [list, lambda, parseLet, parseIf, parseNot, parseEmpty, parseHead, parseTail, isEmpty, numeric, boolean] term :: Parser Expr term = value >>= precedent1 precedent :: [Expr -> Parser Expr] -> Expr -> Parser Expr precedent operators e = (choice . map try $ (operators <*> [e])) <|> return e precedent0 = precedent [add, sub, or, gt, lt, eq, cons] add = operator "+" (curry Add) expr sub = operator "-" (curry Sub) expr or = operator "or" (curry Or) expr cons = operator ":" Cons expr gt = operator ">" (Cmp GT) expr lt = operator "<" (Cmp LT) expr eq = operator "==" (Cmp EQ) expr precedent1 = precedent [mul, div, and] mul = operator "*" (curry Mul) expr div = operator "/" (curry Div) expr and = operator "and" (curry And) expr operator :: String -> (Expr -> Expr -> Expr) -> (Parser Expr) -> Expr -> Parser Expr operator op constructor nextExpr e0 = do string op <* spaces e1 <- nextExpr <* spaces return (constructor e0 e1) list = head >>= tail where head = do {char '['; spaces; e <- expr; spaces; return (Cons e) } tail part = try (more part) <|> end where more part = do {char ','; spaces; e <- expr; spaces; tail (part . Cons e)} end = do {char ']'; spaces; return (part Empty)} lambda = do char '\\' <* spaces id <- identifier' <* spaces string "->" <* spaces e <- expr <* spaces return (Fun id e) isEmpty = do string "isEmpty" <* spaces e <- expr <* spaces return . IsEmpty $ e parseTail = do string "tail" <* spaces e <- expr <* spaces return . Tail $ e parseHead = do string "head" <* spaces e <- expr <* spaces return . Head $ e parseEmpty = string "[]" >> spaces >> return Empty parseNot = do {string "not"; e <- expr; spaces; return (Not e)} parseIf = do string "if" <* spaces1 cond <- expr <* spaces string "then" <* spaces t <- expr <* spaces string "else" <* spaces1 f <- expr <* spaces return (If cond t f) parseLet = do string "let" <* spaces1 id <- identifier' <* spaces char '=' <* spaces arg <- expr <* spaces string "in" <* spaces1 body <- expr <* spaces return (Let (id, arg) body) (<++>) a b = (++) <$> a <*> b (<:>) a b = (:) <$> a <*> b identifier = Id <$> identifier' identifier' = do str <- (letter <:> many (try alphaNum <|> char '_')) spaces if elem str keywords then unexpected ("reserved keyword: " ++ str) else return str keywords = ["let", "in", "if", "then", "else"] boolean = try true <|> false true = true' >> return (Boolean True) true' = string "true" <* spaces false = false' >> return (Boolean False) false' = string "false" <* spaces integer = Number . IntN . read <$> integer' float = Number . FloatN . read <$> float' numeric = try float <|> integer number' = many1 digit <* spaces integer' = plus <|> minus <|> number' where plus = char '+' <:> number' minus = char '-' <:> number' float' = integer' <++> (try decimal <|> eff) where decimal = char '.' <:> number' eff = char 'f' >> spaces >> return ""
jcollard/sinterp
Parser.hs
gpl-3.0
4,135
0
15
922
1,804
917
887
115
2
{-# LANGUAGE OverloadedStrings #-} module Network.Refraction.Generator ( makeSimpleTransaction , makeAdTransaction , makeAliceClaim , makeAliceCommit , makeBobClaim , makeBobCommit , makePairRequest , makeSplitTransaction , mkInput -- TODO do not export this once we're testing the higher level functions ) where import Data.Word (Word64) import qualified Data.ByteString as B import Data.ByteString.Char8 (pack) import qualified Data.Serialize as S import Network.Haskoin.Crypto import Network.Haskoin.Script import Network.Haskoin.Transaction import Network.Haskoin.Util (updateIndex) import Network.Refraction.BitcoinUtils -- Default transaction fee in satoshis dTxFee = 10000 -- Mix Unit in satoshis (0.00080000 BTC for now) mixUnit = 80000 -- We set a cap to how much we split the inputs to Refraction just in case the mixUnit -- is too small comparatively (otherwise we'd create a huge split transaction) splitCountMax = 10 -- |Takes a UTXO and returns a SigInput that can be used to sign a Tx mkInput :: UTXO -> Either String SigInput mkInput utxo = do pso <- decodeOutputBS . scriptOutput $ _txOut utxo return $ SigInput pso (_outPoint utxo) (SigAll False) Nothing -- TODO(hudon): do we want a smarter fee approach? Should we interact with the full node for fee? -- |Our miner fee grows linearly with the number of inputs calculateAmount :: [UTXO] -> SatoshiValue calculateAmount = foldl sumVal 0 where sumVal v utxo = v + coinValue utxo - dTxFee -- |Takes a list of utxos and associated private keys and pays to an address makeSimpleTransaction :: [UTXO] -> [PrvKey] -> Address -> Either String Tx makeSimpleTransaction utxos prvkeys addr = do tx <- buildTx (map _outPoint utxos) [(addressToOutput addr, calculateAmount utxos)] ins <- mapM mkInput utxos signTx tx ins prvkeys -- |Takes a list of utxos and associated private keys and splits the amount into mixUnit outputs -- the outputs all go to the first private key given, except for the excess amounts, which -- go to the refundAddr makeSplitTransaction :: [UTXO] -> [PrvKey] -> Address -> Either String Tx makeSplitTransaction utxos prvkeys@(p:_) refundAddr = do let outAddr = pubKeyAddr $ derivePubKey p outputSum = calculateAmount utxos splitCount = min splitCountMax (outputSum `div` mixUnit) refundAmount = outputSum - (splitCount * mixUnit) refundOut = (addrToBase58 refundAddr, refundAmount) outs = replicate (fromIntegral splitCount) (addrToBase58 outAddr, mixUnit) tx <- buildAddrTx (map _outPoint utxos) (refundOut:outs) ins <- mapM mkInput utxos signTx tx ins prvkeys -- We reverse the hashes here because the redeem script will expect the secrets in reverse order makeAliceCommit :: [UTXO] -> [PrvKey] -> PubKey -> PubKey -> [Hash256] -> Either String (Tx, Script) makeAliceCommit utxos prvkeys aPubkey bPubkey bHashes = do let redeemScript = makeAliceCommitRedeem aPubkey bPubkey (reverse bHashes) 100000 tx <- signP2SH utxos prvkeys redeemScript return (tx, redeemScript) makeAliceClaim :: [UTXO] -> [PrvKey] -> Script -> Integer -> PubKey -> Either String Tx makeAliceClaim utxos prvkeys redeemScript secret aPubkey = do let addr = pubKeyAddr aPubkey unsigned <- buildTx (map _outPoint utxos) [(addressToOutput addr, calculateAmount utxos)] signClaimTx unsigned [secret] 0 redeemScript (head prvkeys) makeBobCommit :: [UTXO] -> [PrvKey] -> PubKey -> PubKey -> [Hash256] -> Either String (Tx, Script) makeBobCommit utxos prvkeys aPubkey bPubkey bHashes = do let redeemScript = makeBobCommitRedeem aPubkey bPubkey bHashes 100000 tx <- signP2SH utxos prvkeys redeemScript return (tx, redeemScript) makeBobClaim :: [UTXO] -> [PrvKey] -> Script -> [Integer] -> PubKey -> Either String Tx makeBobClaim utxos prvkeys redeemScript sums bPubkey = do let addr = pubKeyAddr bPubkey unsigned <- buildTx (map _outPoint utxos) [(addressToOutput addr, calculateAmount utxos)] signClaimTx unsigned sums 0 redeemScript (head prvkeys) -- TODO does this need to be in an either? -- | Sign a single input in a transaction deterministically (RFC-6979). signClaimTx :: Tx -> [Integer] -> Int -> Script -> PrvKey -> Either String Tx signClaimTx tx inputData i rdm key = do let sh = SigAll False sig = TxSignature (signMsg (txSigHash tx rdm i sh) key) sh ins = updateIndex i (txIn tx) (addInput sig) return $ createTx (txVersion tx) ins (txOut tx) (txLockTime tx) where addInput sig x = x{ scriptInput = S.encode . si $ encodeSig sig } si sig = Script $ map (opPushData . S.encode) inputData ++ [opPushData sig, OP_0, opPushData $ S.encode rdm] -- TODO put this is haskoin scriptAddrNonStd :: Script -> Address scriptAddrNonStd = ScriptAddress . addressHash . S.encode signP2SH :: [UTXO] -> [PrvKey] -> Script -> Either String Tx signP2SH utxos prvkeys redeemScript = do let scriptOut = addressToOutput $ scriptAddrNonStd redeemScript tx <- buildTx (map _outPoint utxos) [(scriptOut, calculateAmount utxos)] ins <- mapM mkInput utxos signTx tx ins prvkeys makeAliceCommitRedeem :: PubKey -> PubKey -> [Hash256] -> Integer -> Script makeAliceCommitRedeem aPubkey bPubkey sumHashes locktime = Script $ [ OP_IF -- OP_NOP2 is OP_CHECKLOCKTIMEVERIFY (CLTV) -- TODO update haskoin with cltv op , opPushData (S.encode locktime), OP_NOP2, OP_DROP , opPushData (S.encode aPubkey), OP_CHECKSIG , OP_ELSE , opPushData (S.encode bPubkey), OP_CHECKSIGVERIFY ] ++ concat (map (\hash -> [OP_HASH256, opPushData (S.encode hash), OP_EQUALVERIFY]) (init sumHashes)) ++ [ OP_HASH256, opPushData $ S.encode (last sumHashes), OP_EQUAL ] ++ [ OP_ENDIF ] makeBobCommitRedeem :: PubKey -> PubKey -> [Hash256] -> Integer -> Script makeBobCommitRedeem aPubkey bPubkey bHashes locktime = Script $ [ OP_IF -- OP_NOP2 is OP_CHECKLOCKTIMEVERIFY (CLTV) -- TODO update haskoin with cltv op , opPushData (S.encode locktime), OP_NOP2, OP_DROP , opPushData (S.encode bPubkey), OP_CHECKSIG , OP_ELSE , opPushData (S.encode aPubkey), OP_CHECKSIGVERIFY , OP_HASH256 ] ++ concat (map (\hash -> [OP_DUP, opPushData (S.encode hash), OP_EQUAL, OP_SWAP]) (init bHashes)) ++ [ opPushData $ S.encode (last bHashes), OP_EQUAL ] ++ replicate (length bHashes - 1) OP_BOOLOR ++ [ OP_ENDIF ] -- |Takes coins to sign, the data to place in the OP_RETURN and the miner's fee value makeAdTransaction :: [UTXO] -- ^ The outputs to spend -> PrvKey -- ^ the key to sign with -> B.ByteString -- ^ the location to encode in the ad -> Word64 -- ^ the ad nonce to encode -> SatoshiValue -- ^ the ad fee -> B.ByteString -- ^ the Refraction identifier -> Either String Tx makeAdTransaction utxos prvkey loc nonce adFee ref = do let ad = B.concat [ref, loc, S.encode nonce] tx <- buildTx (map _outPoint utxos) [ (DataCarrier ad, 0), (addressToOutput (pubKeyAddr (derivePubKey prvkey)), calculateAmount utxos)] ins <- mapM mkInput utxos signTx tx ins [prvkey] -- |Takes coins to sign, the data to place in the OP_RETURN and the miner's fee value makePairRequest :: [UTXO] -- ^ The outputs to spend -> PrvKey -- ^ the key to sign with -> (Word64, Word64) -- ^ the nonce pair to encode -> SatoshiValue -- ^ the ad fee -> B.ByteString -- ^ the Refraction identifier -> Either String Tx makePairRequest utxos prvkey (aNonce, rNonce) adFee ref = do let ad = B.concat [ref, S.encode aNonce, S.encode rNonce] tx <- buildTx (map _outPoint utxos) [ (DataCarrier ad, 0), (addressToOutput (pubKeyAddr (derivePubKey prvkey)), calculateAmount utxos)] ins <- mapM mkInput utxos signTx tx ins [prvkey]
hudon/refraction-hs
src/Network/Refraction/Generator.hs
gpl-3.0
8,154
0
18
1,900
2,136
1,116
1,020
134
1
module Main where main :: IO () main = do
Jugendhackt/haskell-ricochet
src/Demo/Querschlaeger.hs
gpl-3.0
44
1
7
12
20
11
9
-1
-1
module Pipeline ( process , prettyPrint ) where import Data.Maybe import Data.List (nub) import PGF import ErrM import ParAST import PrintAST import AbsAST import InferenceEngine data Interpretation = Interpretation { language :: Language , ast :: Expression , inferences :: Inferences } process :: PGF -> String -> [String] process pgf str = case parseAllLang pgf (startCat pgf) str of ((l,ts):_) -> map (\ interpretation -> prettyPrint pgf interpretation) $ map (\ t -> let e = ast2expr t in (Interpretation l e (InferenceEngine.run e))) ts _ -> [] prettyPrint :: PGF -> Interpretation -> String prettyPrint pgf (Interpretation l ast is) = "\n" ++ printTree ast ++ "\n" ++ foldl (++) "\n" (map (\ (e,r) -> "\n" ++ printTree r ++ " " ++ linearize pgf l (expr2ast e)) is) ast2expr :: Tree -> Expression ast2expr tree = let str = "(" ++ showExpr [] tree ++ ")" in case pExpression $ myLexer $ str of Ok e -> e _ -> error $ "BNFC could not parse: " ++ str expr2ast :: Expression -> Tree expr2ast e = let str = printTree e in case readExpr str of Just ast -> ast Nothing -> error $ "PGF could not read: " ++ str
cunger/mule
src/Pipeline.hs
gpl-3.0
1,486
0
18
582
453
237
216
34
2
module Functions.Series.Series ( ) where import Functions.Combinatorics.CombFunc (fact) import Functions.Algebra (incSum) import Data.Number.CReal powOfe ::Float -> Float powOfe x = incSum f 0 33 where f i = x**i / (fact i) powOfa :: Float -> Float-> Float powOfa a x = incSum f 0 33 where f i = (x*log a)**i / (fact i) lnOfx :: Float -> Float lnOfx x = netSum f 1 33 where f i = 2*(1/oddTerm)*((x-1)/(x+1))**oddTerm where oddTerm = 2*i-1 netSum f minB maxB = sum $ reverse [f i | i <- [minB .. maxB]] {- - Or another way around lnOfx2 :: Float -> Float lnOfx2 x = netSum f 1 33 where f i = (1/i)*((x-1)/x)**i netSum f minB maxB = sum $ reverse [f i | i <- [minB .. maxB]] -}
LeoMingo/RPNMathParser
Functions/Series/Series.hs
gpl-3.0
759
0
12
215
278
148
130
16
1
{-| Module : Optimization.AST Description : Performs optimizations on the AST. Copyright : 2014, Jonas Cleve License : GPL-3 -} module Optimization.AST ( optimize ) where import Interface.AST ( AST ) import Optimization.AST.ConstantFolding ( foldConstants ) -- | Chain various optimization steps. optimize :: AST -> AST optimize = foldConstants
Potregon/while
src/Optimization/AST.hs
gpl-3.0
380
0
5
85
48
30
18
8
1
module System.DevUtils.Redis.Helpers.Info ( module A ) where import System.DevUtils.Redis.Helpers.Info.Include as A import System.DevUtils.Redis.Helpers.Info.Default as A import System.DevUtils.Redis.Helpers.Info.Parser as A import System.DevUtils.Redis.Helpers.Info.Marshall as A import System.DevUtils.Redis.Helpers.Info.JSON as A import System.DevUtils.Redis.Helpers.Info.Run as A
adarqui/DevUtils-Redis
src/System/DevUtils/Redis/Helpers/Info.hs
gpl-3.0
386
0
4
33
81
65
16
8
0
module GUI.RSCoin.Addresses ( VerboseAddress (..) , getAddresses ) where import Control.Lens ((^.)) import Control.Monad (forM) import qualified Data.IntMap.Strict as M import RSCoin.Core (Coin (..), CoinAmount, PublicKey, defaultNodeContext, genesisAddress, getAddress, userLoggerName) import RSCoin.Timed (ContextArgument (..), runRealModeUntrusted) import RSCoin.User (GetOwnedDefaultAddresses (..), UserState, getAmountNoUpdate, query) data VerboseAddress = VA { address :: PublicKey , balance :: CoinAmount } -- FIXME: this is used only in gui. Now that we are using Rational in -- Coin I am not sure what is correct way to implement this. For now I -- will just round the value. getAddresses :: Maybe FilePath -> UserState -> IO [VerboseAddress] getAddresses confPath st = do as <- query st $ GetOwnedDefaultAddresses $ defaultNodeContext ^. genesisAddress let ctxArg = maybe CADefaultLocation CACustomLocation confPath forM as $ \a -> runRealModeUntrusted userLoggerName ctxArg $ do b <- M.findWithDefault 0 0 <$> getAmountNoUpdate st a return $ VA (getAddress a) (getCoin b)
input-output-hk/rscoin-haskell
src/User/GUI/RSCoin/Addresses.hs
gpl-3.0
1,381
0
15
447
287
162
125
26
1
{-# LANGUAGE TemplateHaskell, BangPatterns #-} module Data.Ephys.TrackPosition where ------------------------------------------------------------------------------ import Control.Lens import Control.Applicative ((<$>),(<*>)) import Data.Graph import Data.List (sortBy) import qualified Data.Map as Map import Data.Ord (comparing) import Data.SafeCopy import qualified Data.Vector as V ------------------------------------------------------------------------------ import Data.Ephys.Position ------------------------------------------------------------------------------ data TrackBin = TrackBin { _binName :: !String , _binLoc :: !Location , _binDir :: !Double -- radians , _binA :: !Double , _binZ :: !Double , _binWid :: !Double , _binCaps :: !BinCaps } deriving (Eq, Ord, Show) data BinCaps = CapCircle | CapFlat (Double,Double) deriving (Eq, Ord, Show) $(makeLenses ''TrackBin) data Track = Track { _trackBins :: [TrackBin] } deriving (Eq, Show) data TrackDirection = Outbound | Inbound deriving (Eq, Ord, Show) data TrackEccentricity = OutOfBounds | InBounds deriving (Eq, Ord, Show) data TrackPos = TrackPos { _trackBin :: !TrackBin , _trackDir :: !TrackDirection , _trackEcc :: !TrackEccentricity } deriving (Eq, Ord, Show) $(makeLenses ''Track) $(makeLenses ''TrackPos) allTrackPos :: Track -> V.Vector TrackPos allTrackPos t = V.fromList [TrackPos bin dir ecc | bin <- t^.trackBins , dir <- [Inbound,Outbound] , ecc <- [OutOfBounds,InBounds]] -- Use mapping from track bin to a to model 'fields' in general -- ie an instantaneous occupancy field, a trial-sum occupancy -- field, or a spike rate field type Field = V.Vector Double type LabeledField a = V.Vector (TrackPos, a) labelField :: Track -> Field -> LabeledField Double labelField t f = V.zip (allTrackPos t) f data PosKernel = PosDelta | PosGaussian Double ------------------------------------------------------------------------------ -- Turn a position into an instantaneous field posToField :: Track -> Position -> PosKernel -> Field posToField t pos kern = let distSq bin = locSqDist (pos^.location) (bin^.binLoc) binC = trackClosestBin t pos tDir | cos (pos^.heading - binC^.binDir) > 0 = Outbound | otherwise = Inbound ecc b | (abs y') > (b^.binWid / 2) = OutOfBounds | otherwise = InBounds where (_,y') = relativeCoords b (pos^.location^.x, pos^.location^.y) trackPosValUnNormalized :: TrackPos -> Double trackPosValUnNormalized tp = case kern of PosDelta -> if tp^.trackBin == binC && tp^.trackDir == tDir && tp^.trackEcc == ecc binC then 1 else 0 PosGaussian sd -> if (tp^.trackEcc) == ecc binC && (tp^.trackDir) == tDir then exp( (-1) / (2 * sd * sd) * distSq (tp^.trackBin) ) else 0 totalVal = V.foldl (\a tp -> a + trackPosValUnNormalized tp) 0 (allTrackPos t :: V.Vector TrackPos) trackPosVal :: TrackPos -> Double trackPosVal tp = if totalVal > 0 then trackPosValUnNormalized tp / totalVal else 1/ (fromIntegral $ V.length (allTrackPos t)) in (V.map trackPosVal (allTrackPos t)) ------------------------------------------------------------------------------ relativeCoords :: TrackBin -> (Double,Double) -> (Double,Double) relativeCoords bin (x',y') = let th = (-1 * bin^.binDir) dx = x' - bin^.binLoc.x dy = y' - bin^.binLoc.y in (dx * cos th - dy * sin th, dx * sin th + dy * cos th) trackClosestBin :: Track -> Position -> TrackBin trackClosestBin track pos = head . sortBy (comparing (posBinDistSq pos)) $ (track ^. trackBins) posBinDistSq :: Position -> TrackBin -> Double posBinDistSq pos bin = locSqDist (bin^.binLoc) (pos^.location) circularTrack :: (Double,Double) -- (x,y) in meters -> Double -- radius in meters -> Double -- height in meters -> Double -- track width in meters -> Double -- bin length in meters -> Track circularTrack (cX,cY) r h w tau = Track [aPoint t [n] | (t,n) <- zip thetaCs names] where fI = fromIntegral circumference = 2*pi*r nPts = floor (circumference / tau) :: Int tau' = circumference / fromIntegral nPts names = map (toEnum . (+ fromEnum 'A')) [0..nPts-1] thetaIncr = 2*pi/ fI nPts thetaCs = [0, thetaIncr .. 2*pi-thetaIncr] aPoint :: Double -> String -> TrackBin aPoint theta n = TrackBin n (Location (r * cos theta + cX) (r * sin theta + cY) h) (theta + pi/2) (-1 * tau' / 2) (tau' / 2) w (CapFlat (thetaIncr/(-2), thetaIncr/2)) ------------------------------------------------------------------------------ updateField :: (Double->Double->Double) -> Field -> Field -> Field updateField = V.zipWith {-# INLINE updateField #-} {- -- TODO - serialize TrackPos putTrackPos :: Put TrackPos putTrackPos tp = do put $ tp^. -}
imalsogreg/tetrode-ephys
lib/Data/Ephys/TrackPosition.hs
gpl-3.0
5,630
0
20
1,748
1,603
863
740
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DoubleClickSearch.Reports.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Polls for the status of a report request. -- -- /See:/ <https://developers.google.com/search-ads Search Ads 360 API Reference> for @doubleclicksearch.reports.get@. module Network.Google.Resource.DoubleClickSearch.Reports.Get ( -- * REST Resource ReportsGetResource -- * Creating a Request , reportsGet , ReportsGet -- * Request Lenses , rgXgafv , rgUploadProtocol , rgAccessToken , rgReportId , rgUploadType , rgCallback ) where import Network.Google.DoubleClickSearch.Types import Network.Google.Prelude -- | A resource alias for @doubleclicksearch.reports.get@ method which the -- 'ReportsGet' request conforms to. type ReportsGetResource = "doubleclicksearch" :> "v2" :> "reports" :> Capture "reportId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Report -- | Polls for the status of a report request. -- -- /See:/ 'reportsGet' smart constructor. data ReportsGet = ReportsGet' { _rgXgafv :: !(Maybe Xgafv) , _rgUploadProtocol :: !(Maybe Text) , _rgAccessToken :: !(Maybe Text) , _rgReportId :: !Text , _rgUploadType :: !(Maybe Text) , _rgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ReportsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rgXgafv' -- -- * 'rgUploadProtocol' -- -- * 'rgAccessToken' -- -- * 'rgReportId' -- -- * 'rgUploadType' -- -- * 'rgCallback' reportsGet :: Text -- ^ 'rgReportId' -> ReportsGet reportsGet pRgReportId_ = ReportsGet' { _rgXgafv = Nothing , _rgUploadProtocol = Nothing , _rgAccessToken = Nothing , _rgReportId = pRgReportId_ , _rgUploadType = Nothing , _rgCallback = Nothing } -- | V1 error format. rgXgafv :: Lens' ReportsGet (Maybe Xgafv) rgXgafv = lens _rgXgafv (\ s a -> s{_rgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). rgUploadProtocol :: Lens' ReportsGet (Maybe Text) rgUploadProtocol = lens _rgUploadProtocol (\ s a -> s{_rgUploadProtocol = a}) -- | OAuth access token. rgAccessToken :: Lens' ReportsGet (Maybe Text) rgAccessToken = lens _rgAccessToken (\ s a -> s{_rgAccessToken = a}) -- | ID of the report request being polled. rgReportId :: Lens' ReportsGet Text rgReportId = lens _rgReportId (\ s a -> s{_rgReportId = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). rgUploadType :: Lens' ReportsGet (Maybe Text) rgUploadType = lens _rgUploadType (\ s a -> s{_rgUploadType = a}) -- | JSONP rgCallback :: Lens' ReportsGet (Maybe Text) rgCallback = lens _rgCallback (\ s a -> s{_rgCallback = a}) instance GoogleRequest ReportsGet where type Rs ReportsGet = Report type Scopes ReportsGet = '["https://www.googleapis.com/auth/doubleclicksearch"] requestClient ReportsGet'{..} = go _rgReportId _rgXgafv _rgUploadProtocol _rgAccessToken _rgUploadType _rgCallback (Just AltJSON) doubleClickSearchService where go = buildClient (Proxy :: Proxy ReportsGetResource) mempty
brendanhay/gogol
gogol-doubleclick-search/gen/Network/Google/Resource/DoubleClickSearch/Reports/Get.hs
mpl-2.0
4,327
0
17
1,052
702
409
293
101
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.Dataflow.Projects.Jobs.Debug.SendCapture -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Send encoded debug capture data for component. -- -- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.jobs.debug.sendCapture@. module Network.Google.Resource.Dataflow.Projects.Jobs.Debug.SendCapture ( -- * REST Resource ProjectsJobsDebugSendCaptureResource -- * Creating a Request , projectsJobsDebugSendCapture , ProjectsJobsDebugSendCapture -- * Request Lenses , pjdscXgafv , pjdscJobId , pjdscUploadProtocol , pjdscAccessToken , pjdscUploadType , pjdscPayload , pjdscProjectId , pjdscCallback ) where import Network.Google.Dataflow.Types import Network.Google.Prelude -- | A resource alias for @dataflow.projects.jobs.debug.sendCapture@ method which the -- 'ProjectsJobsDebugSendCapture' request conforms to. type ProjectsJobsDebugSendCaptureResource = "v1b3" :> "projects" :> Capture "projectId" Text :> "jobs" :> Capture "jobId" Text :> "debug" :> "sendCapture" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SendDebugCaptureRequest :> Post '[JSON] SendDebugCaptureResponse -- | Send encoded debug capture data for component. -- -- /See:/ 'projectsJobsDebugSendCapture' smart constructor. data ProjectsJobsDebugSendCapture = ProjectsJobsDebugSendCapture' { _pjdscXgafv :: !(Maybe Xgafv) , _pjdscJobId :: !Text , _pjdscUploadProtocol :: !(Maybe Text) , _pjdscAccessToken :: !(Maybe Text) , _pjdscUploadType :: !(Maybe Text) , _pjdscPayload :: !SendDebugCaptureRequest , _pjdscProjectId :: !Text , _pjdscCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsJobsDebugSendCapture' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pjdscXgafv' -- -- * 'pjdscJobId' -- -- * 'pjdscUploadProtocol' -- -- * 'pjdscAccessToken' -- -- * 'pjdscUploadType' -- -- * 'pjdscPayload' -- -- * 'pjdscProjectId' -- -- * 'pjdscCallback' projectsJobsDebugSendCapture :: Text -- ^ 'pjdscJobId' -> SendDebugCaptureRequest -- ^ 'pjdscPayload' -> Text -- ^ 'pjdscProjectId' -> ProjectsJobsDebugSendCapture projectsJobsDebugSendCapture pPjdscJobId_ pPjdscPayload_ pPjdscProjectId_ = ProjectsJobsDebugSendCapture' { _pjdscXgafv = Nothing , _pjdscJobId = pPjdscJobId_ , _pjdscUploadProtocol = Nothing , _pjdscAccessToken = Nothing , _pjdscUploadType = Nothing , _pjdscPayload = pPjdscPayload_ , _pjdscProjectId = pPjdscProjectId_ , _pjdscCallback = Nothing } -- | V1 error format. pjdscXgafv :: Lens' ProjectsJobsDebugSendCapture (Maybe Xgafv) pjdscXgafv = lens _pjdscXgafv (\ s a -> s{_pjdscXgafv = a}) -- | The job id. pjdscJobId :: Lens' ProjectsJobsDebugSendCapture Text pjdscJobId = lens _pjdscJobId (\ s a -> s{_pjdscJobId = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pjdscUploadProtocol :: Lens' ProjectsJobsDebugSendCapture (Maybe Text) pjdscUploadProtocol = lens _pjdscUploadProtocol (\ s a -> s{_pjdscUploadProtocol = a}) -- | OAuth access token. pjdscAccessToken :: Lens' ProjectsJobsDebugSendCapture (Maybe Text) pjdscAccessToken = lens _pjdscAccessToken (\ s a -> s{_pjdscAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pjdscUploadType :: Lens' ProjectsJobsDebugSendCapture (Maybe Text) pjdscUploadType = lens _pjdscUploadType (\ s a -> s{_pjdscUploadType = a}) -- | Multipart request metadata. pjdscPayload :: Lens' ProjectsJobsDebugSendCapture SendDebugCaptureRequest pjdscPayload = lens _pjdscPayload (\ s a -> s{_pjdscPayload = a}) -- | The project id. pjdscProjectId :: Lens' ProjectsJobsDebugSendCapture Text pjdscProjectId = lens _pjdscProjectId (\ s a -> s{_pjdscProjectId = a}) -- | JSONP pjdscCallback :: Lens' ProjectsJobsDebugSendCapture (Maybe Text) pjdscCallback = lens _pjdscCallback (\ s a -> s{_pjdscCallback = a}) instance GoogleRequest ProjectsJobsDebugSendCapture where type Rs ProjectsJobsDebugSendCapture = SendDebugCaptureResponse type Scopes ProjectsJobsDebugSendCapture = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/userinfo.email"] requestClient ProjectsJobsDebugSendCapture'{..} = go _pjdscProjectId _pjdscJobId _pjdscXgafv _pjdscUploadProtocol _pjdscAccessToken _pjdscUploadType _pjdscCallback (Just AltJSON) _pjdscPayload dataflowService where go = buildClient (Proxy :: Proxy ProjectsJobsDebugSendCaptureResource) mempty
brendanhay/gogol
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Jobs/Debug/SendCapture.hs
mpl-2.0
6,160
0
21
1,463
876
510
366
135
1
{-# 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.EC2.DescribeVpcAttribute -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- 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 <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Describes the specified attribute of the specified VPC. You can specify only -- one attribute at a time. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpcAttribute.html> module Network.AWS.EC2.DescribeVpcAttribute ( -- * Request DescribeVpcAttribute -- ** Request constructor , describeVpcAttribute -- ** Request lenses , dva1Attribute , dva1DryRun , dva1VpcId -- * Response , DescribeVpcAttributeResponse -- ** Response constructor , describeVpcAttributeResponse -- ** Response lenses , dvarEnableDnsHostnames , dvarEnableDnsSupport , dvarVpcId ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data DescribeVpcAttribute = DescribeVpcAttribute { _dva1Attribute :: Maybe VpcAttributeName , _dva1DryRun :: Maybe Bool , _dva1VpcId :: Text } deriving (Eq, Read, Show) -- | 'DescribeVpcAttribute' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dva1Attribute' @::@ 'Maybe' 'VpcAttributeName' -- -- * 'dva1DryRun' @::@ 'Maybe' 'Bool' -- -- * 'dva1VpcId' @::@ 'Text' -- describeVpcAttribute :: Text -- ^ 'dva1VpcId' -> DescribeVpcAttribute describeVpcAttribute p1 = DescribeVpcAttribute { _dva1VpcId = p1 , _dva1DryRun = Nothing , _dva1Attribute = Nothing } -- | The VPC attribute. dva1Attribute :: Lens' DescribeVpcAttribute (Maybe VpcAttributeName) dva1Attribute = lens _dva1Attribute (\s a -> s { _dva1Attribute = a }) -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have the -- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'. dva1DryRun :: Lens' DescribeVpcAttribute (Maybe Bool) dva1DryRun = lens _dva1DryRun (\s a -> s { _dva1DryRun = a }) -- | The ID of the VPC. dva1VpcId :: Lens' DescribeVpcAttribute Text dva1VpcId = lens _dva1VpcId (\s a -> s { _dva1VpcId = a }) data DescribeVpcAttributeResponse = DescribeVpcAttributeResponse { _dvarEnableDnsHostnames :: Maybe AttributeBooleanValue , _dvarEnableDnsSupport :: Maybe AttributeBooleanValue , _dvarVpcId :: Maybe Text } deriving (Eq, Read, Show) -- | 'DescribeVpcAttributeResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dvarEnableDnsHostnames' @::@ 'Maybe' 'AttributeBooleanValue' -- -- * 'dvarEnableDnsSupport' @::@ 'Maybe' 'AttributeBooleanValue' -- -- * 'dvarVpcId' @::@ 'Maybe' 'Text' -- describeVpcAttributeResponse :: DescribeVpcAttributeResponse describeVpcAttributeResponse = DescribeVpcAttributeResponse { _dvarVpcId = Nothing , _dvarEnableDnsSupport = Nothing , _dvarEnableDnsHostnames = Nothing } -- | Indicates whether the instances launched in the VPC get DNS hostnames. If -- this attribute is 'true', instances in the VPC get DNS hostnames; otherwise, -- they do not. dvarEnableDnsHostnames :: Lens' DescribeVpcAttributeResponse (Maybe AttributeBooleanValue) dvarEnableDnsHostnames = lens _dvarEnableDnsHostnames (\s a -> s { _dvarEnableDnsHostnames = a }) -- | Indicates whether DNS resolution is enabled for the VPC. If this attribute is 'true', the Amazon DNS server resolves DNS hostnames for your instances to -- their corresponding IP addresses; otherwise, it does not. dvarEnableDnsSupport :: Lens' DescribeVpcAttributeResponse (Maybe AttributeBooleanValue) dvarEnableDnsSupport = lens _dvarEnableDnsSupport (\s a -> s { _dvarEnableDnsSupport = a }) -- | The ID of the VPC. dvarVpcId :: Lens' DescribeVpcAttributeResponse (Maybe Text) dvarVpcId = lens _dvarVpcId (\s a -> s { _dvarVpcId = a }) instance ToPath DescribeVpcAttribute where toPath = const "/" instance ToQuery DescribeVpcAttribute where toQuery DescribeVpcAttribute{..} = mconcat [ "Attribute" =? _dva1Attribute , "DryRun" =? _dva1DryRun , "VpcId" =? _dva1VpcId ] instance ToHeaders DescribeVpcAttribute instance AWSRequest DescribeVpcAttribute where type Sv DescribeVpcAttribute = EC2 type Rs DescribeVpcAttribute = DescribeVpcAttributeResponse request = post "DescribeVpcAttribute" response = xmlResponse instance FromXML DescribeVpcAttributeResponse where parseXML x = DescribeVpcAttributeResponse <$> x .@? "enableDnsHostnames" <*> x .@? "enableDnsSupport" <*> x .@? "vpcId"
romanb/amazonka
amazonka-ec2/gen/Network/AWS/EC2/DescribeVpcAttribute.hs
mpl-2.0
5,636
0
11
1,156
701
421
280
79
1
{-# LANGUAGE NoMonomorphismRestriction, PackageImports #-} -- By using Package Qualified Imports, we can shadow HSpec with our own system module Test.Hspec ( -- CodeWars Specification system (shadows Hspec) hspec -- HSpec , Spec , describe , it -- QuickCheck , property -- Exceptions , evaluate -- Expectation Combinators, -- see https://github.com/sol/hspec-expectations/blob/master/src/Test/Hspec/Expectations.hs , Expectation , expectationFailure , shouldBe , shouldNotBe , shouldSatisfy , shouldContain , shouldMatchList , shouldReturn , shouldThrow , Selector , anyException , anyErrorCall , anyIOException , anyArithException , errorCall -- BlackList import declarations , Hidden (..) , BlackList , hidden ) where import "hspec" Test.Hspec hiding (hspec) import Test.CodeWars.Runner (hspec) import Test.CodeWars.BlackList (Hidden (..), BlackList, hidden) import Test.QuickCheck hiding (reason) import Control.Exception (evaluate) import Test.HUnit (assertFailure) import Control.Monad (unless) infix 1 `shouldNotBe` shouldNotBe :: (Eq a, Show a) => a -> a -> Expectation shouldNotBe expected actual = unless (actual /= expected) (assertFailure msg) where msg = "expected: " ++ show expected ++ "\n to be different than: " ++ show actual
remotty/cdr
frameworks/haskell/Test/Hspec.hs
agpl-3.0
1,351
0
10
272
266
165
101
39
1
-- Copyright (c) 2014-2015 Jonathan M. Lange <jml@mumak.net> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Main where import BasicPrelude import Control.Concurrent.STM (atomically) import Web.Spock.Safe import Hazard (hazardWeb, makeHazard) main :: IO () main = do hazard <- atomically makeHazard runSpock 3000 $ spockT id $ hazardWeb hazard
jml/hazard
src/Main.hs
apache-2.0
942
0
9
154
95
58
37
11
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Authentication Statistics | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/authstats/src/main/javahelp/org/zaproxy/zap/extension/authstats/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
986
78
66
159
413
209
204
-1
-1