code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
module Lib
( someFunc
) where
import Data.Text
import Data.Typeable (Typeable)
data Proxy a = Proxy
data a :| b = a :| b deriving Typeable
infixr 9 :|
data (a :: k) := b deriving Typeable
infixr 9 :=
data Column (a :: k) typ deriving Typeable
type SomeTable = "hello" := Column "hello" Text :| Column "world" Int
someTable :: Proxy SomeTable
someTable = Proxy
-- We need some function that actually handles the "stuff" here (a la `serve`)
-- Some ideas: migrate, store, get
-- How is auto-incrementing done? Migrations totally separate from data types in other frameworks etc
someFunc :: IO ()
someFunc = putStrLn "someFunc"
| 5outh/courier | src/Lib.hs | mit | 842 | 0 | 7 | 194 | 149 | 92 | 57 | -1 | -1 |
{-# LANGUAGE ExistentialQuantification #-}
module Vis.Impl (
) where
import Data.IORef
import Vis
import U.Objects
import U.Exec.Mutable
import OpenGLRenderer as R
data RenderableSystem sys d r =
forall body obj. (Renderable (body d) r, Renderable (obj d) r, MutableSystem (sys body obj) body obj d) =>
RenderableSystem (sys body obj d)
visualize :: (Vis.Renderer r (sys body obj d)) => r -> IO state -> RenderableSystem sys d r -> IO()
visualize r stateIO sys = R.run stateIO rend Nothing undefined undefined
where rend state wRef = do let l = do RenderableSystem w <- readIORef wRef
bulkRender r w
return l
| fehu/hgt | space-independent/src/Vis/Impl.hs | mit | 765 | 0 | 15 | 258 | 241 | 125 | 116 | 15 | 1 |
module Antemodulum.Read (
module Export
) where
--------------------------------------------------------------------------------
import Text.Read as Export (Read(..), ReadS, read, reads, readEither, readMaybe)
| docmunch/antemodulum | src/Antemodulum/Read.hs | mit | 214 | 0 | 6 | 22 | 44 | 30 | 14 | 3 | 0 |
{-# LANGUAGE ImplicitParams, DeriveDataTypeable, TypeOperators #-}
module Transformation.CommonBlockElim where
import Control.Monad
import Control.Monad.State.Lazy
import Debug.Trace
import Data.Data
import Data.List
import Data.Ord
import qualified Data.Map as Data.Map
import Data.Generics.Uniplate.Operations
import Language.Fortran
import Language.Fortran.Pretty
import Helpers
import Traverse
import Analysis.Annotations
import Analysis.Syntax
import Analysis.Types
import Transformation.Syntax
-- Typed common block representation
type TCommon p = (Maybe String, [(Variable, Type p)])
-- Typed and "located" common block representation
-- TODO: include column + line information
type TLCommon p = (Filename, (String, TCommon p))
-- Top-level functions for eliminating common blocks in a set of files
commonElimToModules :: Directory -> [(Filename, Program A)] -> (Report, [(Filename, Program A)])
-- Eliminates common blocks in a program directory (and convert to modules)
commonElimToModules d ps = let (ps', (r, cg)) = runState (analyseCommons ps) ("", [])
(r', ps'') = introduceModules d cg
psR = updateUseDecls ps' cg
in (r ++ r', psR ++ ps'')
analyseCommons :: [(Filename, Program A)] -> State (Report, [TLCommon A]) [(Filename, Program A)]
analyseCommons pss = let
defs' :: Filename -> ProgUnit A -> State (Report, [TLCommon A]) (ProgUnit A)
defs' fname p = case (getSubName p) of
Just pname -> transformBiM (collectCommons fname pname) p
Nothing -> case p of
IncludeProg a sp ds f ->
-- ("doing an include: " ++ (show fname)) `trace`
let -- create dummy block
a0 = unitAnnotation
b = Block a (UseBlock (UseNil a0) nullLoc)
(ImplicitNull a0) sp ds
(NullStmt a0 nullSpan)
in do (Block _ _ _ _ ds' _) <- transformBiM (collectCommons fname fname) b
return $ IncludeProg a sp ds' f
otherwise -> return p
-- defs' f (Sub _ _ _ (SubName _ n) _ b) rs = (concat rs) ++ [(f, (n, snd $ runState (collectTCommons' b) []))]
-- Don't support functions yet
-- defs' f (Function _ _ _ (SubName _ n) _ _ b) rs = (concat rs) ++ [(f, (n, snd $ runState (collectTCommons b) []))]
-- defs' _ _ rs = concat rs
in mapM (\(f, ps) -> do ps' <- mapM (transformBiM (defs' f)) ps
return (f, ps')) pss
collectCommons :: Filename -> String -> Block A -> State (Report, [TLCommon A]) (Block A)
collectCommons fname pname b =
let tenv = typeEnv b
commons' :: Decl A -> State (Report, [TLCommon A]) (Decl A)
commons' f@(Common a sp cname exprs) =
do let r' = fname ++ (show $ srcLineCol $ fst sp) ++ ": removed common declaration\n"
(r, env) <- get
put (r ++ r', (fname, (pname, (cname, typeCommonExprs exprs))):env)
return $ (NullDecl (a { refactored = (Just $ fst sp) }) sp)
commons' f = return f
typeCommonExprs :: [Expr Annotation] -> [(Variable, Type Annotation)]
typeCommonExprs [] = []
typeCommonExprs ((Var _ sp [(VarName _ v, _)]):es) =
case (tenvLookup v tenv) of
Just t -> (v, t) : (typeCommonExprs es)
Nothing -> error $ "Variable " ++ (show v) ++ " is of an unknown type at: " ++ show sp
typeCommonExprs (e:_) = error $ "Not expecting a non-variable expression in expression at: " ++ show (srcSpan e)
in transformBiM commons' b
{- Comparison functions for common block names and variables -}
cmpTLConFName :: TLCommon A -> TLCommon A -> Ordering
cmpTLConFName (f1, (_, _)) (f2, (_, _)) = compare f1 f2
cmpTLConPName :: TLCommon A -> TLCommon A -> Ordering
cmpTLConPName (_, (p1, _)) (_, (p2, _)) = compare p1 p2
cmpTLConBNames :: TLCommon A -> TLCommon A -> Ordering
cmpTLConBNames (_, (_, c1)) (_, (_, c2)) = cmpTConBNames c1 c2
cmpTConBNames :: TCommon A -> TCommon A -> Ordering
cmpTConBNames (Nothing, _) (Nothing, _) = EQ
cmpTConBNames (Nothing, _) (Just _, _) = LT
cmpTConBNames (Just _, _) (Nothing, _) = GT
cmpTConBNames (Just n, _) (Just n', _) = if (n < n') then LT
else if (n > n') then GT else EQ
-- Fold [TLCommon p] to get a list of ([(TLCommon p, Renamer p)], [(Filename, Program A)])
-- How to decide which gets to be the "head" perhaps the one which triggers the *least* renaming (ooh!)
-- (this is calculated by looking for the mode of the TLCommon (for a particular Common)
-- (need to do gorouping, but sortBy is used already so... (IS THIS STABLE- does this matter?))
onCommonBlock :: (TCommon A -> TCommon A) -> TLCommon A -> TLCommon A
onCommonBlock f (fname, (pname, tcommon)) = (fname, (pname, f tcommon))
commonName Nothing = "Common"
commonName (Just x) = x
-- Freshen the names for a common block and generate a renamer from the old block to this
freshenCommonNames :: TLCommon A -> (TLCommon A, RenamerCoercer)
freshenCommonNames (fname, (pname, (cname, fields))) =
let mkRenamerAndCommon (r, tc) (v, t) =
let v' = (caml $ commonName cname) ++ "_" ++ v
in (Data.Map.insert v (Just v', Nothing) r, (v', t) : tc)
(r, fields') = foldl mkRenamerAndCommon (Data.Map.empty, []) fields
in ((fname, (pname, (cname, fields'))), Just r)
-- From a list of typed and located common blocks
-- group by the common block name, and then group/sort within such that the "mode" block is first
groupSortCommonBlock :: [TLCommon A] -> [[[TLCommon A]]]
groupSortCommonBlock commons = let -- Group by names of the common blocks
gcs = groupBy (\x y -> cmpEq $ cmpTLConBNames x y) commons
-- Group within by the different common block variable-type fields
gccs = map (sortBy (\y x -> length x `compare` length y) . group . sortBy cmpVarName) gcs
in gccs
cmpVarName :: TLCommon A -> TLCommon A -> Ordering
cmpVarName (fname1, (pname1, (name1, vtys1))) (fnam2, (pname2, (name2, vtys2))) = map fst vtys1 `compare` map fst vtys2
mkTLCommonRenamers :: [TLCommon A] -> [(TLCommon A, RenamerCoercer)]
mkTLCommonRenamers commons = case allCoherentCommonsP commons of
(r, False) -> error $ "Common blocks are incoherent!\n" ++ r -- (r, []) -- Incoherent commons
(_, True) -> let gccs = groupSortCommonBlock commons
-- Find the "mode" common block and freshen the names for this, creating
-- a renamer between this and every module
gcrcs = map (\grp -> -- grp are block decls all for the same block
let (com, r) = freshenCommonNames (head (head grp))
in map (\c -> (c, r)) (head grp) ++
map (\c -> (c, mkRenamerCoercerTLC c com)) (concat $ tail grp)) gccs
-- Now re-sort based on the file and program unit
gcrcs' = sortBy (cmpFst cmpTLConFName) (sortBy (cmpFst cmpTLConPName) (concat gcrcs))
in gcrcs'
updateUseDecls :: [(Filename, Program A)] -> [TLCommon A] -> [(Filename, Program A)]
updateUseDecls fps tcs =
let tcrs = mkTLCommonRenamers tcs
concatUses :: Uses A -> Uses A -> Uses A
concatUses (UseNil p) y = y
concatUses (Use p x us p') y = Use p x (UseNil p) p'
inames :: Decl A -> Maybe String
inames (Include _ (Con _ _ inc)) = Just inc
inames _ = Nothing
importIncludeCommons :: ProgUnit A -> ProgUnit A
importIncludeCommons p = foldl (\p' iname -> ("Iname = " ++ iname) `trace` matchPUnitAlt iname p') p (reduceCollect inames p)
matchPUnitAlt :: Filename -> ProgUnit A -> ProgUnit A
matchPUnitAlt fname p = ("fname = " ++ fname ++ "\n" ++ (show ((lookups' fname) (lookups' fname tcrs)))) `trace`
let tcrs' = (lookups' fname) (lookups' fname tcrs)
srcloc = useSrcLoc p
uses = mkUseStatements srcloc tcrs'
p' = transformBi ((flip concatUses) uses) p
in let ?fname = fname in removeDecls (map snd tcrs') p'
matchPUnit :: Filename -> ProgUnit A -> ProgUnit A
matchPUnit fname p = let pname = case getSubName p of
Nothing -> fname -- If no subname is available, use the filename
Just pname -> pname
tcrs' = (lookups' pname) (lookups' fname tcrs)
srcloc = useSrcLoc p
uses = mkUseStatements srcloc tcrs'
p' = transformBi ((flip concatUses) uses) p
in let ?fname = fname in removeDecls (map snd tcrs') p'
-- Given the list of renamed/coercerd variables form common blocks, remove any declaration sites
removeDecls :: (?fname :: Filename) => [RenamerCoercer] -> ProgUnit A -> ProgUnit A
removeDecls rcs p = let (p', remainingAssignments) = runState (transformBiM (removeDecl rcs) p) []
in addToProgUnit p' remainingAssignments
-- Removes a declaration and collects a list of any default values given at declaration time
-- (which then need to be turned into separate assignment statements)
removeDecl :: (?fname :: Filename) => [RenamerCoercer] -> Decl A -> State [Fortran A] (Decl A)
removeDecl rcs d@(Decl p srcP vars typ) =
(modify (++ assgns)) >> (return $ if (vars' == []) then NullDecl p' srcP
else Decl p' srcP vars' typ)
where
(assgns, vars') = foldl matchVar ([],[]) vars
p' = if (length vars == length vars') then p else p { refactored = Just (fst srcP) }
matchVar :: ([Fortran A], [(Expr A, Expr A, Maybe Int)])
-> (Expr A, Expr A, Maybe Int)
-> ([Fortran A], [(Expr A, Expr A, Maybe Int)])
matchVar (assgns, decls) dec@(lvar@(Var _ _ [(VarName _ v, _)]), e, _) =
if (hasRenaming v rcs) then
case e of
-- Renaming exists and no default, then remove
NullExpr _ _ -> (assgns, decls)
-- Renaming exists but has default, so create an assignment for this
e -> ((Assg p' srcP lvar e) : assgns, decls)
else -- no renaming, preserve declaration
(assgns, dec : decls)
matchVar (assgns, decls) _ = (assgns, decls)
removeDecl _ d = return d
in each fps (\(f, p) -> (f, map importIncludeCommons $ transformBi (matchPUnit f) p))
-- Adds additional statements to the start of the statement block in a program unit
addToProgUnit :: ProgUnit A -> [Fortran A] -> ProgUnit A
addToProgUnit p [] = p
addToProgUnit (IncludeProg p sp decl Nothing) stmts = IncludeProg p sp decl (Just $
prependStatements (Just $ afterEnd sp) (NullStmt unitAnnotation (afterEnd sp)) stmts)
addToProgUnit (IncludeProg p sp decl (Just f)) stmts = IncludeProg p sp decl (Just $ prependStatements Nothing f stmts)
addToProgUnit p stmts = transformBi (flip addToBlock stmts) p
-- Add additional statements to the start of a block
addToBlock :: Block A -> [Fortran A] -> Block A
addToBlock b [] = b
addToBlock (Block p useBlock imps sp decls stmt) stmts = Block p useBlock imps sp decls (prependStatements Nothing stmt stmts)
-- Prepends statements onto a statement
prependStatements :: Maybe SrcSpan -> Fortran A -> [Fortran A] -> Fortran A
prependStatements sp stmt ss = FSeq p' sp' (foldl1 (FSeq p' sp') ss) stmt
where p' = (annotation stmt) { refactored = Just (fst sp') }
sp' = case sp of
Nothing -> srcSpan stmt
Just s -> s
useSrcLoc :: ProgUnit A -> SrcLoc
useSrcLoc (Main _ _ _ _ b _) = useSrcLocB b
useSrcLoc (Sub _ _ _ _ _ b) = useSrcLocB b
useSrcLoc (Function _ _ _ _ _ _ b)= useSrcLocB b
useSrcLoc (Module _ s _ _ _ _ _) = fst s -- TOOD: this isn't very accurate
useSrcLoc (BlockData _ s _ _ _ _) = fst s
useSrcLocB (Block _ (UseBlock _ s) _ _ _ _) = s
renamerToUse :: RenamerCoercer -> [(Variable, Variable)]
renamerToUse Nothing = []
renamerToUse (Just m) = let entryToPair v (Nothing, _) = []
entryToPair v (Just v', _) = [(v, v')]
in Data.Map.foldlWithKey (\xs v e -> (entryToPair v e) ++ xs) [] m
-- make the use statements for a particular program unit's common blocks
mkUseStatements :: SrcLoc -> [(TCommon A, RenamerCoercer)] -> Uses A
mkUseStatements s [] = UseNil (unitAnnotation)
mkUseStatements s (((name, _), r):trs) =
let a = unitAnnotation { refactored = Just s, newNode = True } -- previously-- Just (toCol0 s)
in Use a (commonName name, renamerToUse r) (mkUseStatements s trs) a
mkRenamerCoercerTLC :: TLCommon A :? source -> TLCommon A :? target -> RenamerCoercer
mkRenamerCoercerTLC x@(fname, (pname, common1)) (_, (_, common2)) = mkRenamerCoercer common1 common2
mkRenamerCoercer :: TCommon A :? source -> TCommon A :? target -> RenamerCoercer
mkRenamerCoercer (name1, vtys1) (name2, vtys2)
| name1 == name2 = if (vtys1 == vtys2) then Nothing else Just $ generate vtys1 vtys2 Data.Map.empty
| otherwise = error "Can't generate renamer between different common blocks\n"
where
generate [] [] theta = theta
generate ((var1, ty1):vtys1) ((var2, ty2):vtys2) theta =
let varR = if (var1 == var2) then Nothing else Just var2
typR = if (ty1 == ty2) then Nothing else Just (ty1, ty2)
in generate vtys1 vtys2 (Data.Map.insert var1 (varR, typR) theta)
generate _ _ _ = error "Common blocks of different field length\n"
allCoherentCommonsP :: [TLCommon A] -> (Report, Bool)
allCoherentCommonsP commons = foldM (\p (c1, c2) -> (coherentCommonsP c1 c2) >>= (\p' -> return $ p && p')) True (pairs commons)
coherentCommonsP :: TLCommon A -> TLCommon A -> (Report, Bool)
coherentCommonsP (f1, (p1, (n1, vtys1))) (f2, (p2, (n2, vtys2))) =
if (n1 == n2) then
let coherent :: [(Variable, Type A)] -> [(Variable, Type A)] -> (Report, Bool)
coherent [] [] = ("", True)
coherent ((var1, ty1):xs) ((var2, ty2):ys)
| af ty1 == af ty2 = let (r', c) = coherent xs ys
in (r', c && True)
| otherwise = let ?variant = Alt1 in
let r = (var1 ++ ":" ++ (outputF ty1) ++ "(" ++ (show $ af ty1) ++ ")" ++ " differs from " ++
var2 ++ ":" ++ (outputF ty2) ++ "(" ++ (show $ af ty2) ++ ")" ++ "\n")
(r', _) = coherent xs ys
in (r ++ r', False)
coherent _ _ = ("Common blocks of different field lengths", False) -- Doesn't say which is longer
in coherent vtys1 vtys2
else ("", True) -- Not sure if this is supposed to fail here- in retrospect I think no
-- False -> ("Trying to compare differently named common blocks: " ++ show n1 ++ " and " ++ show n2 ++ "\n", False)
introduceModules :: Directory -> [TLCommon A] -> (Report, [(Filename, Program A)])
introduceModules d cenv = mapM (mkModuleFile d) (map (head . head) (groupSortCommonBlock cenv))
mkModuleFile :: Directory -> (TLCommon A) -> (Report, (Filename, Program A))
mkModuleFile d (_, (_, (name, varTys))) =
let modname = commonName name
fullpath = d ++ "/" ++ modname ++ ".f90"
r = "Created module " ++ modname ++ " at " ++ fullpath ++ "\n"
in (r, (fullpath, [mkModule modname varTys modname]))
mkModule :: String -> [(Variable, Type A)] -> String -> ProgUnit A
mkModule name vtys fname =
let a = unitAnnotation { refactored = Just loc }
loc = SrcLoc (fname ++ ".f90") 0 0
sp = (loc, loc)
toDecl (v, t) = Decl a sp [(Var a sp [(VarName a (name ++ "_" ++ v), [])], NullExpr a sp, Nothing)] -- note here could pull in initialising definition? What if conflicts- highlight as potential source of error?
t
decls = foldl1 (DSeq a) (map toDecl vtys)
in Module a (loc, loc) (SubName a fname) (UseNil a) (ImplicitNone a) decls []
| ucam-cl-dtg/naps-camfort | Transformation/CommonBlockElim.hs | mit | 18,636 | 0 | 31 | 6,953 | 5,429 | 2,877 | 2,552 | 227 | 10 |
{-# LANGUAGE OverloadedStrings, MultiParamTypeClasses, QuasiQuotes, OverloadedLists #-}
module Control.OperationalTransformation.JSON.Apply where
import Control.Lens hiding (Identity)
import Control.OperationalTransformation as OT
import Control.OperationalTransformation.JSON.QuasiQuote (v)
import Control.OperationalTransformation.JSON.Types
import Data.Aeson as A
import Data.Aeson.Lens
import Data.Monoid
import Data.String.Interpolate.IsString
import qualified Data.Text as T
import qualified Data.Vector as V
pathSegmentToTraversal (Pos x) = nth x
pathSegmentToTraversal (Prop k) = key k
pathToTraversal path = foldl (.) id $ map pathSegmentToTraversal path
listAtPath path = (pathToTraversal path) . _Array
objectAtPath path = (pathToTraversal path) . _Object
stringAtPath path = (pathToTraversal path) . _String
numberAtPath path = (pathToTraversal path) . _Number
vectorInsert :: V.Vector a -> Int -> a -> V.Vector a
vectorInsert vec index item = beginning <> [item] <> rest where
(beginning, rest) = V.splitAt index vec
vectorDelete :: V.Vector a -> Int -> a -> V.Vector a
vectorDelete vec index item = beginning <> (V.drop 1 rest) where
(beginning, rest) = V.splitAt index vec
vectorMove :: V.Vector a -> Int -> Int -> V.Vector a
vectorMove vec index1 index2 = V.fromList $ newBeginning ++ (item : newRest) where
list = V.toList vec
(beginning, (item:rest)) = splitAt index1 list
removed = beginning ++ rest
(newBeginning, newRest) = splitAt (if index1 < index2 then index2 else index2) removed
-- TODO: handle invalid index
stringInsert :: T.Text -> Int -> T.Text -> T.Text
stringInsert haystack pos needle = beginning <> needle <> rest
where (beginning, rest) = T.splitAt pos haystack
-- TODO: check the value matches
stringDelete :: T.Text -> Int -> T.Text -> T.Text
stringDelete haystack pos needle = beginning <> (T.drop (T.length needle) rest)
where (beginning, rest) = T.splitAt pos haystack
apply :: JSONOp -> A.Value -> Either String A.Value
apply Identity input = Right input
apply op@(Add path n) input = case input ^? (numberAtPath path) of
Nothing -> Left [i|Couldn't find number in Add #{op} (#{input})|]
Just x -> Right $ set (numberAtPath path) ((fromIntegral n) + x) input
apply op@(ListInsert path pos value) input = case input ^? (listAtPath path) of
Nothing -> Left [i|Couldn't find list in ListInsert #{op} (#{input})|]
Just l -> Right $ set (listAtPath path) (vectorInsert l pos value) input
apply op@(ListDelete path pos value) input = case input ^? (listAtPath path) of
Nothing -> Left [i|Couldn't find list in ListDelete #{op} (#{input})|]
Just l -> Right $ set (listAtPath path) (vectorDelete l pos value) input
apply op@(ListReplace path pos old new) input = case input ^? (listAtPath path) of
Nothing -> Left [i|Couldn't find list in ListReplace #{op} (#{input})|]
Just _ -> Right $ set ((pathToTraversal path) . (nth pos)) new input
-- TODO
apply (ListMove path pos1 pos2) input = case input ^? (listAtPath path) of
Nothing -> Left [i|Couldn't find list at path #{show path} in ListMove|]
Just l -> Right $ set (listAtPath path) (vectorMove l pos1 pos2) input
apply op@(ObjectInsert path (Just k) value) input = case input ^? (objectAtPath path) of
Nothing -> Left [i|Couldn't find object ObjectInsert #{op} (#{input})|]
Just _ -> Right $ set ((objectAtPath path) . (at k)) (Just value) input
apply (ObjectInsert _ Nothing value) _ = Right value
-- TODO: assert value matches
apply op@(ObjectDelete path (Just k) _value) input = case input ^? (objectAtPath path) of
Nothing -> Left [i|Couldn't find object in ObjectDelete #{op} (#{input}))|]
Just _ -> Right $ set ((objectAtPath path) . (at k)) Nothing input
-- TODO: assert value matches
apply (ObjectDelete _ Nothing _) _ = Right A.Null
-- TODO: assert old matches
apply (ObjectReplace path (Just k) _old new) input = Right $ set ((pathToTraversal path) . (key k)) new input
-- TODO: assert old matches
apply (ObjectReplace path Nothing _old new) input = Right new
apply operation@(ApplySubtypeOperation path typ op) input = case input ^? stringAtPath path of
Nothing -> Left [i|Couldn't find text in ApplySubtypeOperation #{operation} (#input)|]
Just t -> case OT.apply op t of
Left err -> Left err
Right result -> Right $ set (stringAtPath path) result input
apply (StringInsert path pos s) input = case input ^? (stringAtPath path) of
Nothing -> Left "Couldn't find string in StringInsert"
Just str -> Right $ set (stringAtPath path) (stringInsert str pos s) input
apply (StringDelete path pos s) input = case input ^? (stringAtPath path) of
Nothing -> Left "Couldn't find string in StringDelete"
Just str -> Right $ set (stringAtPath path) (stringDelete str pos s) input
-- For playing in ghci
test_obj = [v|{
key1: "value1",
key2: 42,
key3: ["a", "b", "c"]
}|]
| thomasjm/ot.hs | src/Control/OperationalTransformation/JSON/Apply.hs | mit | 4,854 | 0 | 14 | 832 | 1,712 | 887 | 825 | 76 | 12 |
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE OverloadedStrings #-}
module ZoomHub.Types.ContentURISpec
( main,
spec,
)
where
import Data.Text (Text)
import qualified Data.Text as T
import Servant (parseUrlPiece)
import Test.Hspec (Spec, describe, hspec, it, shouldBe)
import ZoomHub.Types.ContentURI (ContentURI, unContentURI)
-- International Resource Locator
iri :: T.Text
iri = "http://doyoucity.com/site_media/entradas/panels/plan_vélez_2.jpg"
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "fromText" do
it "supports IRI (Internationalized Resource Identifier)" $
unContentURI <$> (parseUrlPiece iri :: Either Text ContentURI)
`shouldBe` Right iri
| zoomhub/zoomhub | tests/ZoomHub/Types/ContentURISpec.hs | mit | 701 | 0 | 11 | 114 | 163 | 96 | 67 | -1 | -1 |
module Filter.BW where
import Codec.Picture
toBW :: Int -> Image Pixel8 -> Image Pixel8
toBW threshold =
pixelMap ((*255) . fromIntegral . fromEnum . (< fromIntegral threshold))
| lesguillemets/haskell-image-filters | Filter/BW.hs | mit | 184 | 0 | 10 | 33 | 67 | 36 | 31 | 5 | 1 |
pack :: (Eq a) => [a] -> [[a]]
pack [] = []
pack (x:xs) = let (first, rest) = span (== x) xs
in (x : first) : pack rest
main :: IO ()
main = do
let value = pack "aaaabccaadeeee"
print value
| zeyuanxy/haskell-playground | ninety-nine-haskell-problems/vol1/09.hs | mit | 213 | 0 | 10 | 67 | 129 | 66 | 63 | 8 | 1 |
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Smelkov Ilya
-- License : MIT (see the file LICENSE)
-- Maintainer : Smelkov Ilya <triplepointfive@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- Walker over the directory and builder the dependency tree.
--
-----------------------------------------------------------------------------
module Sanre.FileTree (
buildDirTree
) where
import qualified Data.Map.Strict as Map
import Language.Haskell.Meta
import Language.Haskell.Exts.Syntax
import System.Directory.Tree
import Sanre.Types
-- | Recursively goes through the directory and build a tree.
buildDirTree :: FilePath -> IO Tree
buildDirTree filePath = do
(_ :/ at) <- readDirectory filePath
return (foldDirTree Map.empty at)
-- | Folds a node, which could be eight a dir or file.
-- Doesn't fail, all errors are swallowed.
foldDirTree :: Tree -> DirTree String -> Tree
foldDirTree tree (File _ content) = case parseHsModule content of
Right m -> addNode (moduleNode m) tree
Left _ -> tree -- Just for now
foldDirTree tree (Dir _ nodes) = foldl foldDirTree tree nodes
foldDirTree tree (Failed _ _) = tree
-- | Adds a node to a tree.
addNode :: Node -> Tree -> Tree
addNode (key, val) = Map.insert key val
-- | Converts module struct into a node.
moduleNode :: Module -> Node
moduleNode (Module _ (ModuleName modName) _ _ _ imp _) =
(modName, (\ (ModuleName x) -> x) <$> importModule <$> imp)
| triplepointfive/sanre | src/Sanre/FileTree.hs | mit | 1,525 | 0 | 11 | 266 | 330 | 181 | 149 | 22 | 2 |
-- Copyright © 2012 Julian Blake Kongslie <jblake@omgwallhack.org>
-- Licensed under the MIT license.
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RecordWildCards #-}
module Main
where
import Control.Monad
import Data.Char
import Data.Data
import Data.DateTime
import Data.List
import Data.Maybe
import System.Console.CmdArgs.Implicit
import System.Directory
import System.IO.Error
import System.Posix.Files
import Text.Regex.Posix
import Text.XML.HXT.Core
import Database.Local
import Database.MoonReader
import Source.FanfictionNet
import Source.HPFanficArchiveCom
data RunMode
= Add
{ sources :: [String]
}
| Update
| Prune
{ storyIDs :: [String]
}
deriving (Data, Typeable)
main :: IO ()
main = do
mode <- cmdArgs $ modes
[ Add
{ sources = [] &= args
} &= help "Add new stories to the database"
, Update &= help "Update all ebooks to their latest revisions"
, Prune
{ storyIDs = [] &= args
} &= help "Prune ebooks that aren't worth updating"
] &= program "ff" &= summary "Fan fiction ebook library manager"
runMode mode
runMode :: RunMode -> IO ()
runMode (Add {..}) = do
local <- connectLocal
let
addSource source = msum
[ do
[_,_,ref] <- listToMaybe $ source =~ "^http://(m|www)\\.fanfiction\\.net/s/([0-9]+)"
return $ do
storyID <- addStory local "fanfiction.net" ref
putStrLn $ source ++ " -> fanfiction.net:" ++ ref ++ " -> " ++ storyID
, do
[_,_,ref] <- listToMaybe $ source =~ "^http://www\\.hpfanficarchive\\.com/stories/viewstory\\.php\\?(|.+&)sid=([0-9]+)"
return $ do
storyID <- addStory local "hpfanficarchive.com" ref
putStrLn $ source ++ " -> hpfanficarchive.com:" ++ ref ++ " -> " ++ storyID
]
forM_ sources $ \source -> case addSource source of
Nothing -> putStrLn $ "Unrecognized source " ++ source
Just act -> act
runMode Update = do
local <- connectLocal
moon <- connectMoonReader
dead <- deadBooks local
rmBooks moon dead
forM_ dead $ \filename -> do
e <- tryIOError $ removeFile $ "books/" ++ filename
case e of
Right _ -> return ()
Left e | isDoesNotExistError e -> return ()
| otherwise -> ioError e
let
processBook storyID [] = putStrLn $ "No sources for " ++ storyID ++ "!"
processBook storyID (("fanfiction.net", ref):sources) = do
info <- runX $ infoFanfictionNet ref
case info of
(title,author,date):_ -> do
filename <- makeFilename local storyID $ defaultFilename storyID title author
let
getBook = do
putStrLn $ " Fetching " ++ storyID ++ " from fanfiction.net:" ++ ref
book <- runX $ fetchFanfictionNet ref >>> writeDocument [] ("books/" ++ filename)
case book of
[] -> do
putStrLn $ "Can't fetch fanfiction.net:" ++ ref ++ " for " ++ storyID ++ "!"
processBook storyID sources
_ -> do
setFileTimes ("books/" ++ filename) (fromIntegral $ toSeconds date) (fromIntegral $ toSeconds date)
touchBook moon filename (title, author, date)
e <- tryIOError $ getFileStatus $ "books/" ++ filename
case e of
Right s | fromIntegral (toSeconds date) > modificationTime s -> getBook
| otherwise -> return ()
Left e | isDoesNotExistError e -> getBook
| otherwise -> ioError e
_ -> do
putStrLn $ "Can't get info fanfiction.net:" ++ ref ++ " for " ++ storyID ++ "!"
processBook storyID sources
processBook storyID (("hpfanficarchive.com", ref):sources) = do
info <- runX $ infoHPFanficArchiveCom ref
case info of
(title,author,date):_ -> do
filename <- makeFilename local storyID $ defaultFilename storyID title author
let
getBook = do
putStrLn $ " Fetching " ++ storyID ++ " from hpfanficarchive.com:" ++ ref
book <- runX $ fetchHPFanficArchiveCom ref >>> writeDocument [] ("books/" ++ filename)
case book of
[] -> do
putStrLn $ "Can't fetch hpfanficarchive.com:" ++ ref ++ " for " ++ storyID ++ "!"
processBook storyID sources
_ -> do
setFileTimes ("books/" ++ filename) (fromIntegral $ toSeconds date) (fromIntegral $ toSeconds date)
touchBook moon filename (title, author, date)
e <- tryIOError $ getFileStatus $ "books/" ++ filename
case e of
Right s | fromIntegral (toSeconds date) > modificationTime s -> getBook
| otherwise -> return ()
Left e | isDoesNotExistError e -> getBook
| otherwise -> ioError e
_ -> do
putStrLn $ "Can't get info hpfanficarchive.com:" ++ ref ++ " for " ++ storyID ++ "!"
processBook storyID sources
processBook storyID ((source, ref):sources) = do
putStrLn $ "Unsupported source " ++ source ++ ":" ++ ref ++ " for " ++ storyID ++ "!"
processBook storyID sources
foreachBook local processBook
runMode (Prune {..}) = do
local <- connectLocal
pruneBooks local storyIDs
defaultFilename :: String -> String -> String -> String
defaultFilename storyID title author = mangle storyID ++ "_" ++ mangle title ++ "_by_" ++ mangle author ++ ".fb2"
where
mangle s = intercalate "_" $ filter (/= "_") $ groupBy (\a b -> a /= '_' && b /= '_') $ [ if allowed c then c else '_' | c <- s ]
allowed c = isAscii c && isAlphaNum c
| jblake/fanfiction | src/Main.hs | mit | 5,691 | 0 | 31 | 1,690 | 1,687 | 820 | 867 | 130 | 12 |
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module XMonad.Hooks.DBusLog
( dbusPP
, connectDBusSession
, dbusLog
, dbusLogWithPP
, pangoColor
, pangoBold
, pangoSanitize
-- re-export some useful stuff
, PP(..)
, wrap
, pad
, trim
, shorten
) where
import Codec.Binary.UTF8.String (decodeString)
import Data.Monoid
import DBus
import DBus.Client
import XMonad
import XMonad.Hooks.DynamicLog
import qualified XMonad.Util.ExtensibleState as XS
data DBusSession = Connected Client | Disconnected deriving Typeable
instance ExtensionClass DBusSession where
initialValue = Disconnected
connectDBusSession :: X ()
connectDBusSession = do
dbus <- io $ connectSession
io $ requestName dbus (busName_ "org.xmonad.Log")
[ nameAllowReplacement
, nameReplaceExisting
, nameDoNotQueue
]
XS.put $ Connected dbus
dbusLog :: X ()
dbusLog = dbusLogWithPP dbusPP
dbusLogWithPP :: PP -> X ()
dbusLogWithPP pp = do
line <- dynamicLogString pp
session <- XS.get
case session of
Connected client -> io $ dbusOutput client line
Disconnected -> return ()
dbusOutput :: Client -> String -> IO ()
dbusOutput dbus str = do
let sig = (signal "/org/xmonad/Log" "org.xmonad.Log" "Update") {
signalBody = [toVariant $ decodeString str]
}
emit dbus sig
pangoColor :: String -> String -> String
pangoColor fg = wrap left right
where
left = "<span foreground=\"" ++ fg ++ "\">"
right = "</span>"
pangoBold :: String -> String
pangoBold = wrap "<b>" "</b>"
pangoSanitize = foldr sanitize ""
where
sanitize '>' xs = ">" ++ xs
sanitize '<' xs = "<" ++ xs
sanitize '\"' xs = """ ++ xs
sanitize '&' xs = "&" ++ xs
sanitize x xs = x:xs
dbusPP :: PP
dbusPP = defaultPP
{ ppCurrent = pangoColor "#4894E3" . pangoSanitize
, ppVisible = pangoColor "yellow" . pangoSanitize
, ppHidden = pangoSanitize
, ppUrgent = pangoColor "red" . pangoSanitize
, ppTitle = pangoSanitize . shorten 80
, ppLayout = pangoSanitize
}
| jdpage/xmonad-config | lib/XMonad/Hooks/DBusLog.hs | mit | 2,178 | 0 | 14 | 573 | 580 | 311 | 269 | 66 | 5 |
--https://raw.githubusercontent.com/JakeWheat/intro_to_parsing/master/Text/Parsec/String/Combinator.hs
module ProjectRosalind.Motif.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 | brodyberg/Notes | ProjectRosalind.hsproj/LearnHaskell/lib/ProjectRosalind/Motif/Combinator.hs | mit | 1,894 | 0 | 10 | 356 | 723 | 369 | 354 | 49 | 1 |
{-# LANGUAGE DeriveFunctor #-}
module FreeMonad where
{-
http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html
http://dlaing.org/cofun/posts/free_and_cofree.html
http://arxiv.org/pdf/1403.0749v3.pdf
http://okmij.org/ftp/Haskell/extensible/more.pdf
http://apfelmus.nfshost.com/articles/operational-monad.html
-}
data Free f a = Pure a
| Free (f (Free f a))
instance Functor f => Functor (Free f) where
fmap f (Pure x) = Pure (f x)
fmap f (Free x) = Free (fmap (fmap f) x)
instance Functor f => Applicative (Free f) where
pure x = Pure x
g <*> x = fmap₂ ($) g x
where fmap₂ h z y = (fmap h z) <*> y
instance Functor f => Monad (Free f) where
return x = Pure x
(Pure r) >>= f = f r
(Free x) >>= f = Free (fmap (>>= f) x)
-- Application 1: option parsers
data User = User {
username :: String,
fullname :: String,
id :: Int
} deriving Show
data Option a = Option {
optName :: String,
optDefault :: Maybe a,
optReader :: String -> Maybe a
} deriving Functor
readInt :: String -> Maybe Int
readInt x = case reads x of
[(x', "")] -> Just x'
_ -> Nothing
userP :: Free Option User
userP = User <$> one (Option "username" Nothing Just)
<*> one (Option "fullname" (Just "") Just)
<*> one (Option "id" Nothing readInt)
one :: Option a -> Free Option a
one = undefined
-- Application 2: Toy language
data Toy b next = Output b next
| Bell next
| Done
deriving Functor
{-
There is only one way to derive a Functor instance for Toy, see
http://programmers.stackexchange.com/questions/242795/what-is-the-free-monad-interpreter-pattern
but here is the definition
instance Functor (Toy b) where
fmap f (Output x next) = Output x (f next)
fmap f (Bell next) = Bell (f next)
fmap f Done = Done
-}
liftF :: (Functor f) => f r -> Free f r
liftF command = Free (fmap Pure command)
output x = liftF (Output x ())
bell = liftF (Bell ())
done = liftF Done
subroutine :: Free (Toy Char) ()
subroutine = output 'A'
program :: Free (Toy Char) r
program = do
subroutine
bell
done
showProgram :: (Show a, Show r) => Free (Toy a) r -> String
showProgram (Free (Output a x)) =
"output " ++ show a ++ "\n" ++ showProgram x
showProgram (Free (Bell x)) =
"bell\n" ++ showProgram x
showProgram (Free Done) =
"done\n"
showProgram (Pure r) =
"return " ++ show r ++ "\n"
| limdauto/learning-haskell | monads/FreeMonad.hs | mit | 2,542 | 4 | 11 | 679 | 811 | 413 | 398 | 60 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | Parsing of Unification Grammars with no CFG backbone
-- Following http://cs.haifa.ac.il/~shuly/teaching/06/nlp/ug3.pdf
module NLP.UG.Parse where
import Common
import NLP.AVM
import NLP.UG.Grammar
import qualified Data.Map as M
------------------------------------------------------------------------------
-- Naive parse function
-- This essentially enumerates all trees to a certain depth and finds matching one
-- | Parse a string given a grammar and print output
-- Sets max tree depth based on length of input
parse :: String -> Grammar -> IO ()
parse s g = mapM_ pp $ parse' tokens g depth
where
tokens = words s
depth = (\x -> ceiling $ 1 + log (5*fromIntegral x)) $ length tokens
-- | Parse a string given a grammar and print output
parseD :: String -> Grammar -> Int -> IO ()
parseD s g d = mapM_ pp $ parse' tokens g d
where tokens = words s
-- | Parse a string given a grammar and return all possible derivation trees
parse' :: [Token] -> Grammar -> Int -> [DerivationTree]
parse' ts g d = [ tree | tree <- allTrees g d, lin tree == ts]
-- | Get all valid, complete sentences in a grammar, up to a certain tree depth
allStrings :: Grammar -> Int -> [String]
allStrings g depth = map (unwords.lin) $ filter isComplete $ allTrees g depth
-- | Get all valid derivation trees from a grammar, up to a certain depth
allTrees :: Grammar -> Int -> [DerivationTree]
allTrees g depth = allTrees' (mkAVM1 "CAT" (ValAtom $ start g)) g depth
allTrees' :: AVM -> Grammar -> Int -> [DerivationTree]
allTrees' avm g depth = go 0 avm
where
go :: Int -> AVM -> [DerivationTree]
go d avm = concat drvs
where
drvs :: [[DerivationTree]] = filtermap f (rules g)
f :: (Rule -> Maybe [DerivationTree])
-- Get matching rules (recurses)
f (Rule mavm) =
if avm ⊔? lhs
then Just [ Node (mergeKids par kids) (cleanKids kids) -- cleaning is probably unnecessary, just good practice
| kids <- kidss
, compatibleKids par kids ]
else Nothing
where
-- replace all indices in rule to avoid clashes
rs = M.fromList $ zip [1..100] [newIndex avm..] -- TODO remove this hard limit
ravms = map (reIndex rs) (unMultiAVM mavm)
lhs = head ravms
rhs = map (setDict (avmDict par)) $ tail ravms
par = lhs ⊔ avm -- new parent (want to keep indices as in LHS)
kidss :: [[DerivationTree]] =
if d < depth-1
then combos [ go (d+1) ravm | ravm <- rhs ]
else combos [ [Node ravm []] | ravm <- rhs ]
-- Get matching terminals
f (Terminal tok lhs) =
if avm ⊔? lhs
then Just [ Node par [Leaf tok] ]
else Nothing
where
par = lhs ⊔ avm -- new parent
-- NOTE reindexing not necessary here as terminals have no indices
-- Are all these kids compatible with parent?
compatibleKids :: AVM -> [DerivationTree] -> Bool
compatibleKids avm kids = fst $ foldl (\(t,b) (Node a _) -> (t && canMergeAVMDicts b a, mergeAVMDicts b a)) (True,avm) kids
-- Merge these kids with parent (dictionaries)
mergeKids :: AVM -> [DerivationTree] -> AVM
mergeKids avm kids = foldl (\b (Node a _) -> mergeAVMDicts b a) avm kids
-- Clean dictionaries of kids
cleanKids :: [DerivationTree] -> [DerivationTree]
cleanKids kids = [ Node (cleanDict avm) ks | Node avm ks <- kids ]
| johnjcamilleri/hpsg | NLP/UG/Parse.hs | mit | 3,553 | 0 | 16 | 971 | 975 | 516 | 459 | 51 | 5 |
module IntroducaoAProgramacaoFuncionalEHaskell where
import Data.Char
-- fatorial, sintaxe da matemática, sem muita redundância
-- if statement in haskell
-- then obrigatório
-- parênteses opcional na condição
fat n = if n == 0 then 1 else n * fat (n-1)
-- comentários com -- ou {- -}
-- respondendo perguntas de sintaxe com o google
-- or grammar: http://www.haskell.org/onlinereport/haskell2010/
-- f n-1 é equivalente a (f n) - 1, se f só recebe um argumento
fatinfinito n = if n == 0 then 1 else n * fatinfinito n-1
-- casamento de padrão e recursão, tipos fortes, mas com inferência de tipos
fatorial :: Int -> Int
fatorial 0 = 1
fatorial n = n * fatorial (n-1)
-- tipos básicos
-- Int operators: +, *, -, ^, div, mod :: Int -> Int -> Int
-- >, >=, ==, /=, <=, < :: Int -> Int -> Bool
-- Actually works for Num, to be discussed later, with type classes
-- Olhar http://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x13-1160006
max :: Int -> Int -> Int
max a b = if (a > b) then a else b
-- True, False :: Bool
-- &&, || :: Bool -> Bool -> Bool
-- not :: Bool -> Bool
xor a b = (a || b) && not(a && b)
axor :: Bool -> Bool -> Bool
axor True a = not a
axor False a = a
-- ’a’,’b’,...:: Char
-- ’\t’, ’\n’, ’\\’, ’\’’, ’\"’ :: Char
-- ord :: Char -> Int
-- chr :: Int -> Char
-- bem similar a Java
offset = ord 'A' - ord 'a'
maiuscula :: Char -> Char
maiuscula ch = if (ch >= 'a' && ch <= 'z') then
chr (ord ch + offset)
else ch
-- String
-- ++ :: String -> String -> String
-- show :: ? -> String (overloading)
-- Float e Double
-- +,-,*,/ :: Float -> Float -> Float
-- pi :: Float
-- ceiling, floor, round :: Float -> Int
-- fromIntegral :: Int -> Float
-- read :: String -> Float
-- show :: Float -> String
-- Tuplas, agregando valores
addPair :: (Int,Int) -> Int
addPair (x,y) = x+y
shift ((x,y),z) = (x,(y,z))
shiftt ((x,_),_) = (x,(x,x))
-- Nomeando tipos
type Name = String
type Age = Int
type Phone = Int
type Person = (Name, Age, Phone)
name :: Person -> Name
name (n,a,p) = n
type Saldo = Double
type Conta = (String,Saldo)
creditarConta (n,s) v = (n,s + v)
debitarConta (n,s) v = (n,s - v)
-- Listas
-- Ao contrário de Java, sintaxe concreta específica para listas.
-- type String = [Char]
-- [] e :
-- toda lista ou é vazia ou contém uma cabeça (elemento) e uma cauda (outra lista)
-- toda lista finita acaba com a lista vazia
-- sintaxe equivalente: [12,3,4] e 12:3:4:[]
-- ordem e quantidade é relevante
-- parênteses no pattern matching de listas é obrigatório
soma [] = 0
soma (nota : l) = nota + soma l
-- avaliar passo a passo a soma, como máquina de reescrita
nossohead (x:xs) = x
-- sem outra equação, a avaliação de nossohead [] leva a
-- *** Exception: AplicacaoParcial.hs:114:1-20: Non-exhaustive patterns in function nossohead
-- por conta de coisas como essa, noção de fortemente tipada não é 100% correta para Haskell. Similar a Java, mas um pouco melhor.
tamanho [] = 0
tamanho (nota : l) = 1 + tamanho l
procurarIndice [] i = []
procurarIndice (e:l) 0 = [e]
procurarIndice (e:l) i = procurarIndice l (i-1)
-- visão geral do interpretador e do ambiente
ex = tamanho [4,1,2,3]
-- equações de funcões diferentes intercaladas dá erro: Multiple declarations of f1
-- duas equações começando com f 0 ou f n dá warning de overllaping de padrões, não erro
-- a primeira equação é usada; a ordem importa
-- o mesmo ocorre quando a equação de f n aparece antes de f 0
f1 0 = 1
f1 n = n * f1 (n-1)
f2 0 = 0
f2 m = m * f2 (m-1)
-- contar elementos em uma lista
count e [] = 0
count e (x:xs) | e == x = 1 + count e xs
| otherwise = count e xs
-- conjuntos: união, interseção, diferença
member e [] = False
member e (x:xs) | x == e = True
| otherwise = member e xs
-- reuso versus eficiência
outromember e l = (count e l) > 0
union [] c = c
union (x:xs) c | member x c = union xs c
| otherwise = x:(union xs c)
-- exemplo de reescrita
-- union (1:[]) [] =
-- { x=1 xs=[] c=[] }
-- 1:(union [] [])
-- 1:[]
-- declaração redundante, mas mais eficiente quando o segundo argumento é []
union1 [] [] = []
union1 [] l = l
union1 l [] = l
union1 (x:xs) c | member x c = union1 xs c
| otherwise = x:(union1 xs c)
-- union [1] [5,4,3,2,1,1] = [5,4,3,2,1,1]
-- union assume que listas recebidas não têm elementos repetidos;
-- pode haver duplicatas entre as listas, no entanto.
-- Exercícios
removeDups [] = []
removeDups (e:l) = if member e l then removeDups l else e:removeDups l
-- unique Elimina apenas elementos repetidos em sequência
unique [] = []
unique [e] = [e]
unique (x:y:ys) | x == y = unique (y:ys)
| x /= y = x:unique (y:ys)
eliminarDuplicatas [] = []
eliminarDuplicatas (x:xs) | member x xs = eliminarDuplicatas xs
| otherwise = x:(eliminarDuplicatas xs)
unionduplicata a b = union (eliminarDuplicatas a) (eliminarDuplicatas b)
-- simetria
intersection [] c = []
intersection (x:xs) c | member x c = x:(intersection xs c)
| otherwise = intersection xs c
-- underscore poderia ter sido usado acima também
-- observar as similaridades entre as recursões e diferenças nas bases
diff [] _ = []
diff c [] = c
diff (x:xs) c | member x c = diff xs c
| otherwise = x:(diff xs c) | pauloborba/plc | src/IntroducaoAProgramacaoFuncionalEHaskell.hs | cc0-1.0 | 5,610 | 0 | 9 | 1,422 | 1,477 | 795 | 682 | 77 | 2 |
import Data.List
type Matrix = (Int, Int, [(Int, Int, Int)])
transp :: Matrix -> Matrix
transp (mm, nn, ee) = (nn, mm, e)
where e = map flipEl ee
flipEl :: (Int, Int, Int) -> (Int, Int, Int)
flipEl (i,j,a) = (j,i,a)
multi :: Matrix -> Matrix -> Matrix
multi mat1@(m1, n1, e1) mat2@(m2, n2, e2) | n1 /= m2 = error "wrong"
| otherwise = (m1, n2, e)
where e = filter (\ (_,_,v) -> v /=0) $ map scalarP (zip [1..m1] [1..n2])
scalarP (i,j) = (i, j, (val i j))
val i j = sum $ map (\ ((_,_,x), (_,_,y)) -> x*y) (zip (row mat1 i) (col mat2 j))
row :: Matrix -> Int -> [(Int, Int, Int)]
row (m,n,e) i = unionBy sameAs ready [(i,v,0) | v <- [1..n]]
where ready = filter (\ (x,_,_) -> x==i) e
sameAs (x, y, _) (u, v, _) = x==u && y==v
col :: Matrix -> Int -> [(Int, Int, Int)]
col mat j = map flipEl (row (transp mat) j)
| machl/NPRG005-non-procedural-programming | matrix/matrix.hs | gpl-2.0 | 924 | 3 | 12 | 284 | 594 | 336 | 258 | 19 | 1 |
{-# OPTIONS -w -O0 #-}
{- |
Module : Fpl/ATC_Fpl.der.hs
Description : generated Typeable, ShATermConvertible instances
Copyright : (c) DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable(overlapping Typeable instances)
Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible
for the type(s):
'Fpl.As.FplExt'
'Fpl.As.FplSortItem'
'Fpl.As.FplOpItem'
'Fpl.As.FunDef'
'Fpl.As.TermExt'
'Fpl.Sign.SignExt'
-}
{-
Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!!
dependency files:
Fpl/As.hs
Fpl/Sign.hs
-}
module Fpl.ATC_Fpl () where
import ATerm.Lib
import CASL.AS_Basic_CASL
import CASL.ATC_CASL
import CASL.Formula
import CASL.OpItem
import CASL.Sign
import CASL.SortItem
import CASL.ToDoc
import Common.AS_Annotation
import Common.AnnoState
import Common.Doc
import Common.Doc as Doc
import Common.DocUtils
import Common.Id
import Common.Keywords
import Common.Lexer
import Common.Parsec
import Common.Token hiding (innerList)
import Data.List
import Data.List (delete)
import Data.Maybe (isNothing)
import Data.Ord
import Data.Typeable
import Fpl.As
import Fpl.Sign
import Text.ParserCombinators.Parsec
import qualified Common.Lib.MapSet as MapSet
import qualified Common.Lib.Rel as Rel
{-! for Fpl.As.FplExt derive : Typeable !-}
{-! for Fpl.As.FplSortItem derive : Typeable !-}
{-! for Fpl.As.FplOpItem derive : Typeable !-}
{-! for Fpl.As.FunDef derive : Typeable !-}
{-! for Fpl.As.TermExt derive : Typeable !-}
{-! for Fpl.Sign.SignExt derive : Typeable !-}
{-! for Fpl.As.FplExt derive : ShATermConvertible !-}
{-! for Fpl.As.FplSortItem derive : ShATermConvertible !-}
{-! for Fpl.As.FplOpItem derive : ShATermConvertible !-}
{-! for Fpl.As.FunDef derive : ShATermConvertible !-}
{-! for Fpl.As.TermExt derive : ShATermConvertible !-}
{-! for Fpl.Sign.SignExt derive : ShATermConvertible !-}
| nevrenato/Hets_Fork | Fpl/ATC_Fpl.der.hs | gpl-2.0 | 1,977 | 0 | 5 | 264 | 191 | 126 | 65 | 30 | 0 |
{- |
Module : ./RDF/StaticAnalysis.hs
Copyright : Felix Gabriel Mance
License : GPLv2 or higher, see LICENSE.txt
Maintainer : f.mance@jacobs-university.de
Stability : provisional
Portability : portable
Static analysis for RDF
-}
module RDF.StaticAnalysis where
import qualified OWL2.AS as AS
import Common.IRI
import OWL2.Parse
import RDF.AS
import RDF.Sign
import RDF.Parse (predefinedPrefixes)
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
import Text.ParserCombinators.Parsec hiding (State)
import Common.AS_Annotation hiding (Annotation)
import Common.Id
import Common.Result
import Common.GlobalAnnotations
import Common.ExtSign
import Common.Lib.State
-- * URI Resolution
resolveFullIRI :: IRI -> IRI -> IRI
resolveFullIRI _absol rel = rel
{-if isAbsoluteIRI rel then rel else
let r = fromJust $ parseIRIReference $ fromJust $ expandCurie Map.empty rel
a = fromJust $ parseIRI $ fromJust $ expandCurie Map.empty absol
Just ra = IRI.relativeTo r a
resolved = IRI.iriToStringUnsecure ra
Right new = parse uriQ "" $ "<" ++ resolved ++ ">"
in rel {expandedIRI = expandedIRI new}
-}
resolveAbbreviatedIRI :: RDFPrefixMap -> IRI -> IRI
resolveAbbreviatedIRI pm new = fromJust $ expandCurie pm new
{-case Map.lookup (namePrefix new) pm of
Nothing -> error $ namePrefix new ++ ": prefix not declared"
Just iri -> let new2 = if null (namePrefix new)
{- FIXME: If null (localPart new)
then head will fail! -}
&& null (localPart new)
&& head (localPart new) == ':'
then new {localPart = tail $ localPart new}
else new
in new2 {expandedIRI = expandedIRI iri ++ localPart new2}
-}
resolveIRI :: Base -> RDFPrefixMap -> IRI -> IRI
resolveIRI (Base current) pm new
| hasFullIRI new = resolveFullIRI current new
| isBlankNode new = new
| otherwise = resolveAbbreviatedIRI pm new
resolveBase :: Base -> RDFPrefixMap -> Base -> Base
resolveBase b pm (Base new) = Base $ resolveIRI b pm new
resolvePrefix :: Base -> RDFPrefixMap -> Prefix -> (Prefix, RDFPrefixMap)
resolvePrefix b pm (PrefixR s new) = let res = resolveIRI b pm new
in (PrefixR s res, Map.insert s res pm)
resolvePredicate :: Base -> RDFPrefixMap -> Predicate -> Predicate
resolvePredicate b pm (Predicate p) = Predicate $
if null (prefixName p) && show (iriPath p) == "a" then
p { iriScheme = "http:",
iriPath = stringToId "//www.w3.org/1999/02/22-rdf-syntax-ns#type"
}
else resolveIRI b pm p
resolveSubject :: Base -> RDFPrefixMap -> Subject -> Subject
resolveSubject b pm s = case s of
Subject iri -> Subject $ resolveIRI b pm iri
SubjectList ls -> SubjectList $ map (resolvePOList b pm) ls
SubjectCollection ls -> SubjectCollection $ map (resolveObject b pm) ls
resolvePOList :: Base -> RDFPrefixMap -> PredicateObjectList
-> PredicateObjectList
resolvePOList b pm (PredicateObjectList p ol) =
PredicateObjectList (resolvePredicate b pm p) $ map (resolveObject b pm) ol
resolveObject :: Base -> RDFPrefixMap -> Object -> Object
resolveObject b pm o = case o of
Object s -> Object $ resolveSubject b pm s
ObjectLiteral lit -> case lit of
RDFLiteral bool lf (AS.Typed dt) ->
ObjectLiteral $ RDFLiteral bool lf $ AS.Typed $ resolveIRI b pm dt
_ -> o
resolveTriples :: Base -> RDFPrefixMap -> Triples -> Triples
resolveTriples b pm (Triples s ls) =
Triples (resolveSubject b pm s) $ map (resolvePOList b pm) ls
resolveStatements :: Base -> RDFPrefixMap -> [Statement] -> [Statement]
resolveStatements b pm ls = case ls of
[] -> []
BaseStatement base : t -> let newBase = resolveBase b pm base
in BaseStatement newBase : resolveStatements newBase pm t
PrefixStatement pref : t -> let (newPref, newPrefMap) = resolvePrefix b pm pref
in PrefixStatement newPref : resolveStatements b newPrefMap t
Statement triples : t ->
Statement (resolveTriples b pm triples) : resolveStatements b pm t
extractPrefixMap :: RDFPrefixMap -> [Statement] -> RDFPrefixMap
extractPrefixMap pm ls = case ls of
[] -> pm
h : t -> case h of
PrefixStatement (PrefixR p iri) -> extractPrefixMap (Map.insert p iri pm) t
_ -> extractPrefixMap pm t
resolveDocument :: TurtleDocument -> TurtleDocument
resolveDocument doc = let newStatements = resolveStatements
(Base $ documentName doc) predefinedPrefixes $ statements doc
in doc { statements = newStatements
, prefixMap = Map.union predefinedPrefixes $
extractPrefixMap Map.empty newStatements }
-- * Axiom extraction
generateBNode :: Int -> IRI
generateBNode i = nullIRI { iriPath = stringToId ("bnode" ++ show i)
, isAbbrev = True
, isBlankNode = True}
collectionToPOList :: [Object] -> [PredicateObjectList]
collectionToPOList objs = case objs of
[] -> []
h : t -> [ PredicateObjectList (Predicate rdfFirst) [h]
, PredicateObjectList (Predicate rdfRest) [Object $ if null t
then Subject rdfNil else SubjectList $ collectionToPOList t]]
expandPOList1 :: Triples -> [Triples]
expandPOList1 (Triples s pols) = map (\ pol -> Triples s [pol]) pols
-- | this assumes exactly one subject and one predicate
expandPOList2 :: Triples -> [Triples]
expandPOList2 (Triples s pols) = case pols of
[PredicateObjectList p objs] ->
map (\ obj -> Triples s [PredicateObjectList p [obj]]) objs
_ -> error "unexpected ; abbreviated triple"
-- | converts a triple to a list of triples with one predicate and one object
expandPOList :: Triples -> [Triples]
expandPOList = concatMap expandPOList2 . expandPOList1
-- | this assumes exactly one subject, one predicate and one object
expandObject1 :: Int -> Triples -> (Int, [Triples])
expandObject1 i t@(Triples s ls) = case ls of
[PredicateObjectList p [obj]] -> case obj of
ObjectLiteral _ -> (i, [t])
Object (Subject _) -> (i, [t])
Object (SubjectList pol) ->
let bnode = Subject $ generateBNode i
newTriple = Triples s [PredicateObjectList p [Object bnode]]
connectedTriples = expandPOList $ Triples bnode pol
(j, expandedTriples) = expandObject2 (i + 1) connectedTriples
in (j, newTriple : expandedTriples)
Object (SubjectCollection col) -> let pol = collectionToPOList col
in if null pol then
(i, [Triples s [PredicateObjectList p [Object $ Subject rdfNil]]])
else expandObject1 i $ Triples s [PredicateObjectList p [Object $ SubjectList pol]]
_ -> error "unexpected , or ; abbreviated triple"
-- | this assumes each triple has one subject, one predicate and one object
expandObject2 :: Int -> [Triples] -> (Int, [Triples])
expandObject2 i tl = case tl of
[] -> (i, [])
h : t -> let (j, triples1) = expandObject1 i h
(k, triples2) = expandObject2 j t
in (k, triples1 ++ triples2)
expandObject :: Int -> Triples -> (Int, [Triples])
expandObject i t = expandObject2 i $ expandPOList t
expandSubject :: Int -> Triples -> (Int, [Triples])
expandSubject i t@(Triples s ls) = case s of
Subject _ -> (i, [t])
SubjectList pol -> let bnode = Subject $ generateBNode i
in (i + 1, map (Triples bnode) [ls, pol])
SubjectCollection col -> let pol = collectionToPOList col
in if null col then (i, [Triples (Subject rdfNil) ls])
else expandSubject i $ Triples (SubjectList pol) ls
expandTriple :: Int -> Triples -> (Int, [Triples])
expandTriple i t = let (j, sst) = expandSubject i t in case sst of
[triple] -> expandObject j triple
[triple, connectedTriple] ->
let (k, tl1) = expandObject j triple
(l, tl2) = expandObject k connectedTriple
in (l, tl1 ++ tl2)
_ -> error "expanding triple before expanding subject"
expandTripleList :: Int -> [Triples] -> (Int, [Triples])
expandTripleList i tl = case tl of
[] -> (i, [])
h : t -> let (j, tl1) = expandTriple i h
(k, tl2) = expandTripleList j t
in (k, tl1 ++ tl2)
simpleTripleToAxiom :: Triples -> Axiom
simpleTripleToAxiom (Triples s pol) = case (s, pol) of
(Subject sub, [PredicateObjectList (Predicate pr) [o]]) ->
Axiom (SubjectTerm sub) (PredicateTerm pr) $ ObjectTerm $ case o of
ObjectLiteral lit -> Right lit
Object (Subject obj) -> Left obj
_ -> error "object should be an URI"
_ -> error "subject should be an URI or triple should not be abbreviated"
createAxioms :: TurtleDocument -> [Axiom]
createAxioms doc = map simpleTripleToAxiom $ snd $ expandTripleList 1
$ triplesOfDocument $ resolveDocument doc
-- | takes an entity and modifies the sign according to the given function
modEntity :: (Term -> Set.Set Term -> Set.Set Term) -> RDFEntity -> State Sign ()
modEntity f (RDFEntity ty u) = do
s <- get
let chg = f u
put $ case ty of
SubjectEntity -> s { subjects = chg $ subjects s }
PredicateEntity -> s { predicates = chg $ predicates s }
ObjectEntity -> s { objects = chg $ objects s }
-- | adding entities to the signature
addEntity :: RDFEntity -> State Sign ()
addEntity = modEntity Set.insert
collectEntities :: Axiom -> State Sign ()
collectEntities (Axiom sub pre obj) = do
addEntity (RDFEntity SubjectEntity sub)
addEntity (RDFEntity PredicateEntity pre)
addEntity (RDFEntity ObjectEntity obj)
-- | collects all entites from the axioms
createSign :: TurtleDocument -> State Sign ()
createSign = mapM_ collectEntities . createAxioms
anaAxiom :: Axiom -> Named Axiom
anaAxiom = makeNamed ""
-- | static analysis of document with incoming sign.
basicRDFAnalysis :: (TurtleDocument, Sign, GlobalAnnos)
-> Result (TurtleDocument, ExtSign Sign RDFEntity, [Named Axiom])
basicRDFAnalysis (doc, inSign, _) = do
let syms = Set.difference (symOf accSign) $ symOf inSign
accSign = execState (createSign doc) inSign
axioms = map anaAxiom $ createAxioms doc
return (doc, ExtSign accSign syms, axioms)
| spechub/Hets | RDF/StaticAnalysis.hs | gpl-2.0 | 10,476 | 0 | 21 | 2,682 | 3,072 | 1,572 | 1,500 | 179 | 6 |
module Network.Gitit.Plugins.ShowUser (plugin) where
-- This plugin replaces $USER$ with the name of the currently logged in
-- user, or the empty string if no one is logged in.
import Network.Gitit.Interface
plugin :: Plugin
plugin = mkPageTransformM showuser
showuser :: Inline -> PluginM Inline
showuser (Math InlineMath x) | x == "USER" = do
doNotCache -- tell gitit not to cache this page, as it has dynamic content
mbUser <- askUser
case mbUser of
Nothing -> return $ Str ""
Just u -> return $ Str $ uUsername u
showuser x = return x
| jraygauthier/jrg-gitit-plugins | src/Network/Gitit/Plugins/ShowUser.hs | gpl-2.0 | 568 | 0 | 12 | 122 | 134 | 68 | 66 | 12 | 2 |
{-# OPTIONS_GHC -O2 #-}
module Main where
import Data.Binary
import Data.Binary.Get
import System.Process
import Control.Monad
import Data.IORef
import System.FilePath
import System.IO
import System.IO.Unsafe
import System.Environment (getArgs)
import System.Environment.FindBin
import Data.ByteString (ByteString)
import qualified Data.IntMap as IM
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Char8 as C
__AlignRight__ :: Bool
__AlignRight__ = False
main :: IO ()
main = do
args <- getArgs
hSetBinaryMode stdout True
case args of
[] -> putStrLn "Usage: pdf2line input.pdf ... > output.txt"
["-"] -> do
hSetBinaryMode stdin True
res <- L.getContents
mapM_ dumpPage (fromDoc $! decode res)
_ -> forM_ args $! \inFile -> do
let pdfdump = __Bin__ </> "pdfdump"
(_,out,err,pid) <- runInteractiveCommand $! pdfdump ++ " \"" ++ inFile ++ "\""
res <- L.hGetContents out
L.length res `seq` waitForProcess pid
when (L.null res) $! do
L.hPutStr stderr =<< L.hGetContents err
mapM_ dumpPage (fromDoc $! decode res)
dumpPage :: Page -> IO ()
dumpPage page
| IM.null pg = return ()
| otherwise = do
_CurrentLine <- newIORef maxBound
forM_ (IM.toAscList pg) $! \(lineNum, MkLine pt strs) -> do
linePrev <- readIORef _CurrentLine
replicateM_ ((lineNum - linePrev + (pt `div` 4)) `div` pt) (S.putStr _NewLine)
_CurrentColumn <- newIORef 0
forM_ (IM.toAscList strs) $! \(col, str) -> do
cur <- readIORef _CurrentColumn
S.putStr $! S.take (col - cur) _Spaces
S.putStr str
writeIORef _CurrentColumn (col + S.length str)
S.putStr _NewLine
writeIORef _CurrentLine (lineNum+pt)
S.putStr _NewPage
where
pg = fromPage page
_Spaces, _NewLine, _NewPage :: ByteString
_Spaces = S.replicate 4096 0x20
_NewLine = C.pack "\r\n"
_NewPage = C.pack "\r\n\x0C\r\n"
-- A Page is a IntMap from line-number to a map from column-number to bytestring.
newtype Doc = MkDoc { fromDoc :: [Page] } deriving Show
newtype Page = MkPage { fromPage :: IM.IntMap Line } deriving Show
data Line = MkLine
{ linePt :: !Int
, lineStrs :: !(IM.IntMap S.ByteString)
}
deriving Show
instance Binary Doc where
put = undefined
get = liftM MkDoc getList
where
getList = do
rv <- isEmpty
if rv then return []
else liftM2 (:) get getList
data Chunk = MkChunk
{ c_right :: !Int
, c_upper :: !Int
, c_pt :: !Int
, c_str :: !ByteString
}
deriving Show
instance Binary Page where
put = error "put Page is not defined"
get = getChunk maxBound []
where
getChunk minPt chunks = do
rv <- isEmpty
if rv then done else do
w8 <- getWord8
case w8 of
0x6C -> do -- 'l'
skip 1
col <- if __AlignRight__
then skip 9 >> getInt 6
else getInt 6 >>= ((skip 9 >>) . return)
skip 21
ln <- getInt 6
skip 3
pt <- getInt 6
skip 7
sz <- getInt 4
skip 1
str <- getByteString sz
w8' <- getWord8
case w8' of
0x0D -> skip 1
0x0A -> return ()
_ -> fail $! "Bad parse: " ++ show w8'
let pt' = min minPt pt
getChunk pt' (MkChunk col ln pt str:chunks)
0x0D -> skip 1 >> done
0x0A -> done
_ -> fail $! "Bad parse: " ++ show w8
where
done = return $! pageOf (foldl (buildPage minPt) (MkBuild (MkPage IM.empty) 0) chunks)
getInt :: Int -> Get Int
getInt n = liftM2 mkInt getWord8 (getInt (n-1))
where
mkInt digit rest = fromEnum (digit - 0x30) * (10 ^ (n-1)) + rest
getInt _ = return 0
buildPage minPt (MkBuild (MkPage pg) base) (MkChunk col ln pt str) = MkBuild (MkPage (IM.insert base' entry pg)) base'
where
sz = S.length str
width = if __AlignRight__
then ((col * 2) `div` minPt) - sz
else ((col * 2) `div` minPt)
base' = if abs (ln - base) + (minPt `div` 4) < minPt then base else ln
entry = case IM.lookup base' pg of
Just (MkLine pt' strs) -> MkLine (max pt pt') (IM.insert width str strs)
_ -> MkLine pt (IM.singleton width str)
data Build = MkBuild
{ pageOf :: !Page
, baseOf :: !Int
}
deriving Show
| audreyt/pdf2line | pdf2line.hs | gpl-2.0 | 5,108 | 0 | 24 | 1,982 | 1,592 | 808 | 784 | 143 | 4 |
{-
Copyright (C) 2013,2014 Ellis Whitehead
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
-}
{-# LANGUAGE OverloadedStrings #-}
module OnTopOfThings.Commands.Import
( modeInfo_import
, optsToCommandRecord
) where
import Control.Applicative ((<$>), (<*>), empty)
import Control.Monad
import Data.Aeson
import Data.Aeson.Types (Parser)
import Data.Char (isAlphaNum)
import Data.Generics.Aliases (orElse)
import Data.List (inits, intercalate, sortBy)
import Data.Maybe (catMaybes, fromMaybe)
import Data.Monoid (mempty)
import Data.Time.Clock
import Data.Time.LocalTime (utc)
import Data.Time.Format (parseTime)
import Data.Time.ISO8601 (formatISO8601, formatISO8601Millis)
import Debug.Hood.Observe
import Debug.Trace
import System.Console.CmdArgs.Explicit
import System.Directory (getDirectoryContents)
import System.FilePath (joinPath, splitDirectories, takeExtension, takeFileName)
import System.IO
import System.Locale (defaultTimeLocale)
--import qualified System.FilePath.Find as FF
import Text.Regex (mkRegex, matchRegexAll)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as M
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Vector as V
import qualified Data.Yaml as Yaml
import Args
import Command (CommandRecord(..))
import DatabaseTables
import Utils
import OnTopOfThings.Data.FileJson
import OnTopOfThings.Data.Json
import OnTopOfThings.Data.Patch
import OnTopOfThings.Data.Time
import OnTopOfThings.Data.Types
modeInfo_import :: ModeInfo
modeInfo_import = (mode_import, ModeRunIO optsRun_import)
mode_import = Mode
{ modeGroupModes = mempty
, modeNames = ["import"]
, modeValue = options_empty "import"
, modeCheck = Right
, modeReform = Just . reform
, modeExpandAt = True
, modeHelp = "Import task warrior JSON"
, modeHelpSuffix = []
, modeArgs = ([flagArg updArgs "ID"], Nothing)
, modeGroupFlags = toGroup
[ flagReq ["output", "o"] (upd "output") "FILE" "file to use for output"
, flagHelpSimple updHelp
]
}
optsValidate :: Options -> Validation ()
optsValidate opts = do
when (null $ optionsArgs opts) (Left ["You must supply a filename"])
Right ()
optsRun_import :: Options -> IO (Validation ())
optsRun_import opts = do
case optsValidate opts of
Left msgs -> return (Left msgs)
Right () -> do
let filename = head (optionsArgs opts)
--mapM_ print $ catMaybes $ map checkLine $ zip [1..] $ lines s
input <- B.readFile filename
let m = (optionsMap opts)
h <- case M.lookup "output" m of
Just (Just f) -> openFile f WriteMode
_ -> return stdout
case convert' input of
Left msgs -> return (Left msgs)
Right items' -> do
time <- getCurrentTime
let items = sortBy (\(ItemForJson a _) (ItemForJson b _) -> compare (itemCreated a) (itemCreated b)) items'
let export = CopyFile (Just time) (Just "default") (Just "Task Warrior import") items
--BS.hPutStr h $ Yaml.encode export
BL.hPutStr h $ encode export
hClose h
return (Right ())
convert' :: BL.ByteString -> Validation [ItemForJson]
convert' input = l_ where
l_ = case eitherDecode input of
Left msg -> Left [msg]
Right (Array l) -> items_ where
db' = createItems' (V.toList l) (M.empty, M.empty)
items_ = case db' of
Left msgs -> Left msgs
Right db -> Right l where
l = M.elems db
-- TODO: need to sort l
createItems' :: [Value] -> (M.Map String ItemForJson, M.Map FilePath Item) -> Validation (M.Map String ItemForJson)
createItems' [] (db, _) = Right db
createItems' ((Object m):rest) both = createItems both m >>= \both -> createItems' rest both
createItems' _ _ = Left ["Expected object"]
--x -> Left ["Expected an array, got" ++ show input]
createItems :: (M.Map String ItemForJson, M.Map FilePath Item) -> Object -> Validation (M.Map String ItemForJson, M.Map FilePath Item)
--createItems uuids projects m | trace ("createItems " ++ show uuids) False = undefined
createItems (db, folders) m = do
uuid <- get "uuid" m
entry' <- get "entry" m
description <- get "description" m
project <- getMaybe "project" m
status' <- getMaybe "status" m
end' <- getMaybe "end" m
tags <- getList "tags" m
created <- (parseTime defaultTimeLocale "%Y%m%dT%H%M%SZ" entry') `maybeToValidation` ["Could not parse entry time"]
--closed <- (end' >>= \end -> (parseTime defaultTimeLocale "%Y%m%dT%H%M%SZ" (T.unpack end))) `maybeToValidation` ["Could not parse end time"]
closed <- getClosed end'
let parentPath_ = project >>= Just . (substituteInList '.' '/')
let (db', folders') = case parentPath_ of
Nothing -> (db, folders)
Just parentPath -> createFolder (db, folders) parentPath created
let parentUuid_ = fmap (T.unpack . getProjectUuid . T.pack) parentPath_
let parentUuid = fromMaybe uuidRoot parentUuid_
let item = Item { itemUuid = uuid
, itemCreated = created
, itemCreator = "default"
, itemType = "task"
, itemStatus = getStatus status'
, itemParent = Just parentUuid
, itemName = Nothing
, itemTitle = Just description
, itemContent = Nothing
, itemStage = Just "new"
, itemClosed = closed
, itemStart = Nothing
, itemEnd = Nothing
, itemDue = Nothing
, itemDefer = Nothing
, itemEstimate = Nothing
, itemIndex = Nothing
}
let properties = if null tags then M.empty else M.fromList [("tag", tags)]
let json = ItemForJson item properties
let db'' = M.insert uuid json db'
return (db'', folders')
--let mode = if Set.member (T.pack uuid) uuids then mode_mod else mode_add
--let status = getStatus status'
--let parent = project >>= Just . (substituteInList '.' '/')
--let parentUuid = fmap (T.unpack . getProjectUuid . T.pack) parent
--let args = catMaybes [wrap "id" uuid, wrap "title" description, wrapMaybe "parent" parentUuid, wrapMaybe "status" status, wrapMaybeTime "closed" closed, wrapList "tag" tags']
--let projects' = updateProjects (fmap T.pack parent) time
--opts0 <- eitherStringToValidation $ process mode args
--let record = optsToCommandRecord time "default" opts0
--let uuids' = Set.insert (T.pack uuid) uuids
--return (uuids', projects', record)
where
getStatus status' = case status' of
Just "completed" -> "closed"
Just "deleted" -> "deleted"
_ -> "open"
getClosed :: Maybe String -> Validation (Maybe String)
getClosed closed' = case closed' of
Just closed'' ->
case parseTime defaultTimeLocale "%Y%m%dT%H%M%SZ" closed'' of
Nothing -> Left ["Could not parse end time: " ++ closed'']
Just x -> Right (Just (formatTime' $ zonedToTime x))
Nothing -> Right Nothing
-- updateProjects :: Maybe T.Text -> UTCTime -> M.Map T.Text UTCTime
-- updateProjects parent time = case parent of
-- Nothing -> projects
-- Just p -> M.insert p t projects where
-- t = fromMaybe time (M.lookup p projects >>= \t -> Just $ min time t)
uuidRoot = "00000000-0000-0000-0000-000000000000"
createFolder :: (M.Map String ItemForJson, M.Map FilePath Item) -> FilePath -> UTCTime -> (M.Map String ItemForJson, M.Map FilePath Item)
createFolder both@(db, lists) path time =
case M.lookup path lists of
Just _ -> both
Nothing -> (db', folders') where
dirs = splitDirectories path
path_l = map joinPath $ tail $ inits dirs
(db', folders') = createFolders both path_l time uuidRoot
createFolders :: (M.Map String ItemForJson, M.Map FilePath Item) -> [FilePath] -> UTCTime -> String -> (M.Map String ItemForJson, M.Map FilePath Item)
createFolders both [] _ _ = both
createFolders (db, folders) (path:rest) time parentUuid = createFolders (db', folders') rest time uuid where
uuid = T.unpack $ getProjectUuid (T.pack path)
folder = Item
{ itemUuid = uuid
, itemCreated = time
, itemCreator = "default"
, itemType = "folder"
, itemStatus = "open"
, itemParent = Just parentUuid
, itemName = Just (takeFileName path)
, itemTitle = Nothing
, itemContent = Nothing
, itemStage = Nothing
, itemClosed = Nothing
, itemStart = Nothing
, itemEnd = Nothing
, itemDue = Nothing
, itemDefer = Nothing
, itemEstimate = Nothing
, itemIndex = Nothing
}
db' = M.insert uuid (ItemForJson folder M.empty) db
folders' = M.insert path folder folders
--convert :: BL.ByteString -> Validation [CommandRecord]
--convert input =
-- case eitherDecode input of
-- Left msg -> Left [msg]
-- Right (Array l) -> records where
-- (_, projectMap, itemRecords') = foldl createItem' (Set.empty, M.empty, []) (V.toList l)
-- records = case concatEithersN (reverse itemRecords') of
-- Left msgs -> Left msgs
-- Right itemRecords'' -> Right l where
-- itemRecords = sortBy compareRecordTime itemRecords''
-- projectRecords = map createProject $ M.toList (trace ("projectMap: " ++ (show projectMap)) projectMap)
-- l = sortBy compareRecordTime (projectRecords ++ itemRecords)
-- --l = sortBy compareRecordTime (projectRecords)
-- where
-- createItem'
-- :: (Set.Set T.Text, M.Map T.Text UTCTime, [Validation CommandRecord])
-- -> Value
-- -> (Set.Set T.Text, M.Map T.Text UTCTime, [Validation CommandRecord])
-- createItem' (uuids, projects, records) (Object m) = case createItem uuids projects m of
-- Left msgs -> (uuids, projects, Left msgs : records)
-- Right (uuids', projects', record) -> (uuids', projects', (Right record) : records)
-- createItem' (uuids, projects, records) _ = (uuids, projects, (Left ["Expected object"]) : records)
-- --x -> Left ["Expected an array, got" ++ show input]
--compareRecordTime :: CommandRecord -> CommandRecord -> Ordering
--compareRecordTime a b = compare (Command.commandTime a) (Command.commandTime b)
--createItem :: Set.Set T.Text -> M.Map T.Text UTCTime -> Object -> Validation (Set.Set T.Text, M.Map T.Text UTCTime, CommandRecord)
----createItem uuids projects m | trace ("createItem " ++ show uuids) False = undefined
--createItem uuids projects m = do
-- uuid <- get "uuid" m
-- entry' <- get "entry" m
-- description <- get "description" m
-- project <- getMaybe "project" m
-- status' <- getMaybe "status" m
-- end' <- getMaybe "end" m
-- tags' <- getList "tags" m
-- time <- (parseTime defaultTimeLocale "%Y%m%dT%H%M%SZ" entry') `maybeToValidation` ["Could not parse entry time"]
-- --closed <- (end' >>= \end -> (parseTime defaultTimeLocale "%Y%m%dT%H%M%SZ" (T.unpack end))) `maybeToValidation` ["Could not parse end time"]
-- closed <- getClosed end'
-- let mode = if Set.member (T.pack uuid) uuids then mode_mod else mode_add
-- let status = getStatus status'
-- let parent = project >>= Just . (substituteInList '.' '/')
-- let parentUuid = fmap (T.unpack . getProjectUuid . T.pack) parent
-- let args = catMaybes [wrap "id" uuid, wrap "title" description, wrapMaybe "parent" parentUuid, wrapMaybe "status" status, wrapMaybeTime "closed" closed, wrapList "tag" tags']
-- let projects' = updateProjects (fmap T.pack parent) time
-- opts0 <- eitherStringToValidation $ process mode args
-- let record = optsToCommandRecord time "default" opts0
-- let uuids' = Set.insert (T.pack uuid) uuids
-- return (uuids', projects', record)
-- where
-- getStatus status' = case status' of
-- Just "completed" -> Just "closed"
-- Just "deleted" -> Just "deleted"
-- _ -> Nothing
-- getClosed :: Maybe String -> Validation (Maybe UTCTime)
-- getClosed closed' = case closed' of
-- Just closed'' ->
-- case parseTime defaultTimeLocale "%Y%m%dT%H%M%SZ" closed'' of
-- Nothing -> Left ["Could not parse end time: " ++ closed'']
-- Just x -> Right (Just x)
-- Nothing -> Right Nothing
-- updateProjects :: Maybe T.Text -> UTCTime -> M.Map T.Text UTCTime
-- updateProjects parent time = case parent of
-- Nothing -> projects
-- Just p -> M.insert p t projects where
-- t = fromMaybe time (M.lookup p projects >>= \t -> Just $ min time t)
-- wrap :: String -> String -> Maybe String
-- wrap name value = Just (concat ["--", name, "=", value])
-- wrapMaybe :: String -> Maybe String -> Maybe String
-- wrapMaybe name value = value >>= (\x -> Just (concat ["--", name, "=", x]))
-- wrapMaybeTime :: String -> Maybe UTCTime -> Maybe String
-- wrapMaybeTime name value = value >>= (\x -> Just (concat ["--", name, "=", formatISO8601Millis x]))
-- wrapList :: String -> [String] -> Maybe String
-- wrapList _ [] = Nothing
-- wrapList name l = Just $ (concat ["--", name, "=", intercalate "," l])
get :: T.Text -> HM.HashMap T.Text Value -> Validation String
get name m = case HM.lookup name m of
Nothing -> Left ["Missing `" ++ (T.unpack name) ++ "`"]
Just (String text) -> Right (T.unpack text)
Just _ -> Left ["Field `" ++ (T.unpack name) ++ "` is not text"]
getMaybe :: T.Text -> Object -> Validation (Maybe String)
getMaybe name m = case HM.lookup name m of
Nothing -> Right Nothing
Just (String text) -> Right $ Just (T.unpack text)
Just _ -> Left ["Field `" ++ (T.unpack name) ++ "` is not text"]
getList :: T.Text -> Object -> Validation ([String])
getList name m = case HM.lookup name m of
Nothing -> Right []
Just (Array v) -> Right $ V.toList $ V.map (\(String text) -> T.unpack text) v
Just _ -> Left ["Field `" ++ (T.unpack name) ++ "` is not and array"]
createProject :: (T.Text, UTCTime) -> CommandRecord
createProject (label, time) = CommandRecord 1 time' "default" "add" args where
time' = addUTCTime (-1 :: NominalDiffTime) time
-- Create a uuid from the label
-- Use only alphanumeric lower-case characters,
-- insert hypens at the right places (e.g. 0a815f87-ab07-45e7-abbd-21a71c21c176)
-- and fill with 0s
uuid = getProjectUuid label
args = [T.concat ["--id=", uuid], "--type=list", T.concat ["--label=", label], T.concat ["--title=", label]]
getProjectUuid label = uuid where
label' = T.toLower $ T.filter isAlphaNum label
uuid0 = T.justifyLeft (8+4+4+4+12) '0' label'
uuid = insertHyphen 8 $ insertHyphen (8+4) $ insertHyphen (8+4+4) $ insertHyphen (8+4+4+4) uuid0
insertHyphen :: Int -> T.Text -> T.Text
insertHyphen i s = T.concat [left, "-", right] where
(left, right) = T.splitAt i s
optsToCommandRecord :: UTCTime -> T.Text -> Options -> CommandRecord
optsToCommandRecord time user opts = CommandRecord 1 time user (T.pack $ optionsCmd opts) opts'' where
opts' = reform opts
opts'' = map T.pack opts'
| ellis/OnTopOfThings | old-20150308/src/OnTopOfThings/Commands/Import.hs | gpl-3.0 | 15,642 | 0 | 25 | 3,422 | 3,169 | 1,720 | 1,449 | 209 | 7 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Module : ImportEnvironment
License : GPL
Maintainer : helium@cs.uu.nl
Stability : experimental
Portability : portable
-}
module Helium.ModuleSystem.ImportEnvironment where
import qualified Data.Map as M
import Helium.Utils.Utils (internalError)
import Helium.Syntax.UHA_Syntax -- (Name)
import Helium.Syntax.UHA_Utils
import Top.Types
import Helium.Parser.OperatorTable
import Helium.StaticAnalysis.Messages.Messages () -- instance Show Name
import Helium.StaticAnalysis.Heuristics.RepairHeuristics (Siblings)
import Helium.StaticAnalysis.Directives.TS_CoreSyntax
import Data.List
import Data.Maybe (catMaybes)
import Data.Function (on)
type TypeEnvironment = M.Map Name TpScheme
type ValueConstructorEnvironment = M.Map Name TpScheme
type TypeConstructorEnvironment = M.Map Name Int
type TypeSynonymEnvironment = M.Map Name (Int, Tps -> Tp)
type ClassMemberEnvironment = M.Map Name [(Name, Bool)]
type ImportEnvironments = [ImportEnvironment]
data ImportEnvironment =
ImportEnvironment { -- types
typeConstructors :: TypeConstructorEnvironment
, typeSynonyms :: TypeSynonymEnvironment
, typeEnvironment :: TypeEnvironment
-- values
, valueConstructors :: ValueConstructorEnvironment
, operatorTable :: OperatorTable
-- type classes
, classEnvironment :: ClassEnvironment
, classMemberEnvironment :: ClassMemberEnvironment
-- other
, typingStrategies :: Core_TypingStrategies
}
emptyEnvironment :: ImportEnvironment
emptyEnvironment = ImportEnvironment
{ typeConstructors = M.empty
, typeSynonyms = M.empty
, typeEnvironment = M.empty
, valueConstructors = M.empty
, operatorTable = M.empty
, classEnvironment = emptyClassEnvironment
, classMemberEnvironment = M.empty
, typingStrategies = []
}
addTypeConstructor :: Name -> Int -> ImportEnvironment -> ImportEnvironment
addTypeConstructor name int importenv =
importenv {typeConstructors = M.insert name int (typeConstructors importenv)}
-- add a type synonym also to the type constructor environment
addTypeSynonym :: Name -> (Int,Tps -> Tp) -> ImportEnvironment -> ImportEnvironment
addTypeSynonym name (arity, function) importenv =
importenv { typeSynonyms = M.insert name (arity, function) (typeSynonyms importenv)
, typeConstructors = M.insert name arity (typeConstructors importenv)
}
addType :: Name -> TpScheme -> ImportEnvironment -> ImportEnvironment
addType name tpscheme importenv =
importenv {typeEnvironment = M.insert name tpscheme (typeEnvironment importenv)}
addToTypeEnvironment :: TypeEnvironment -> ImportEnvironment -> ImportEnvironment
addToTypeEnvironment new importenv =
importenv {typeEnvironment = typeEnvironment importenv `M.union` new}
addValueConstructor :: Name -> TpScheme -> ImportEnvironment -> ImportEnvironment
addValueConstructor name tpscheme importenv =
importenv {valueConstructors = M.insert name tpscheme (valueConstructors importenv)}
addOperator :: Name -> (Int,Assoc) -> ImportEnvironment -> ImportEnvironment
addOperator name pair importenv =
importenv {operatorTable = M.insert name pair (operatorTable importenv) }
setValueConstructors :: M.Map Name TpScheme -> ImportEnvironment -> ImportEnvironment
setValueConstructors new importenv = importenv {valueConstructors = new}
setTypeConstructors :: M.Map Name Int -> ImportEnvironment -> ImportEnvironment
setTypeConstructors new importenv = importenv {typeConstructors = new}
setTypeSynonyms :: M.Map Name (Int,Tps -> Tp) -> ImportEnvironment -> ImportEnvironment
setTypeSynonyms new importenv = importenv {typeSynonyms = new}
setTypeEnvironment :: M.Map Name TpScheme -> ImportEnvironment -> ImportEnvironment
setTypeEnvironment new importenv = importenv {typeEnvironment = new}
setOperatorTable :: OperatorTable -> ImportEnvironment -> ImportEnvironment
setOperatorTable new importenv = importenv {operatorTable = new}
getOrderedTypeSynonyms :: ImportEnvironment -> OrderedTypeSynonyms
getOrderedTypeSynonyms importEnvironment =
let synonyms = let insertIt name = M.insert (show name)
in M.foldWithKey insertIt M.empty (typeSynonyms importEnvironment)
ordering = fst (getTypeSynonymOrdering synonyms)
in (ordering, synonyms)
setClassMemberEnvironment :: ClassMemberEnvironment -> ImportEnvironment -> ImportEnvironment
setClassMemberEnvironment new importenv = importenv { classMemberEnvironment = new }
setClassEnvironment :: ClassEnvironment -> ImportEnvironment -> ImportEnvironment
setClassEnvironment new importenv = importenv { classEnvironment = new }
addTypingStrategies :: Core_TypingStrategies -> ImportEnvironment -> ImportEnvironment
addTypingStrategies new importenv = importenv {typingStrategies = new ++ typingStrategies importenv}
removeTypingStrategies :: ImportEnvironment -> ImportEnvironment
removeTypingStrategies importenv = importenv {typingStrategies = []}
getSiblingGroups :: ImportEnvironment -> [[String]]
getSiblingGroups importenv =
[ xs | Siblings xs <- typingStrategies importenv ]
getSiblings :: ImportEnvironment -> Siblings
getSiblings importenv =
let f s = [ (s, ts) | ts <- findTpScheme (nameFromString s) ]
findTpScheme n =
catMaybes [ M.lookup n (valueConstructors importenv)
, M.lookup n (typeEnvironment importenv)
]
in map (concatMap f) (getSiblingGroups importenv)
combineImportEnvironments :: ImportEnvironment -> ImportEnvironment -> ImportEnvironment
combineImportEnvironments (ImportEnvironment tcs1 tss1 te1 vcs1 ot1 ce1 cm1 xs1) (ImportEnvironment tcs2 tss2 te2 vcs2 ot2 ce2 cm2 xs2) =
ImportEnvironment
(tcs1 `exclusiveUnion` tcs2)
(tss1 `exclusiveUnion` tss2)
(te1 `exclusiveUnion` te2 )
(vcs1 `exclusiveUnion` vcs2)
(ot1 `exclusiveUnion` ot2)
(M.unionWith combineClassDecls ce1 ce2)
(cm1 `exclusiveUnion` cm2)
(xs1 ++ xs2)
combineImportEnvironmentList :: ImportEnvironments -> ImportEnvironment
combineImportEnvironmentList = foldr combineImportEnvironments emptyEnvironment
exclusiveUnion :: Ord key => M.Map key a -> M.Map key a -> M.Map key a
exclusiveUnion m1 m2 =
let keys = M.keys (M.intersection m1 m2)
f m = foldr (M.update (const Nothing)) m keys
in f m1 `M.union` f m2
containsClass :: ClassEnvironment -> Name -> Bool
containsClass cEnv n = M.member (getNameName n) cEnv
{-
-- Bastiaan:
-- For the moment, this function combines class-environments.
-- The only instances that are added to the standard instances
-- are the derived Show instances (Show has no superclasses).
-- If other instances are added too, then the class environment
-- should be split into a class declaration environment, and an
-- instance environment.-}
combineClassDecls :: ([[Char]],[(Predicate,[Predicate])]) ->
([[Char]],[(Predicate,[Predicate])]) ->
([[Char]],[(Predicate,[Predicate])])
combineClassDecls (super1, inst1) (super2, inst2)
| super1 == super2 = (super1, inst1 ++ inst2)
| otherwise = internalError "ImportEnvironment.hs" "combineClassDecls" "cannot combine class environments"
-- Bastiaan:
-- Create a class environment from the dictionaries in the import environment
createClassEnvironment :: ImportEnvironment -> ClassEnvironment
createClassEnvironment importenv =
let dicts = map (drop (length dictPrefix) . show)
. M.keys
. M.filterWithKey isDict
$ typeEnvironment importenv
isDict n _ = dictPrefix `isPrefixOf` show n
dictPrefix = "$dict"
-- classes = ["Eq","Num","Ord","Enum","Show"]
-- TODO: put $ between class name and type in dictionary name
-- i.e. $dictEq$Int instead of $dictEqInt
splitDictName ('E':'q':t) = ("Eq", t)
splitDictName ('N':'u':'m':t) = ("Num", t)
splitDictName ('O':'r':'d':t) = ("Ord", t)
splitDictName ('E':'n':'u':'m':t) = ("Enum", t)
splitDictName ('S':'h':'o':'w':t) = ("Show", t)
splitDictName x = internalError "ImportEnvironment" "splitDictName" ("illegal dictionary: " ++ show x)
arity s | s == "()" = 0
| isTupleConstructor s = length s - 1
| otherwise = M.findWithDefault
(internalError "ImportEnvironment" "splitDictName" ("unknown type constructor: " ++ show s))
(nameFromString s)
(typeConstructors importenv)
dictTuples = [ (c, makeInstance c (arity t) t)
| d <- dicts, let (c, t) = splitDictName d
]
classEnv = foldr
(\(className, inst) e -> insertInstance className inst e)
superClassRelation
dictTuples
in classEnv
superClassRelation :: ClassEnvironment
superClassRelation = M.fromList
[ ("Num", ( ["Eq","Show"], []))
, ("Enum", ( [], []))
, ("Eq" , ( [], []))
, ("Ord", ( ["Eq"], []))
, ("Show", ( [], []))
]
makeInstance :: String -> Int -> String -> Instance
makeInstance className nrOfArgs tp =
let tps = take nrOfArgs [ TVar i | i <- [0..] ]
in ( Predicate className (foldl TApp (TCon tp) tps)
, [ Predicate className x | x <- tps ]
)
-- added for holmes
holmesShowImpEnv :: Module -> ImportEnvironment -> String
holmesShowImpEnv module_ (ImportEnvironment _ _ te _ _ _ _ _) =
concat functions
where
localName = getModuleName module_
functions =
let (xs, ys) = partition (isIdentifierName . fst) (M.assocs te)
list = map (\(n,_) -> getHolmesName localName n) (ys++xs)
in map (++ ";") list
instance Show ImportEnvironment where
show (ImportEnvironment tcs tss te vcs ot ce cm _) =
unlines (concat [ fixities
, datatypes
, typesynonyms
, theValueConstructors
, functions
, classes
, classmembers
])
where
fixities =
let sorted = let cmp (name, (priority, associativity)) = (10 - priority, associativity, not (isOperatorName name), name)
in sortBy (compare `on` cmp) (M.assocs ot)
grouped = groupBy ((==) `on` snd) sorted
list = let f ((name, (priority, associativity)) : rest) =
let names = name : map fst rest
prefix = (case associativity of
AssocRight -> "infixr"
AssocLeft -> "infixl"
AssocNone -> "infix "
)++" "++ show priority ++ " "
in prefix ++ foldr1 (\x y -> x++", "++y) (map showNameAsOperator names)
f [] = error "Pattern match failure in ModuleSystem.ImportEnvironment"
in map f grouped
in showWithTitle "Fixity declarations" list
datatypes =
let allDatas = filter ((`notElem` M.keys tss). fst) (M.assocs tcs)
f (n,i) = unwords ("data" : showNameAsVariable n : take i variableList)
in showWithTitle "Data types" (showEm f allDatas)
typesynonyms =
let f (n,(i,g)) = let tcons = take i (map TCon variableList)
in unwords ("type" : showNameAsVariable n : map show tcons ++ ["=", show (g tcons)])
in showWithTitle "Type synonyms" (showEm f (M.assocs tss))
theValueConstructors =
let f (n,t) = showNameAsVariable n ++ " :: "++show t
in showWithTitle "Value constructors" (showEm f (M.assocs vcs))
functions =
let f (n,t) = showNameAsVariable n ++ " :: "++show t
in showWithTitle "Functions" (showEm f (M.assocs te))
classes =
let f = undefined
in showWithTitle "Classes" (map f (M.assocs ce))
classmembers =
let f = undefined
in showWithTitle "Class members" (showEm f (M.assocs cm))
showWithTitle title xs
| null xs = []
| otherwise = (title++":") : map (" "++) xs
showEm showf aMap = map showf (part2 ++ part1)
where
(part1, part2) = partition (isIdentifierName . fst) aMap
instance Ord Assoc where
x <= y = let f :: Assoc -> Int
f AssocLeft = 0
f AssocRight = 1
f AssocNone = 2
in f x <= f y
| roberth/uu-helium | src/Helium/ModuleSystem/ImportEnvironment.hs | gpl-3.0 | 13,502 | 0 | 26 | 4,045 | 3,452 | 1,847 | 1,605 | 221 | 6 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Values.Plain where
import MyPrelude
import Data.Int
import OpenGL
import OpenAL
import Game.Font
import Game.Data.Color
import Game.Data.View
--------------------------------------------------------------------------------
-- Perspective
valuePerspectiveFOVY :: Float
valuePerspectiveFOVY =
1.047
valuePerspectiveNear :: Float
valuePerspectiveNear =
0.1
valuePerspectiveFar :: Float
valuePerspectiveFar =
512.0
-- | call this value r. let mx my mz be the x, y, z colums of the current
-- modelview matrix. then
-- r : r * abs(mx + my + mz) < projection_far
-- but we assume that modelview(3x3) is orthonormal, so
-- r : r < (projection_far / sqrt 3)
valuePerspectiveRadius :: Float
valuePerspectiveRadius =
valuePerspectiveFar * 0.57735
--------------------------------------------------------------------------------
-- Scene
valueSceneCornerSize :: Float
valueSceneCornerSize =
0.12
--------------------------------------------------------------------------------
-- Grid
valueGridPathRadius :: Float
valueGridPathRadius =
0.3
--------------------------------------------------------------------------------
-- Memory
valueMemoryPathRadius :: Float
valueMemoryPathRadius =
valueGridPathRadius
--------------------------------------------------------------------------------
-- LevelPuzzle
valueLevelPuzzleEatTicks :: Float
valueLevelPuzzleEatTicks = 1.0
valueLevelPuzzleEatTicksInv :: Float
valueLevelPuzzleEatTicksInv = 1.0 / valueLevelPuzzleEatTicks
valueLevelPuzzleView :: View
valueLevelPuzzleView =
View 0.0 0.3 10.0
valueLevelPuzzleDotRadius :: Float
valueLevelPuzzleDotRadius =
0.16
valueLevelPuzzleDotSlices :: UInt
valueLevelPuzzleDotSlices =
16
valueLevelPuzzleDotStacks :: UInt
valueLevelPuzzleDotStacks =
16
valueLevelPuzzleDotTeleColor :: Color
valueLevelPuzzleDotTeleColor =
Color 0.0 0.5 0.9 1.0
valueLevelPuzzleDotBonusColor :: Color
valueLevelPuzzleDotBonusColor =
Color 0.3 0.0 0.9 1.0
valueLevelPuzzleDotFinishColor :: Color
valueLevelPuzzleDotFinishColor =
Color 0.3 1.0 0.9 1.0
valueFadeContentTicks :: Float
valueFadeContentTicks =
4.0
valueFadeContentTicksInv :: Float
valueFadeContentTicksInv =
1.0 / valueFadeContentTicks
valueFadeRoomTicks :: Float
valueFadeRoomTicks =
1.0
valueFadeRoomTicksInv :: Float
valueFadeRoomTicksInv =
1.0 / valueFadeRoomTicks
valueFadeFailureTicks :: Float
valueFadeFailureTicks =
8.0
valueFadeFailureTicksInv :: Float
valueFadeFailureTicksInv =
1.0 / valueFadeRoomTicks
valueLevelPuzzlePathRadius :: Float
valueLevelPuzzlePathRadius =
valueGridPathRadius
--------------------------------------------------------------------------------
-- Run
valueRunCubeFontSize :: Float
valueRunCubeFontSize =
5.5
valueRunCubeFontColor :: FontColor
valueRunCubeFontColor =
FontColor 0.2 1.0 0.5 1.0
valueRunPathColor :: Color
valueRunPathColor =
Color 0.0 0.04 0.8 1.0
valueRunPathRadius :: Float
valueRunPathRadius =
1.0
--------------------------------------------------------------------------------
-- SoundPath. fixme: into module!!
valueSoundPathConeInnerAngle :: ALfloat
valueSoundPathConeInnerAngle = 360.0
valueSoundPathConeOuterAngle :: ALfloat
valueSoundPathConeOuterAngle = 360.0
valueSoundPathConeOuterGain :: ALfloat
valueSoundPathConeOuterGain = 1.0
valueSoundPathReferenceDistance :: ALfloat
valueSoundPathReferenceDistance = 32.0
valueSoundPathMaxDistance :: ALfloat
valueSoundPathMaxDistance = 128.0
valueSoundPathRolloffFactor :: ALfloat
valueSoundPathRolloffFactor = 1.0
--------------------------------------------------------------------------------
-- SoundScene. fixme: into module!
valueSoundSceneNoiseSize :: UInt
valueSoundSceneNoiseSize = 4
valueSoundSceneNoiseConeInnerAngle :: ALfloat
valueSoundSceneNoiseConeInnerAngle = 360.0
valueSoundSceneNoiseConeOuterAngle :: ALfloat
valueSoundSceneNoiseConeOuterAngle = 360.0
valueSoundSceneNoiseConeOuterGain :: ALfloat
valueSoundSceneNoiseConeOuterGain = 1.0
valueSoundSceneNoiseReferenceDistance :: ALfloat
valueSoundSceneNoiseReferenceDistance = 50.0
valueSoundSceneNoiseMaxDistance :: ALfloat
valueSoundSceneNoiseMaxDistance = 1024.0
valueSoundSceneNoiseRolloffFactor :: ALfloat
valueSoundSceneNoiseRolloffFactor = 3.0
valueSoundSceneNoiseNodeRadius :: Int16
valueSoundSceneNoiseNodeRadius = 1024
valueSoundSceneNoiseTickMin :: Float
valueSoundSceneNoiseTickMin = 11.0
valueSoundSceneNoiseTickMax :: Float
valueSoundSceneNoiseTickMax = 20.0
valueSoundSceneNoisePitchMin :: Float
valueSoundSceneNoisePitchMin = 0.3
valueSoundSceneNoisePitchMax :: Float
valueSoundSceneNoisePitchMax = 2.0
--------------------------------------------------------------------------------
-- SoundLevelPuzzle. fixme: into module!
valueSoundLevelPuzzleNodeConeInnerAngle :: ALfloat
valueSoundLevelPuzzleNodeConeInnerAngle = 45.0
valueSoundLevelPuzzleNodeConeOuterAngle :: ALfloat
valueSoundLevelPuzzleNodeConeOuterAngle = 360.0
valueSoundLevelPuzzleNodeConeOuterGain :: ALfloat
valueSoundLevelPuzzleNodeConeOuterGain = 0.4
valueSoundLevelPuzzleNodeReferenceDistance :: ALfloat
valueSoundLevelPuzzleNodeReferenceDistance = 8.0
valueSoundLevelPuzzleNodeMaxDistance :: ALfloat
valueSoundLevelPuzzleNodeMaxDistance = 32.0
valueSoundLevelPuzzleNodeRolloffFactor :: ALfloat
valueSoundLevelPuzzleNodeRolloffFactor = 1.0
--------------------------------------------------------------------------------
-- SpaceBox. fixme: into module!!
valueSpaceBoxDefaultColor :: Color
valueSpaceBoxDefaultColor =
Color 0.3 0.9 0.0 1.0
--------------------------------------------------------------------------------
-- ColorMap. fixme: into module!
valueColorMapSize :: UInt
valueColorMapSize =
23
--------------------------------------------------------------------------------
-- Text
-- | (relative to Scene hth)
valueTextFontASize :: Float
valueTextFontASize =
0.1
-- | (relative to Scene hth)
valueTextFontAY :: Float
valueTextFontAY =
0.4
valueTextFontAColor :: FontColor
valueTextFontAColor =
FontColor 0.0 1.0 0.6 1.0
-- | (relative to Scene hth)
valueTextFontBSize :: Float
valueTextFontBSize =
0.05
-- | (relative to Scene hth)
valueTextFontBY :: Float
valueTextFontBY =
0.3
valueTextFontBColor :: FontColor
valueTextFontBColor =
FontColor 0.6 1.0 0.0 1.0
-- | (relative to Scene hth)
valueTextFontCSize :: Float
valueTextFontCSize =
0.02
-- | (relative to Scene hth)
valueTextFontCY :: Float
valueTextFontCY =
0.05
valueTextFontCColor :: FontColor
valueTextFontCColor =
FontColor 0.6 0.0 1.0 1.0
| karamellpelle/grid | source/Game/Values/Plain.hs | gpl-3.0 | 7,436 | 0 | 5 | 1,007 | 819 | 499 | 320 | 168 | 1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -pgmP cpp #-}
module Config(
Config(..)
, ColorTheme
, RefreshMode(..)
, defaultConfig
, configFromFile
, configToFile
, makeColorsFromList
) where
import Graphics.UI.Gtk (SortType(..), Window)
import Data.Array
import Data.Char
import Control.Exception
import Control.Applicative
import Network.Tremulous.Protocol
import Control.Monad.State.Strict
import Network.Tremulous.TupleReader (lookupDelete)
import Network.Tremulous.StrictMaybe as SM
import Network.Tremulous.MicroTime
import Constants
import List2
import GtkUtils
import TremFormatting
type ColorTheme = Array Int TremFmt
data SortingOrderPretty = Ascending | Descending
deriving (Show, Read, Enum)
data RefreshMode = Startup | Auto | Manual
deriving (Show, Read, Eq)
data Config = Config
{ masterServers :: ![(String, Int, Int)]
, clanlistURL :: !String
, tremulousPath
, tremulousGppPath
, unvanquishedPath :: !String
, refreshMode :: !RefreshMode
, autoClan
, restoreGeometry :: !Bool
, autoRefreshDelay :: !MicroTime
, filterBrowser
, filterPlayers :: !String
, showEmpty :: !Bool
, browserSortColumn
, playersSortColumn
, clanlistSortColumn :: !Int
, browserOrder
, playersOrder
, clanlistOrder :: !SortType
, delays :: !Delay
, colors :: !ColorTheme
}
defaultConfig :: Config
defaultConfig = Config
{ masterServers = [ ("master.tremulous.net", 30710, 69)
, ("master.tremulous.net", 30700, 70)
, ("unvanquished.net", 27950, 86)
]
, clanlistURL = "http://ddos-tremulous.eu/cw/api/2/clanlist"
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
, tremulousPath = "C:\\Program Files\\Tremulous\\tremulous.exe"
, tremulousGppPath = "C:\\Program Files\\Tremulous\\tremulous-gpp.exe"
, unvanquishedPath = "C:\\Program Files (x86)\\Unvanquished\\daemon.exe"
#else
, tremulousPath = "tremulous"
, tremulousGppPath = "tremulous-gpp"
, unvanquishedPath = "unvanquished"
#endif
, refreshMode = Startup
, autoClan = True
, restoreGeometry = True
, autoRefreshDelay = 120000000 -- 120 seconds
, filterBrowser = ""
, filterPlayers = ""
, showEmpty = True
, browserSortColumn = 3
, playersSortColumn = 0
, clanlistSortColumn = 1
, browserOrder = ascending
, playersOrder = ascending
, clanlistOrder = ascending
, delays = defaultDelay
, colors = makeColorsFromList
[ TremFmt False "#000000"
, TremFmt True "#d60503"
, TremFmt True "#25c200"
, TremFmt True "#eab93d"
, TremFmt True "#0021fe"
, TremFmt True "#04c9c9"
, TremFmt True "#e700d7"
, TremFmt False "#000000"
]
}
where ascending = (toEnum . fromEnum) Ascending
#define NS(x) (showKV x #x)
#define NSF(x, y) (showKV ((y) x) #x)
newSave :: Config -> String
newSave Config{delays=Delay{..}, ..} = unlines $
[ NS(masterServers)
, NS(clanlistURL)
, NS(tremulousPath)
, NS(tremulousGppPath)
, NS(unvanquishedPath)
, NS(refreshMode)
, NS(autoClan)
, NS(restoreGeometry)
, NSF(autoRefreshDelay, (`quot`1000000))
, NS(filterBrowser)
, NS(filterPlayers)
, NS(showEmpty)
, NS(browserSortColumn)
, NS(playersSortColumn)
, NS(clanlistSortColumn)
, NSF(browserOrder, conv)
, NSF(playersOrder, conv)
, NSF(clanlistOrder, conv)
, NS(packetTimeout)
, NS(packetDuplication)
, NS(throughputDelay)
] ++ zipWith
(\a b -> showKV b ("color" ++ [a])) ['0'..'7']
(elems colors)
where
conv :: SortType -> SortingOrderPretty
conv = toEnum . fromEnum
showKV :: Show v => v -> String -> String
showKV v k = k ++ " " ++ show v
#define NP(x) x <- getKV #x id (x defaultConfig)
#define NP_NODEF(x) x <- getKV #x id
#define NPF(x, f) x <- getKV #x (f) (x defaultConfig)
newParse :: [(String, String)] -> Config
newParse = evalState $ do
NP(masterServers)
NP(clanlistURL)
NP(tremulousPath)
NP(tremulousGppPath)
NP(unvanquishedPath)
NP(refreshMode)
NP(autoClan)
NP(restoreGeometry)
NPF(autoRefreshDelay, (*1000000))
NP(filterBrowser)
NP(filterPlayers)
NP(showEmpty)
NP(browserSortColumn)
NP(playersSortColumn)
NP(clanlistSortColumn)
NPF(browserOrder , conv)
NPF(playersOrder , conv)
NPF(clanlistOrder, conv)
NP_NODEF(packetTimeout) (packetTimeout defaultDelay)
NP_NODEF(packetDuplication) (packetDuplication defaultDelay)
NP_NODEF(throughputDelay) (throughputDelay defaultDelay)
colors <- makeColorsFromList <$> zipWithM
(\a b -> getKV ("color" ++ [a]) id b)
['0'..'7']
(elems (colors defaultConfig))
return Config{delays = Delay{..}, ..}
where
conv :: SortingOrderPretty -> SortType
conv = toEnum . fromEnum
getKV :: Read b => String -> (b -> c) -> c -> State [(String, String)] c
getKV key f def = do
s <- get
let (e, sNew) = lookupDelete key s
put sNew
return $ SM.maybe def f $ smread =<< e
smread :: (Read a) => String -> SM.Maybe a
smread x = case reads x of
[(a, _)] -> SM.Just a
_ -> SM.Nothing
makeColorsFromList :: [e] -> Array Int e
makeColorsFromList = listArray (0,7)
parse :: String -> Config
parse = newParse . map (breakDrop isSpace) . lines
configToFile :: Window -> Config -> IO ()
configToFile win config = do
file <- inConfDir "config"
handle err $ writeFile file (newSave config)
where
err (e::IOError) = gtkWarn win $ "Unable to save settings:\n" ++ show e
configFromFile :: IO Config
configFromFile = catch
(parse <$> (readFile =<< inConfDir "config"))
(\(_::IOError) -> return defaultConfig)
| Cadynum/Apelsin | src/Config.hs | gpl-3.0 | 6,375 | 0 | 16 | 1,936 | 1,669 | 924 | 745 | -1 | -1 |
import KNN.KNN
import KMeans.KMeans
import Svm.Svm
import Linear.Linear
import Logistic.Logistic
import LSA.LSA
import NaiveBayes.NaiveBayes
import HMM.HMM
main = do print "done"
| rahulaaj/ML-Library | src/Main.hs | gpl-3.0 | 180 | 0 | 7 | 22 | 52 | 29 | 23 | 9 | 1 |
{-# LANGUAGE MultiWayIf #-}
module Heqet.Output.Symbols
( renderSymbols
) where
import Heqet.Output.Render
import Heqet.Types
import qualified Heqet.Tables as Tables
import Heqet.Output.Templates
import Heqet.Tools
import Heqet.List
import qualified Heqet.Output.LilypondSettings as Output.LilypondSettings
import Heqet.LyInstances
import Heqet.Meters
import qualified Heqet.Instruments as Instruments
import Control.Lens
import Data.Maybe
import Data.Tuple
import Data.List
import Data.Typeable
import Control.Applicative
import Data.Monoid
import Data.Ord
import Safe
import Data.Ratio
{-
The PointInTime is where we measure the clefs and keys for the heading.
-}
renderSymbols :: Music -> StaffOrdering -> PointInTime -> ([HeadingSymbol],[Symbol])
renderSymbols m order pit = let
heading = [ (ClefH Treble,1) ]
syms = concatMap toSym m
in (heading,syms)
toSym :: InTime (Note Ly) -> [Symbol]
toSym it = let
lyt = typeOfLy $ it^.val.pitch
in if
| lyt == lyPitchType -> [(NoteHead Filled,1,0,it^.t)]
| otherwise -> []
| Super-Fluid/heqet | Heqet/Output/Symbols.hs | gpl-3.0 | 1,074 | 0 | 11 | 186 | 302 | 175 | 127 | -1 | -1 |
{- |
Module : Cell
Description : A `Cell` in a `Grid`.
Copyright : (c) Frédéric BISSON, 2015
License : GPL-3
Maintainer : zigazou@free.fr
Stability : experimental
Portability : POSIX
-}
module Cell
( Direction (..)
, Axis (..)
, Cell (..)
, toCell
) where
{- |
Direction an `Arrow` may take.
-}
data Direction = GoUp | GoRight | GoDown | GoLeft deriving (Eq, Show)
{- |
Axis of a `Line`.
-}
data Axis = Horizontal | Vertical deriving (Eq, Show)
{- |
A `Cell` may contain 6 kinds of value.
-}
data Cell = Start -- ^ A starting point
| Line Axis -- ^ An horizontal or vertical line
| Crossroad -- ^ An axis changer
| Arrow Direction -- ^ An arrow pointing to a direction
| Value Char -- ^ A character
| Empty -- ^ An empty cell
deriving (Eq, Show)
{- |
Convert a `Char` to a `Cell`.
-}
toCell :: Char -> Cell
toCell 'S' = Start
toCell '-' = Line Horizontal
toCell '|' = Line Vertical
toCell '+' = Crossroad
toCell '>' = Arrow GoRight
toCell '<' = Arrow GoLeft
toCell '^' = Arrow GoUp
toCell 'V' = Arrow GoDown
toCell ' ' = Empty
toCell c = Value c
| Zigazou/ArrowPointing | src/Cell.hs | gpl-3.0 | 1,165 | 0 | 6 | 327 | 238 | 135 | 103 | 25 | 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.IAM.DeleteRole
-- 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.
-- | Deletes the specified role. The role must not have any policies attached. For
-- more information about roles, go to <http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html Working with Roles>.
--
-- Make sure you do not have any Amazon EC2 instances running with the role you
-- are about to delete. Deleting a role or instance profile that is associated
-- with a running instance will break any applications running on the instance.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRole.html>
module Network.AWS.IAM.DeleteRole
(
-- * Request
DeleteRole
-- ** Request constructor
, deleteRole
-- ** Request lenses
, drRoleName
-- * Response
, DeleteRoleResponse
-- ** Response constructor
, deleteRoleResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
newtype DeleteRole = DeleteRole
{ _drRoleName :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteRole' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drRoleName' @::@ 'Text'
--
deleteRole :: Text -- ^ 'drRoleName'
-> DeleteRole
deleteRole p1 = DeleteRole
{ _drRoleName = p1
}
-- | The name of the role to delete.
drRoleName :: Lens' DeleteRole Text
drRoleName = lens _drRoleName (\s a -> s { _drRoleName = a })
data DeleteRoleResponse = DeleteRoleResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteRoleResponse' constructor.
deleteRoleResponse :: DeleteRoleResponse
deleteRoleResponse = DeleteRoleResponse
instance ToPath DeleteRole where
toPath = const "/"
instance ToQuery DeleteRole where
toQuery DeleteRole{..} = mconcat
[ "RoleName" =? _drRoleName
]
instance ToHeaders DeleteRole
instance AWSRequest DeleteRole where
type Sv DeleteRole = IAM
type Rs DeleteRole = DeleteRoleResponse
request = post "DeleteRole"
response = nullResponse DeleteRoleResponse
| romanb/amazonka | amazonka-iam/gen/Network/AWS/IAM/DeleteRole.hs | mpl-2.0 | 3,060 | 0 | 9 | 680 | 334 | 207 | 127 | 45 | 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.Redis.Projects.Locations.Instances.Patch
-- 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)
--
-- Updates the metadata and configuration of a specific Redis instance.
-- Completed longrunning.Operation will contain the new instance object in
-- the response field. The returned operation is automatically deleted
-- after a few hours, so there is no need to call DeleteOperation.
--
-- /See:/ <https://cloud.google.com/memorystore/docs/redis/ Google Cloud Memorystore for Redis API Reference> for @redis.projects.locations.instances.patch@.
module Network.Google.Resource.Redis.Projects.Locations.Instances.Patch
(
-- * REST Resource
ProjectsLocationsInstancesPatchResource
-- * Creating a Request
, projectsLocationsInstancesPatch
, ProjectsLocationsInstancesPatch
-- * Request Lenses
, plipXgafv
, plipUploadProtocol
, plipUpdateMask
, plipAccessToken
, plipUploadType
, plipPayload
, plipName
, plipCallback
) where
import Network.Google.Prelude
import Network.Google.Redis.Types
-- | A resource alias for @redis.projects.locations.instances.patch@ method which the
-- 'ProjectsLocationsInstancesPatch' request conforms to.
type ProjectsLocationsInstancesPatchResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Instance :> Patch '[JSON] Operation
-- | Updates the metadata and configuration of a specific Redis instance.
-- Completed longrunning.Operation will contain the new instance object in
-- the response field. The returned operation is automatically deleted
-- after a few hours, so there is no need to call DeleteOperation.
--
-- /See:/ 'projectsLocationsInstancesPatch' smart constructor.
data ProjectsLocationsInstancesPatch =
ProjectsLocationsInstancesPatch'
{ _plipXgafv :: !(Maybe Xgafv)
, _plipUploadProtocol :: !(Maybe Text)
, _plipUpdateMask :: !(Maybe GFieldMask)
, _plipAccessToken :: !(Maybe Text)
, _plipUploadType :: !(Maybe Text)
, _plipPayload :: !Instance
, _plipName :: !Text
, _plipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsInstancesPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plipXgafv'
--
-- * 'plipUploadProtocol'
--
-- * 'plipUpdateMask'
--
-- * 'plipAccessToken'
--
-- * 'plipUploadType'
--
-- * 'plipPayload'
--
-- * 'plipName'
--
-- * 'plipCallback'
projectsLocationsInstancesPatch
:: Instance -- ^ 'plipPayload'
-> Text -- ^ 'plipName'
-> ProjectsLocationsInstancesPatch
projectsLocationsInstancesPatch pPlipPayload_ pPlipName_ =
ProjectsLocationsInstancesPatch'
{ _plipXgafv = Nothing
, _plipUploadProtocol = Nothing
, _plipUpdateMask = Nothing
, _plipAccessToken = Nothing
, _plipUploadType = Nothing
, _plipPayload = pPlipPayload_
, _plipName = pPlipName_
, _plipCallback = Nothing
}
-- | V1 error format.
plipXgafv :: Lens' ProjectsLocationsInstancesPatch (Maybe Xgafv)
plipXgafv
= lens _plipXgafv (\ s a -> s{_plipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plipUploadProtocol :: Lens' ProjectsLocationsInstancesPatch (Maybe Text)
plipUploadProtocol
= lens _plipUploadProtocol
(\ s a -> s{_plipUploadProtocol = a})
-- | Required. Mask of fields to update. At least one path must be supplied
-- in this field. The elements of the repeated paths field may only include
-- these fields from Instance: * \`displayName\` * \`labels\` *
-- \`memorySizeGb\` * \`redisConfig\`
plipUpdateMask :: Lens' ProjectsLocationsInstancesPatch (Maybe GFieldMask)
plipUpdateMask
= lens _plipUpdateMask
(\ s a -> s{_plipUpdateMask = a})
-- | OAuth access token.
plipAccessToken :: Lens' ProjectsLocationsInstancesPatch (Maybe Text)
plipAccessToken
= lens _plipAccessToken
(\ s a -> s{_plipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plipUploadType :: Lens' ProjectsLocationsInstancesPatch (Maybe Text)
plipUploadType
= lens _plipUploadType
(\ s a -> s{_plipUploadType = a})
-- | Multipart request metadata.
plipPayload :: Lens' ProjectsLocationsInstancesPatch Instance
plipPayload
= lens _plipPayload (\ s a -> s{_plipPayload = a})
-- | Required. Unique name of the resource in this scope including project
-- and location using the form:
-- \`projects\/{project_id}\/locations\/{location_id}\/instances\/{instance_id}\`
-- Note: Redis instances are managed and addressed at regional level so
-- location_id here refers to a GCP region; however, users may choose which
-- specific zone (or collection of zones for cross-zone instances) an
-- instance should be provisioned in. Refer to location_id and
-- alternative_location_id fields for more details.
plipName :: Lens' ProjectsLocationsInstancesPatch Text
plipName = lens _plipName (\ s a -> s{_plipName = a})
-- | JSONP
plipCallback :: Lens' ProjectsLocationsInstancesPatch (Maybe Text)
plipCallback
= lens _plipCallback (\ s a -> s{_plipCallback = a})
instance GoogleRequest
ProjectsLocationsInstancesPatch
where
type Rs ProjectsLocationsInstancesPatch = Operation
type Scopes ProjectsLocationsInstancesPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsInstancesPatch'{..}
= go _plipName _plipXgafv _plipUploadProtocol
_plipUpdateMask
_plipAccessToken
_plipUploadType
_plipCallback
(Just AltJSON)
_plipPayload
redisService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsInstancesPatchResource)
mempty
| brendanhay/gogol | gogol-redis/gen/Network/Google/Resource/Redis/Projects/Locations/Instances/Patch.hs | mpl-2.0 | 6,914 | 0 | 17 | 1,451 | 872 | 514 | 358 | 125 | 1 |
{-# LANGUAGE UnicodeSyntax, TemplateHaskell, DeriveDataTypeable, StandaloneDeriving #-}
module Text.LogMerger.Types (
BasicLogEntry(..)
, basic_origin
, basic_date
, basic_text
, Origin(..)
, DateTime
, TimeAs(..)
, module Data.Time
) where
import Data.Time
import Data.Word
-- import qualified Data.ByteString.Lazy.Internal as B
import qualified Data.ByteString as B
import Data.ByteString
import Data.Data
import Data.Typeable
import Data.ByteString.Internal (c2w, w2c)
import Control.Lens
import qualified Data.Map as M
type DateTime = UTCTime
data TimeAs = AsUTC | AsLocalTime | AsUnixTime
data Origin o =
OData o
| Location {
_file ∷ FilePath
-- TODO: We've had a problem. Looks like attoparsec doesn't keep offset
-- , _offset ∷ Word64
-- , _size ∷ Word32
} deriving (Data, Eq, Ord, Typeable)
data BasicLogEntry o =
BasicLogEntry {
_basic_date ∷ DateTime
, _basic_origin ∷ [Origin o]
, _basic_text ∷ B.ByteString
} | -- TODO: this is ugly!
DataStreamEntry {
_ds_date ∷ DateTime
, _ds_origin ∷ [Origin o]
, _ds_data ∷ M.Map String Double
}
deriving (Eq, Data, Typeable)
makeLenses ''BasicLogEntry
instance (Eq o) ⇒ Ord (BasicLogEntry o) where
compare a b = compare (_basic_date a) (_basic_date b)
deriving instance (Show o) ⇒ Show (BasicLogEntry o)
instance (Show o) ⇒ Show (Origin o) where
show (Location {_file = f}) = f
show (OData o) = show o
| k32/visualsgsn | src/Text/LogMerger/Types.hs | unlicense | 1,459 | 0 | 10 | 289 | 401 | 235 | 166 | 43 | 0 |
{-
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://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.
-}
import Distribution.Simple
main = defaultMain
| deepmind/logical-entailment-dataset | Setup.hs | apache-2.0 | 649 | 0 | 4 | 141 | 12 | 7 | 5 | 2 | 1 |
module AlecSequences.A333398Spec (main, spec) where
import Test.Hspec
import AlecSequences.A333398 (a333398)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A333398" $
it "correctly computes the first 20 elements" $
map a333398 [1..20] `shouldBe` expectedValue where
expectedValue = [0,-1,-3,-2,-5,-9,-7,-4,1,5,11,6,13,7,15,8,17,9,19,10]
| peterokagey/haskellOEIS | test/AlecSequences/A333398Spec.hs | apache-2.0 | 366 | 0 | 8 | 57 | 168 | 99 | 69 | 10 | 1 |
module Convert(
convertFiles
, ConvertFormat(..)
, ConvertOptions(..)
, readConvertFormat
, BlpFormat(..)
, readBlpFormat
) where
import Codec.Picture
import Codec.Picture.Blp
import Control.Monad
import Data.Char
import Data.Maybe
import Data.Monoid
import System.Directory
import System.FilePath
import qualified Data.ByteString as BS
import File
data BlpFormat =
BlpJpeg
| BlpUncompressedWithAlpha
| BlpUncompressedWithoutAlpha
deriving (Eq, Ord, Show, Enum, Bounded)
readBlpFormat :: String -> Maybe BlpFormat
readBlpFormat s = case toLower <$> s of
"jpeg" -> Just BlpJpeg
"jpg" -> Just BlpJpeg
"uncompressed1" -> Just BlpUncompressedWithAlpha
"uncompressedwithalpha" -> Just BlpUncompressedWithAlpha
"uncompressed2" -> Just BlpUncompressedWithoutAlpha
"uncompressedwithoutalpha" -> Just BlpUncompressedWithoutAlpha
_ -> Nothing
data ConvertFormat =
Blp
| Png
| Jpeg
| Tiff
| Gif
| Bmp
| UnspecifiedFormat
deriving (Eq, Ord, Show, Enum, Bounded)
readConvertFormat :: String -> Maybe ConvertFormat
readConvertFormat s = case toLower <$> s of
"blp" -> Just Blp
"png" -> Just Png
"jpeg" -> Just Jpeg
"jpg" -> Just Jpeg
"jpe" -> Just Jpeg
"jif" -> Just Jpeg
"jfif" -> Just Jpeg
"jfi" -> Just Jpeg
"tiff" -> Just Tiff
"gif" -> Just Gif
"bmp" -> Just Bmp
_ -> Nothing
-- | Replaces Unspecified
defaultFormat :: ConvertFormat
defaultFormat = Png
formatExtension :: ConvertFormat -> [String]
formatExtension c = case c of
Blp -> [".blp"]
Png -> [".png"]
Jpeg -> [".jpeg", ".jpg", ".jpe", ".jif", ".jfif", ".jfi"]
Tiff -> [".tiff"]
Gif -> [".gif"]
Bmp -> [".bmp"]
UnspecifiedFormat -> []
supportedExtensions :: [String]
supportedExtensions = concat $ formatExtension <$> [Blp .. Bmp]
data ConvertOptions = ConvertOptions {
convertInput :: FilePath
, convertOutput :: FilePath
, convertInputFormat :: ConvertFormat
, convertFormat :: ConvertFormat
, convertQuality :: Int
, convertPreservesDirs :: Bool
, convertShallow :: Bool
, convertBlpFormat :: BlpFormat
, convertBlpMinMipSize :: Int
}
convertFiles :: ConvertOptions -> IO ()
convertFiles opts@ConvertOptions{..} = do
efx <- doesFileExist convertInput
if efx
then convertFile opts False convertInput
else do
edx <- doesDirectoryExist convertInput
if edx then do
putStrLn $ "Converting all files from " ++ convertInput ++ " folder"
forEachFile' convertInput fileFilter $ convertFile opts True
else fail $ "Given path " ++ convertInput ++ " doesn't exsist!"
where
fileFilter s = case convertFormat of
Blp -> (fmap toLower $ takeExtension s) `elem` supportedExtensions
_ -> (".blp" ==) . fmap toLower . takeExtension $ s
-- | Trye to guess format from name of file
guessFormat :: FilePath -> Maybe ConvertFormat
guessFormat = readConvertFormat . drop 1 . takeExtension
-- | Try to load input file with desired format
readInputFile :: FilePath -> ConvertFormat -> IO DynamicImage
readInputFile inputFile format = case format of
Blp -> do
fc <- BS.readFile inputFile
case decodeBlp fc of
Left err -> fail $ "Failed to load file " <> inputFile <> ", parse error: " <> err
Right img -> pure img
Png -> loadJuicy readPng
Jpeg -> loadJuicy readJpeg
Tiff -> loadJuicy readTiff
Gif -> loadJuicy readGif
Bmp -> loadJuicy readBitmap
UnspecifiedFormat -> case guessFormat inputFile of
Just newFormat -> readInputFile inputFile newFormat
Nothing -> fail $ "Cannot infer format from filename " <> inputFile
where
loadJuicy :: (FilePath -> IO (Either String DynamicImage)) -> IO DynamicImage
loadJuicy f = do
mres <- f inputFile
case mres of
Left err -> fail $ "Failed to load file " <> inputFile <> " as " <> show format <> ", error: " <> err
Right img -> pure img
convertFile :: ConvertOptions -> Bool -> FilePath -> IO ()
convertFile ConvertOptions{..} isDir inputFile = do
img <- readInputFile inputFile convertInputFormat
let distFormat = case convertFormat of
UnspecifiedFormat -> if isDir then defaultFormat
else case guessFormat convertOutput of
Just f -> f
Nothing -> defaultFormat
_ -> convertFormat
when isDir $ createDirectoryIfMissing True convertOutput
let outputFile = if isDir
then convertOutput
</> drop (length convertInput + 1) (takeDirectory inputFile)
</> (takeBaseName inputFile <> fromMaybe "" (listToMaybe $ formatExtension distFormat))
else convertOutput
createDirectoryIfMissing True $ takeDirectory outputFile
let mipsCount = mipMapsUpTo convertBlpMinMipSize img
res <- convertionFunction distFormat convertQuality convertBlpFormat outputFile mipsCount img
case res of
Left err -> fail $ inputFile <> ": " <> err
Right _ -> putStrLn $ inputFile <> ": Success"
convertionFunction :: ConvertFormat -> Int -> BlpFormat -> FilePath -> Int -> DynamicImage -> IO (Either String ())
convertionFunction f quality blpFormat path mipsCount img = case f of
Blp -> case blpFormat of
BlpJpeg -> writeBlpJpeg path quality mipsCount img >> pure (Right ())
BlpUncompressedWithAlpha -> writeBlpUncompressedWithAlpha path mipsCount img >> pure (Right ())
BlpUncompressedWithoutAlpha -> writeBlpUncompressedWithoutAlpha path mipsCount img >> pure (Right ())
Png -> do
res <- writeDynamicPng path img
pure $ void res
Jpeg -> saveJpgImage quality path img >> pure (Right ())
Tiff -> saveTiffImage path img >> pure (Right ())
Gif -> case saveGifImage path img of
Left er -> pure $ Left er
Right io -> io >> pure (Right ())
Bmp -> saveBmpImage path img >> pure (Right ())
UnspecifiedFormat -> pure $ Left "no conversion format specified"
| NCrashed/JuicyPixels-blp | blp2any/Convert.hs | bsd-3-clause | 5,830 | 0 | 17 | 1,261 | 1,720 | 860 | 860 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS -Wall #-}
module NN.NeuralNetwork
(
NN (..)
, NNVars
, createNetworkW
, Net (..)
, module Util.Vars
) where
import AI.HNN.FF.Network
import Numeric.LinearAlgebra.HMatrix hiding (corr)
import System.Random (RandomGen, random)
import qualified Data.Vector as V
import Control.Monad.Reader
import RandomUtil.Random
import Util.Vars
import Matrix.Traversable
import Data.Traversable
type NNVars = Vars
class NN n where
create :: NNVars -> IO n
get :: n -> Vector Double -> Vector Double
train :: n -> Sample Double -> n
train net samp = trainV net [samp]
trainV :: n -> Samples Double -> n
randomize :: (RandomGen g) => g -> n -> (g,n)
getWeights :: n -> V.Vector (Matrix Double)
getVars :: n -> NNVars
data Net = Net
{
_network :: Network Double
, _vars :: NNVars
}
instance NN Net where
create vars = do
n <- createNetworkW vars
return $ Net n vars
get net input = getNetwork (_vars net) (_network net) input
trainV net io = let vars = _vars net in Net (trainNetwork vars (_network net) io) vars
randomize g net = let vars = _vars net
(g',n) = randomizeNetwork vars g (_network net)
in (g', Net n vars)
getWeights (Net (Network m) _) = m
getVars (Net _ vars) = vars
createNetworkW :: NNVars -> IO (Network Double)
createNetworkW env = runReader createNetworkReader env
createNetworkReader :: Reader NNVars (IO (Network Double))
createNetworkReader = do
numInput <- asks (getVar numberInputsS)
numHidden <- asks (getVar numberHiddenS)
numOutput <- asks (getVar numberOutputsS)
return $ createNetwork (round numInput) [(round numHidden)] (round numOutput)
getNetwork :: NNVars -> Network Double -> Vector Double -> Vector Double
getNetwork vars net input = runReader (getNetworkReader net input) vars
getNetworkReader :: Network Double -> Vector Double -> Reader NNVars (Vector Double)
getNetworkReader net input = do
sigOrTanh <- asks (getVar sigmoidTanS)
let (act, _) = getActivationFunctions sigOrTanh
return $ output net act input
trainNetwork :: NNVars -> Network Double -> Samples Double -> Network Double
trainNetwork vars net samples = runReader (trainNetworkReader net samples) vars
trainNetworkReader :: Network Double -> Samples Double -> Reader NNVars (Network Double)
trainNetworkReader net samples = do
timesToTrain <- asks (getVar timesToTrainS)
learningRate <- asks (getVar learningRateS)
sigOrTanh <- asks (getVar sigmoidTanS)
let (act, act') = getActivationFunctions sigOrTanh
return $ trainNTimes (round timesToTrain) learningRate act act' net samples
type RandNet g = g -> Network Double -> (g, Network Double)
randomizeNetwork :: RandomGen g => NNVars -> RandNet g
randomizeNetwork vars g net = runReader (randomizeNetworkReader g net) vars
randomizeNetworkReader :: RandomGen g
=> g -> Network Double -> Reader NNVars (g, Network Double)
randomizeNetworkReader g net@(Network weights) = do
mean <- asks (getVar meanS)
std <- asks (getVar stddevS)
rate <- asks (getVar mutationRate)
let mutF = probApply rate (addNormalNoise mean std)
(g', weights') = mapAccumL (matrixTraverse mutF) g weights
return $ (g',fromWeightMatrices weights')
type MutateElementF g a b = (g -> a -> (g, b))
-- With a probability of the provided double, apply the random function
-- Otherwise, apply nothing
probApply :: RandomGen g
=> Double -> MutateElementF g a a -> MutateElementF g a a
probApply p rF g a = let (r,g') = random g
in if r > p then randomID g' a else rF g' a
randomID :: MutateElementF g a a
randomID g a = (g,a)
getActivationFunctions :: (Floating a) => Double -> (ActivationFunction a, ActivationFunctionDerivative a)
getActivationFunctions inp = let asInt :: Integer
asInt = round inp
in case asInt of
1 -> (sigmoid, sigmoid')
_ -> (tanh, tanh')
| eklinkhammer/neural-algorithms | src/NN/NeuralNetwork.hs | bsd-3-clause | 4,075 | 0 | 12 | 951 | 1,424 | 718 | 706 | 91 | 2 |
-- | Type inference for Python 3. It serves as the entry point for users of the
-- library.
module Language.Python.TypeInference.TypeInference (
parseModules,
toCFG,
inferTypes,
parseUserSuppliedTypes
) where
import Data.Map (Map)
import Data.Set (Set)
import Language.Python.Common.AST
import Language.Python.TypeInference.Analysis.Analysis
import Language.Python.TypeInference.Analysis.TypeLattice
import Language.Python.TypeInference.CFG.CFG
import Language.Python.TypeInference.CFG.ToCFG
import Language.Python.TypeInference.Common
import Language.Python.TypeInference.Configuration
import Language.Python.TypeInference.Error
import Language.Python.TypeInference.Parse
import Language.Python.TypeInference.UserSuppliedTypes
-- | Parse modules.
parseModules :: [(SourceCode, Filename)]
-> TypeInferenceMonad [(String, ModuleSpan)]
parseModules = mapM (uncurry parse)
-- | Create control flow graph.
toCFG :: [(String, ModuleSpan)] -> UserSuppliedTypes -> TypeInferenceMonad CFG
toCFG = createCFG
-- | Run type inference analysis.
inferTypes :: Configuration -> CFG -> Map Identifier UnionType
-> TypeInferenceMonad (TypeInferenceResult, Set Edge', Int)
inferTypes = analyze
-- | Parse the contents of a file with user-supplied types.
parseUserSuppliedTypes :: String -> TypeInferenceMonad UserSuppliedTypes
parseUserSuppliedTypes = parseFile
| lfritz/python-type-inference | python-type-inference/src/Language/Python/TypeInference/TypeInference.hs | bsd-3-clause | 1,391 | 0 | 10 | 179 | 255 | 160 | 95 | 27 | 1 |
import Data.Maybe
prices :: [(String, Integer)]
prices = [
("apple", 100),
("banana", 70),
("orange", 90) ]
myMapMaybe :: (a -> Maybe b) -> [a] -> [b]
myMapMaybe f (x : xs) = case f x of
Just y -> y : myMapMaybe f xs
_ -> myMapMaybe f xs
myMapMaybe _ _ = []
justs :: [Maybe a] -> [a]
justs (mx : xs) = case mx of
Just x -> x : justs xs
_ -> justs xs
justs _ = []
| YoshikuniJujo/funpaala | samples/others/mapMaybe.hs | bsd-3-clause | 373 | 6 | 9 | 93 | 224 | 119 | 105 | 16 | 2 |
module CharParser (
getText
, getTitleFiles
, getTitleFileURLs
, getTDs
) where
import qualified Data.Text.Lazy as L
import LineParser
import Notation
import Types
----------------------------------------------------------------
getText :: L.Text -> LineParser XText
getText txt = case parse text "getText" txt of
Right cooked -> return cooked
Left _ -> fail ": link or quote error"
text :: Parser XText
text = spaces *> contents
where
contents = many (link <|> shrinkSpaces <|> rawtext)
link :: Parser PText
link = A <$> (open *> word) <*> (spaces *> word <* close)
where
open = char pikiAOpen
close = char pikiAClose
shrinkSpaces :: Parser PText
shrinkSpaces = do
many1 space
try (Null <$ eof) <|> return (R ' ')
rawtext :: Parser PText
rawtext = do
c <- anyChar
if c == pikiEscape
then do
e <- anyChar
return $ E e
else return $ R c
----------------------------------------------------------------
getTitleFiles :: L.Text -> LineParser [Image]
getTitleFiles str = case parse titleFiles "getTitleFiles" str of
Right imgs -> return imgs
Left _ -> fail ": illegal '@ title file'"
titleFiles :: Parser [Image]
titleFiles = spaces *> sepBy1 titleFile spaces
titleFile :: Parser Image
titleFile = Image <$> word <*> (spaces *> word) <*> pure Nothing
----------------------------------------------------------------
getTitleFileURLs :: L.Text -> LineParser [Image]
getTitleFileURLs str = case parse titleFileURLs "getTitleFileURLs" str of
Right imgs -> return imgs
Left _ -> fail ": illegal '@@ title file url'"
titleFileURLs :: Parser [Image]
titleFileURLs = spaces *> sepBy1 titleFileURL spaces
titleFileURL :: Parser Image
titleFileURL = Image <$> word <*> (spaces *> word) <*> (Just <$> (spaces *> word))
----------------------------------------------------------------
word :: Parser L.Text
word = quoted <|> unquoted
quoted :: Parser L.Text
quoted = L.pack <$> (open *> inside <* close)
where
open = char '"'
inside = many1 $ noneOf "\t\n[]\""
close = char '"'
unquoted :: Parser L.Text
unquoted = L.pack <$> many1 (noneOf " \t\n[]\"")
----------------------------------------------------------------
getTDs :: Char -> Char -> L.Text -> LineParser [L.Text]
getTDs c e txt = case parse (tds c e) "getTDs" txt of
Right elms -> return elms
Left _ -> fail "| illegal '|elm|elm|"
tds :: Char -> Char -> Parser [L.Text]
tds c e = map L.pack <$> many1 (td c e)
td :: Char -> Char -> Parser String
td c e = ([] <$ char c)
<|> try ((\x1 x2 xs -> x1:x2:xs) <$> char e <*> anyChar <*> td c e)
<|> ((:) <$> anyChar <*> td c e)
| kazu-yamamoto/piki | src/CharParser.hs | bsd-3-clause | 2,705 | 0 | 15 | 594 | 902 | 457 | 445 | 67 | 2 |
module Win32Region where
import StdDIS
import Win32Types
import GDITypes
----------------------------------------------------------------
-- Regions
----------------------------------------------------------------
combineRgn :: HRGN -> HRGN -> HRGN -> ClippingMode -> IO RegionType
combineRgn arg1 arg2 arg3 arg4 =
prim_Win32Region_combineRgn arg1 arg2 arg3 arg4 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1))
primitive prim_Win32Region_combineRgn :: ForeignObj -> ForeignObj -> ForeignObj -> Word32 -> IO (Word32,Int,Addr)
offsetRgn :: HRGN -> INT -> INT -> IO RegionType
offsetRgn arg1 gc_arg1 gc_arg2 =
case ( fromIntegral gc_arg1) of { arg2 ->
case ( fromIntegral gc_arg2) of { arg3 ->
prim_Win32Region_offsetRgn arg1 arg2 arg3 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1))}}
primitive prim_Win32Region_offsetRgn :: ForeignObj -> Int -> Int -> IO (Word32,Int,Addr)
getRgnBox :: HRGN -> LPRECT -> IO RegionType
getRgnBox arg1 arg2 =
prim_Win32Region_getRgnBox arg1 arg2 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1))
primitive prim_Win32Region_getRgnBox :: ForeignObj -> Addr -> IO (Word32,Int,Addr)
createEllipticRgn :: INT -> INT -> INT -> INT -> IO HRGN
createEllipticRgn gc_arg1 gc_arg2 gc_arg3 gc_arg4 =
case ( fromIntegral gc_arg1) of { arg1 ->
case ( fromIntegral gc_arg2) of { arg2 ->
case ( fromIntegral gc_arg3) of { arg3 ->
case ( fromIntegral gc_arg4) of { arg4 ->
prim_Win32Region_createEllipticRgn arg1 arg2 arg3 arg4 >>= \ (gc_res3,gc_res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (makeForeignObj gc_res1 gc_res3) >>= \ gc_res2 ->
(return (gc_res2))}}}}
primitive prim_Win32Region_createEllipticRgn :: Int -> Int -> Int -> Int -> IO (Addr,Addr,Int,Addr)
createEllipticRgnIndirect :: LPRECT -> IO HRGN
createEllipticRgnIndirect arg1 =
prim_Win32Region_createEllipticRgnIndirect arg1 >>= \ (gc_res3,gc_res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (makeForeignObj gc_res1 gc_res3) >>= \ gc_res2 ->
(return (gc_res2))
primitive prim_Win32Region_createEllipticRgnIndirect :: Addr -> IO (Addr,Addr,Int,Addr)
createRectRgn :: INT -> INT -> INT -> INT -> IO HRGN
createRectRgn gc_arg1 gc_arg2 gc_arg3 gc_arg4 =
case ( fromIntegral gc_arg1) of { arg1 ->
case ( fromIntegral gc_arg2) of { arg2 ->
case ( fromIntegral gc_arg3) of { arg3 ->
case ( fromIntegral gc_arg4) of { arg4 ->
prim_Win32Region_createRectRgn arg1 arg2 arg3 arg4 >>= \ (gc_res3,gc_res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (makeForeignObj gc_res1 gc_res3) >>= \ gc_res2 ->
(return (gc_res2))}}}}
primitive prim_Win32Region_createRectRgn :: Int -> Int -> Int -> Int -> IO (Addr,Addr,Int,Addr)
createRectRgnIndirect :: LPRECT -> IO HRGN
createRectRgnIndirect arg1 =
prim_Win32Region_createRectRgnIndirect arg1 >>= \ (gc_res3,gc_res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (makeForeignObj gc_res1 gc_res3) >>= \ gc_res2 ->
(return (gc_res2))
primitive prim_Win32Region_createRectRgnIndirect :: Addr -> IO (Addr,Addr,Int,Addr)
createRoundRectRgn :: INT -> INT -> INT -> INT -> INT -> INT -> IO HRGN
createRoundRectRgn gc_arg1 gc_arg2 gc_arg3 gc_arg4 gc_arg5 gc_arg6 =
case ( fromIntegral gc_arg1) of { arg1 ->
case ( fromIntegral gc_arg2) of { arg2 ->
case ( fromIntegral gc_arg3) of { arg3 ->
case ( fromIntegral gc_arg4) of { arg4 ->
case ( fromIntegral gc_arg5) of { arg5 ->
case ( fromIntegral gc_arg6) of { arg6 ->
prim_Win32Region_createRoundRectRgn arg1 arg2 arg3 arg4 arg5 arg6 >>= \ (gc_res3,gc_res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (makeForeignObj gc_res1 gc_res3) >>= \ gc_res2 ->
(return (gc_res2))}}}}}}
primitive prim_Win32Region_createRoundRectRgn :: Int -> Int -> Int -> Int -> Int -> Int -> IO (Addr,Addr,Int,Addr)
createPolygonRgn :: [POINT] -> PolyFillMode -> IO HRGN
createPolygonRgn gc_arg1 gc_arg3 =
(marshall_listLenPOINT_ gc_arg1) >>= \ (gc_arg2) ->
case gc_arg2 of { (ps,num_ps) ->
case ( fromIntegral gc_arg3) of { mode ->
prim_Win32Region_createPolygonRgn ps num_ps mode >>= \ (gc_res3,gc_res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (makeForeignObj gc_res1 gc_res3) >>= \ gc_res2 ->
(return (gc_res2))}}
primitive prim_Win32Region_createPolygonRgn :: Addr -> Int -> Word32 -> IO (Addr,Addr,Int,Addr)
-- Needs to do proper error test for EqualRgn; GSL ???
equalRgn :: HRGN -> HRGN -> IO Bool
equalRgn arg1 arg2 =
prim_Win32Region_equalRgn arg1 arg2 >>= \ (res1) ->
(unmarshall_bool_ res1) >>= \ gc_res1 ->
(return (gc_res1))
primitive prim_Win32Region_equalRgn :: ForeignObj -> ForeignObj -> IO (Int)
fillRgn :: HDC -> HRGN -> HBRUSH -> IO ()
fillRgn arg1 arg2 arg3 =
prim_Win32Region_fillRgn arg1 arg2 arg3 >>= \ (gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (()))
primitive prim_Win32Region_fillRgn :: Addr -> ForeignObj -> Addr -> IO (Int,Addr)
invertRgn :: HDC -> HRGN -> IO ()
invertRgn arg1 arg2 =
prim_Win32Region_invertRgn arg1 arg2 >>= \ (gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (()))
primitive prim_Win32Region_invertRgn :: Addr -> ForeignObj -> IO (Int,Addr)
paintRgn :: HDC -> HRGN -> IO ()
paintRgn arg1 arg2 =
prim_Win32Region_paintRgn arg1 arg2
primitive prim_Win32Region_paintRgn :: Addr -> ForeignObj -> IO ()
-- Evil hack to get rid of error message that doesn't seem to mean
-- anything and is very hard to repeat.
-- %fail { !success } { ErrorString("PaintRgn") }
frameRgn :: HDC -> HRGN -> HBRUSH -> Int -> Int -> IO ()
frameRgn arg1 arg2 arg3 arg4 arg5 =
prim_Win32Region_frameRgn arg1 arg2 arg3 arg4 arg5 >>= \ (gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (()))
primitive prim_Win32Region_frameRgn :: Addr -> ForeignObj -> Addr -> Int -> Int -> IO (Int,Addr)
ptInRegion :: HRGN -> Int -> Int -> IO Bool
ptInRegion arg1 arg2 arg3 =
prim_Win32Region_ptInRegion arg1 arg2 arg3 >>= \ (res1) ->
(unmarshall_bool_ res1) >>= \ gc_res1 ->
(return (gc_res1))
primitive prim_Win32Region_ptInRegion :: ForeignObj -> Int -> Int -> IO (Int)
rectInRegion :: HRGN -> RECT -> IO Bool
rectInRegion arg1 gc_arg1 =
case gc_arg1 of { (gc_arg2,gc_arg4,gc_arg6,gc_arg8) ->
case ( fromIntegral gc_arg2) of { gc_arg3 ->
case ( fromIntegral gc_arg4) of { gc_arg5 ->
case ( fromIntegral gc_arg6) of { gc_arg7 ->
case ( fromIntegral gc_arg8) of { gc_arg9 ->
prim_Win32Region_rectInRegion arg1 gc_arg3 gc_arg5 gc_arg7 gc_arg9 >>= \ (res1) ->
(unmarshall_bool_ res1) >>= \ gc_res1 ->
(return (gc_res1))}}}}}
primitive prim_Win32Region_rectInRegion :: ForeignObj -> Int -> Int -> Int -> Int -> IO (Int)
deleteRegion :: HRGN -> IO ()
deleteRegion arg1 =
prim_Win32Region_deleteRegion arg1 >>= \ (gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (()))
primitive prim_Win32Region_deleteRegion :: ForeignObj -> IO (Int,Addr)
----------------------------------------------------------------
-- End
----------------------------------------------------------------
needPrims_hugs 3
| OS2World/DEV-UTIL-HUGS | libraries/win32/Win32Region.hs | bsd-3-clause | 8,270 | 128 | 31 | 1,396 | 2,677 | 1,455 | 1,222 | -1 | -1 |
module Main where
import Data.Map as Map
dat = [("a", "apache"), ("e", "emacs"), ("a", "ant"), ("c", "ceph")]
main :: IO ()
main = do
putStrLn (show ks)
putStrLn (show es)
where
m = tomap dat
ks = Map.keys m
es = Map.elems m
tomap :: [(String, String)] -> Map String [String]
tomap [] = Map.empty
tomap (x:xs) = insertItem x (tomap xs)
insertItem :: (String, String) -> Map String [String] -> Map String [String]
insertItem x m = Map.insert k l m
where
k = fst x
l = tolist x (Map.lookup k m)
tolist :: (String, String) -> Maybe [String] -> [String]
tolist x Nothing = [snd x]
tolist x (Just l) = (snd x:l)
| eijian/picfinder | src/Main-t2.hs | bsd-3-clause | 645 | 0 | 10 | 154 | 339 | 182 | 157 | 20 | 1 |
import Data.List
solveRPN :: String -> Float
solveRPN = head . foldl foldingFunction [] . words
where foldingFunction (x:y:ys) "*" = (x * y):ys
foldingFunction (x:y:ys) "+" = (x + y):ys
foldingFunction (x:y:ys) "-" = (y - x):ys
foldingFunction (x:y:ys) "/" = (y / x):ys
foldingFunction (x:y:ys) "^" = (y ** x):ys
foldingFunction (x:xs) "ln" = log x:xs
foldingFunction xs "sum" = [sum xs]
foldingFunction xs numberString = read numberString:xs
| randallalexander/LYAH | src/Ch10.hs | bsd-3-clause | 534 | 0 | 10 | 161 | 254 | 132 | 122 | 11 | 8 |
module Main where
import System.Environment
import Euler201
import Text.Printf
import Data.Time.Clock
main :: IO ()
main = do
startTime <- getCurrentTime
arg1:arg2:arg3:_ <- getArgs
let [min, max, len] = map (\x -> read x::Int) [arg1, arg2, arg3]
cnt = findUniqueSums len [min..max] in
do finishTime <- getCurrentTime
let msg = printf "Result: %s Time elapsed: %s" (show cnt) (show $ diffUTCTime startTime finishTime) in
putStr msg
| hackle/hscripting | app/Main.hs | bsd-3-clause | 596 | 0 | 18 | 230 | 180 | 93 | 87 | 14 | 1 |
module Main where
import Repository (loadRepository)
import ParsePackage (parseAndSaveAllPackages)
import NameResolution (resolveAndSaveAllPackageNames)
import Fragmentation (splitAndSaveAllDeclarations)
import Insertion (insertAllPackages)
import System.Process (system)
import System.Directory (removeDirectoryRecursive,createDirectory)
import Control.Concurrent (threadDelay)
import Control.Monad (void)
main :: IO ()
main = do
resetDatabase
sourcerepository <- loadRepository
parsedrepository <- parseAndSaveAllPackages sourcerepository
resolveAndSaveAllPackageNames parsedrepository
splitAndSaveAllDeclarations parsedrepository
insertAllPackages parsedrepository
putStrLn "done"
resetDatabase :: IO ()
resetDatabase = do
void (system "neo4j-community-2.0.1/bin/neo4j stop")
removeDirectoryRecursive "neo4j-community-2.0.1/data/"
createDirectory "neo4j-community-2.0.1/data"
void (system "neo4j-community-2.0.1/bin/neo4j start")
threadDelay 1000000
| phischu/hackage-analysis | src/Main.hs | bsd-3-clause | 1,007 | 0 | 9 | 128 | 203 | 102 | 101 | 26 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Spec where
import Control.Monad ((>=>))
import Data.Aeson (Value (Object, String))
import Data.HashMap.Strict as HM (fromList)
import Data.Json.Util
import Data.Text as T (Text)
import System.Directory (doesFileExist)
import System.IO.Unsafe (unsafePerformIO)
import Test.HUnit (Counts, Test (TestList), runTestTT)
import Test.HUnit.Util as U (t)
test :: IO Counts
test = runTestTT $ TestList $ ts1 ++ ts2 ++ ts3 ++ ts4
iRead :: FilePath -> IO FilePath
iRead filename = do
e <- doesFileExist filename
return $ if e then filename else "test/" ++ filename
readFind :: Text -> FilePath -> IO PathsPropertyNameValue
readFind goal filename = iRead filename >>= (readJson >=> (\(Just s) -> return $ findInJson goal s))
ts1 :: [Test]
ts1 = U.t "ts1"
(unsafePerformIO (readFind "$ref" "refs-simple-invalid.json"))
[([P "definitions",P "Parent"]
,("$ref",String "#/definitions/DoesNotExist"))
,([P "definitions",P "Pet",P "properties",P "tags",P "items"]
,("$ref",String "#/definitions/Tag"))
,([P "paths",P "/pets",P "get",P "responses",P "200",P "schema",P "items"]
,("$ref",String "#/definitions/Pet"))]
ts2 :: [Test]
ts2 = U.t "ts2"
(unsafePerformIO (readFind "$ref" "refs-indirect-circular-ancestor-invalid.json"))
[([P "definitions",P "Parent",P "allOf", VRef 0]
,("$ref",String "#/definitions/Circular2"))
,([P "definitions",P "Circular1",P "allOf", VRef 0]
,("$ref",String "#/definitions/Parent"))
,([P "definitions",P "Circular2",P "allOf", VRef 0]
,("$ref",String "#/definitions/Circular1"))
,([P "definitions",P "Pet",P "properties",P "category"]
,("$ref",String "#/definitions/Category"))
,([P "definitions",P "Pet",P "properties",P "tags",P "items"]
,("$ref",String "#/definitions/Tag"))
,([P "paths",P "/pets",P "get",P "responses",P "200",P "schema",P "items"]
,("$ref",String "#/definitions/Pet"))]
ts3 :: [Test]
ts3 = U.t "ts3"
(unsafePerformIO (readFind "X" "x.json"))
[([P "Tag"]
,("X",Object (fromList [("Tag-X-value",Object (fromList [("X",String "Tag-X-value-X-value")]))])))
,([P "responses",P "default"]
,("X",String "responses-default-X-value"))
,([P "responses",P "200",P "schema",P "items"]
,("X",String "responses-200-schema-items-X-value"))
,([P "responses",P "200"]
,("X",String "responses-200-X-value"))
,([P "tags",P "items"]
,("X",String "tags-items-X-value-2"))]
ts4 :: [Test]
ts4 = U.t "ts4"
(findInJson
"X"
(Object
(fromList
[("default" ,Object (fromList [("X",String "responses-default-X-value")]))
,("200" ,Object (fromList [("schema",Object (fromList [("items",Object (fromList [("X",String "responses-200-schema-items-X-value")]))
,("type",String "array")]))
,("X",String "responses-200-X-value")]))])))
[([P "default"] ,("X",String "responses-default-X-value"))
,([P "200",P "schema",P "items"] ,("X",String "responses-200-schema-items-X-value"))
,([P "200"] ,("X",String "responses-200-X-value"))]
| haroldcarr/data-json-validation | test/Spec.hs | bsd-3-clause | 3,352 | 0 | 29 | 767 | 1,223 | 680 | 543 | 69 | 2 |
{-# LANGUAGE StandaloneDeriving, GeneralizedNewtypeDeriving, FlexibleInstances #-}
-- module IFS.Density where
import IFS
import IFS.Transform2D
import System.Random
import Data.Array.IO
import Data.Array
import Data.Array.MArray
import Data.Ord
import Data.List
import Control.Monad (when)
import Control.Concurrent
import Control.Arrow
type Density a = [(a,Int)]
deriving instance Ix (V Int)
project :: RealFrac a => a -> V a -> V Int
project ro = fmap (round . (*ro))
clean :: Density a -> Density a
clean = sortBy (flip $ comparing snd) . filter ((>0) . snd)
density :: (V Int, V Int) -> [V Int] -> Density (V Int)
density dlur = assocs . accumArray (+) 0 dlur . map (flip (,) 1) . filter (inRange dlur) where
densityIO :: Int -> (V Int, V Int) -> [V Int] -> IO (Density (V Int))
densityIO time dlur xs = do
m <- newMVar False
forkIO $ threadDelay time >> swapMVar m True >> return ()
arr <- accumArrayBounded m (+) 0 dlur. map (flip (,) 1) . filter (inRange dlur) $ xs -- :: IO (IOArray (V Int) Int)
assocs `fmap` unsafeFreeze arr
accumArrayBounded :: Ix i => MVar Bool -> (e -> e' -> e) -> e -> (i,i) -> [(i, e')] -> IO (IOArray i e)
accumArrayBounded stop f e (l,u) ies = do
marr <- newArray (l,u) e
let action [] = return ()
action ((i,new):rs)= do
t <- readMVar stop
when (not t) $ do
old <- readArray marr i
writeArray marr i (f old new)
action rs
action ies
return marr
main = do
ps <- pointsIO (ifunc (scaling 0.5 0.4 ° rotation 90) `mappend` ifunc (translation 0.6 0.3 ° rotation 45)) (V 0 (0::Double))
-- zs <- fmap clean . densityIO 10000000 (V (-50) (-50), V 50 50) . map (project 16) $ ps
let zs = normalize . wfuncs . map ((const :: V Int -> V Int -> V Int) *** fromIntegral) . clean . density (V (-50) (-50), V 50 50) . map (project 16) $ take 100000 ps
pointsIO zs (V 0 0 :: V Int) >>= print . take 100
| paolino/hifs | IFS/Density.hs | bsd-3-clause | 2,049 | 0 | 21 | 570 | 896 | 450 | 446 | 42 | 2 |
module HsBot.Base.Database where
import HsBot.Base.Conf
import qualified Database.HSQL.MySQL as MySQL
import qualified Database.HSQL.Types as Types
data Database = Database {
connection :: IO Types.Connection,
connectionString :: String
}
instance Show Database where
show database = show $ connectionString database
databaseMake :: Conf -> IO Database
databaseMake conf = do
dbHost <- get "dbHost" conf
dbUser <- get "dbUser" conf
dbSchema <- get "dbSchema" conf
dbPass <- get "dbPass" conf
return $ Database {
connection = MySQL.connect dbHost dbUser dbSchema dbPass,
connectionString = dbHost ++ " " ++ dbUser ++ " " ++ dbSchema ++ " " ++ dbPass
}
| buetow/hsbot | HsBot/Base/Database.hs | bsd-3-clause | 675 | 12 | 15 | 123 | 216 | 114 | 102 | 18 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Dependency.TopDown.Types
-- Copyright : (c) Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : cabal-devel@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Types for the top-down dependency resolver.
-----------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
module Distribution.Client.Dependency.TopDown.Types where
import Distribution.Client.Types
( UnresolvedPkgLoc, UnresolvedSourcePackage
, OptionalStanza, SolverPackage(..), SolverId(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import qualified Distribution.Client.ComponentDeps as CD
import Distribution.Package
( PackageId, PackageIdentifier, Dependency
, Package(packageId) )
import Distribution.PackageDescription
( FlagAssignment )
-- ------------------------------------------------------------
-- * The various kinds of packages
-- ------------------------------------------------------------
type SelectablePackage
= InstalledOrSource InstalledPackageEx UnconfiguredPackage
type SelectedPackage
= InstalledOrSource InstalledPackageEx SemiConfiguredPackage
data InstalledOrSource installed source
= InstalledOnly installed
| SourceOnly source
| InstalledAndSource installed source
deriving Eq
data FinalSelectedPackage
= SelectedInstalled InstalledPackage
| SelectedSource (SolverPackage UnresolvedPkgLoc)
type TopologicalSortNumber = Int
-- | InstalledPackage caches its dependencies as source package IDs.
data InstalledPackage
= InstalledPackage
InstalledPackageInfo
[PackageId]
data InstalledPackageEx
= InstalledPackageEx
InstalledPackage
!TopologicalSortNumber
[PackageIdentifier] -- transitive closure of installed deps
data UnconfiguredPackage
= UnconfiguredPackage
UnresolvedSourcePackage
!TopologicalSortNumber
FlagAssignment
[OptionalStanza]
-- | This is a minor misnomer: it's more of a 'SemiSolverPackage'.
data SemiConfiguredPackage
= SemiConfiguredPackage
UnresolvedSourcePackage -- package info
FlagAssignment -- total flag assignment for the package
[OptionalStanza] -- enabled optional stanzas
[Dependency] -- dependencies we end up with when we apply
-- the flag assignment
instance Package InstalledPackage where
packageId (InstalledPackage pkg _) = packageId pkg
instance Package InstalledPackageEx where
packageId (InstalledPackageEx p _ _) = packageId p
instance Package UnconfiguredPackage where
packageId (UnconfiguredPackage p _ _ _) = packageId p
instance Package SemiConfiguredPackage where
packageId (SemiConfiguredPackage p _ _ _) = packageId p
instance (Package installed, Package source)
=> Package (InstalledOrSource installed source) where
packageId (InstalledOnly p ) = packageId p
packageId (SourceOnly p ) = packageId p
packageId (InstalledAndSource p _) = packageId p
instance Package FinalSelectedPackage where
packageId (SelectedInstalled pkg) = packageId pkg
packageId (SelectedSource pkg) = packageId pkg
-- | We can have constraints on selecting just installed or just source
-- packages.
--
-- In particular, installed packages can only depend on other installed
-- packages while packages that are not yet installed but which we plan to
-- install can depend on installed or other not-yet-installed packages.
--
data InstalledConstraint = InstalledConstraint
| SourceConstraint
deriving (Eq, Show)
-- | Package dependencies
--
-- The top-down solver uses its down type class for package dependencies,
-- because it wants to know these dependencies as PackageIds, rather than as
-- ComponentIds (so it cannot use PackageFixedDeps).
--
-- Ideally we would switch the top-down solver over to use ComponentIds
-- throughout; that means getting rid of this type class, and changing over the
-- package index type to use Cabal's rather than cabal-install's. That will
-- avoid the need for the local definitions of dependencyGraph and
-- reverseTopologicalOrder in the top-down solver.
--
-- Note that the top-down solver does not (and probably will never) make a
-- distinction between the various kinds of dependencies, so we return a flat
-- list here. If we get rid of this type class then any use of `sourceDeps`
-- should be replaced by @fold . depends@.
class Package a => PackageSourceDeps a where
sourceDeps :: a -> [PackageIdentifier]
instance PackageSourceDeps InstalledPackageEx where
sourceDeps (InstalledPackageEx _ _ deps) = deps
instance PackageSourceDeps (SolverPackage loc) where
sourceDeps pkg = map solverSrcId $ CD.nonSetupDeps (solverPkgDeps pkg)
instance PackageSourceDeps InstalledPackage where
sourceDeps (InstalledPackage _ deps) = deps
instance PackageSourceDeps FinalSelectedPackage where
sourceDeps (SelectedInstalled pkg) = sourceDeps pkg
sourceDeps (SelectedSource pkg) = sourceDeps pkg
| gbaz/cabal | cabal-install/Distribution/Client/Dependency/TopDown/Types.hs | bsd-3-clause | 5,281 | 0 | 9 | 1,030 | 709 | 399 | 310 | 81 | 0 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE Safe, PatternGuards #-}
module Cryptol.Parser.ParserUtils where
import Cryptol.Parser.AST
import Cryptol.Parser.Lexer
import Cryptol.Parser.Position
import Cryptol.Parser.Utils (translateExprToNumT)
import Cryptol.Utils.PP
import Cryptol.Utils.Panic
import Data.Maybe(listToMaybe,fromMaybe)
import Data.Bits(testBit,setBit)
import Control.Monad(liftM,ap,unless)
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>),Applicative(..))
import Data.Traversable (mapM)
import Prelude hiding (mapM)
#endif
parseString :: Config -> ParseM a -> String -> Either ParseError a
parseString cfg p cs = parse cfg p (T.pack cs)
parse :: Config -> ParseM a -> Text -> Either ParseError a
parse cfg p cs = case unP p cfg eofPos (S toks) of
Left err -> Left err
Right (a,_) -> Right a
where (toks,eofPos) = lexer cfg cs
{- The parser is parameterized by the pozition of the final token. -}
data ParseM a = P { unP :: Config -> Position -> S -> Either ParseError (a,S) }
lexerP :: (Located Token -> ParseM a) -> ParseM a
lexerP k = P $ \cfg p (S ts) ->
case ts of
t : _ | Err e <- tokenType it ->
Left $ HappyErrorMsg (srcRange t) $
case e of
UnterminatedComment -> "unterminated comment"
UnterminatedString -> "unterminated string"
UnterminatedChar -> "unterminated character"
InvalidString -> "invalid string literal: " ++ T.unpack (tokenText it)
InvalidChar -> "invalid character literal: " ++ T.unpack (tokenText it)
LexicalError -> "unrecognized character: " ++ T.unpack (tokenText it)
where it = thing t
t : more -> unP (k t) cfg p (S more)
[] -> Left (HappyError (cfgSource cfg) p Nothing)
data ParseError = HappyError FilePath Position (Maybe Token)
| HappyErrorMsg Range String
deriving Show
newtype S = S [Located Token]
instance PP ParseError where
ppPrec _ (HappyError _ _ tok) = case tok of
Nothing -> text "end of input"
Just t -> pp t
ppPrec _ (HappyErrorMsg _ x) = text x
ppError :: ParseError -> Doc
ppError (HappyError path pos (Just tok))
| Err _ <- tokenType tok = text "Parse error at" <+>
text path <> char ':' <> pp pos <> comma <+>
pp tok
ppError e@(HappyError path pos _) =
text "Parse error at" <+>
text path <> char ':' <> pp pos <> comma <+>
text "unexpected" <+> pp e
ppError (HappyErrorMsg p x) = text "Parse error at" <+> pp p $$ nest 2 (text x)
instance Monad ParseM where
return a = P (\_ _ s -> Right (a,s))
fail s = panic "[Parser] fail" [s]
m >>= k = P (\cfg p s1 -> case unP m cfg p s1 of
Left e -> Left e
Right (a,s2) -> unP (k a) cfg p s2)
instance Functor ParseM where
fmap = liftM
instance Applicative ParseM where
pure = return
(<*>) = ap
happyError :: ParseM a
happyError = P $ \cfg p (S ls) ->
Left $ case listToMaybe ls of
Nothing -> HappyError (cfgSource cfg) p Nothing
Just l -> HappyError (cfgSource cfg) (from (srcRange l)) (Just (thing l))
errorMessage :: Range -> String -> ParseM a
errorMessage r x = P $ \_ _ _ -> Left (HappyErrorMsg r x)
customError :: String -> Located Token -> ParseM a
customError x t = P $ \_ _ _ -> Left (HappyErrorMsg (srcRange t) x)
mkModName :: LQName -> Located ModName
mkModName = fmap $ \ (QName mb (Name n)) ->
case mb of
Just (ModName ns) -> ModName (ns ++ [n])
Nothing -> ModName [n]
mkQName :: {-reversed-} [LName] -> Located QName
mkQName [x] = fmap mkUnqual x
mkQName xs =
Located { srcRange = rComb (srcRange f) (srcRange l)
, thing = mkQual (ModName [ x | Name x <- map thing ns ]) (thing l)
}
where l : ls = xs
ns@(f : _) = reverse ls
-- Note that type variables are not resolved at this point: they are tcons.
mkSchema :: [TParam] -> [Prop] -> Type -> Schema
mkSchema xs ps t = Forall xs ps t Nothing
getName :: Located Token -> Name
getName l = case thing l of
Token (Ident [] x) _ -> Name x
_ -> panic "[Parser] getName" ["not an Ident:", show l]
getNum :: Located Token -> Integer
getNum l = case thing l of
Token (Num x _ _) _ -> x
Token (ChrLit x) _ -> fromIntegral (fromEnum x)
_ -> panic "[Parser] getNum" ["not a number:", show l]
getStr :: Located Token -> String
getStr l = case thing l of
Token (StrLit x) _ -> x
_ -> panic "[Parser] getStr" ["not a string:", show l]
numLit :: TokenT -> Expr
numLit (Num x base digs)
| base == 2 = ELit $ ECNum x (BinLit digs)
| base == 8 = ELit $ ECNum x (OctLit digs)
| base == 10 = ELit $ ECNum x DecLit
| base == 16 = ELit $ ECNum x (HexLit digs)
numLit x = panic "[Parser] numLit" ["invalid numeric literal", show x]
intVal :: Located Token -> ParseM Integer
intVal tok =
case tokenType (thing tok) of
Num x _ _ -> return x
_ -> errorMessage (srcRange tok) "Expected an integer"
mkFixity :: Assoc -> Located Token -> [LName] -> ParseM Decl
mkFixity assoc tok qns =
do l <- intVal tok
unless (l >= 1 && l <= 100)
(errorMessage (srcRange tok) "Fixity levels must be between 0 and 20")
return (DFixity (Fixity assoc (fromInteger l)) (map (fmap mkUnqual) qns))
mkTupleSel :: Range -> Integer -> ParseM (Located Selector)
mkTupleSel pos n
| n < 0 = errorMessage pos
(show n ++ " is not a valid tuple selector (they start from 0).")
| toInteger asInt /= n = errorMessage pos "Tuple selector is too large."
| otherwise = return $ Located pos $ TupleSel asInt Nothing
where asInt = fromInteger n
fromStrLit :: Located Token -> ParseM (Located String)
fromStrLit loc = case tokenType (thing loc) of
StrLit str -> return loc { thing = str }
_ -> errorMessage (srcRange loc) "Expected a string literal"
validDemotedType :: Range -> Type -> ParseM Type
validDemotedType rng ty =
case ty of
TLocated t r -> validDemotedType r t
TRecord {} -> bad "Record types"
TTuple {} -> bad "Tuple types"
TFun {} -> bad "Function types"
TSeq {} -> bad "Sequence types"
TBit -> bad "Type bit"
TNum {} -> ok
TChar {} -> ok
TInf -> bad "Infinity type"
TWild -> bad "Wildcard types"
TUser {} -> ok
TApp {} -> ok
TParens t -> validDemotedType rng t
TInfix{} -> ok
where bad x = errorMessage rng (x ++ " cannot be demoted.")
ok = return $ at rng ty
mkEApp :: [Expr] -> Expr
mkEApp es@(eLast : _) = at (eFirst,eLast) $ foldl EApp f xs
where
eFirst : rest = reverse es
f : xs = cvtTypeParams eFirst rest
{- Type applications are parsed as `ETypeVal (TRecord fs)` expressions.
Here we associate them with their corresponding functions,
converting them into `EAppT` constructs. For example:
[ f, x, `{ a = 2 }, y ]
becomes
[ f, x ` { a = 2 }, y ]
-}
cvtTypeParams e [] = [e]
cvtTypeParams e (p : ps) =
case toTypeParam p of
Just fs -> cvtTypeParams (EAppT e fs) ps
Nothing -> e : cvtTypeParams p ps
toTypeParam e =
case dropLoc e of
ETypeVal t -> case dropLoc t of
TRecord fs -> Just (map mkTypeInst fs)
_ -> Nothing
_ -> Nothing
mkEApp es = panic "[Parser] mkEApp" ["Unexpected:", show es]
unOp :: Expr -> Expr -> Expr
unOp f x = at (f,x) $ EApp f x
-- Use defaultFixity as a placeholder, it will be fixed during renaming.
binOp :: Expr -> Located QName -> Expr -> Expr
binOp x f y = at (x,y) $ EInfix x f defaultFixity y
eFromTo :: Range -> Expr -> Maybe Expr -> Maybe Expr -> ParseM Expr
eFromTo r e1 e2 e3 = EFromTo <$> exprToNumT r e1
<*> mapM (exprToNumT r) e2
<*> mapM (exprToNumT r) e3
exprToNumT :: Range -> Expr -> ParseM Type
exprToNumT r expr =
case translateExprToNumT expr of
Just t -> return t
Nothing -> bad
where
bad = errorMessage (fromMaybe r (getLoc expr)) $ unlines
[ "The boundaries of .. sequences should be valid numeric types."
, "The expression `" ++ show (pp expr) ++ "` is not."
, ""
, "If you were trying to specify the width of the elements,"
, "you may add a type annotation outside the sequence. For example:"
, " [ 1 .. 10 ] : [_][16]"
]
-- | WARNING: This is a bit of a hack.
-- It is used to represent anonymous type applications.
anonRecord :: Maybe Range -> [Type] -> Type
anonRecord ~(Just r) ts = TRecord (map toField ts)
where noName = Located { srcRange = r, thing = Name "" }
toField t = Named { name = noName, value = t }
exportDecl :: Maybe (Located String) -> ExportType -> Decl -> TopDecl
exportDecl mbDoc e d = Decl TopLevel { tlExport = e
, tlDoc = mbDoc
, tlValue = d }
exportNewtype :: ExportType -> Newtype -> TopDecl
exportNewtype e n = TDNewtype TopLevel { tlExport = e
, tlDoc = Nothing
, tlValue = n }
changeExport :: ExportType -> [TopDecl] -> [TopDecl]
changeExport e = map change
where
change (Decl d) = Decl d { tlExport = e }
change (TDNewtype n) = TDNewtype n { tlExport = e }
change td@Include{} = td
mkTypeInst :: Named Type -> TypeInst
mkTypeInst x | thing (name x) == Name "" = PosInst (value x)
| otherwise = NamedInst x
mkTParam :: Located Name -> Maybe Kind -> ParseM TParam
mkTParam Located { srcRange = rng, thing = n } k
| Name "width" <- n = errorMessage rng "`width` is not a valid type parameter name."
| otherwise = return (TParam n k (Just rng))
mkTySyn :: Located Name -> [TParam] -> Type -> ParseM Decl
mkTySyn n ps b
| Name "width" <- thing n = errorMessage (srcRange n) "`width` is not a valid type synonym name."
| otherwise = return $ DType $ TySyn (fmap mkUnqual n) ps b
polyTerm :: Range -> Integer -> Integer -> ParseM (Bool, Integer)
polyTerm rng k p
| k == 0 = return (False, p)
| k == 1 = return (True, p)
| otherwise = errorMessage rng "Invalid polynomial coefficient"
mkPoly :: Range -> [ (Bool,Integer) ] -> ParseM Expr
mkPoly rng terms = mk 0 (map fromInteger bits)
where
w = case terms of
[] -> 0
_ -> 1 + maximum (map (fromInteger . snd) terms)
bits = [ n | (True,n) <- terms ]
mk res [] = return $ ELit $ ECNum res (PolyLit w)
mk res (n : ns)
| testBit res n = errorMessage rng
("Polynomial contains multiple terms with exponent "
++ show n)
| otherwise = mk (setBit res n) ns
-- NOTE: The list of patterns is reversed!
mkProperty :: LName -> [Pattern] -> Expr -> Decl
mkProperty f ps e = DBind Bind { bName = fmap mkUnqual f
, bParams = reverse ps
, bDef = at e (Located emptyRange (DExpr (ETyped e TBit)))
, bSignature = Nothing
, bPragmas = [PragmaProperty]
, bMono = False
, bInfix = False
, bFixity = Nothing
, bDoc = Nothing
}
mkIf :: [(Expr, Expr)] -> Expr -> Expr
mkIf ifThens theElse = foldr addIfThen theElse ifThens
where
addIfThen (cond, doexpr) elseExpr = EIf cond doexpr elseExpr
-- | Generate a signature and a primitive binding. The reason for generating
-- both instead of just adding the signature at this point is that it means the
-- primitive declarations don't need to be treated differently in the noPat
-- pass. This is also the reason we add the doc to the TopLevel constructor,
-- instead of just place it on the binding directly. A better solution might be
-- to just have a different constructor for primitives.
mkPrimDecl :: Maybe (Located String) -> Bool -> LName -> Schema -> [TopDecl]
mkPrimDecl mbDoc isInfix n sig =
[ exportDecl mbDoc Public
$ DBind Bind { bName = qname
, bParams = []
, bDef = at sig (Located emptyRange DPrim)
, bSignature = Nothing
, bPragmas = []
, bMono = False
, bInfix = isInfix
, bFixity = Nothing
, bDoc = Nothing
}
, exportDecl Nothing Public
$ DSignature [qname] sig
]
where
qname = fmap mkUnqual n
-- | Fix-up the documentation strings by removing the comment delimiters on each
-- end, and stripping out common prefixes on all the remaining lines.
mkDoc :: Located Text -> Located String
mkDoc ltxt = ltxt { thing = docStr }
where
docStr = unlines
$ map T.unpack
$ dropPrefix
$ trimFront
$ T.lines
$ T.dropWhileEnd (`elem` "/* \r\n\t")
$ thing ltxt
trimFront [] = []
trimFront (l:ls)
| T.all (`elem` "/* \r\n\t") l = ls
| otherwise = T.dropWhile (`elem` "/* ") l : ls
dropPrefix [] = []
dropPrefix [t] = [T.dropWhile (`elem` "/* ") t]
dropPrefix ts@(l:ls) =
case T.uncons l of
Just (c,_) | all (commonPrefix c) ls -> dropPrefix (map (T.drop 1) ts)
_ -> ts
where
commonPrefix c t =
case T.uncons t of
Just (c',_) -> c == c'
Nothing -> False
mkProp :: Type -> ParseM (Located [Prop])
mkProp ty =
case ty of
TLocated t r -> Located r `fmap` props r t
_ -> panic "Parser" [ "Invalid type given to mkProp"
, "expected a location"
, show ty ]
where
props r t =
case t of
TInfix{} -> infixProp t
TUser f xs -> prefixProp r f xs
TTuple ts -> concat `fmap` mapM (props r) ts
TParens t' -> props r t'
TLocated t' r' -> props r' t'
TApp{} -> err
TFun{} -> err
TSeq{} -> err
TBit{} -> err
TNum{} -> err
TChar{} -> err
TInf{} -> err
TWild -> err
TRecord{} -> err
where
err = errorMessage r "Invalid constraint"
-- we have to delay these until renaming, when we have the fixity table
-- present
infixProp t = return [CType t]
-- these can be translated right away
prefixProp r f xs =
case f of
QName Nothing (Name "Arith") | [x] <- xs ->
return [CLocated (CArith x) r]
QName Nothing (Name "fin") | [x] <- xs ->
return [CLocated (CFin x) r]
QName Nothing (Name "Cmp") | [x] <- xs ->
return [CLocated (CCmp x) r]
_ -> errorMessage r "Invalid constraint"
| ntc2/cryptol | src/Cryptol/Parser/ParserUtils.hs | bsd-3-clause | 15,637 | 0 | 18 | 5,244 | 5,119 | 2,577 | 2,542 | 319 | 18 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Prelude hiding (Monad, return )
-- | TODO
-- |
-- | 1. default methods are currently not supported
data ST s a = ST {runState :: s -> (a,s)}
[lq| data ST s a <r :: a -> Prop>
= ST (runState :: x:s -> (a<r>, s)) |]
[lq| runState :: forall <r :: a -> Prop>. ST <r> s a -> x:s -> (a<r>, s) |]
class Foo m where
return :: a -> m a
instance Foo (ST s) where
[lq| instance Foo ST s where
return :: forall s a. x:a -> ST <{\v -> x == v}> s a
|]
return x = ST $ \s -> (x, s)
[lq| foo :: w:a -> ST <{v:a | v = w}> Bool a |]
foo :: a -> ST Bool a
foo x = return x
bar = runState (foo 0) True
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/StateConstraints00.hs | bsd-3-clause | 695 | 3 | 10 | 209 | 173 | 101 | 72 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ViewPatterns #-}
module Physics.Bullet.Types where
import Foreign.C
import Foreign.Ptr
import Linear.Extra
import Data.Binary
import GHC.Generics
foreign import ccall "&free" freePtr :: FunPtr (Ptr CFloat -> IO ())
newtype CollisionObjectID = CollisionObjectID
{ unCollisionObjectID :: Word32 }
deriving (Eq, Show, Ord, Binary, Num, Enum, Real, Integral)
newtype DynamicsWorld = DynamicsWorld
{ unDynamicsWorld :: Ptr () }
deriving Show
newtype SpringConstraint = SpringConstraint
{ unSpringConstraint :: Ptr () }
deriving Show
newtype PointToPointConstraint = PointToPointConstraint
{ unPointToPointConstraint :: Ptr () }
deriving Show
newtype CollisionShape = CollisionShape
{ unCollisionShape :: Ptr () }
deriving Show
newtype CollisionObject = CollisionObject
{ unCollisionObject :: Ptr () }
deriving Show
newtype RigidBody = RigidBody
{ unRigidBody :: CollisionObject }
deriving Show
newtype GhostObject = GhostObject
{ unGhostObject :: CollisionObject }
deriving Show
data RigidBodyConfig = RigidBodyConfig
{ rbRestitution :: !Float
, rbPosition :: !(V3 Float)
, rbRotation :: !(Quaternion Float)
, rbInertia :: !(V3 Float)
, rbMass :: !Float
, rbLinearDamping :: !Float
, rbAngularDamping :: !Float
, rbFriction :: !Float
, rbRollingFriction :: !Float
, rbCollisionGroup :: !CShort
, rbCollisionMask :: !CShort
}
instance Monoid RigidBodyConfig where
mempty = RigidBodyConfig
{ rbPosition = V3 0 0 0
, rbInertia = V3 0 0 0
, rbRotation = axisAngle ( V3 1 0 0 ) 0
, rbMass = 1
, rbRestitution = 0.5
, rbFriction = 0.5
, rbRollingFriction = 0
, rbCollisionGroup = 1
, rbCollisionMask = 1
, rbLinearDamping = 0
, rbAngularDamping = 0
}
mappend _ b = b
data DynamicsWorldConfig = DynamicsWorldConfig
{ dwGravity :: Float
}
-- We're just implementing this for mempty;
-- the mappend instance isn't useful as it just
-- takes the rightmost DynamicsWorldConfig.
instance Monoid DynamicsWorldConfig where
mempty = DynamicsWorldConfig
{ dwGravity = -9.8
}
mappend _ b = b
-- I've switched from carrying the pointers in this structure
-- so it can be serialized across the network.
-- We could also split it into 2 pieces,
-- since it's nice to query the rigidbody directly.
data Collision = Collision
-- { cbBodyA :: !RigidBody
-- , cbBodyB :: !RigidBody
{ cbBodyAID :: !CollisionObjectID
, cbBodyBID :: !CollisionObjectID
, cbPositionOnA :: !(V3 Float)
, cbPositionOnB :: !(V3 Float)
, cbNormalOnB :: !(V3 Float)
, cbAppliedImpulse :: !Float
} deriving (Show, Generic)
instance Binary Collision
class ToCollisionObjectPointer a where
toCollisionObjectPointer :: a -> Ptr ()
instance ToCollisionObjectPointer CollisionObject where
toCollisionObjectPointer = unCollisionObject
instance ToCollisionObjectPointer RigidBody where
toCollisionObjectPointer = toCollisionObjectPointer . unRigidBody
instance ToCollisionObjectPointer GhostObject where
toCollisionObjectPointer = toCollisionObjectPointer . unGhostObject
| lukexi/bullet-mini | src/Physics/Bullet/Types.hs | bsd-3-clause | 3,658 | 0 | 11 | 935 | 693 | 404 | 289 | 122 | 0 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Pattern-matching literal patterns
-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module MatchLit ( dsLit, dsOverLit, hsLitKey, hsOverLitKey
, tidyLitPat, tidyNPat
, matchLiterals, matchNPlusKPats, matchNPats
, warnAboutIdentities, warnAboutEmptyEnumerations
) where
#include "HsVersions.h"
import {-# SOURCE #-} Match ( match )
import {-# SOURCE #-} DsExpr ( dsExpr )
import DsMonad
import DsUtils
import HsSyn
import Id
import CoreSyn
import MkCore
import TyCon
import DataCon
import TcHsSyn ( shortCutLit )
import TcType
import Name
import Type
import PrelNames
import TysWiredIn
import Literal
import SrcLoc
import Data.Ratio
import Outputable
import BasicTypes
import DynFlags
import Util
import FastString
import Control.Monad
import Data.Int
#if __GLASGOW_HASKELL__ < 709
import Data.Traversable (traverse)
#endif
import Data.Word
{-
************************************************************************
* *
Desugaring literals
[used to be in DsExpr, but DsMeta needs it,
and it's nice to avoid a loop]
* *
************************************************************************
We give int/float literals type @Integer@ and @Rational@, respectively.
The typechecker will (presumably) have put \tr{from{Integer,Rational}s}
around them.
ToDo: put in range checks for when converting ``@i@''
(or should that be in the typechecker?)
For numeric literals, we try to detect there use at a standard type
(@Int@, @Float@, etc.) are directly put in the right constructor.
[NB: down with the @App@ conversion.]
See also below where we look for @DictApps@ for \tr{plusInt}, etc.
-}
dsLit :: HsLit -> DsM CoreExpr
dsLit (HsStringPrim _ s) = return (Lit (MachStr s))
dsLit (HsCharPrim _ c) = return (Lit (MachChar c))
dsLit (HsIntPrim _ i) = return (Lit (MachInt i))
dsLit (HsWordPrim _ w) = return (Lit (MachWord w))
dsLit (HsInt64Prim _ i) = return (Lit (MachInt64 i))
dsLit (HsWord64Prim _ w) = return (Lit (MachWord64 w))
dsLit (HsFloatPrim f) = return (Lit (MachFloat (fl_value f)))
dsLit (HsDoublePrim d) = return (Lit (MachDouble (fl_value d)))
dsLit (HsChar _ c) = return (mkCharExpr c)
dsLit (HsString _ str) = mkStringExprFS str
dsLit (HsInteger _ i _) = mkIntegerExpr i
dsLit (HsInt _ i) = do dflags <- getDynFlags
return (mkIntExpr dflags i)
dsLit (HsRat r ty) = do
num <- mkIntegerExpr (numerator (fl_value r))
denom <- mkIntegerExpr (denominator (fl_value r))
return (mkCoreConApps ratio_data_con [Type integer_ty, num, denom])
where
(ratio_data_con, integer_ty)
= case tcSplitTyConApp ty of
(tycon, [i_ty]) -> ASSERT(isIntegerTy i_ty && tycon `hasKey` ratioTyConKey)
(head (tyConDataCons tycon), i_ty)
x -> pprPanic "dsLit" (ppr x)
dsOverLit :: HsOverLit Id -> DsM CoreExpr
dsOverLit lit = do { dflags <- getDynFlags
; warnAboutOverflowedLiterals dflags lit
; dsOverLit' dflags lit }
dsOverLit' :: DynFlags -> HsOverLit Id -> DsM CoreExpr
-- Post-typechecker, the SyntaxExpr field of an OverLit contains
-- (an expression for) the literal value itself
dsOverLit' dflags (OverLit { ol_val = val, ol_rebindable = rebindable
, ol_witness = witness, ol_type = ty })
| not rebindable
, Just expr <- shortCutLit dflags val ty = dsExpr expr -- Note [Literal short cut]
| otherwise = dsExpr witness
{-
Note [Literal short cut]
~~~~~~~~~~~~~~~~~~~~~~~~
The type checker tries to do this short-cutting as early as possible, but
because of unification etc, more information is available to the desugarer.
And where it's possible to generate the correct literal right away, it's
much better to do so.
************************************************************************
* *
Warnings about overflowed literals
* *
************************************************************************
Warn about functions like toInteger, fromIntegral, that convert
between one type and another when the to- and from- types are the
same. Then it's probably (albeit not definitely) the identity
-}
warnAboutIdentities :: DynFlags -> CoreExpr -> Type -> DsM ()
warnAboutIdentities dflags (Var conv_fn) type_of_conv
| wopt Opt_WarnIdentities dflags
, idName conv_fn `elem` conversionNames
, Just (arg_ty, res_ty) <- splitFunTy_maybe type_of_conv
, arg_ty `eqType` res_ty -- So we are converting ty -> ty
= warnDs (vcat [ ptext (sLit "Call of") <+> ppr conv_fn <+> dcolon <+> ppr type_of_conv
, nest 2 $ ptext (sLit "can probably be omitted")
, parens (ptext (sLit "Use -fno-warn-identities to suppress this message"))
])
warnAboutIdentities _ _ _ = return ()
conversionNames :: [Name]
conversionNames
= [ toIntegerName, toRationalName
, fromIntegralName, realToFracName ]
-- We can't easily add fromIntegerName, fromRationalName,
-- because they are generated by literals
warnAboutOverflowedLiterals :: DynFlags -> HsOverLit Id -> DsM ()
warnAboutOverflowedLiterals dflags lit
| wopt Opt_WarnOverflowedLiterals dflags
, Just (i, tc) <- getIntegralLit lit
= if tc == intTyConName then check i tc (undefined :: Int)
else if tc == int8TyConName then check i tc (undefined :: Int8)
else if tc == int16TyConName then check i tc (undefined :: Int16)
else if tc == int32TyConName then check i tc (undefined :: Int32)
else if tc == int64TyConName then check i tc (undefined :: Int64)
else if tc == wordTyConName then check i tc (undefined :: Word)
else if tc == word8TyConName then check i tc (undefined :: Word8)
else if tc == word16TyConName then check i tc (undefined :: Word16)
else if tc == word32TyConName then check i tc (undefined :: Word32)
else if tc == word64TyConName then check i tc (undefined :: Word64)
else return ()
| otherwise = return ()
where
check :: forall a. (Bounded a, Integral a) => Integer -> Name -> a -> DsM ()
check i tc _proxy
= when (i < minB || i > maxB) $ do
warnDs (vcat [ ptext (sLit "Literal") <+> integer i
<+> ptext (sLit "is out of the") <+> ppr tc <+> ptext (sLit "range")
<+> integer minB <> ptext (sLit "..") <> integer maxB
, sug ])
where
minB = toInteger (minBound :: a)
maxB = toInteger (maxBound :: a)
sug | minB == -i -- Note [Suggest NegativeLiterals]
, i > 0
, not (xopt Opt_NegativeLiterals dflags)
= ptext (sLit "If you are trying to write a large negative literal, use NegativeLiterals")
| otherwise = Outputable.empty
{-
Note [Suggest NegativeLiterals]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you write
x :: Int8
x = -128
it'll parse as (negate 128), and overflow. In this case, suggest NegativeLiterals.
We get an erroneous suggestion for
x = 128
but perhaps that does not matter too much.
-}
warnAboutEmptyEnumerations :: DynFlags -> LHsExpr Id -> Maybe (LHsExpr Id) -> LHsExpr Id -> DsM ()
-- Warns about [2,3 .. 1] which returns the empty list
-- Only works for integral types, not floating point
warnAboutEmptyEnumerations dflags fromExpr mThnExpr toExpr
| wopt Opt_WarnEmptyEnumerations dflags
, Just (from,tc) <- getLHsIntegralLit fromExpr
, Just mThn <- traverse getLHsIntegralLit mThnExpr
, Just (to,_) <- getLHsIntegralLit toExpr
, let check :: forall a. (Enum a, Num a) => a -> DsM ()
check _proxy
= when (null enumeration) $
warnDs (ptext (sLit "Enumeration is empty"))
where
enumeration :: [a]
enumeration = case mThn of
Nothing -> [fromInteger from .. fromInteger to]
Just (thn,_) -> [fromInteger from, fromInteger thn .. fromInteger to]
= if tc == intTyConName then check (undefined :: Int)
else if tc == int8TyConName then check (undefined :: Int8)
else if tc == int16TyConName then check (undefined :: Int16)
else if tc == int32TyConName then check (undefined :: Int32)
else if tc == int64TyConName then check (undefined :: Int64)
else if tc == wordTyConName then check (undefined :: Word)
else if tc == word8TyConName then check (undefined :: Word8)
else if tc == word16TyConName then check (undefined :: Word16)
else if tc == word32TyConName then check (undefined :: Word32)
else if tc == word64TyConName then check (undefined :: Word64)
else return ()
| otherwise = return ()
getLHsIntegralLit :: LHsExpr Id -> Maybe (Integer, Name)
-- See if the expression is an Integral literal
-- Remember to look through automatically-added tick-boxes! (Trac #8384)
getLHsIntegralLit (L _ (HsPar e)) = getLHsIntegralLit e
getLHsIntegralLit (L _ (HsTick _ e)) = getLHsIntegralLit e
getLHsIntegralLit (L _ (HsBinTick _ _ e)) = getLHsIntegralLit e
getLHsIntegralLit (L _ (HsOverLit over_lit)) = getIntegralLit over_lit
getLHsIntegralLit _ = Nothing
getIntegralLit :: HsOverLit Id -> Maybe (Integer, Name)
getIntegralLit (OverLit { ol_val = HsIntegral _ i, ol_type = ty })
| Just tc <- tyConAppTyCon_maybe ty
= Just (i, tyConName tc)
getIntegralLit _ = Nothing
{-
************************************************************************
* *
Tidying lit pats
* *
************************************************************************
-}
tidyLitPat :: HsLit -> Pat Id
-- Result has only the following HsLits:
-- HsIntPrim, HsWordPrim, HsCharPrim, HsFloatPrim
-- HsDoublePrim, HsStringPrim, HsString
-- * HsInteger, HsRat, HsInt can't show up in LitPats
-- * We get rid of HsChar right here
tidyLitPat (HsChar src c) = unLoc (mkCharLitPat src c)
tidyLitPat (HsString src s)
| lengthFS s <= 1 -- Short string literals only
= unLoc $ foldr (\c pat -> mkPrefixConPat consDataCon
[mkCharLitPat src c, pat] [charTy])
(mkNilPat charTy) (unpackFS s)
-- The stringTy is the type of the whole pattern, not
-- the type to instantiate (:) or [] with!
tidyLitPat lit = LitPat lit
----------------
tidyNPat :: (HsLit -> Pat Id) -- How to tidy a LitPat
-- We need this argument because tidyNPat is called
-- both by Match and by Check, but they tidy LitPats
-- slightly differently; and we must desugar
-- literals consistently (see Trac #5117)
-> HsOverLit Id -> Maybe (SyntaxExpr Id) -> SyntaxExpr Id
-> Pat Id
tidyNPat tidy_lit_pat (OverLit val False _ ty) mb_neg _
-- False: Take short cuts only if the literal is not using rebindable syntax
--
-- Once that is settled, look for cases where the type of the
-- entire overloaded literal matches the type of the underlying literal,
-- and in that case take the short cut
-- NB: Watch out for weird cases like Trac #3382
-- f :: Int -> Int
-- f "blah" = 4
-- which might be ok if we hvae 'instance IsString Int'
--
| isIntTy ty, Just int_lit <- mb_int_lit
= mk_con_pat intDataCon (HsIntPrim "" int_lit)
| isWordTy ty, Just int_lit <- mb_int_lit
= mk_con_pat wordDataCon (HsWordPrim "" int_lit)
| isFloatTy ty, Just rat_lit <- mb_rat_lit = mk_con_pat floatDataCon (HsFloatPrim rat_lit)
| isDoubleTy ty, Just rat_lit <- mb_rat_lit = mk_con_pat doubleDataCon (HsDoublePrim rat_lit)
| isStringTy ty, Just str_lit <- mb_str_lit
= tidy_lit_pat (HsString "" str_lit)
where
mk_con_pat :: DataCon -> HsLit -> Pat Id
mk_con_pat con lit = unLoc (mkPrefixConPat con [noLoc $ LitPat lit] [])
mb_int_lit :: Maybe Integer
mb_int_lit = case (mb_neg, val) of
(Nothing, HsIntegral _ i) -> Just i
(Just _, HsIntegral _ i) -> Just (-i)
_ -> Nothing
mb_rat_lit :: Maybe FractionalLit
mb_rat_lit = case (mb_neg, val) of
(Nothing, HsIntegral _ i) -> Just (integralFractionalLit (fromInteger i))
(Just _, HsIntegral _ i) -> Just (integralFractionalLit
(fromInteger (-i)))
(Nothing, HsFractional f) -> Just f
(Just _, HsFractional f) -> Just (negateFractionalLit f)
_ -> Nothing
mb_str_lit :: Maybe FastString
mb_str_lit = case (mb_neg, val) of
(Nothing, HsIsString _ s) -> Just s
_ -> Nothing
tidyNPat _ over_lit mb_neg eq
= NPat over_lit mb_neg eq
{-
************************************************************************
* *
Pattern matching on LitPat
* *
************************************************************************
-}
matchLiterals :: [Id]
-> Type -- Type of the whole case expression
-> [[EquationInfo]] -- All PgLits
-> DsM MatchResult
matchLiterals (var:vars) ty sub_groups
= ASSERT( notNull sub_groups && all notNull sub_groups )
do { -- Deal with each group
; alts <- mapM match_group sub_groups
-- Combine results. For everything except String
-- we can use a case expression; for String we need
-- a chain of if-then-else
; if isStringTy (idType var) then
do { eq_str <- dsLookupGlobalId eqStringName
; mrs <- mapM (wrap_str_guard eq_str) alts
; return (foldr1 combineMatchResults mrs) }
else
return (mkCoPrimCaseMatchResult var ty alts)
}
where
match_group :: [EquationInfo] -> DsM (Literal, MatchResult)
match_group eqns
= do dflags <- getDynFlags
let LitPat hs_lit = firstPat (head eqns)
match_result <- match vars ty (shiftEqns eqns)
return (hsLitKey dflags hs_lit, match_result)
wrap_str_guard :: Id -> (Literal,MatchResult) -> DsM MatchResult
-- Equality check for string literals
wrap_str_guard eq_str (MachStr s, mr)
= do { -- We now have to convert back to FastString. Perhaps there
-- should be separate MachBytes and MachStr constructors?
let s' = mkFastStringByteString s
; lit <- mkStringExprFS s'
; let pred = mkApps (Var eq_str) [Var var, lit]
; return (mkGuardedMatchResult pred mr) }
wrap_str_guard _ (l, _) = pprPanic "matchLiterals/wrap_str_guard" (ppr l)
matchLiterals [] _ _ = panic "matchLiterals []"
---------------------------
hsLitKey :: DynFlags -> HsLit -> Literal
-- Get a Core literal to use (only) a grouping key
-- Hence its type doesn't need to match the type of the original literal
-- (and doesn't for strings)
-- It only works for primitive types and strings;
-- others have been removed by tidy
hsLitKey dflags (HsIntPrim _ i) = mkMachInt dflags i
hsLitKey dflags (HsWordPrim _ w) = mkMachWord dflags w
hsLitKey _ (HsInt64Prim _ i) = mkMachInt64 i
hsLitKey _ (HsWord64Prim _ w) = mkMachWord64 w
hsLitKey _ (HsCharPrim _ c) = MachChar c
hsLitKey _ (HsStringPrim _ s) = MachStr s
hsLitKey _ (HsFloatPrim f) = MachFloat (fl_value f)
hsLitKey _ (HsDoublePrim d) = MachDouble (fl_value d)
hsLitKey _ (HsString _ s) = MachStr (fastStringToByteString s)
hsLitKey _ l = pprPanic "hsLitKey" (ppr l)
---------------------------
hsOverLitKey :: OutputableBndr a => HsOverLit a -> Bool -> Literal
-- Ditto for HsOverLit; the boolean indicates to negate
hsOverLitKey (OverLit { ol_val = l }) neg = litValKey l neg
---------------------------
litValKey :: OverLitVal -> Bool -> Literal
litValKey (HsIntegral _ i) False = MachInt i
litValKey (HsIntegral _ i) True = MachInt (-i)
litValKey (HsFractional r) False = MachFloat (fl_value r)
litValKey (HsFractional r) True = MachFloat (negate (fl_value r))
litValKey (HsIsString _ s) neg = ASSERT( not neg) MachStr
(fastStringToByteString s)
{-
************************************************************************
* *
Pattern matching on NPat
* *
************************************************************************
-}
matchNPats :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
matchNPats (var:vars) ty (eqn1:eqns) -- All for the same literal
= do { let NPat lit mb_neg eq_chk = firstPat eqn1
; lit_expr <- dsOverLit lit
; neg_lit <- case mb_neg of
Nothing -> return lit_expr
Just neg -> do { neg_expr <- dsExpr neg
; return (App neg_expr lit_expr) }
; eq_expr <- dsExpr eq_chk
; let pred_expr = mkApps eq_expr [Var var, neg_lit]
; match_result <- match vars ty (shiftEqns (eqn1:eqns))
; return (mkGuardedMatchResult pred_expr match_result) }
matchNPats vars _ eqns = pprPanic "matchOneNPat" (ppr (vars, eqns))
{-
************************************************************************
* *
Pattern matching on n+k patterns
* *
************************************************************************
For an n+k pattern, we use the various magic expressions we've been given.
We generate:
\begin{verbatim}
if ge var lit then
let n = sub var lit
in <expr-for-a-successful-match>
else
<try-next-pattern-or-whatever>
\end{verbatim}
-}
matchNPlusKPats :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult
-- All NPlusKPats, for the *same* literal k
matchNPlusKPats (var:vars) ty (eqn1:eqns)
= do { let NPlusKPat (L _ n1) lit ge minus = firstPat eqn1
; ge_expr <- dsExpr ge
; minus_expr <- dsExpr minus
; lit_expr <- dsOverLit lit
; let pred_expr = mkApps ge_expr [Var var, lit_expr]
minusk_expr = mkApps minus_expr [Var var, lit_expr]
(wraps, eqns') = mapAndUnzip (shift n1) (eqn1:eqns)
; match_result <- match vars ty eqns'
; return (mkGuardedMatchResult pred_expr $
mkCoLetMatchResult (NonRec n1 minusk_expr) $
adjustMatchResult (foldr1 (.) wraps) $
match_result) }
where
shift n1 eqn@(EqnInfo { eqn_pats = NPlusKPat (L _ n) _ _ _ : pats })
= (wrapBind n n1, eqn { eqn_pats = pats })
-- The wrapBind is a no-op for the first equation
shift _ e = pprPanic "matchNPlusKPats/shift" (ppr e)
matchNPlusKPats vars _ eqns = pprPanic "matchNPlusKPats" (ppr (vars, eqns))
| bitemyapp/ghc | compiler/deSugar/MatchLit.hs | bsd-3-clause | 19,908 | 1 | 23 | 5,942 | 4,648 | 2,375 | 2,273 | -1 | -1 |
module Main
where
import TestsCommon
import GalFld.Core hiding (examplePoly, examplePoly')
import GalFld.Core.Matrix
import GalFld.Sandbox.FFSandbox
import GalFld.Sandbox.MatrixSandbox
--------------------------------------------------------------------------------
-- TODO: Test Matrix Multiplikation
testSize = 10
main :: IO ()
main = do
hspec $
describe "GalFld.Core.Matrix" $ do
it "eye is multiplikative neutral" $ do
m * eye3 `shouldBe` m
m23 * eye3 `shouldBe` m23
m32 * eye2 `shouldBe` m32
m * eye `shouldBe` m
m23 * eye `shouldBe` m23
m32 * eye `shouldBe` m32
eye * m `shouldBe` m
eye * m23 `shouldBe` m23
eye * m32 `shouldBe` m32
it "detLapM(eye) = 1 (1,2,3,alg)" $ do
detLapM (fromListsM[[1::F7]]) `shouldBe` 1
detLapM eye2 `shouldBe` 1
detLapM eye3 `shouldBe` 1
detLapM eye `shouldBe` 1
it "detLapM(2 * eye) = 2^n" $ do
detLapM (fromListsM[[2::F7]]) `shouldBe` 2
detLapM (eye2 * Mdiag 2) `shouldBe` 4
detLapM (eye3 * Mdiag 2) `shouldBe` 8
it "detLapM == detM (F3 (2,2))" $
pMapM_ (\ x -> detLapM x `shouldBe` detM x )
(getAllM (elems (1::F3)) (2,2))
it "detLapM == detM (e2f2 (2,2))" $
pMapM_ (\ x -> detLapM x `shouldBe` detM x )
(getAllM (elems e2f2) (2,2))
{-
it "detLapM == detM (e2e2f2 (2,2))" $
pMapM_ (\ x -> detLapM x `shouldBe` detM x )
(getAllM (elems e2e2f2) (2,2))
-}
{-
list <- rndSelect (getAllM (elems e2e2f2) (3,3)) testSize
hspec $
describe "GalFld.Core.Matrix" $ do
it "detLapM == detM (e2e2f2 (3,3) subset)" $
pMapM_ (\ x -> detLapM x `shouldBe` detM x ) list
-}
| maximilianhuber/softwareProjekt | test/MatrixTests.hs | bsd-3-clause | 1,774 | 0 | 18 | 520 | 474 | 252 | 222 | 36 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE PostfixOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
--------------------------------------------------------------------------------
-- UART client example, corresponding to
-- smaccm/models/Trusted_Build_Test/test_uart_active2.
--
-- (c) 2015 Galois, Inc.
--
--------------------------------------------------------------------------------
module Main where
import Ivory.Language
import Ivory.Stdlib
import Ivory.Tower
import Tower.AADL
import qualified Ivory.Tower.HAL.Bus.Interface as I
import Tower.Odroid.UART
--------------------------------------------------------------------------------
testSerial :: Tower e ()
testSerial = do
towerModule towerDepModule
towerDepends towerDepModule
per <- period (2000`ms`)
-- Driver wrapper
(b, o) <- uartTower
monitor "sender" $ do
c <- stateInit "charState" (ival 65) -- 'A'
packet <- stateInit "packet" (izero :: Init UartPacket)
handler per "periodicHandler" $ do
e <- emitter (I.backpressureTransmit b) 1 -- Send to wrapper
callback $ \_msg -> do
for 5 $ \ix -> do
let arr = packet ~> stringDataL
c' <- deref c
store (arr!ix) c'
call_ printf2 "Sending code: 0x%x --> %c\n" c' c'
ifte_ (c' >? 90) -- 'Z'
(store c 65)
(c += 1)
store (packet ~> stringLengthL) 5
call_ printf0 "Sent!\n"
emit e (constRef packet)
handler (I.backpressureComplete b) "resp" $ do
callback $ \_msg -> do
call_ printf0 "Received response.\n"
monitor "receiver" $ do
handler o "receiverHandler" $ do
callback $ \msg -> do -- Receive from wrapper
d <- deref msg
call_ printf1 "Received input: %c\n" d
--------------------------------------------------------------------------------
-- Compiler
main :: IO ()
main = compileTowerAADL id p testSerial
where
p _ = return uartConfig
--------------------------------------------------------------------------------
-- Helpers
[ivory|
import (stdio.h, printf) void printf0(string x)
import (stdio.h, printf) void printf1(string x, uint8_t y)
import (stdio.h, printf) void printf2(string x, uint8_t y, uint8_t z)
|]
towerDepModule :: Module
towerDepModule = package "towerDeps" $ do
incl printf0
incl printf1
incl printf2
depend uartModule
| agacek/tower-camkes-odroid | test/SerialTest.hs | bsd-3-clause | 2,606 | 0 | 24 | 526 | 530 | 267 | 263 | 58 | 1 |
--it's first time recursive function
series 1 = 1
series x = x + series (x - 1)
{--this is comment
TODO LIST
-- haskell list
first (x:_) = x;
--Redefine list functions
length'
sum'
take'
drop'
reverse'
--use where
addsub x y = (add,sub)
--math practice
A straight line passing through (p,q)
and cross at right angles the line ax + by = c.
Find the intersection of thease lines.
-- prePoint p q a b c = (x,y)
--}
main = do
print $ series 5
-- print $ first [1..5]
-- print $ length' [1..5]
-- print $ sum' [1..5]
-- print $ take' 3 [1..5]
-- print $ drop' 0 [1..5]
-- print $ drop' 3 [1..5]
-- print $ reverse' [1..5]
-- print $ addsub 5 3
-- try let
-- let (add,_) = addsub 5 3
-- print add
-- print $ prePoint 0 0 1 1 2 | 82p/haskell_sample | app/Main.hs | bsd-3-clause | 735 | 0 | 8 | 168 | 60 | 36 | 24 | 4 | 1 |
{-# language GADTs #-}
{-# language StandaloneDeriving #-}
{-# language TypeOperators #-}
{-# language FlexibleInstances #-}
{-# language FlexibleContexts #-}
{-# language UndecidableInstances #-}
{-# language MultiParamTypeClasses #-}
{-# language ConstraintKinds #-}
{-# language TypeFamilies #-}
{-# options_ghc -fwarn-incomplete-patterns #-}
module Feldspar.Software.Expression where
import Feldspar.Sugar
import Feldspar.Representation
import Feldspar.Software.Primitive
import Data.Struct
import Data.Complex (Complex)
import Data.Int
import Data.Word
import Data.List (genericTake)
import Data.Constraint
import Data.Typeable (Typeable)
-- syntactic.
import Language.Syntactic hiding (Signature, Args)
import Language.Syntactic.Functional hiding (Lam)
import Language.Syntactic.Functional.Tuple
import qualified Language.Syntactic as Syn
-- imperative-edsl.
import Language.Embedded.Expression
--------------------------------------------------------------------------------
-- * Software expressions.
--------------------------------------------------------------------------------
type instance Pred SoftwareDomain = SoftwarePrimType
--------------------------------------------------------------------------------
-- hmm...
type instance ExprOf (SExp a) = SExp
type instance PredOf SExp = SoftwarePrimType
type instance DomainOf SExp = SoftwareDomain
type instance RepresentationOf SoftwarePrimType = SoftwarePrimTypeRep
--------------------------------------------------------------------------------
-- ** Software types.
-- | Representation of supported software types.
type STypeRep = TypeRep SoftwarePrimType SoftwarePrimTypeRep
-- | ...
type STypeRepF = TypeRepF SoftwarePrimType SoftwarePrimTypeRep
instance Type SoftwarePrimType Bool where typeRep = Node BoolST
instance Type SoftwarePrimType Int8 where typeRep = Node Int8ST
instance Type SoftwarePrimType Int16 where typeRep = Node Int16ST
instance Type SoftwarePrimType Int32 where typeRep = Node Int32ST
instance Type SoftwarePrimType Int64 where typeRep = Node Int64ST
instance Type SoftwarePrimType Word8 where typeRep = Node Word8ST
instance Type SoftwarePrimType Word16 where typeRep = Node Word16ST
instance Type SoftwarePrimType Word32 where typeRep = Node Word32ST
instance Type SoftwarePrimType Word64 where typeRep = Node Word64ST
instance Type SoftwarePrimType Float where typeRep = Node FloatST
instance Type SoftwarePrimType Double where typeRep = Node DoubleST
instance Type SoftwarePrimType (Complex Float) where typeRep = Node ComplexFloatST
instance Type SoftwarePrimType (Complex Double) where typeRep = Node ComplexDoubleST
-- | Compare two software types for equality.
softwareTypeEq :: STypeRep a -> STypeRep b -> Maybe (Dict (a ~ b))
softwareTypeEq (Node t) (Node u) = softwarePrimTypeEq t u
softwareTypeEq (Branch t1 u1) (Branch t2 u2) = do
Dict <- softwareTypeEq t1 t2
Dict <- softwareTypeEq u1 u2
return Dict
softwareTypeEq _ _ = Nothing
-- | Construct the software type representation of 'a'.
softwareTypeRep :: Struct SoftwarePrimType c a -> STypeRep a
softwareTypeRep = mapStruct (const softwareRep)
--------------------------------------------------------------------------------
-- | Short-hand for software types.
type SType = Type SoftwarePrimType
-- | Short-hand for primitive software types.
type SType' = PrimType SoftwarePrimType
--------------------------------------------------------------------------------
-- ** Software expression symbols.
data AssertionLabel =
-- ^ Internal assertion to guarantee meaningful results.
InternalAssertion
-- ^ User made assertion.
| UserAssertion String
deriving (Eq, Show)
-- | Guard a value with an assertion.
data GuardVal sig
where
GuardVal :: AssertionLabel -> String -> GuardVal (Bool :-> a :-> Full a)
deriving instance Eq (GuardVal a)
deriving instance Show (GuardVal a)
deriving instance Typeable (GuardVal a)
--------------------------------------------------------------------------------
-- | Hint that a value may appear in an invariant
data HintVal sig
where
HintVal :: SoftwarePrimType a => HintVal (a :-> b :-> Full b)
deriving instance Eq (HintVal a)
deriving instance Show (HintVal a)
deriving instance Typeable (HintVal a)
--------------------------------------------------------------------------------
-- | For loop.
data ForLoop sig
where
ForLoop :: SType st =>
ForLoop (Length :-> Length :-> st :-> (Index -> st -> st) :-> Full st)
deriving instance Eq (ForLoop a)
deriving instance Show (ForLoop a)
deriving instance Typeable (ForLoop a)
--------------------------------------------------------------------------------
{-
-- |
data Foreign sig
where
Foreign :: Signature sig => String -> Denotation sig -> Foreign sig
-}
--------------------------------------------------------------------------------
-- | Software symbols.
type SoftwareConstructs =
BindingT
Syn.:+: Let
Syn.:+: Tuple
Syn.:+: SoftwarePrimConstructs
Syn.:+: Construct
-- ^ Software specific symbol.
Syn.:+: GuardVal
Syn.:+: HintVal
Syn.:+: ForLoop
-- | Software symbols tagged with their type representation.
type SoftwareDomain = SoftwareConstructs :&: TypeRepF SoftwarePrimType SoftwarePrimTypeRep
-- | Software expressions.
newtype SExp a = SExp { unSExp :: ASTF SoftwareDomain a }
-- | Evaluate a closed software expression.
eval :: (Syntactic a, Domain a ~ SoftwareDomain) => a -> Internal a
eval = evalClosed . desugar
-- | Sugar a software symbol as a smart constructor.
sugarSymSoftware
:: ( Syn.Signature sig
, fi ~ SmartFun dom sig
, sig ~ SmartSig fi
, dom ~ SmartSym fi
, dom ~ SoftwareDomain
, SyntacticN f fi
, sub :<: SoftwareConstructs
, Type SoftwarePrimType (DenResult sig)
)
=> sub sig -> f
sugarSymSoftware = sugarSymDecor $ ValT $ typeRep
-- | Sugar a software symbol as a primitive smart constructor.
sugarSymPrimSoftware
:: ( Syn.Signature sig
, fi ~ SmartFun dom sig
, sig ~ SmartSig fi
, dom ~ SmartSym fi
, dom ~ SoftwareDomain
, SyntacticN f fi
, sub :<: SoftwareConstructs
, SoftwarePrimType (DenResult sig)
)
=> sub sig -> f
sugarSymPrimSoftware = sugarSymDecor $ ValT $ Node softwareRep
--------------------------------------------------------------------------------
instance Syntactic (SExp a)
where
type Domain (SExp a) = SoftwareDomain
type Internal (SExp a) = a
desugar = unSExp
sugar = SExp
instance Syntactic (Struct SoftwarePrimType SExp a)
where
type Domain (Struct SoftwarePrimType SExp a) = SoftwareDomain
type Internal (Struct SoftwarePrimType SExp a) = a
desugar (Node a) = unSExp a
desugar (Branch a b) = sugarSymDecor (ValT $ Branch ta tb) Pair a' b'
where
a' = desugar a
b' = desugar b
ValT ta = getDecor a'
ValT tb = getDecor b'
sugar a = case getDecor a of
ValT (Node _) -> Node $ SExp a
ValT (Branch ta tb) -> Branch
(sugarSymDecor (ValT ta) Fst a)
(sugarSymDecor (ValT tb) Snd a)
FunT _ _ -> error "Syntactic can't sugar a function."
instance Tuples SoftwareDomain
where
pair = sugarSymSoftware Pair
first = sugarSymSoftware Fst
second = sugarSymSoftware Snd
instance FreeExp SExp
where
type FreePred SExp = PrimType SoftwarePrimType
constExp = sugarSymSoftware . Lit
varExp = sugarSymSoftware . FreeVar
--------------------------------------------------------------------------------
-- syntactic instances.
instance Eval GuardVal
where
evalSym (GuardVal InternalAssertion msg) = \cond a ->
if cond then a else error $ "Internal assertion failure: " ++ show msg
evalSym (GuardVal (UserAssertion ass) msg) = \cond a ->
if cond then a else error $ "User assertion " ++ show ass ++ " failure: " ++ show msg
instance Symbol GuardVal
where
symSig (GuardVal _ _) = signature
instance Render GuardVal
where
renderSym = show
renderArgs = renderArgsSmart
instance EvalEnv GuardVal env
instance StringTree GuardVal
instance Equality GuardVal
--------------------------------------------------------------------------------
instance Eval HintVal
where
evalSym (HintVal) = flip const
instance Symbol HintVal
where
symSig (HintVal) = signature
instance Render HintVal
where
renderSym = show
renderArgs = renderArgsSmart
instance EvalEnv HintVal env
instance StringTree HintVal
instance Equality HintVal
--------------------------------------------------------------------------------
instance Eval ForLoop
where
evalSym ForLoop = \min max init body ->
foldl (flip body) init [min..max]
instance Symbol ForLoop
where
symSig (ForLoop) = signature
instance Render ForLoop
where
renderSym = show
renderArgs = renderArgsSmart
instance EvalEnv ForLoop env
instance StringTree ForLoop
instance Equality ForLoop
--------------------------------------------------------------------------------
-- *** Temporary fix until GHC fixes their class resolution for DTC ***
instance {-# OVERLAPPING #-} Project sub SoftwareConstructs =>
Project sub (AST SoftwareDomain)
where
prj (Sym s) = Syn.prj s
prj _ = Nothing
instance {-# OVERLAPPING #-} Project sub SoftwareConstructs =>
Project sub SoftwareDomain
where
prj (expr :&: info) = Syn.prj expr
instance {-# OVERLAPPING #-} Project BindingT SoftwareConstructs
where
prj (InjL a) = Just a
prj _ = Nothing
instance {-# OVERLAPPING #-} Project Let SoftwareConstructs
where
prj (InjR (InjL a)) = Just a
prj _ = Nothing
instance {-# OVERLAPPING #-} Project Tuple SoftwareConstructs
where
prj (InjR (InjR (InjL a))) = Just a
prj _ = Nothing
instance {-# OVERLAPPING #-} Project SoftwarePrimConstructs SoftwareConstructs
where
prj (InjR (InjR (InjR (InjL a)))) = Just a
prj _ = Nothing
instance {-# OVERLAPPING #-} Project Construct SoftwareConstructs
where
prj (InjR (InjR (InjR (InjR (InjL a))))) = Just a
prj _ = Nothing
instance {-# OVERLAPPING #-} Project GuardVal SoftwareConstructs
where
prj (InjR (InjR (InjR (InjR (InjR (InjL a)))))) = Just a
prj _ = Nothing
instance {-# OVERLAPPING #-} Project HintVal SoftwareConstructs
where
prj (InjR (InjR (InjR (InjR (InjR (InjR (InjL a))))))) = Just a
prj _ = Nothing
instance {-# OVERLAPPING #-} Project ForLoop SoftwareConstructs
where
prj (InjR (InjR (InjR (InjR (InjR (InjR (InjR a))))))) = Just a
prj _ = Nothing
--------------------------------------------------------------------------------
| markus-git/co-feldspar | src/Feldspar/Software/Expression.hs | bsd-3-clause | 10,819 | 0 | 20 | 2,095 | 2,574 | 1,340 | 1,234 | 205 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module System.FastLogger
( Logger
, timestampedLogEntry
, combinedLogEntry
, newLogger
, newLoggerWithCustomErrorFunction
, logMsg
, stopLogger
) where
------------------------------------------------------------------------------
import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char.Utf8
import Control.Concurrent
import Control.Concurrent.Extended (forkIOLabeledWithUnmaskBs)
import Control.Exception
import Control.Monad
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.ByteString.Internal (c2w)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Int
import Data.IORef
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
#if !MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import System.IO
import Snap.Internal.Http.Server.Date
------------------------------------------------------------------------------
-- | Holds the state for a logger.
data Logger = Logger
{ _queuedMessages :: !(IORef Builder)
, _dataWaiting :: !(MVar ())
, _loggerPath :: !(FilePath)
, _loggingThread :: !(MVar ThreadId)
, _errAction :: ByteString -> IO ()
}
------------------------------------------------------------------------------
-- | Creates a new logger, logging to the given file. If the file argument is
-- \"-\", then log to stdout; if it's \"stderr\" then we log to stderr,
-- otherwise we log to a regular file in append mode. The file is closed and
-- re-opened every 15 minutes to facilitate external log rotation.
newLogger :: FilePath -- ^ log file to use
-> IO Logger
newLogger = newLoggerWithCustomErrorFunction
(\s -> S.hPutStr stderr s >> hFlush stderr)
------------------------------------------------------------------------------
-- | Like 'newLogger', but uses a custom error action if the logger needs to
-- print an error message of its own (for instance, if it can't open the
-- output file.)
newLoggerWithCustomErrorFunction :: (ByteString -> IO ())
-- ^ logger uses this action to log any
-- error messages of its own
-> FilePath -- ^ log file to use
-> IO Logger
newLoggerWithCustomErrorFunction errAction fp = do
q <- newIORef mempty
dw <- newEmptyMVar
th <- newEmptyMVar
let lg = Logger q dw fp th errAction
mask_ $ do
tid <- forkIOLabeledWithUnmaskBs "snap-server: logging" $
loggingThread lg
putMVar th tid
return lg
------------------------------------------------------------------------------
-- | Prepares a log message with the time prepended.
timestampedLogEntry :: ByteString -> IO ByteString
timestampedLogEntry msg = do
timeStr <- getLogDateString
return $! toByteString
$! mconcat [ fromWord8 $ c2w '['
, fromByteString timeStr
, fromByteString "] "
, fromByteString msg ]
------------------------------------------------------------------------------
-- | Prepares a log message in \"combined\" format.
combinedLogEntry :: ByteString -- ^ remote host
-> Maybe ByteString -- ^ remote user
-> ByteString -- ^ request line (up to you to ensure
-- there are no quotes in here)
-> Int -- ^ status code
-> Maybe Int64 -- ^ num bytes sent
-> Maybe ByteString -- ^ referer (up to you to ensure
-- there are no quotes in here)
-> ByteString -- ^ user agent (up to you to ensure
-- there are no quotes in here)
-> IO ByteString
combinedLogEntry !host !mbUser !req !status !mbNumBytes !mbReferer !ua = do
timeStr <- getLogDateString
let !l = [ fromByteString host
, fromByteString " - "
, user
, fromByteString " ["
, fromByteString timeStr
, fromByteString "] \""
, fromByteString req
, fromByteString "\" "
, fromShow status
, space
, numBytes
, space
, referer
, fromByteString " \""
, fromByteString ua
, quote ]
let !output = toByteString $ mconcat l
return $! output
where
dash = fromWord8 $ c2w '-'
quote = fromWord8 $ c2w '\"'
space = fromWord8 $ c2w ' '
user = maybe dash fromByteString mbUser
numBytes = maybe dash fromShow mbNumBytes
referer = maybe dash
(\s -> mconcat [ quote
, fromByteString s
, quote ])
mbReferer
------------------------------------------------------------------------------
-- | Sends out a log message verbatim with a newline appended. Note:
-- if you want a fancy log message you'll have to format it yourself
-- (or use 'combinedLogEntry').
logMsg :: Logger -> ByteString -> IO ()
logMsg !lg !s = do
let !s' = fromByteString s `mappend` (fromWord8 $ c2w '\n')
atomicModifyIORef (_queuedMessages lg) $ \d -> (d `mappend` s',())
tryPutMVar (_dataWaiting lg) () >> return ()
------------------------------------------------------------------------------
loggingThread :: Logger -> (forall a. IO a -> IO a) -> IO ()
loggingThread (Logger queue notifier filePath _ errAct) unmask = do
initialize >>= go
where
openIt =
if filePath == "-"
then return stdout
else
if filePath == "stderr"
then return stderr
else openFile filePath AppendMode `catch`
\(e::IOException) -> do
logInternalError $ "Can't open log file \"" ++
filePath ++ "\".\n"
logInternalError $ "Exception: " ++ show e ++ "\n"
logInternalError $ "Logging to stderr instead. " ++
"**THIS IS BAD, YOU OUGHT TO " ++
"FIX THIS**\n\n"
return stderr
closeIt h = unless (h == stdout || h == stderr) $
hClose h
logInternalError = errAct . T.encodeUtf8 . T.pack
go (href, lastOpened) =
(unmask $ forever $ waitFlushDelay (href, lastOpened))
`catches`
[ Handler $ \(_::AsyncException) -> killit (href, lastOpened)
, Handler $ \(e::SomeException) -> do
logInternalError $ "logger got exception: "
++ Prelude.show e ++ "\n"
threadDelay 20000000
go (href, lastOpened) ]
initialize = do
lh <- openIt
href <- newIORef lh
t <- getCurrentDateTime
tref <- newIORef t
return (href, tref)
killit (href, lastOpened) = do
flushIt (href, lastOpened)
h <- readIORef href
closeIt h
flushIt (!href, !lastOpened) = do
dl <- atomicModifyIORef queue $ \x -> (mempty,x)
let !msgs = toLazyByteString dl
h <- readIORef href
(do L.hPut h msgs
hFlush h) `catch` \(e::IOException) -> do
logInternalError $ "got exception writing to log " ++
filePath ++ ": " ++ show e ++ "\n"
logInternalError $ "writing log entries to stderr.\n"
mapM_ errAct $ L.toChunks msgs
-- close the file every 15 minutes (for log rotation)
t <- getCurrentDateTime
old <- readIORef lastOpened
when (t-old > 900) $ do
closeIt h
mask_ $ openIt >>= writeIORef href
writeIORef lastOpened t
waitFlushDelay !d = do
-- wait on the notification mvar
_ <- takeMVar notifier
-- grab the queued messages and write them out
flushIt d
-- at least five seconds between log dumps
threadDelay 5000000
------------------------------------------------------------------------------
-- | Kills a logger thread, causing any unwritten contents to be
-- flushed out to disk
stopLogger :: Logger -> IO ()
stopLogger lg = withMVar (_loggingThread lg) killThread
| jonpetterbergman/wai-snap | src/System/FastLogger.hs | bsd-3-clause | 9,023 | 0 | 17 | 3,167 | 1,661 | 858 | 803 | 174 | 3 |
module Data.TestCase1TypeSynExpand where
type String1 = [Char]
f :: String1 -> String1
f x = x
data Tree a = Leaf | Node a (Tree a) (Tree a)
type ITree = Tree String1
g :: ITree -> ITree
g x = x
h x = let
y :: ITree -> ITree
y = g
in g Leaf
| rodrigogribeiro/mptc | test/Data/TestCase1TypeSynExpand.hs | bsd-3-clause | 271 | 0 | 9 | 87 | 118 | 64 | 54 | 12 | 1 |
{-# LANGUAGE CPP, ScopedTypeVariables #-}
{-
Uses pattern guards
This is an interpreter of the Unlambda language, written in
the pure, lazy, functional language Haskell.
Copyright (C) 2001 by Ørjan Johansen <oerjan@nvg.ntnu.no>
Copyright (C) 2006 by Don Stewart - http://www.cse.unsw.edu.au/~dons
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module Language.Unlambda where
#if !MIN_VERSION_base(4,6,0)
import Prelude hiding(catch)
#endif
import Control.Exception (catch, IOException)
------------------------------------------------------------------------
-- Abstract syntax
data Exp
= App Exp Exp
| K
| K1 Exp
| S
| S1 Exp
| S2 Exp Exp
| I
| V
| C
| Cont (Cont Exp)
| D
| D1 Exp
| Dot Char
| E
| At
| Ques Char
| Pipe
------------------------------------------------------------------------
-- Printing
instance Show Exp where
showsPrec _ = sh
sh :: Exp -> String -> String
sh (App x y) = showChar '`' . sh x . sh y
sh K = showChar 'k'
sh (K1 x) = showString "`k" . sh x
sh S = showChar 's'
sh (S1 x) = showString "`s" . sh x
sh (S2 x y) = showString "``s" . sh x . sh y
sh I = showChar 'i'
sh V = showChar 'v'
sh C = showChar 'c'
sh (Cont _) = showString "<cont>"
sh D = showChar 'd'
sh (D1 x) = showString "`d" . sh x
sh (Dot '\n') = showChar 'r'
sh (Dot c) = showChar '.' . showChar c
sh E = showChar 'e'
sh At = showChar '@'
sh (Ques c) = showChar '?' . showChar c
sh Pipe = showChar '|'
------------------------------------------------------------------------
-- Eval monad
newtype Eval a = Eval ((Maybe Char, Int) -> Cont a -> IO Exp)
type Cont a = (Maybe Char, Int) -> a -> IO Exp
instance Monad Eval where
(Eval cp1) >>= f = Eval $ \dat1 cont2 ->
cp1 dat1 $ \dat2 a ->
let (Eval cp2) = f a in cp2 dat2 cont2
return a = Eval $ \dat cont -> cont dat a
------------------------------------------------------------------------
-- Basics
currentChar :: Eval (Maybe Char)
currentChar = Eval (\dat@(c,_) cont -> cont dat c)
setCurrentChar :: Maybe Char -> Eval ()
setCurrentChar c = Eval (\(_,i) cont -> cont (c,i) ())
io :: IO a -> Eval a
io iocp = Eval (\dat cont -> iocp >>= cont dat)
throw :: ((Maybe Char, Int) -> t -> IO Exp) -> t -> Eval a
throw c x = Eval (\dat _ -> c dat x)
exit :: Exp -> Eval a
exit e = Eval (\_ _ -> return e)
callCC :: (((Maybe Char, Int) -> a -> IO Exp) -> Eval a) -> Eval a
callCC f = Eval $ \dat cont -> let Eval cp2 = f cont in cp2 dat cont
step :: Eval ()
step = Eval (\(c,i) cont -> if i<1 then return E else cont (c,i-1) ())
------------------------------------------------------------------------
-- Interpretation in the Eval monad
eval :: Exp -> Eval Exp
eval (App e1 e2) = do
f <- eval e1
case f of
D -> return (D1 e2)
_ -> eval e2 >>= apply f
eval e = return e
apply :: Exp -> Exp -> Eval Exp
apply K x = return (K1 x)
apply (K1 x) _ = return x
apply S x = return (S1 x)
apply (S1 x) y = return (S2 x y)
apply (S2 x y) z = eval (App (App x z) (App y z))
apply I x = return x
apply V _ = return V
apply C x = callCC (apply x . Cont)
apply (Cont c) x = throw c x
apply D x = return x
apply (D1 e) x = do f <- eval e; apply f x
apply (Dot c) x = step >> io (putChar c) >> return x
apply E x = exit x
apply At f = do
dat <- io $ catch (fmap Just getChar) (\(_ :: IOException) -> return Nothing)
setCurrentChar dat
apply f (case dat of Nothing -> V ; Just _ -> I)
apply (Ques c) f = do
cur <- currentChar
apply f (if cur == Just c then I else V)
apply Pipe f = do
cur <- currentChar
apply f (case cur of Nothing -> V ; Just c -> Dot c)
apply (App _ _) _ = error "Unknown application"
| jwiegley/lambdabot-1 | unlambda/Language/Unlambda.hs | mit | 4,539 | 0 | 15 | 1,214 | 1,644 | 819 | 825 | 96 | 4 |
{- |
Module : ./Proofs/InferBasic.hs
Description : devGraph rule that calls provers for specific logics
Copyright : (c) J. Gerken, T. Mossakowski, K. Luettich, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : provisional
Portability : non-portable(Logic)
devGraph rule that calls provers for specific logics
Proof rule "basic inference" in the development graphs calculus.
Follows Sect. IV:4.4 of the CASL Reference Manual.
References:
T. Mossakowski, S. Autexier and D. Hutter:
Extending Development Graphs With Hiding.
H. Hussmann (ed.): Fundamental Approaches to Software Engineering 2001,
Lecture Notes in Computer Science 2029, p. 269-283,
Springer-Verlag 2001.
-}
module Proofs.InferBasic
( basicInferenceNode
) where
import Static.GTheory
import Static.DevGraph
import Static.ComputeTheory
import Proofs.EdgeUtils
import Proofs.AbstractState
import Proofs.FreeDefLinks
import Common.LibName
import Common.Result
import Common.ResultT
import Common.AS_Annotation
import Logic.Logic
import Logic.Prover
import Logic.Grothendieck
import Logic.Comorphism
import Logic.Coerce
import Comorphisms.KnownProvers
import GUI.Utils
import GUI.ProverGUI
import Interfaces.DataTypes
import Interfaces.Utils
import Data.IORef
import Data.Graph.Inductive.Graph
import Data.Maybe
import Control.Monad.Trans
selectProver :: [(G_prover, AnyComorphism)]
-> ResultT IO (G_prover, AnyComorphism)
selectProver ps = case ps of
[] -> fail "No prover available"
[p] -> return p
_ -> do
sel <- lift $ listBox "Choose a translation to a prover-supported logic"
$ map (\ (aGN, cm) -> shows cm $ " (" ++ getProverName aGN ++ ")") ps
i <- case sel of
Just j -> return j
_ -> fail "Proofs.Proofs: selection"
return $ ps !! i
proveTheory :: Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree
=> lid -> Prover sign sentence morphism sublogics proof_tree
-> String -> Theory sign sentence proof_tree
-> [FreeDefMorphism sentence morphism]
-> IO ( [ProofStatus proof_tree]
, [(Named sentence, ProofStatus proof_tree)])
proveTheory _ =
fromMaybe (\ _ _ -> fail "proveGUI not implemented") . proveGUI
{- | applies basic inference to a given node. The result is a theory which is
either a model after a consistency check or a new theory for the node
label -}
basicInferenceNode :: LogicGraph -> LibName -> DGraph -> LNode DGNodeLab
-> LibEnv -> IORef IntState
-> IO (Result G_theory)
basicInferenceNode lg ln dGraph (node, lbl) libEnv intSt =
runResultT $ do
-- compute the theory (that may contain proved theorems) and its name
thForProof <- liftR $ getGlobalTheory lbl
let thName = libToFileName ln ++ "_" ++ getDGNodeName lbl
freedefs = getCFreeDefMorphs libEnv ln dGraph node
ps <- lift $ getUsableProvers ProveGUI (sublogicOfTh thForProof) lg
kpMap <- liftR knownProversGUI
{- let kpMap = foldl (\m (G_prover _ p,c) ->
case Map.lookup (proverName p) m of
Just cs -> Map.insert (proverName p) (c:cs) m
Nothing -> Map.insert (proverName p) [c] m) Map.empty ps -}
ResultT $ proverGUI ProofActions
{ proveF = proveKnownPMap lg intSt freedefs
, fineGrainedSelectionF = proveFineGrainedSelect lg intSt freedefs
, recalculateSublogicF = return . recalculateSublogicAndSelectedTheory
} thName (hidingLabelWarning lbl) thForProof kpMap ps
proveKnownPMap :: LogicGraph
-> IORef IntState
-> [GFreeDefMorphism]
-> ProofState -> IO (Result ProofState)
proveKnownPMap lg intSt freedefs st =
maybe (proveFineGrainedSelect lg intSt freedefs st)
(callProver st intSt False freedefs) $
lookupKnownProver st ProveGUI
callProver :: ProofState
-> IORef IntState
-> Bool -- indicates if a translation was chosen
-> [GFreeDefMorphism]
-> (G_prover, AnyComorphism) -> IO (Result ProofState)
callProver st intSt trans_chosen freedefs p_cm@(_, acm) =
runResultT $ do
(_, exit) <- lift $ pulseBar "prepare for proving" "please wait..."
G_theory_with_prover lid th p <- liftR $ prepareForProving st p_cm
freedefs1 <- mapM (\ (GFreeDefMorphism fdlid fd) ->
coerceFreeDefMorphism fdlid lid "" fd) freedefs
lift exit
(ps, _) <- lift $ proveTheory lid p (theoryName st) th freedefs1
let st' = markProved acm lid ps st
lift $ addCommandHistoryToState intSt st'
(if trans_chosen then Just p_cm else Nothing) ps "" (False, 0)
return st'
proveFineGrainedSelect :: LogicGraph
-> IORef IntState
-> [GFreeDefMorphism]
-> ProofState -> IO (Result ProofState)
proveFineGrainedSelect lg intSt freedefs st =
runResultT $ do
let sl = sublogicOfTheory st
cmsToProvers <- lift $ getUsableProvers ProveGUI sl lg
pr <- selectProver cmsToProvers
ResultT $ callProver st { comorphismsToProvers = cmsToProvers }
intSt True freedefs pr
| spechub/Hets | Proofs/InferBasic.hs | gpl-2.0 | 5,275 | 0 | 18 | 1,254 | 1,133 | 574 | 559 | 99 | 4 |
--
-- 2.SystemInfo.hs
-- R_Functional_Programming
--
-- Created by RocKK on 2/13/14.
-- Copyright (c) 2014 RocKK.
-- All rights reserved.
--
-- Redistribution and use in source and binary forms are permitted
-- provided that the above copyright notice and this paragraph are
-- duplicated in all such forms and that any documentation,
-- advertising materials, and other materials related to such
-- distribution and use acknowledge that the software was developed
-- by the RocKK. The name of the
-- RocKK may not be used to endorse or promote products derived
-- from this software without specific prior written permission.
-- THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESS OR
-- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
import System.Info
main = do
print os
print arch
print compilerName
print compilerVersion
| RocKK-MD/R_Functional_Programming | Sources/2.SystemInfo.hs | bsd-2-clause | 956 | 0 | 7 | 181 | 54 | 33 | 21 | 6 | 1 |
module Bugs.Bug6 (main) where
import Text.Megaparsec
import Text.Megaparsec.String
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
import Util
main :: Test
main =
testCase "Look-ahead preserving error location (#6)" $
parseErrors variable "return" @?= ["'return' is a reserved keyword"]
variable :: Parser String
variable = do
x <- lookAhead (some letterChar)
if x == "return"
then fail "'return' is a reserved keyword"
else string x
| neongreen/megaparsec | old-tests/Bugs/Bug6.hs | bsd-2-clause | 512 | 0 | 10 | 99 | 127 | 70 | 57 | 17 | 2 |
{-# OPTIONS_GHC -fno-implicit-prelude -fallow-overlapping-instances #-}
-- The -fallow-overlapping-instances flag allows the user to over-ride
-- the instances for Typeable given here. In particular, we provide an instance
-- instance ... => Typeable (s a)
-- But a user might want to say
-- instance ... => Typeable (MyType a b)
-----------------------------------------------------------------------------
-- |
-- Module : Data.Typeable
-- Copyright : (c) The University of Glasgow, CWI 2001--2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- The 'Typeable' class reifies types to some extent by associating type
-- representations to types. These type representations can be compared,
-- and one can in turn define a type-safe cast operation. To this end,
-- an unsafe cast is guarded by a test for type (representation)
-- equivalence. The module "Data.Dynamic" uses Typeable for an
-- implementation of dynamics. The module "Data.Generics" uses Typeable
-- and type-safe cast (but not dynamics) to support the \"Scrap your
-- boilerplate\" style of generic programming.
--
-----------------------------------------------------------------------------
module Data.Typeable
(
-- * The Typeable class
Typeable( typeOf ), -- :: a -> TypeRep
-- * Type-safe cast
cast, -- :: (Typeable a, Typeable b) => a -> Maybe b
gcast, -- a generalisation of cast
-- * Type representations
TypeRep, -- abstract, instance of: Eq, Show, Typeable
TyCon, -- abstract, instance of: Eq, Show, Typeable
-- * Construction of type representations
mkTyCon, -- :: String -> TyCon
mkTyConApp, -- :: TyCon -> [TypeRep] -> TypeRep
mkAppTy, -- :: TypeRep -> TypeRep -> TypeRep
mkFunTy, -- :: TypeRep -> TypeRep -> TypeRep
-- * Observation of type representations
splitTyConApp, -- :: TypeRep -> (TyCon, [TypeRep])
funResultTy, -- :: TypeRep -> TypeRep -> Maybe TypeRep
typeRepTyCon, -- :: TypeRep -> TyCon
typeRepArgs, -- :: TypeRep -> [TypeRep]
tyConString, -- :: TyCon -> String
-- * The other Typeable classes
-- | /Note:/ The general instances are provided for GHC only.
Typeable1( typeOf1 ), -- :: t a -> TypeRep
Typeable2( typeOf2 ), -- :: t a b -> TypeRep
Typeable3( typeOf3 ), -- :: t a b c -> TypeRep
Typeable4( typeOf4 ), -- :: t a b c d -> TypeRep
Typeable5( typeOf5 ), -- :: t a b c d e -> TypeRep
Typeable6( typeOf6 ), -- :: t a b c d e f -> TypeRep
Typeable7( typeOf7 ), -- :: t a b c d e f g -> TypeRep
gcast1, -- :: ... => c (t a) -> Maybe (c (t' a))
gcast2, -- :: ... => c (t a b) -> Maybe (c (t' a b))
-- * Default instances
-- | /Note:/ These are not needed by GHC, for which these instances
-- are generated by general instance declarations.
typeOfDefault, -- :: (Typeable1 t, Typeable a) => t a -> TypeRep
typeOf1Default, -- :: (Typeable2 t, Typeable a) => t a b -> TypeRep
typeOf2Default, -- :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
typeOf3Default, -- :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
typeOf4Default, -- :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
typeOf5Default, -- :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
typeOf6Default -- :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
) where
import qualified Data.HashTable as HT
import Data.Maybe
import Data.Either
import Data.Int
import Data.Word
import Data.List( foldl )
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.Show
import GHC.Err
import GHC.Num
import GHC.Float
import GHC.Real ( rem, Ratio )
import GHC.IOBase (IORef,newIORef,unsafePerformIO)
-- These imports are so we can define Typeable instances
-- It'd be better to give Typeable instances in the modules themselves
-- but they all have to be compiled before Typeable
import GHC.IOBase ( IO, MVar, Exception, ArithException, IOException,
ArrayException, AsyncException, Handle )
import GHC.ST ( ST )
import GHC.STRef ( STRef )
import GHC.Ptr ( Ptr, FunPtr )
import GHC.ForeignPtr ( ForeignPtr )
import GHC.Stable ( StablePtr, newStablePtr, freeStablePtr,
deRefStablePtr, castStablePtrToPtr,
castPtrToStablePtr )
import GHC.Exception ( block )
import GHC.Arr ( Array, STArray )
#endif
#ifdef __HUGS__
import Hugs.Prelude ( Key(..), TypeRep(..), TyCon(..), Ratio,
Exception, ArithException, IOException,
ArrayException, AsyncException, Handle,
Ptr, FunPtr, ForeignPtr, StablePtr )
import Hugs.IORef ( IORef, newIORef, readIORef, writeIORef )
import Hugs.IOExts ( unsafePerformIO, unsafeCoerce )
-- For the Typeable instance
import Hugs.Array ( Array )
import Hugs.ConcBase ( MVar )
#endif
#ifdef __GLASGOW_HASKELL__
unsafeCoerce :: a -> b
unsafeCoerce = unsafeCoerce#
#endif
#ifdef __NHC__
import NonStdUnsafeCoerce (unsafeCoerce)
import NHC.IOExtras (IORef,newIORef,readIORef,writeIORef,unsafePerformIO)
import IO (Handle)
import Ratio (Ratio)
-- For the Typeable instance
import NHC.FFI ( Ptr,FunPtr,StablePtr,ForeignPtr )
import Array ( Array )
#endif
#include "Typeable.h"
#ifndef __HUGS__
-------------------------------------------------------------
--
-- Type representations
--
-------------------------------------------------------------
-- | A concrete representation of a (monomorphic) type. 'TypeRep'
-- supports reasonably efficient equality.
data TypeRep = TypeRep !Key TyCon [TypeRep]
-- Compare keys for equality
instance Eq TypeRep where
(TypeRep k1 _ _) == (TypeRep k2 _ _) = k1 == k2
-- | An abstract representation of a type constructor. 'TyCon' objects can
-- be built using 'mkTyCon'.
data TyCon = TyCon !Key String
instance Eq TyCon where
(TyCon t1 _) == (TyCon t2 _) = t1 == t2
#endif
--
-- let fTy = mkTyCon "Foo" in show (mkTyConApp (mkTyCon ",,")
-- [fTy,fTy,fTy])
--
-- returns "(Foo,Foo,Foo)"
--
-- The TypeRep Show instance promises to print tuple types
-- correctly. Tuple type constructors are specified by a
-- sequence of commas, e.g., (mkTyCon ",,,,") returns
-- the 5-tuple tycon.
----------------- Construction --------------------
-- | Applies a type constructor to a sequence of types
mkTyConApp :: TyCon -> [TypeRep] -> TypeRep
mkTyConApp tc@(TyCon tc_k _) args
= TypeRep (appKeys tc_k arg_ks) tc args
where
arg_ks = [k | TypeRep k _ _ <- args]
-- | A special case of 'mkTyConApp', which applies the function
-- type constructor to a pair of types.
mkFunTy :: TypeRep -> TypeRep -> TypeRep
mkFunTy f a = mkTyConApp funTc [f,a]
-- | Splits a type constructor application
splitTyConApp :: TypeRep -> (TyCon,[TypeRep])
splitTyConApp (TypeRep _ tc trs) = (tc,trs)
-- | Applies a type to a function type. Returns: @'Just' u@ if the
-- first argument represents a function of type @t -> u@ and the
-- second argument represents a function of type @t@. Otherwise,
-- returns 'Nothing'.
funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep
funResultTy trFun trArg
= case splitTyConApp trFun of
(tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2
_ -> Nothing
-- | Adds a TypeRep argument to a TypeRep.
mkAppTy :: TypeRep -> TypeRep -> TypeRep
mkAppTy (TypeRep tr_k tc trs) arg_tr
= let (TypeRep arg_k _ _) = arg_tr
in TypeRep (appKey tr_k arg_k) tc (trs++[arg_tr])
-- If we enforce the restriction that there is only one
-- @TyCon@ for a type & it is shared among all its uses,
-- we can map them onto Ints very simply. The benefit is,
-- of course, that @TyCon@s can then be compared efficiently.
-- Provided the implementor of other @Typeable@ instances
-- takes care of making all the @TyCon@s CAFs (toplevel constants),
-- this will work.
-- If this constraint does turn out to be a sore thumb, changing
-- the Eq instance for TyCons is trivial.
-- | Builds a 'TyCon' object representing a type constructor. An
-- implementation of "Data.Typeable" should ensure that the following holds:
--
-- > mkTyCon "a" == mkTyCon "a"
--
mkTyCon :: String -- ^ the name of the type constructor (should be unique
-- in the program, so it might be wise to use the
-- fully qualified name).
-> TyCon -- ^ A unique 'TyCon' object
mkTyCon str = TyCon (mkTyConKey str) str
----------------- Observation ---------------------
-- | Observe the type constructor of a type representation
typeRepTyCon :: TypeRep -> TyCon
typeRepTyCon (TypeRep _ tc _) = tc
-- | Observe the argument types of a type representation
typeRepArgs :: TypeRep -> [TypeRep]
typeRepArgs (TypeRep _ _ args) = args
-- | Observe string encoding of a type representation
tyConString :: TyCon -> String
tyConString (TyCon _ str) = str
----------------- Showing TypeReps --------------------
instance Show TypeRep where
showsPrec p (TypeRep _ tycon tys) =
case tys of
[] -> showsPrec p tycon
[x] | tycon == listTc -> showChar '[' . shows x . showChar ']'
[a,r] | tycon == funTc -> showParen (p > 8) $
showsPrec 9 a .
showString " -> " .
showsPrec 8 r
xs | isTupleTyCon tycon -> showTuple tycon xs
| otherwise ->
showParen (p > 9) $
showsPrec p tycon .
showChar ' ' .
showArgs tys
instance Show TyCon where
showsPrec _ (TyCon _ s) = showString s
isTupleTyCon :: TyCon -> Bool
isTupleTyCon (TyCon _ (',':_)) = True
isTupleTyCon _ = False
-- Some (Show.TypeRep) helpers:
showArgs :: Show a => [a] -> ShowS
showArgs [] = id
showArgs [a] = showsPrec 10 a
showArgs (a:as) = showsPrec 10 a . showString " " . showArgs as
showTuple :: TyCon -> [TypeRep] -> ShowS
showTuple (TyCon _ str) args = showChar '(' . go str args
where
go [] [a] = showsPrec 10 a . showChar ')'
go _ [] = showChar ')' -- a failure condition, really.
go (',':xs) (a:as) = showsPrec 10 a . showChar ',' . go xs as
go _ _ = showChar ')'
-------------------------------------------------------------
--
-- The Typeable class and friends
--
-------------------------------------------------------------
-- | The class 'Typeable' allows a concrete representation of a type to
-- be calculated.
class Typeable a where
typeOf :: a -> TypeRep
-- ^ Takes a value of type @a@ and returns a concrete representation
-- of that type. The /value/ of the argument should be ignored by
-- any instance of 'Typeable', so that it is safe to pass 'undefined' as
-- the argument.
-- | Variant for unary type constructors
class Typeable1 t where
typeOf1 :: t a -> TypeRep
-- | For defining a 'Typeable' instance from any 'Typeable1' instance.
typeOfDefault :: (Typeable1 t, Typeable a) => t a -> TypeRep
typeOfDefault x = typeOf1 x `mkAppTy` typeOf (argType x)
where
argType :: t a -> a
argType = undefined
-- | Variant for binary type constructors
class Typeable2 t where
typeOf2 :: t a b -> TypeRep
-- | For defining a 'Typeable1' instance from any 'Typeable2' instance.
typeOf1Default :: (Typeable2 t, Typeable a) => t a b -> TypeRep
typeOf1Default x = typeOf2 x `mkAppTy` typeOf (argType x)
where
argType :: t a b -> a
argType = undefined
-- | Variant for 3-ary type constructors
class Typeable3 t where
typeOf3 :: t a b c -> TypeRep
-- | For defining a 'Typeable2' instance from any 'Typeable3' instance.
typeOf2Default :: (Typeable3 t, Typeable a) => t a b c -> TypeRep
typeOf2Default x = typeOf3 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c -> a
argType = undefined
-- | Variant for 4-ary type constructors
class Typeable4 t where
typeOf4 :: t a b c d -> TypeRep
-- | For defining a 'Typeable3' instance from any 'Typeable4' instance.
typeOf3Default :: (Typeable4 t, Typeable a) => t a b c d -> TypeRep
typeOf3Default x = typeOf4 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d -> a
argType = undefined
-- | Variant for 5-ary type constructors
class Typeable5 t where
typeOf5 :: t a b c d e -> TypeRep
-- | For defining a 'Typeable4' instance from any 'Typeable5' instance.
typeOf4Default :: (Typeable5 t, Typeable a) => t a b c d e -> TypeRep
typeOf4Default x = typeOf5 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d e -> a
argType = undefined
-- | Variant for 6-ary type constructors
class Typeable6 t where
typeOf6 :: t a b c d e f -> TypeRep
-- | For defining a 'Typeable5' instance from any 'Typeable6' instance.
typeOf5Default :: (Typeable6 t, Typeable a) => t a b c d e f -> TypeRep
typeOf5Default x = typeOf6 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d e f -> a
argType = undefined
-- | Variant for 7-ary type constructors
class Typeable7 t where
typeOf7 :: t a b c d e f g -> TypeRep
-- | For defining a 'Typeable6' instance from any 'Typeable7' instance.
typeOf6Default :: (Typeable7 t, Typeable a) => t a b c d e f g -> TypeRep
typeOf6Default x = typeOf7 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d e f g -> a
argType = undefined
#ifdef __GLASGOW_HASKELL__
-- Given a @Typeable@/n/ instance for an /n/-ary type constructor,
-- define the instances for partial applications.
-- Programmers using non-GHC implementations must do this manually
-- for each type constructor.
-- (The INSTANCE_TYPEABLE/n/ macros in Typeable.h include this.)
-- | One Typeable instance for all Typeable1 instances
instance (Typeable1 s, Typeable a)
=> Typeable (s a) where
typeOf = typeOfDefault
-- | One Typeable1 instance for all Typeable2 instances
instance (Typeable2 s, Typeable a)
=> Typeable1 (s a) where
typeOf1 = typeOf1Default
-- | One Typeable2 instance for all Typeable3 instances
instance (Typeable3 s, Typeable a)
=> Typeable2 (s a) where
typeOf2 = typeOf2Default
-- | One Typeable3 instance for all Typeable4 instances
instance (Typeable4 s, Typeable a)
=> Typeable3 (s a) where
typeOf3 = typeOf3Default
-- | One Typeable4 instance for all Typeable5 instances
instance (Typeable5 s, Typeable a)
=> Typeable4 (s a) where
typeOf4 = typeOf4Default
-- | One Typeable5 instance for all Typeable6 instances
instance (Typeable6 s, Typeable a)
=> Typeable5 (s a) where
typeOf5 = typeOf5Default
-- | One Typeable6 instance for all Typeable7 instances
instance (Typeable7 s, Typeable a)
=> Typeable6 (s a) where
typeOf6 = typeOf6Default
#endif /* __GLASGOW_HASKELL__ */
-------------------------------------------------------------
--
-- Type-safe cast
--
-------------------------------------------------------------
-- | The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b
cast x = r
where
r = if typeOf x == typeOf (fromJust r)
then Just $ unsafeCoerce x
else Nothing
-- | A flexible variation parameterised in a type constructor
gcast :: (Typeable a, Typeable b) => c a -> Maybe (c b)
gcast x = r
where
r = if typeOf (getArg x) == typeOf (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> *
gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
gcast1 x = r
where
r = if typeOf1 (getArg x) == typeOf1 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-- | Cast for * -> * -> *
gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))
gcast2 x = r
where
r = if typeOf2 (getArg x) == typeOf2 (getArg (fromJust r))
then Just $ unsafeCoerce x
else Nothing
getArg :: c x -> x
getArg = undefined
-------------------------------------------------------------
--
-- Instances of the Typeable classes for Prelude types
--
-------------------------------------------------------------
INSTANCE_TYPEABLE0((),unitTc,"()")
INSTANCE_TYPEABLE1([],listTc,"[]")
INSTANCE_TYPEABLE1(Maybe,maybeTc,"Maybe")
INSTANCE_TYPEABLE1(Ratio,ratioTc,"Ratio")
INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
INSTANCE_TYPEABLE2((->),funTc,"->")
INSTANCE_TYPEABLE1(IO,ioTc,"IO")
#if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
-- Types defined in GHC.IOBase
INSTANCE_TYPEABLE1(MVar,mvarTc,"MVar" )
INSTANCE_TYPEABLE0(Exception,exceptionTc,"Exception")
INSTANCE_TYPEABLE0(IOException,ioExceptionTc,"IOException")
INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
#endif
-- Types defined in GHC.Arr
INSTANCE_TYPEABLE2(Array,arrayTc,"Array")
#ifdef __GLASGOW_HASKELL__
-- Hugs has these too, but their Typeable<n> instances are defined
-- elsewhere to keep this module within Haskell 98.
-- This is important because every invocation of runhugs or ffihugs
-- uses this module via Data.Dynamic.
INSTANCE_TYPEABLE2(ST,stTc,"ST")
INSTANCE_TYPEABLE2(STRef,stRefTc,"STRef")
INSTANCE_TYPEABLE3(STArray,sTArrayTc,"STArray")
#endif
#ifndef __NHC__
INSTANCE_TYPEABLE2((,),pairTc,",")
INSTANCE_TYPEABLE3((,,),tup3Tc,",,")
tup4Tc :: TyCon
tup4Tc = mkTyCon ",,,"
instance Typeable4 (,,,) where
typeOf4 tu = mkTyConApp tup4Tc []
tup5Tc :: TyCon
tup5Tc = mkTyCon ",,,,"
instance Typeable5 (,,,,) where
typeOf5 tu = mkTyConApp tup5Tc []
tup6Tc :: TyCon
tup6Tc = mkTyCon ",,,,,"
instance Typeable6 (,,,,,) where
typeOf6 tu = mkTyConApp tup6Tc []
tup7Tc :: TyCon
tup7Tc = mkTyCon ",,,,,,"
instance Typeable7 (,,,,,,) where
typeOf7 tu = mkTyConApp tup7Tc []
#endif /* __NHC__ */
INSTANCE_TYPEABLE1(Ptr,ptrTc,"Ptr")
INSTANCE_TYPEABLE1(FunPtr,funPtrTc,"FunPtr")
INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
INSTANCE_TYPEABLE1(StablePtr,stablePtrTc,"StablePtr")
INSTANCE_TYPEABLE1(IORef,iORefTc,"IORef")
-------------------------------------------------------
--
-- Generate Typeable instances for standard datatypes
--
-------------------------------------------------------
INSTANCE_TYPEABLE0(Bool,boolTc,"Bool")
INSTANCE_TYPEABLE0(Char,charTc,"Char")
INSTANCE_TYPEABLE0(Float,floatTc,"Float")
INSTANCE_TYPEABLE0(Double,doubleTc,"Double")
INSTANCE_TYPEABLE0(Int,intTc,"Int")
#ifndef __NHC__
INSTANCE_TYPEABLE0(Word,wordTc,"Word" )
#endif
INSTANCE_TYPEABLE0(Integer,integerTc,"Integer")
INSTANCE_TYPEABLE0(Ordering,orderingTc,"Ordering")
INSTANCE_TYPEABLE0(Handle,handleTc,"Handle")
INSTANCE_TYPEABLE0(Int8,int8Tc,"Int8")
INSTANCE_TYPEABLE0(Int16,int16Tc,"Int16")
INSTANCE_TYPEABLE0(Int32,int32Tc,"Int32")
INSTANCE_TYPEABLE0(Int64,int64Tc,"Int64")
INSTANCE_TYPEABLE0(Word8,word8Tc,"Word8" )
INSTANCE_TYPEABLE0(Word16,word16Tc,"Word16")
INSTANCE_TYPEABLE0(Word32,word32Tc,"Word32")
INSTANCE_TYPEABLE0(Word64,word64Tc,"Word64")
INSTANCE_TYPEABLE0(TyCon,tyconTc,"TyCon")
INSTANCE_TYPEABLE0(TypeRep,typeRepTc,"TypeRep")
#ifdef __GLASGOW_HASKELL__
INSTANCE_TYPEABLE0(RealWorld,realWorldTc,"RealWorld")
#endif
---------------------------------------------
--
-- Internals
--
---------------------------------------------
#ifndef __HUGS__
newtype Key = Key Int deriving( Eq )
#endif
data KeyPr = KeyPr !Key !Key deriving( Eq )
hashKP :: KeyPr -> Int32
hashKP (KeyPr (Key k1) (Key k2)) = (HT.hashInt k1 + HT.hashInt k2) `rem` HT.prime
data Cache = Cache { next_key :: !(IORef Key), -- Not used by GHC (calls genSym instead)
tc_tbl :: !(HT.HashTable String Key),
ap_tbl :: !(HT.HashTable KeyPr Key) }
{-# NOINLINE cache #-}
#ifdef __GLASGOW_HASKELL__
foreign import ccall unsafe "RtsTypeable.h getOrSetTypeableStore"
getOrSetTypeableStore :: Ptr a -> IO (Ptr a)
#endif
cache :: Cache
cache = unsafePerformIO $ do
empty_tc_tbl <- HT.new (==) HT.hashString
empty_ap_tbl <- HT.new (==) hashKP
key_loc <- newIORef (Key 1)
let ret = Cache { next_key = key_loc,
tc_tbl = empty_tc_tbl,
ap_tbl = empty_ap_tbl }
#ifdef __GLASGOW_HASKELL__
block $ do
stable_ref <- newStablePtr ret
let ref = castStablePtrToPtr stable_ref
ref2 <- getOrSetTypeableStore ref
if ref==ref2
then deRefStablePtr stable_ref
else do
freeStablePtr stable_ref
deRefStablePtr
(castPtrToStablePtr ref2)
#else
return ret
#endif
newKey :: IORef Key -> IO Key
#ifdef __GLASGOW_HASKELL__
newKey kloc = do i <- genSym; return (Key i)
#else
newKey kloc = do { k@(Key i) <- readIORef kloc ;
writeIORef kloc (Key (i+1)) ;
return k }
#endif
#ifdef __GLASGOW_HASKELL__
foreign import ccall unsafe "genSymZh"
genSym :: IO Int
#endif
mkTyConKey :: String -> Key
mkTyConKey str
= unsafePerformIO $ do
let Cache {next_key = kloc, tc_tbl = tbl} = cache
mb_k <- HT.lookup tbl str
case mb_k of
Just k -> return k
Nothing -> do { k <- newKey kloc ;
HT.insert tbl str k ;
return k }
appKey :: Key -> Key -> Key
appKey k1 k2
= unsafePerformIO $ do
let Cache {next_key = kloc, ap_tbl = tbl} = cache
mb_k <- HT.lookup tbl kpr
case mb_k of
Just k -> return k
Nothing -> do { k <- newKey kloc ;
HT.insert tbl kpr k ;
return k }
where
kpr = KeyPr k1 k2
appKeys :: Key -> [Key] -> Key
appKeys k ks = foldl appKey k ks
| alekar/hugs | packages/base/Data/Typeable.hs | bsd-3-clause | 21,045 | 143 | 16 | 4,010 | 4,899 | 2,699 | 2,200 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.UI.SDL.TTF.Render
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : lemmih@gmail.com
-- Stability : provisional
-- Portability : portable
--
-----------------------------------------------------------------------------
{-# CFILES Graphics/UI/SDL/TTF/Wrapper.c #-}
module Graphics.UI.SDL.TTF.Render
( tryRenderTextSolid
, renderTextSolid
, tryRenderUTF8Solid
, renderUTF8Solid
, tryRenderGlyphSolid
, renderGlyphSolid
, tryRenderTextShaded
, renderTextShaded
, tryRenderUTF8Shaded
, renderUTF8Shaded
, tryRenderGlyphShaded
, renderGlyphShaded
, tryRenderTextBlended
, renderTextBlended
, tryRenderUTF8Blended
, renderUTF8Blended
, tryRenderGlyphBlended
, renderGlyphBlended
) where
import Graphics.UI.SDL.TTF.Types
import Graphics.UI.SDL.General
import Graphics.UI.SDL.Video
import Graphics.UI.SDL.Color
import Graphics.UI.SDL.Types
import Foreign
import Foreign.C
import Data.Char
renderOneColor :: (Ptr FontStruct -> CString -> Ptr Color -> IO (Ptr SurfaceStruct))
-> Font -> String -> Color -> IO (Maybe Surface)
renderOneColor render font text color
= withForeignPtr font $ \fontPtr ->
withCString text $ \cString ->
with color $ \colorPtr ->
do image <- render fontPtr cString colorPtr
if image == nullPtr
then return Nothing
else fmap Just (mkFinalizedSurface image)
renderTwoColor :: (Ptr FontStruct -> CString -> Ptr Color -> Ptr Color -> IO (Ptr SurfaceStruct))
-> Font -> String -> Color -> Color -> IO (Maybe Surface)
renderTwoColor render font text color1 color2
= withForeignPtr font $ \fontPtr ->
withCString text $ \cString ->
with color1 $ \colorPtr1 ->
with color2 $ \colorPtr2 ->
do image <- render fontPtr cString colorPtr1 colorPtr2
if image == nullPtr
then return Nothing
else fmap Just (mkFinalizedSurface image)
--------------------------------------------------------------
-- Solid
--------------------------------------------------------------
-- SDL_Surface *TTF_RenderText_Solid(TTF_Font *font, const char *text, SDL_Color fg)
foreign import ccall unsafe "renderTextSolid" ttfRenderTextSolid
:: Ptr FontStruct -> CString -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderTextSolid :: Font -> String -> Color -> IO (Maybe Surface)
tryRenderTextSolid = renderOneColor ttfRenderTextSolid
renderTextSolid :: Font -> String -> Color -> IO Surface
renderTextSolid font text color
= unwrapMaybe "TTF_RenderText_Solid" (tryRenderTextSolid font text color)
-- SDL_Surface * SDLCALL TTF_RenderUTF8_Solid(TTF_Font *font, const char *text, SDL_Color fg);
foreign import ccall unsafe "renderUTF8Solid" ttfRenderUTF8Solid
:: Ptr FontStruct -> CString -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderUTF8Solid :: Font -> String -> Color -> IO (Maybe Surface)
tryRenderUTF8Solid = renderOneColor ttfRenderUTF8Solid
renderUTF8Solid :: Font -> String -> Color -> IO Surface
renderUTF8Solid font text color
= unwrapMaybe "TTF_RenderUTF8_Solid" (tryRenderUTF8Solid font text color)
-- SDL_Surface * renderGlyphSolid(TTF_Font *font, Uint16 ch, SDL_Color *fg);
foreign import ccall unsafe "renderGlyphSolid" renderGlyphSolid
:: Ptr FontStruct -> Word16 -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderGlyphSolid :: Font -> Char -> Color -> IO (Maybe Surface)
tryRenderGlyphSolid font ch fg
= withForeignPtr font $ \fontPtr ->
with fg $ \color ->
do image <- renderGlyphSolid fontPtr (fromIntegral (ord ch)) color
if image == nullPtr
then return Nothing
else fmap Just (mkFinalizedSurface image)
--------------------------------------------------------------
-- Shaded
--------------------------------------------------------------
-- SDL_Surface *TTF_RenderText_Shaded(TTF_Font *font, const char *text, SDL_Color fg)
foreign import ccall unsafe "renderTextShaded" ttfRenderTextShaded
:: Ptr FontStruct -> CString -> Ptr Color -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderTextShaded :: Font -> String -> Color -> Color -> IO (Maybe Surface)
tryRenderTextShaded = renderTwoColor ttfRenderTextShaded
renderTextShaded :: Font -> String -> Color -> Color -> IO Surface
renderTextShaded font text fg bg
= unwrapMaybe "TTF_RenderText_Shaded" (tryRenderTextShaded font text fg bg)
-- SDL_Surface * SDLCALL TTF_RenderUTF8_Shaded(TTF_Font *font, const char *text, SDL_Color fg);
foreign import ccall unsafe "renderUTF8Shaded" ttfRenderUTF8Shaded
:: Ptr FontStruct -> CString -> Ptr Color -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderUTF8Shaded :: Font -> String -> Color -> Color -> IO (Maybe Surface)
tryRenderUTF8Shaded = renderTwoColor ttfRenderUTF8Shaded
renderUTF8Shaded :: Font -> String -> Color -> Color -> IO Surface
renderUTF8Shaded font text fg bg
= unwrapMaybe "TTF_RenderUTF8_Shaded" (tryRenderUTF8Shaded font text fg bg)
-- SDL_Surface * renderGlyphShaded(TTF_Font *font, Uint16 ch, SDL_Color *fg);
foreign import ccall unsafe "renderGlyphShaded" renderGlyphShaded
:: Ptr FontStruct -> Word16 -> Ptr Color -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderGlyphShaded :: Font -> Char -> Color -> Color -> IO (Maybe Surface)
tryRenderGlyphShaded font ch fg bg
= withForeignPtr font $ \fontPtr ->
with fg $ \fgPtr ->
with bg $ \bgPtr ->
do image <- renderGlyphShaded fontPtr (fromIntegral (ord ch)) fgPtr bgPtr
if image == nullPtr
then return Nothing
else fmap Just (mkFinalizedSurface image)
--------------------------------------------------------------
-- Blended
--------------------------------------------------------------
-- SDL_Surface *TTF_RenderText_Blended(TTF_Font *font, const char *text, SDL_Color fg)
foreign import ccall unsafe "renderTextBlended" ttfRenderTextBlended
:: Ptr FontStruct -> CString -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderTextBlended :: Font -> String -> Color -> IO (Maybe Surface)
tryRenderTextBlended = renderOneColor ttfRenderTextBlended
renderTextBlended :: Font -> String -> Color -> IO Surface
renderTextBlended font text color
= unwrapMaybe "TTF_RenderText_Blended" (tryRenderTextBlended font text color)
-- SDL_Surface * SDLCALL TTF_RenderUTF8_Blended(TTF_Font *font, const char *text, SDL_Color fg);
foreign import ccall unsafe "renderUTF8Blended" ttfRenderUTF8Blended
:: Ptr FontStruct -> CString -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderUTF8Blended :: Font -> String -> Color -> IO (Maybe Surface)
tryRenderUTF8Blended = renderOneColor ttfRenderUTF8Blended
renderUTF8Blended :: Font -> String -> Color -> IO Surface
renderUTF8Blended font text color
= unwrapMaybe "TTF_RenderUTF8_Blended" (tryRenderUTF8Blended font text color)
-- SDL_Surface * renderGlyphBlended(TTF_Font *font, Uint16 ch, SDL_Color *fg);
foreign import ccall unsafe "renderGlyphBlended" renderGlyphBlended
:: Ptr FontStruct -> Word16 -> Ptr Color -> IO (Ptr SurfaceStruct)
tryRenderGlyphBlended :: Font -> Char -> Color -> IO (Maybe Surface)
tryRenderGlyphBlended font ch fg
= withForeignPtr font $ \fontPtr ->
with fg $ \color ->
do image <- renderGlyphBlended fontPtr (fromIntegral (ord ch)) color
if image == nullPtr
then return Nothing
else fmap Just (mkFinalizedSurface image)
| joelburget/sdl2-ttf | Graphics/UI/SDL/TTF/Render.hs | bsd-3-clause | 7,540 | 0 | 18 | 1,362 | 1,748 | 891 | 857 | 121 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.GHC.ImplInfo
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This module contains the data structure describing invocation
-- details for a GHC or GHC-derived compiler, such as supported flags
-- and workarounds for bugs.
module Distribution.Simple.GHC.ImplInfo (
GhcImplInfo(..), getImplInfo,
ghcVersionImplInfo, ghcjsVersionImplInfo, lhcVersionImplInfo
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Simple.Compiler
import Distribution.Version
{- |
Information about features and quirks of a GHC-based implementation.
Compiler flavors based on GHC behave similarly enough that some of
the support code for them is shared. Every implementation has its
own peculiarities, that may or may not be a direct result of the
underlying GHC version. This record keeps track of these differences.
All shared code (i.e. everything not in the Distribution.Simple.FLAVOR
module) should use implementation info rather than version numbers
to test for supported features.
-}
data GhcImplInfo = GhcImplInfo
{ supportsHaskell2010 :: Bool -- ^ -XHaskell2010 and -XHaskell98 flags
, reportsNoExt :: Bool -- ^ --supported-languages gives Ext and NoExt
, alwaysNondecIndent :: Bool -- ^ NondecreasingIndentation is always on
, flagGhciScript :: Bool -- ^ -ghci-script flag supported
, flagProfAuto :: Bool -- ^ new style -fprof-auto* flags
, flagPackageConf :: Bool -- ^ use package-conf instead of package-db
, flagDebugInfo :: Bool -- ^ -g flag supported
, supportsPkgEnvFiles :: Bool -- ^ picks up @.ghc.environment@ files
, flagWarnMissingHomeModules :: Bool -- ^ -Wmissing-home-modules is supported
}
getImplInfo :: Compiler -> GhcImplInfo
getImplInfo comp =
case compilerFlavor comp of
GHC -> ghcVersionImplInfo (compilerVersion comp)
LHC -> lhcVersionImplInfo (compilerVersion comp)
GHCJS -> case compilerCompatVersion GHC comp of
Just ghcVer -> ghcjsVersionImplInfo (compilerVersion comp) ghcVer
_ -> error ("Distribution.Simple.GHC.Props.getImplProps: " ++
"could not find GHC version for GHCJS compiler")
x -> error ("Distribution.Simple.GHC.Props.getImplProps only works" ++
"for GHC-like compilers (GHC, GHCJS, LHC)" ++
", but found " ++ show x)
ghcVersionImplInfo :: Version -> GhcImplInfo
ghcVersionImplInfo ver = GhcImplInfo
{ supportsHaskell2010 = v >= [7]
, reportsNoExt = v >= [7]
, alwaysNondecIndent = v < [7,1]
, flagGhciScript = v >= [7,2]
, flagProfAuto = v >= [7,4]
, flagPackageConf = v < [7,5]
, flagDebugInfo = v >= [7,10]
, supportsPkgEnvFiles = v >= [8,0,1,20160901] -- broken in 8.0.1, fixed in 8.0.2
, flagWarnMissingHomeModules = v >= [8,2]
}
where
v = versionNumbers ver
ghcjsVersionImplInfo :: Version -- ^ The GHCJS version
-> Version -- ^ The GHC version
-> GhcImplInfo
ghcjsVersionImplInfo _ghcjsver ghcver = GhcImplInfo
{ supportsHaskell2010 = True
, reportsNoExt = True
, alwaysNondecIndent = False
, flagGhciScript = True
, flagProfAuto = True
, flagPackageConf = False
, flagDebugInfo = False
, supportsPkgEnvFiles = ghcv >= [8,0,2] --TODO: check this works in ghcjs
, flagWarnMissingHomeModules = False
}
where
ghcv = versionNumbers ghcver
lhcVersionImplInfo :: Version -> GhcImplInfo
lhcVersionImplInfo = ghcVersionImplInfo
| mydaum/cabal | Cabal/Distribution/Simple/GHC/ImplInfo.hs | bsd-3-clause | 3,761 | 0 | 13 | 901 | 560 | 338 | 222 | 57 | 5 |
module Network.HPACK.Builder where
newtype Builder a = Builder ([a] -> [a])
(<<) :: Builder a -> a -> Builder a
Builder b << entry = Builder $ b . (entry :)
empty :: Builder a
empty = Builder id
singleton :: a -> Builder a
singleton x = Builder (x :)
run :: Builder a -> [a]
run (Builder b) = b []
| bergmark/http2 | Network/HPACK/Builder.hs | bsd-3-clause | 303 | 0 | 8 | 68 | 153 | 82 | 71 | 10 | 1 |
module Api.Mailers.Verify where
import Network.Mail.Mime hiding (simpleMail)
import Network.Mail.SMTP (simpleMail)
import Text.Email.Validate (toByteString)
import qualified Data.ByteString.Lazy.Char8 as LC
import qualified Data.Text as ST
import qualified Data.Text.Encoding as SE
import Api.Types.PendingUserResource
import Api.Types.Fields
mkEmail :: PendingUserResource -> Mail
mkEmail pending = simpleMail from to cc bcc subject parts
where
from = Address (Just "Api") "no-reply@example.com"
to = [Address Nothing $ addr pending]
cc = []
bcc = []
subject = "Verify your email address"
parts = [Part { partType = "text/plain"
, partEncoding = QuotedPrintableText
, partFilename = Nothing
, partHeaders = []
, partContent = body pending
}]
-- private functions
body :: PendingUserResource -> LC.ByteString
body pending = LC.concat
[ "Verify your email by clicking this link: https://example.com/verify/"
, uuid pending
]
addr :: PendingUserResource -> ST.Text
addr pending = SE.decodeUtf8 $ toByteString e
where
(ResourceEmail e) = pend_resourceEmail $ pend_fields pending
uuid :: PendingUserResource -> LC.ByteString
uuid pending = LC.fromStrict $ SE.encodeUtf8 u
where
(PendingUUID u) = pend_uuid pending
| cawinkelmann/api-server | lib/Api/Mailers/Verify.hs | mit | 1,401 | 0 | 10 | 352 | 340 | 193 | 147 | 31 | 1 |
{-# LANGUAGE CPP #-}
{- |
Module : $Header$
Description : Menu creation functions for the Graphdisplay
Copyright : (c) Thiemo Wiedemeyer, Uni Bremen 2002-2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : raider@informatik.uni-bremen.de
Stability : provisional
Portability : non-portable (imports Logic)
Menu creation
-}
module GUI.GraphMenu (createGraph) where
import qualified GUI.GraphAbstraction as GA
import GUI.GraphTypes
import GUI.GraphLogic
import GUI.Utils
import GUI.UDGUtils
#ifdef GTKGLADE
import GUI.GtkDisprove
import GUI.GtkConsistencyChecker
import GUI.GtkAutomaticProofs
import GUI.GtkAddSentence
#endif
import Data.IORef
import qualified Data.Map as Map
import System.Directory (getCurrentDirectory)
import System.FilePath
import Static.DevGraph
import Static.DgUtils
import Static.PrintDevGraph ()
import Static.ComputeTheory (computeTheory)
import Static.ConsInclusions
import qualified Proofs.VSE as VSE
import Common.DocUtils
import Driver.Options (HetcatsOpts, rmSuffix, prfSuffix)
import Driver.ReadFn (libNameToFile)
import Interfaces.DataTypes
import Interfaces.Command
import Interfaces.CmdAction
import GUI.ShowRefTree
-- | Adds to the DGNodeType list style options for each type
nodeTypes :: HetcatsOpts
-> [( DGNodeType -- Nodetype
, Shape GA.NodeValue -- Shape
, String -- Color
)]
nodeTypes opts = map
((\ (n, s) -> if isProvenNode n then -- Add color
if isProvenCons n
then (n, s, getColor opts Green True False)
else (n, s, getColor opts Yellow False True)
else (n, s, getColor opts Coral False $ isProvenCons n))
. \ n -> (n, if isRefType n then Box else Ellipse) -- Add shape
) listDGNodeTypes
-- | A Map of all nodetypes and their properties.
mapNodeTypes :: HetcatsOpts -> Map.Map DGNodeType (Shape GA.NodeValue, String)
mapNodeTypes = Map.fromList . map (\ (n, s, c) -> (n, (s, c))) . nodeTypes
-- | Adds to the DGEdgeType list style options for each type
edgeTypes :: HetcatsOpts
-> [( DGEdgeType -- Edgetype
, EdgePattern GA.EdgeValue -- Lineformat
, String -- Color
, Bool -- has conservativity
)]
edgeTypes opts = map
( (\ (e, l, c) -> case edgeTypeModInc e of -- Add menu options
ThmType { thmEdgeType = GlobalOrLocalThm _ _ } -> (e, l, c, True)
GlobalDef -> (e, l, c, True)
HetDef -> (e, l, c, True)
LocalDef -> (e, l, c, True)
_ -> (e, l, c, False)
)
. (\ (e, l) -> case edgeTypeModInc e of -- Add colors
HidingDef -> (e, l, getColor opts Blue True $ not $ isInc e)
FreeOrCofreeDef _ -> (e, l, getColor opts Blue False $ not $ isInc e)
ThmType { thmEdgeType = thmType
, isProvenEdge = False } -> case thmType of
GlobalOrLocalThm { thmScope = Local, isHomThm = False }
-> (e, l, getColor opts Coral True $ not $ isInc e)
HidingThm -> (e, l, getColor opts Yellow False $ not $ isInc e)
_ -> (e, l, getColor opts Coral False $ not $ isInc e)
ThmType { thmEdgeType = thmType
, isConservativ = False } -> case thmType of
GlobalOrLocalThm { thmScope = Local, isHomThm = False }
-> (e, l, getColor opts Yellow True $ not $ isInc e)
_ -> (e, l, getColor opts Yellow False $ not $ isInc e)
ThmType { thmEdgeType = thmType
, isPending = True } -> case thmType of
GlobalOrLocalThm { thmScope = Local, isHomThm = False }
-> (e, l, getColor opts Yellow True $ not $ isInc e)
_ -> (e, l, getColor opts Yellow False $ not $ isInc e)
ThmType { thmEdgeType = thmType } -> case thmType of
GlobalOrLocalThm { thmScope = Local, isHomThm = False }
-> (e, l, getColor opts Green True $ not $ isInc e)
HidingThm -> (e, l, getColor opts Green True $ not $ isInc e)
_ -> (e, l, getColor opts Green False $ not $ isInc e)
_ -> (e, l, getColor opts Black False $ not $ isInc e)
)
. (\ e -> case edgeTypeModInc e of -- Add lineformat
ThmType { thmEdgeType = GlobalOrLocalThm { thmScope = Local
, isHomThm = True } }
-> (e, Dashed)
ThmType { thmEdgeType = GlobalOrLocalThm { isHomThm = False } }
-> (e, Double)
LocalDef -> (e, Dashed)
HetDef -> (e, Double)
_ -> (e, Solid)
)
) listDGEdgeTypes
-- | A Map of all edgetypes and their properties.
mapEdgeTypes
:: HetcatsOpts -> Map.Map DGEdgeType (EdgePattern GA.EdgeValue, String)
mapEdgeTypes =
Map.fromList . map (\ (e, l, c, _) -> (e, (l, c))) . edgeTypes
-- | Creates the graph. Runs makegraph
createGraph :: GInfo -> String -> ConvFunc -> LibFunc -> IO ()
createGraph gi title convGraph showLib = do
ost <- readIORef $ intState gi
case i_state ost of
Nothing -> return ()
Just _ -> do
let ln = libName gi
opts = options gi
file = libNameToFile ln ++ prfSuffix
deselectEdgeTypes <- newIORef []
globMenu <- createGlobalMenu gi showLib deselectEdgeTypes
GA.makeGraph (graphInfo gi)
title
(createOpen gi file convGraph showLib)
(createSave gi file)
(createSaveAs gi file)
(createClose gi)
(Just (exitGInfo gi))
globMenu
(createNodeTypes gi convGraph showLib)
(createEdgeTypes gi)
(getColor (hetcatsOpts gi) Purple False False)
$ runAndLock gi $ do
flags <- readIORef opts
writeIORef opts $ flags { flagHideNodes = False}
updateGraph gi []
-- | Returns the open-function
createOpen :: GInfo -> FilePath -> ConvFunc -> LibFunc -> Maybe (IO ())
createOpen gi file convGraph showLib = Just (
do
maybeFilePath <- fileOpenDialog file [ ("Proof", ["*.prf"])
, ("All Files", ["*"])] Nothing
case maybeFilePath of
Just fPath -> do
openProofStatus gi fPath convGraph showLib
return ()
Nothing -> fail "Could not open file."
)
-- | Returns the save-function
createSave :: GInfo -> FilePath -> Maybe (IO ())
createSave gi = Just . saveProofStatus gi
-- | Returns the saveas-function
createSaveAs :: GInfo -> FilePath -> Maybe (IO ())
createSaveAs gi file = Just (
do
maybeFilePath <- fileSaveDialog file [ ("Proof", ["*.prf"])
, ("All Files", ["*"])] Nothing
case maybeFilePath of
Just fPath -> saveProofStatus gi fPath
Nothing -> fail "Could not save file."
)
-- | Returns the close-function
createClose :: GInfo -> IO Bool
createClose gi = do
let oGrRef = openGraphs gi
updateWindowCount gi pred
oGraphs <- readIORef oGrRef
writeIORef oGrRef $ Map.delete (libName gi) oGraphs
return True
-- | Creates the global menu
createGlobalMenu :: GInfo -> LibFunc -> IORef [String]
-> IO [GlobalMenu]
createGlobalMenu gi showLib _ = do
ost <- readIORef $ intState gi
case i_state ost of
Nothing -> return []
Just _ -> do
let ln = libName gi
opts = hetcatsOpts gi
ral = runAndLock gi
performProofMenuAction cmd =
ral . proofMenu gi cmd
mkGlobProofButton cmd =
Button (menuTextGlobCmd cmd) . performProofMenuAction (GlobCmd cmd)
return
[GlobalMenu (Menu Nothing
[ Button "Undo" $ ral $ undo gi True
, Button "Redo" $ ral $ undo gi False
, Menu (Just "Hide/Show names/nodes/edges")
[ Button "Hide/Show internal node names"
$ ral $ toggleHideNames gi
, Button "Hide/Show unnamed nodes without open proofs"
$ ral $ toggleHideNodes gi
, Button "Hide/Show newly added proven edges"
$ ral $ toggleHideEdges gi
]
, Button "Focus node" $ ral $ focusNode gi
#ifdef GTKGLADE
, Button "Consistency checker"
(performProofMenuAction (GlobCmd CheckConsistencyCurrent)
$ showConsistencyChecker Nothing gi)
, Button "Automatic proofs"
(performProofMenuAction (CommentCmd "generated by \"automatic proofs\"")
$ showAutomaticProofs gi)
#endif
, Menu (Just "Proofs") $ map (\ (cmd, act) ->
mkGlobProofButton cmd $ return . return . act ln) globLibAct
++ map (\ (cmd, act) -> mkGlobProofButton cmd $ return . act ln)
globLibResultAct
++ [ Menu (Just "Flattening") $ map ( \ (cmd, act) ->
mkGlobProofButton cmd $ return . act) globResultAct ]
, Button "Dump Development Graph" $ do
ost2 <- readIORef $ intState gi
case i_state ost2 of
Nothing -> putStrLn "no lib"
Just ist2 -> print . pretty . lookupDGraph (i_ln ist2)
$ i_libEnv ist2
, Button "Dump Cons Inclusions" $ do
ost2 <- readIORef $ intState gi
case i_state ost2 of
Nothing -> putStrLn "no lib"
Just ist2 -> dumpConsInclusions (hetcatsOpts gi)
$ lookupDGraph (i_ln ist2) $ i_libEnv ist2
, Button "Show Library Graph" $ ral $ showLibGraph gi showLib
, Button "Show RefinementTree" $ ral $ showLibGraph gi showRefTree
, Button "Save Graph for uDrawGraph" $ ral
$ saveUDGraph gi (mapNodeTypes opts) $ mapEdgeTypes opts
, Button "Save proof-script" $ ral
$ askSaveProofScript (graphInfo gi) $ intState gi
])
]
-- | A list of all Node Types
createNodeTypes :: GInfo -> ConvFunc -> LibFunc
-> [(DGNodeType, DaVinciNodeTypeParms GA.NodeValue)]
createNodeTypes gi cGraph showLib = map
(\ (n, s, c) -> (n, if isRefType n
then createMenuNodeRef s c gi cGraph showLib $ isInternalSpec n
else createMenuNode s c gi $ isInternalSpec n)) $ nodeTypes $ hetcatsOpts gi
-- | the edge types (share strings to avoid typos)
createEdgeTypes :: GInfo -> [(DGEdgeType, DaVinciArcTypeParms GA.EdgeValue)]
createEdgeTypes gi =
map (\ (title, look, color, hasCons) ->
(title, look
$$$ Color color
$$$ (if hasCons then createEdgeMenuConsEdge gi
else createEdgeMenu gi)
$$$ (if hasCons then createMenuValueTitleShowConservativity
$$$ emptyArcTypeParms :: DaVinciArcTypeParms GA.EdgeValue
else emptyArcTypeParms :: DaVinciArcTypeParms GA.EdgeValue))
) $ edgeTypes $ hetcatsOpts gi
-- * methods to create the local menus of the different nodetypes
titleNormal :: ValueTitle (String, t)
titleNormal = ValueTitle $ return . fst
titleInternal :: GInfo -> ValueTitleSource (String, t)
titleInternal gi =
ValueTitleSource (\ (s, _) -> do
b <- newSimpleBroadcaster ""
let updaterIORef = internalNames gi
updater <- readIORef updaterIORef
let upd = (s, applySimpleUpdate b)
writeIORef updaterIORef $ upd : updater
return $ toSimpleSource b)
-- | local menu for the nodetypes spec and locallyEmpty_spec
createMenuNode :: Shape GA.NodeValue -> String -> GInfo -> Bool
-> DaVinciNodeTypeParms GA.NodeValue
createMenuNode shape color gi internal = shape
$$$ Color color
$$$ (if internal then Just $ titleInternal gi else Nothing)
$$$? (if internal then Nothing else Just titleNormal)
$$$? LocalMenu (Menu Nothing (map ($ gi)
[ createMenuButtonShowNodeInfo
, createMenuButtonShowTheory
, createMenuButtonTranslateTheory
, createMenuTaxonomy
, createMenuButtonShowProofStatusOfNode
, createMenuButtonProveAtNode
, createMenuButtonProveStructured
#ifdef GTKGLADE
, createMenuButtonDisproveAtNode
, createMenuButtonAddSentence
, createMenuButtonCCCAtNode
#endif
, createMenuButtonCheckCons
]))
$$$ emptyNodeTypeParms
-- | local menu for the nodetypes dg_ref and locallyEmpty_dg_ref
createMenuNodeRef :: Shape GA.NodeValue -> String -> GInfo -> ConvFunc
-> LibFunc -> Bool -> DaVinciNodeTypeParms GA.NodeValue
createMenuNodeRef shape color gi convGraph showLib internal = shape
$$$ Color color
$$$ (if internal then Just $ titleInternal gi else Nothing)
$$$? (if internal then Nothing else Just titleNormal)
$$$? LocalMenu (Menu Nothing
[ createMenuButtonShowNodeInfo gi
, createMenuButtonShowTheory gi
, createMenuButtonShowProofStatusOfNode gi
, createMenuButtonProveAtNode gi
#ifdef GTKGLADE
, createMenuButtonDisproveAtNode gi
#endif
, Button "Show referenced library"
(\ (_, n) -> showReferencedLibrary n gi convGraph showLib)
])
$$$ emptyNodeTypeParms
type ButtonMenu a = MenuPrim (Maybe String) (a -> IO ())
-- | menu button for local menus
createMenuButton :: String -> (Int -> DGraph -> IO ())
-> GInfo -> ButtonMenu GA.NodeValue
createMenuButton title menuFun gi = Button title
$ \ (_, descr) -> do
ost <- readIORef $ intState gi
case i_state ost of
Nothing -> return ()
Just ist -> do
let le = i_libEnv ist
dGraph = lookupDGraph (libName gi) le
menuFun descr dGraph
return ()
createMenuButtonShowTheory :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonShowTheory gi =
createMenuButton "Show theory" (getTheoryOfNode gi) gi
createMenuButtonTranslateTheory :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonTranslateTheory gi =
createMenuButton "Translate theory" (translateTheoryOfNode gi) gi
-- | create a sub menu for taxonomy visualisation
createMenuTaxonomy :: GInfo -> ButtonMenu GA.NodeValue
createMenuTaxonomy gi = let
passTh displayFun descr _ = do
ost <- readIORef $ intState gi
case i_state ost of
Nothing -> return ()
Just ist -> case computeTheory (i_libEnv ist) (libName gi) descr of
Just th -> displayFun (show descr) th
Nothing -> errorDialog "Error"
$ "no global theory for node " ++ show descr
in Menu (Just "Taxonomy graphs")
[ createMenuButton "Subsort graph" (passTh displaySubsortGraph) gi
, createMenuButton "Concept graph" (passTh displayConceptGraph) gi ]
createMenuButtonShowProofStatusOfNode :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonShowProofStatusOfNode gi =
createMenuButton "Show proof status" (showProofStatusOfNode gi) gi
createMenuButtonProveAtNode :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonProveAtNode gi =
createMenuButton "Prove" (proveAtNode gi) gi
createMenuButtonProveStructured :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonProveStructured gi =
createMenuButton "Prove VSE Structured" (\ descr _ ->
proofMenu gi (SelectCmd Prover $ "VSE structured: " ++ show descr)
$ VSE.prove (libName gi, descr)) gi
#ifdef GTKGLADE
createMenuButtonDisproveAtNode :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonDisproveAtNode gi =
createMenuButton "Disprove" (disproveAtNode gi) gi
createMenuButtonCCCAtNode :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonCCCAtNode gi =
createMenuButton "Check consistency" (consCheckNode gi) gi
consCheckNode :: GInfo -> Int -> DGraph -> IO ()
consCheckNode gi descr _ = proofMenu gi (GlobCmd CheckConsistencyCurrent)
$ showConsistencyChecker (Just descr) gi
createMenuButtonAddSentence :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonAddSentence gi =
createMenuButton "Add sentence" (gtkAddSentence gi) gi
#endif
createMenuButtonCheckCons :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonCheckCons gi =
createMenuButton "Check conservativity"
(checkconservativityOfNode gi) gi
createMenuButtonShowNodeInfo :: GInfo -> ButtonMenu GA.NodeValue
createMenuButtonShowNodeInfo =
createMenuButton "Show node info" showNodeInfo
-- * methods to create the local menus for the edges
createEdgeMenu :: GInfo -> LocalMenu GA.EdgeValue
createEdgeMenu = LocalMenu . createMenuButtonShowEdgeInfo
createEdgeMenuConsEdge :: GInfo -> LocalMenu GA.EdgeValue
createEdgeMenuConsEdge gi = LocalMenu $ Menu Nothing
[ createMenuButtonShowEdgeInfo gi
, createMenuButtonCheckconservativityOfEdge gi]
createMenuButtonShowEdgeInfo :: GInfo -> ButtonMenu GA.EdgeValue
createMenuButtonShowEdgeInfo _ = Button "Show info"
(\ (_, EdgeId descr, maybeLEdge) -> showEdgeInfo descr maybeLEdge)
createMenuButtonCheckconservativityOfEdge :: GInfo -> ButtonMenu GA.EdgeValue
createMenuButtonCheckconservativityOfEdge gi =
Button "Check conservativity"
(\ (_, EdgeId descr, maybeLEdge) ->
checkconservativityOfEdge descr gi maybeLEdge)
createMenuValueTitleShowConservativity :: ValueTitle GA.EdgeValue
createMenuValueTitleShowConservativity = ValueTitle
(\ (_, _, maybeLEdge) -> return $ case maybeLEdge of
Just (_, _, edgelab) -> showConsStatus $ getEdgeConsStatus edgelab
Nothing -> "")
-- Suggests a proof-script filename.
getProofScriptFileName :: String -> IO FilePath
getProofScriptFileName f = let fn = f <.> "hpf" in
if isAbsolute fn then return fn else
fmap (</> fn) getCurrentDirectory
-- | Displays a Save-As dialog and writes the proof-script.
askSaveProofScript :: GA.GraphInfo -> IORef IntState -> IO ()
askSaveProofScript gi ch = do
h <- readIORef ch
case undoList $ i_hist h of
[] -> infoDialog "Information" "The history is empty. No file written."
_ -> do
ff <- getProofScriptFileName $ rmSuffix $ filename h
maybeFilePath <- fileSaveDialog ff [ ("Proof Script", ["*.hpf"])
, ("All Files", ["*"])] Nothing
case maybeFilePath of
Just fPath -> do
GA.showTemporaryMessage gi "Saving proof script ..."
saveCommandHistory ch fPath
GA.showTemporaryMessage gi $ "Proof script saved to " ++ fPath ++ "!"
Nothing -> GA.showTemporaryMessage gi "Aborted!"
-- Saves the history of commands in a file.
saveCommandHistory :: IORef IntState -> String -> IO ()
saveCommandHistory c f = do
h <- readIORef c
let history = [ "# automatically generated hets proof-script", ""
, "use " ++ filename h, ""]
++ reverse (map (showCmd . command) $ undoList $ i_hist h)
writeFile f $ unlines history
| mariefarrell/Hets | GUI/GraphMenu.hs | gpl-2.0 | 18,451 | 0 | 28 | 4,812 | 5,038 | 2,588 | 2,450 | 345 | 21 |
{-# LANGUAGE BangPatterns,OverloadedStrings #-}
module TclLib.IOCmds (ioCmds, ioInits) where
import Common
import Control.Monad (unless, liftM2)
import System.IO
import System.Exit
import System.Directory (getCurrentDirectory,
doesFileExist,
doesDirectoryExist,
getPermissions,
Permissions(..))
import System.Environment (getEnvironment)
import Core ()
import VarName (arrNameNS)
import qualified TclObj as T
import qualified TclChan as T
import qualified System.IO.Error as IOE
import qualified Data.ByteString.Char8 as B
import TclObj ((.==))
import TclLib.LibUtil
import Util
setupEnv = do
env <- io $ getEnvironment
mapM_ (\(n,v) -> arrSet "env" (B.pack n) (T.fromStr v)) env
return ()
where arrSet n i v = varSetNS (arrNameNS n i) v
ioInits = [setupEnv]
ioCmds = nsCmdList "" $ safe ++ unsafe
where safe = safeCmds [("puts",cmdPuts),("gets",cmdGets),("read",cmdRead),
("close", cmdClose),("flush", cmdFlush),("eof", cmdEof),
("tell", cmdTell)]
unsafe = unsafeCmds [("exit", cmdExit), ("source", cmdSource),
("pwd", cmdPwd), ("open", cmdOpen),("file", cmdFile)]
cmdEof args = case args of
[ch] -> do h <- getReadable ch
io (hIsEOF h) >>= return . T.fromBool
_ -> vArgErr "eof channelId"
cmdTell args = case args of
[ch] -> do h <- lookupChan (T.asBStr ch) >>= return . T.chanHandle
io (hTell h) >>= return . T.fromInt . fromIntegral
_ -> vArgErr "tell channelId"
cmdRead args = case args of
[ch] -> do
h <- getReadable ch
c <- io $ B.hGetContents h
return $ c `seq` T.fromBStr c
_ -> argErr "read"
cmdFile = mkEnsemble "file" [
("channels", file_channels),
("size", file_size),
pred_check "exists" (\fn -> liftM2 (||) (doesFileExist fn)
(doesDirectoryExist fn)),
pred_check "isfile" doesFileExist,
pred_check "isdirectory" doesDirectoryExist,
permtest "readable" readable,
permtest "executable" executable,
permtest "writable" writable]
where permtest n a = pred_check n (get_perm a)
get_perm a fn = catch (getPermissions fn >>= return . a) (\_ -> return False)
pred_check n p =
let cmd args = case args of
[name] -> (io $ p (T.asStr name)) >>= return . T.fromBool
_ -> vArgErr $ "file " ++ n ++ " name"
in (n,cmd)
file_channels args = case args of
[] -> namesChan >>= return . T.fromBList
_ -> vArgErr "file channels"
file_size args = case args of
[n] -> do
let name = T.asStr n
esiz <- io $ IOE.try (withFile name ReadMode hFileSize)
case esiz of
Left _ -> tclErr $ "could not read " ++ show name ++ ": no such file or directory"
Right siz -> return . T.fromInt . fromIntegral $ siz
_ -> vArgErr "file size name"
cmdPuts args = case args of
[s] -> (io . B.putStrLn . T.asBStr) s >> ret
[a1,str] -> if a1 .== "-nonewline" then tPut stdout str
else do h <- getWritable a1
tPutLn h str
[a1,a2,str] ->do unless (a1 .== "-nonewline") bad
h <- getWritable a2
tPut h str
_ -> bad
where tPut = putFun B.hPutStr
tPutLn = putFun B.hPutStrLn
getWritable c = lookupChan (T.asBStr c) >>= checkWritable . T.chanHandle
bad = vArgErr "puts ?-nonewline? ?channelId? string"
putFun f h s = (io . f h . T.asBStr) s >> ret
cmdGets args = case args of
[ch] -> do h <- getReadable ch
eof <- io (hIsEOF h)
if eof then ret else (io . B.hGetLine) h >>= treturn
[ch,vname] -> do h <- getReadable ch
eof <- io (hIsEOF h)
if eof
then varSetNS (T.asVarName vname) (T.empty) >> return (T.fromInt (-1))
else do s <- io (B.hGetLine h)
varSetNS (T.asVarName vname) (T.fromBStr s)
return $ T.fromInt (B.length s)
_ -> vArgErr "gets channelId ?varName?"
getReadable c = lookupChan (T.asBStr c) >>= checkReadable . T.chanHandle
cmdSource args = case args of
[s] -> do
let fn = T.asStr s
dat <- useFile fn (slurpFile fn)
evalTcl (T.fromBStr dat :: T.TclObj)
_ -> vArgErr "source fileName"
cmdPwd args = case args of
[] -> io getCurrentDirectory >>= return . T.fromStr
_ -> vArgErr "pwd"
checkReadable c = do r <- io (hIsReadable c)
if r then return c else (tclErr "channel wasn't opened for reading")
checkWritable c = do r <- io (hIsWritable c)
if r then return c else (tclErr "channel wasn't opened for writing")
cmdOpen args = case args of
[fn] -> openChan fn ReadMode
[fn,m] -> parseMode (T.asStr m) >>= openChan fn
_ -> argErr "open"
where parseMode m =
case m of
"w" -> return WriteMode
"r" -> return ReadMode
"a" -> return AppendMode
_ -> fail "Unknown file mode"
openChan fn m = do
let name = T.asStr fn
h <- useFile name (openFile name m)
chan <- io (T.mkChan h)
addChan chan
treturn (T.chanName chan)
useFile fn fun = do
eh <- io $ IOE.try fun
case eh of
Left e -> if IOE.isDoesNotExistError e
then tclErr $ "could not open " ++ show fn ++ ": no such file or directory"
else tclErr (show e)
Right h -> return h
cmdClose args = case args of
[ch] -> do h <- lookupChan (T.asBStr ch)
removeChan h
io (hClose (T.chanHandle h))
ret
_ -> vArgErr "close channelId"
cmdFlush args = case args of
[ch] -> do h <- lookupChan (T.asBStr ch)
io (hFlush (T.chanHandle h))
ret
_ -> vArgErr "flush channelId"
cmdExit args = case args of
[] -> io (exitWith ExitSuccess)
[i] -> do v <- T.asInt i
let ecode = if v == 0 then ExitSuccess else ExitFailure v
io (exitWith ecode)
_ -> vArgErr "exit ?returnCode?"
lookupChan :: BString -> TclM T.TclChan
lookupChan c = do chan <- getChan c
case chan of
Nothing -> tclErr ("cannot find channel named " ++ show c)
Just ch -> return ch
| muspellsson/hiccup | TclLib/IOCmds.hs | lgpl-2.1 | 6,797 | 4 | 21 | 2,455 | 2,340 | 1,171 | 1,169 | 160 | 6 |
{-# OPTIONS_GHC -XOverloadedStrings -funbox-strict-fields -XDeriveDataTypeable #-}
module OpenResty.Request (
parseCGIEnv, Request(..), DataFormat(..), RestyError(..)
) where
import Network.FastCGI
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as B
import Network.URI (unEscapeString, uriPath)
import Data.List (stripPrefix)
import Data.Char (toLower)
import Text.Regex.PCRE.Light
import Control.Exception
import Debug.Trace (trace)
import Data.Typeable
import Text.JSON
import Safe
data RestyError = URIError B.ByteString
| MiscError B.ByteString
| UnknownError B.ByteString
deriving (Typeable)
instance Show RestyError where
show (URIError s) = B.unpack s
show (MiscError s) = B.unpack s
show _ = "Unknown error"
data DataFormat = DFJson | DFYaml
deriving (Show)
toDataFormat = [
("json",DFJson),
("js",DFJson),
("yaml",DFYaml),
("yml",DFYaml)]
data Request = Request {
category :: B.ByteString,
method :: B.ByteString,
content :: BL.ByteString,
format :: DataFormat,
pathBits :: [B.ByteString],
params :: [(String, BL.ByteString)]
}
deriving (Show)
instance JSON Request where
showJSON req =
JSObject $ toJSObject [
("category", showJSON $ B.unpack $ category req),
("method", showJSON $ B.unpack $ method req),
("content", showJSON $ BL.unpack $ content req),
("format", showJSON $ format req),
("pathBits", showList $ pathBits req),
("params", showList' $ params req)]
where showList = JSArray . map (showJSON . B.unpack)
showList' = JSArray . map (showJSON . pair2str)
pair2str p = JSArray $ map showJSON [fst p, BL.unpack $ snd p]
readJSON = undefined
instance JSON DataFormat where
showJSON DFYaml = JSString $ toJSString "yaml"
showJSON DFJson = JSString $ toJSString "json"
readJSON = undefined
parseCGIEnv :: CGI Request
parseCGIEnv = do
uri <- requestURI
inputs <- getInputsFPS
(prefix, cat, pbits, fmt) <- parsePath $ B.pack $ uriPath uri
meth <- if prefix /= ""
then (return prefix) else (fmap B.pack $ requestMethod)
body <- getBodyFPS -- XXX TODO: check if body is too long
dataParam <- getInputFPS "_data"
return $ Request {
category = unescape cat,
method = meth,
content = if (meth == "PUT" || meth == "POST") && body == ""
then maybe "" id dataParam
else body,
format = maybe DFJson id $ lookup (lc fmt) toDataFormat,
pathBits = map unescape $ filter (/="") pbits,
-- pathBits = map (B.pack . unEscapeString . B.unpack) $ B.split '/' pbits,
params = inputs
}
unescape :: B.ByteString -> B.ByteString
unescape = B.pack . unEscapeString . B.unpack
lc :: B.ByteString -> B.ByteString
lc = B.map toLower
parsePath :: B.ByteString -> CGI (B.ByteString, B.ByteString, [B.ByteString], B.ByteString)
parsePath path = if B.isPrefixOf "/=/" path
then splitPath $ B.drop 3 path
else throwDyn $ URIError "URL must be preceded by \"/=/\"."
splitPath :: B.ByteString -> CGI (B.ByteString, B.ByteString, [B.ByteString], B.ByteString)
splitPath p = case B.span (/='/') p of
("put", s) -> fmap (prepend "PUT") $ splitBarePath $ B.tail s
("post", s) -> fmap (prepend "POST") $ splitBarePath $ B.tail s
("delete", s) -> fmap (prepend "DELETE") $ splitBarePath $ B.tail s
("", "") -> return ("version", "", [], "json")
_ -> fmap (prepend "") $ splitBarePath p
where prepend d (a, b, c) = (d, a, b, c)
splitBarePath :: B.ByteString -> CGI (B.ByteString, [B.ByteString], B.ByteString)
splitBarePath p = if null bits
then return ("version", [], "json")
else return (head bits, (init bits) ++ [mid], fmt)
where bits = B.split '/' p
(mid, fmt) = processSuffix (last bits)
processSuffix :: B.ByteString -> (B.ByteString, B.ByteString)
processSuffix str =
let regex = compile "(.*?)\\.(json|js|yaml|yml)$" [] in
case match regex str [] of
Just res -> (res !! 1, res !! 2)
Nothing -> (str, "json")
--dropUtil :: (Char -> Bool) -> B.ByteString
--dropUtil = B.tail . B.dropWhile
| beni55/old-openresty | haskell/src/OpenResty/Request.hs | bsd-3-clause | 4,321 | 0 | 16 | 1,074 | 1,444 | 791 | 653 | 101 | 5 |
{-# LANGUAGE CPP, Rank2Types, TypeFamilies #-}
-- |
-- Module : Data.Vector.Unboxed
-- Copyright : (c) Roman Leshchinskiy 2009-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable
--
-- Adaptive unboxed vectors. The implementation is based on type families
-- and picks an efficient, specialised representation for every element type.
-- In particular, unboxed vectors of pairs are represented as pairs of unboxed
-- vectors.
--
-- Implementing unboxed vectors for new data types can be very easy. Here is
-- how the library does this for 'Complex' by simply wrapping vectors of
-- pairs.
--
-- @
-- newtype instance 'MVector' s ('Complex' a) = MV_Complex ('MVector' s (a,a))
-- newtype instance 'Vector' ('Complex' a) = V_Complex ('Vector' (a,a))
--
-- instance ('RealFloat' a, 'Unbox' a) => 'Data.Vector.Generic.Mutable.MVector' 'MVector' ('Complex' a) where
-- {-\# INLINE basicLength \#-}
-- basicLength (MV_Complex v) = 'Data.Vector.Generic.Mutable.basicLength' v
-- ...
--
-- instance ('RealFloat' a, 'Unbox' a) => Data.Vector.Generic.Vector 'Vector' ('Complex' a) where
-- {-\# INLINE basicLength \#-}
-- basicLength (V_Complex v) = Data.Vector.Generic.basicLength v
-- ...
--
-- instance ('RealFloat' a, 'Unbox' a) => 'Unbox' ('Complex' a)
-- @
module Data.Vector.Unboxed (
-- * Unboxed vectors
Vector, MVector(..), Unbox,
-- * Accessors
-- ** Length information
length, null,
-- ** Indexing
(!), (!?), head, last,
unsafeIndex, unsafeHead, unsafeLast,
-- ** Monadic indexing
indexM, headM, lastM,
unsafeIndexM, unsafeHeadM, unsafeLastM,
-- ** Extracting subvectors (slicing)
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- * Construction
-- ** Initialisation
empty, singleton, replicate, generate, iterateN,
-- ** Monadic initialisation
replicateM, generateM, create,
-- ** Unfolding
unfoldr, unfoldrN,
constructN, constructrN,
-- ** Enumeration
enumFromN, enumFromStepN, enumFromTo, enumFromThenTo,
-- ** Concatenation
cons, snoc, (++), concat,
-- ** Restricting memory usage
force,
-- * Modifying vectors
-- ** Bulk updates
(//), update, update_,
unsafeUpd, unsafeUpdate, unsafeUpdate_,
-- ** Accumulations
accum, accumulate, accumulate_,
unsafeAccum, unsafeAccumulate, unsafeAccumulate_,
-- ** Permutations
reverse, backpermute, unsafeBackpermute,
-- ** Safe destructive updates
modify,
-- * Elementwise operations
-- ** Indexing
indexed,
-- ** Mapping
map, imap, concatMap,
-- ** Monadic mapping
mapM, imapM, mapM_, imapM_, forM, forM_,
-- ** Zipping
zipWith, zipWith3, zipWith4, zipWith5, zipWith6,
izipWith, izipWith3, izipWith4, izipWith5, izipWith6,
zip, zip3, zip4, zip5, zip6,
-- ** Monadic zipping
zipWithM, izipWithM, zipWithM_, izipWithM_,
-- ** Unzipping
unzip, unzip3, unzip4, unzip5, unzip6,
-- * Working with predicates
-- ** Filtering
filter, ifilter, filterM,
takeWhile, dropWhile,
-- ** Partitioning
partition, unstablePartition, span, break,
-- ** Searching
elem, notElem, find, findIndex, findIndices, elemIndex, elemIndices,
-- * Folding
foldl, foldl1, foldl', foldl1', foldr, foldr1, foldr', foldr1',
ifoldl, ifoldl', ifoldr, ifoldr',
-- ** Specialised folds
all, any, and, or,
sum, product,
maximum, maximumBy, minimum, minimumBy,
minIndex, minIndexBy, maxIndex, maxIndexBy,
-- ** Monadic folds
foldM, ifoldM, foldM', ifoldM',
fold1M, fold1M', foldM_, ifoldM_,
foldM'_, ifoldM'_, fold1M_, fold1M'_,
-- * Prefix sums (scans)
prescanl, prescanl',
postscanl, postscanl',
scanl, scanl', scanl1, scanl1',
prescanr, prescanr',
postscanr, postscanr',
scanr, scanr', scanr1, scanr1',
-- * Conversions
-- ** Lists
toList, fromList, fromListN,
-- ** Other vector types
G.convert,
-- ** Mutable vectors
freeze, thaw, copy, unsafeFreeze, unsafeThaw, unsafeCopy
) where
import Data.Vector.Unboxed.Base
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Fusion.Bundle as Bundle
import Data.Vector.Fusion.Util ( delayed_min )
import Control.Monad.ST ( ST )
import Control.Monad.Primitive
import Prelude hiding ( length, null,
replicate, (++), concat,
head, last,
init, tail, take, drop, splitAt, reverse,
map, concatMap,
zipWith, zipWith3, zip, zip3, unzip, unzip3,
filter, takeWhile, dropWhile, span, break,
elem, notElem,
foldl, foldl1, foldr, foldr1,
all, any, and, or, sum, product, minimum, maximum,
scanl, scanl1, scanr, scanr1,
enumFromTo, enumFromThenTo,
mapM, mapM_ )
import Text.Read ( Read(..), readListPrecDefault )
import Data.Monoid ( Monoid(..) )
#if __GLASGOW_HASKELL__ >= 708
import qualified GHC.Exts as Exts (IsList(..))
#endif
#define NOT_VECTOR_MODULE
#include "vector.h"
-- See http://trac.haskell.org/vector/ticket/12
instance (Unbox a, Eq a) => Eq (Vector a) where
{-# INLINE (==) #-}
xs == ys = Bundle.eq (G.stream xs) (G.stream ys)
{-# INLINE (/=) #-}
xs /= ys = not (Bundle.eq (G.stream xs) (G.stream ys))
-- See http://trac.haskell.org/vector/ticket/12
instance (Unbox a, Ord a) => Ord (Vector a) where
{-# INLINE compare #-}
compare xs ys = Bundle.cmp (G.stream xs) (G.stream ys)
{-# INLINE (<) #-}
xs < ys = Bundle.cmp (G.stream xs) (G.stream ys) == LT
{-# INLINE (<=) #-}
xs <= ys = Bundle.cmp (G.stream xs) (G.stream ys) /= GT
{-# INLINE (>) #-}
xs > ys = Bundle.cmp (G.stream xs) (G.stream ys) == GT
{-# INLINE (>=) #-}
xs >= ys = Bundle.cmp (G.stream xs) (G.stream ys) /= LT
instance Unbox a => Monoid (Vector a) where
{-# INLINE mempty #-}
mempty = empty
{-# INLINE mappend #-}
mappend = (++)
{-# INLINE mconcat #-}
mconcat = concat
instance (Show a, Unbox a) => Show (Vector a) where
showsPrec = G.showsPrec
instance (Read a, Unbox a) => Read (Vector a) where
readPrec = G.readPrec
readListPrec = readListPrecDefault
#if __GLASGOW_HASKELL__ >= 708
instance (Unbox e) => Exts.IsList (Vector e) where
type Item (Vector e) = e
fromList = fromList
fromListN = fromListN
toList = toList
#endif
-- Length information
-- ------------------
-- | /O(1)/ Yield the length of the vector.
length :: Unbox a => Vector a -> Int
{-# INLINE length #-}
length = G.length
-- | /O(1)/ Test whether a vector if empty
null :: Unbox a => Vector a -> Bool
{-# INLINE null #-}
null = G.null
-- Indexing
-- --------
-- | O(1) Indexing
(!) :: Unbox a => Vector a -> Int -> a
{-# INLINE (!) #-}
(!) = (G.!)
-- | O(1) Safe indexing
(!?) :: Unbox a => Vector a -> Int -> Maybe a
{-# INLINE (!?) #-}
(!?) = (G.!?)
-- | /O(1)/ First element
head :: Unbox a => Vector a -> a
{-# INLINE head #-}
head = G.head
-- | /O(1)/ Last element
last :: Unbox a => Vector a -> a
{-# INLINE last #-}
last = G.last
-- | /O(1)/ Unsafe indexing without bounds checking
unsafeIndex :: Unbox a => Vector a -> Int -> a
{-# INLINE unsafeIndex #-}
unsafeIndex = G.unsafeIndex
-- | /O(1)/ First element without checking if the vector is empty
unsafeHead :: Unbox a => Vector a -> a
{-# INLINE unsafeHead #-}
unsafeHead = G.unsafeHead
-- | /O(1)/ Last element without checking if the vector is empty
unsafeLast :: Unbox a => Vector a -> a
{-# INLINE unsafeLast #-}
unsafeLast = G.unsafeLast
-- Monadic indexing
-- ----------------
-- | /O(1)/ Indexing in a monad.
--
-- The monad allows operations to be strict in the vector when necessary.
-- Suppose vector copying is implemented like this:
--
-- > copy mv v = ... write mv i (v ! i) ...
--
-- For lazy vectors, @v ! i@ would not be evaluated which means that @mv@
-- would unnecessarily retain a reference to @v@ in each element written.
--
-- With 'indexM', copying can be implemented like this instead:
--
-- > copy mv v = ... do
-- > x <- indexM v i
-- > write mv i x
--
-- Here, no references to @v@ are retained because indexing (but /not/ the
-- elements) is evaluated eagerly.
--
indexM :: (Unbox a, Monad m) => Vector a -> Int -> m a
{-# INLINE indexM #-}
indexM = G.indexM
-- | /O(1)/ First element of a vector in a monad. See 'indexM' for an
-- explanation of why this is useful.
headM :: (Unbox a, Monad m) => Vector a -> m a
{-# INLINE headM #-}
headM = G.headM
-- | /O(1)/ Last element of a vector in a monad. See 'indexM' for an
-- explanation of why this is useful.
lastM :: (Unbox a, Monad m) => Vector a -> m a
{-# INLINE lastM #-}
lastM = G.lastM
-- | /O(1)/ Indexing in a monad without bounds checks. See 'indexM' for an
-- explanation of why this is useful.
unsafeIndexM :: (Unbox a, Monad m) => Vector a -> Int -> m a
{-# INLINE unsafeIndexM #-}
unsafeIndexM = G.unsafeIndexM
-- | /O(1)/ First element in a monad without checking for empty vectors.
-- See 'indexM' for an explanation of why this is useful.
unsafeHeadM :: (Unbox a, Monad m) => Vector a -> m a
{-# INLINE unsafeHeadM #-}
unsafeHeadM = G.unsafeHeadM
-- | /O(1)/ Last element in a monad without checking for empty vectors.
-- See 'indexM' for an explanation of why this is useful.
unsafeLastM :: (Unbox a, Monad m) => Vector a -> m a
{-# INLINE unsafeLastM #-}
unsafeLastM = G.unsafeLastM
-- Extracting subvectors (slicing)
-- -------------------------------
-- | /O(1)/ Yield a slice of the vector without copying it. The vector must
-- contain at least @i+n@ elements.
slice :: Unbox a => Int -- ^ @i@ starting index
-> Int -- ^ @n@ length
-> Vector a
-> Vector a
{-# INLINE slice #-}
slice = G.slice
-- | /O(1)/ Yield all but the last element without copying. The vector may not
-- be empty.
init :: Unbox a => Vector a -> Vector a
{-# INLINE init #-}
init = G.init
-- | /O(1)/ Yield all but the first element without copying. The vector may not
-- be empty.
tail :: Unbox a => Vector a -> Vector a
{-# INLINE tail #-}
tail = G.tail
-- | /O(1)/ Yield at the first @n@ elements without copying. The vector may
-- contain less than @n@ elements in which case it is returned unchanged.
take :: Unbox a => Int -> Vector a -> Vector a
{-# INLINE take #-}
take = G.take
-- | /O(1)/ Yield all but the first @n@ elements without copying. The vector may
-- contain less than @n@ elements in which case an empty vector is returned.
drop :: Unbox a => Int -> Vector a -> Vector a
{-# INLINE drop #-}
drop = G.drop
-- | /O(1)/ Yield the first @n@ elements paired with the remainder without copying.
--
-- Note that @'splitAt' n v@ is equivalent to @('take' n v, 'drop' n v)@
-- but slightly more efficient.
{-# INLINE splitAt #-}
splitAt :: Unbox a => Int -> Vector a -> (Vector a, Vector a)
splitAt = G.splitAt
-- | /O(1)/ Yield a slice of the vector without copying. The vector must
-- contain at least @i+n@ elements but this is not checked.
unsafeSlice :: Unbox a => Int -- ^ @i@ starting index
-> Int -- ^ @n@ length
-> Vector a
-> Vector a
{-# INLINE unsafeSlice #-}
unsafeSlice = G.unsafeSlice
-- | /O(1)/ Yield all but the last element without copying. The vector may not
-- be empty but this is not checked.
unsafeInit :: Unbox a => Vector a -> Vector a
{-# INLINE unsafeInit #-}
unsafeInit = G.unsafeInit
-- | /O(1)/ Yield all but the first element without copying. The vector may not
-- be empty but this is not checked.
unsafeTail :: Unbox a => Vector a -> Vector a
{-# INLINE unsafeTail #-}
unsafeTail = G.unsafeTail
-- | /O(1)/ Yield the first @n@ elements without copying. The vector must
-- contain at least @n@ elements but this is not checked.
unsafeTake :: Unbox a => Int -> Vector a -> Vector a
{-# INLINE unsafeTake #-}
unsafeTake = G.unsafeTake
-- | /O(1)/ Yield all but the first @n@ elements without copying. The vector
-- must contain at least @n@ elements but this is not checked.
unsafeDrop :: Unbox a => Int -> Vector a -> Vector a
{-# INLINE unsafeDrop #-}
unsafeDrop = G.unsafeDrop
-- Initialisation
-- --------------
-- | /O(1)/ Empty vector
empty :: Unbox a => Vector a
{-# INLINE empty #-}
empty = G.empty
-- | /O(1)/ Vector with exactly one element
singleton :: Unbox a => a -> Vector a
{-# INLINE singleton #-}
singleton = G.singleton
-- | /O(n)/ Vector of the given length with the same value in each position
replicate :: Unbox a => Int -> a -> Vector a
{-# INLINE replicate #-}
replicate = G.replicate
-- | /O(n)/ Construct a vector of the given length by applying the function to
-- each index
generate :: Unbox a => Int -> (Int -> a) -> Vector a
{-# INLINE generate #-}
generate = G.generate
-- | /O(n)/ Apply function n times to value. Zeroth element is original value.
iterateN :: Unbox a => Int -> (a -> a) -> a -> Vector a
{-# INLINE iterateN #-}
iterateN = G.iterateN
-- Unfolding
-- ---------
-- | /O(n)/ Construct a vector by repeatedly applying the generator function
-- to a seed. The generator function yields 'Just' the next element and the
-- new seed or 'Nothing' if there are no more elements.
--
-- > unfoldr (\n -> if n == 0 then Nothing else Just (n,n-1)) 10
-- > = <10,9,8,7,6,5,4,3,2,1>
unfoldr :: Unbox a => (b -> Maybe (a, b)) -> b -> Vector a
{-# INLINE unfoldr #-}
unfoldr = G.unfoldr
-- | /O(n)/ Construct a vector with at most @n@ by repeatedly applying the
-- generator function to the a seed. The generator function yields 'Just' the
-- next element and the new seed or 'Nothing' if there are no more elements.
--
-- > unfoldrN 3 (\n -> Just (n,n-1)) 10 = <10,9,8>
unfoldrN :: Unbox a => Int -> (b -> Maybe (a, b)) -> b -> Vector a
{-# INLINE unfoldrN #-}
unfoldrN = G.unfoldrN
-- | /O(n)/ Construct a vector with @n@ elements by repeatedly applying the
-- generator function to the already constructed part of the vector.
--
-- > constructN 3 f = let a = f <> ; b = f <a> ; c = f <a,b> in f <a,b,c>
--
constructN :: Unbox a => Int -> (Vector a -> a) -> Vector a
{-# INLINE constructN #-}
constructN = G.constructN
-- | /O(n)/ Construct a vector with @n@ elements from right to left by
-- repeatedly applying the generator function to the already constructed part
-- of the vector.
--
-- > constructrN 3 f = let a = f <> ; b = f<a> ; c = f <b,a> in f <c,b,a>
--
constructrN :: Unbox a => Int -> (Vector a -> a) -> Vector a
{-# INLINE constructrN #-}
constructrN = G.constructrN
-- Enumeration
-- -----------
-- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+1@
-- etc. This operation is usually more efficient than 'enumFromTo'.
--
-- > enumFromN 5 3 = <5,6,7>
enumFromN :: (Unbox a, Num a) => a -> Int -> Vector a
{-# INLINE enumFromN #-}
enumFromN = G.enumFromN
-- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+y@,
-- @x+y+y@ etc. This operations is usually more efficient than 'enumFromThenTo'.
--
-- > enumFromStepN 1 0.1 5 = <1,1.1,1.2,1.3,1.4>
enumFromStepN :: (Unbox a, Num a) => a -> a -> Int -> Vector a
{-# INLINE enumFromStepN #-}
enumFromStepN = G.enumFromStepN
-- | /O(n)/ Enumerate values from @x@ to @y@.
--
-- /WARNING:/ This operation can be very inefficient. If at all possible, use
-- 'enumFromN' instead.
enumFromTo :: (Unbox a, Enum a) => a -> a -> Vector a
{-# INLINE enumFromTo #-}
enumFromTo = G.enumFromTo
-- | /O(n)/ Enumerate values from @x@ to @y@ with a specific step @z@.
--
-- /WARNING:/ This operation can be very inefficient. If at all possible, use
-- 'enumFromStepN' instead.
enumFromThenTo :: (Unbox a, Enum a) => a -> a -> a -> Vector a
{-# INLINE enumFromThenTo #-}
enumFromThenTo = G.enumFromThenTo
-- Concatenation
-- -------------
-- | /O(n)/ Prepend an element
cons :: Unbox a => a -> Vector a -> Vector a
{-# INLINE cons #-}
cons = G.cons
-- | /O(n)/ Append an element
snoc :: Unbox a => Vector a -> a -> Vector a
{-# INLINE snoc #-}
snoc = G.snoc
infixr 5 ++
-- | /O(m+n)/ Concatenate two vectors
(++) :: Unbox a => Vector a -> Vector a -> Vector a
{-# INLINE (++) #-}
(++) = (G.++)
-- | /O(n)/ Concatenate all vectors in the list
concat :: Unbox a => [Vector a] -> Vector a
{-# INLINE concat #-}
concat = G.concat
-- Monadic initialisation
-- ----------------------
-- | /O(n)/ Execute the monadic action the given number of times and store the
-- results in a vector.
replicateM :: (Monad m, Unbox a) => Int -> m a -> m (Vector a)
{-# INLINE replicateM #-}
replicateM = G.replicateM
-- | /O(n)/ Construct a vector of the given length by applying the monadic
-- action to each index
generateM :: (Monad m, Unbox a) => Int -> (Int -> m a) -> m (Vector a)
{-# INLINE generateM #-}
generateM = G.generateM
-- | Execute the monadic action and freeze the resulting vector.
--
-- @
-- create (do { v \<- new 2; write v 0 \'a\'; write v 1 \'b\'; return v }) = \<'a','b'\>
-- @
create :: Unbox a => (forall s. ST s (MVector s a)) -> Vector a
{-# INLINE create #-}
-- NOTE: eta-expanded due to http://hackage.haskell.org/trac/ghc/ticket/4120
create p = G.create p
-- Restricting memory usage
-- ------------------------
-- | /O(n)/ Yield the argument but force it not to retain any extra memory,
-- possibly by copying it.
--
-- This is especially useful when dealing with slices. For example:
--
-- > force (slice 0 2 <huge vector>)
--
-- Here, the slice retains a reference to the huge vector. Forcing it creates
-- a copy of just the elements that belong to the slice and allows the huge
-- vector to be garbage collected.
force :: Unbox a => Vector a -> Vector a
{-# INLINE force #-}
force = G.force
-- Bulk updates
-- ------------
-- | /O(m+n)/ For each pair @(i,a)@ from the list, replace the vector
-- element at position @i@ by @a@.
--
-- > <5,9,2,7> // [(2,1),(0,3),(2,8)] = <3,9,8,7>
--
(//) :: Unbox a => Vector a -- ^ initial vector (of length @m@)
-> [(Int, a)] -- ^ list of index/value pairs (of length @n@)
-> Vector a
{-# INLINE (//) #-}
(//) = (G.//)
-- | /O(m+n)/ For each pair @(i,a)@ from the vector of index/value pairs,
-- replace the vector element at position @i@ by @a@.
--
-- > update <5,9,2,7> <(2,1),(0,3),(2,8)> = <3,9,8,7>
--
update :: Unbox a
=> Vector a -- ^ initial vector (of length @m@)
-> Vector (Int, a) -- ^ vector of index/value pairs (of length @n@)
-> Vector a
{-# INLINE update #-}
update = G.update
-- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the
-- corresponding value @a@ from the value vector, replace the element of the
-- initial vector at position @i@ by @a@.
--
-- > update_ <5,9,2,7> <2,0,2> <1,3,8> = <3,9,8,7>
--
-- The function 'update' provides the same functionality and is usually more
-- convenient.
--
-- @
-- update_ xs is ys = 'update' xs ('zip' is ys)
-- @
update_ :: Unbox a
=> Vector a -- ^ initial vector (of length @m@)
-> Vector Int -- ^ index vector (of length @n1@)
-> Vector a -- ^ value vector (of length @n2@)
-> Vector a
{-# INLINE update_ #-}
update_ = G.update_
-- | Same as ('//') but without bounds checking.
unsafeUpd :: Unbox a => Vector a -> [(Int, a)] -> Vector a
{-# INLINE unsafeUpd #-}
unsafeUpd = G.unsafeUpd
-- | Same as 'update' but without bounds checking.
unsafeUpdate :: Unbox a => Vector a -> Vector (Int, a) -> Vector a
{-# INLINE unsafeUpdate #-}
unsafeUpdate = G.unsafeUpdate
-- | Same as 'update_' but without bounds checking.
unsafeUpdate_ :: Unbox a => Vector a -> Vector Int -> Vector a -> Vector a
{-# INLINE unsafeUpdate_ #-}
unsafeUpdate_ = G.unsafeUpdate_
-- Accumulations
-- -------------
-- | /O(m+n)/ For each pair @(i,b)@ from the list, replace the vector element
-- @a@ at position @i@ by @f a b@.
--
-- > accum (+) <5,9,2> [(2,4),(1,6),(0,3),(1,7)] = <5+3, 9+6+7, 2+4>
accum :: Unbox a
=> (a -> b -> a) -- ^ accumulating function @f@
-> Vector a -- ^ initial vector (of length @m@)
-> [(Int,b)] -- ^ list of index/value pairs (of length @n@)
-> Vector a
{-# INLINE accum #-}
accum = G.accum
-- | /O(m+n)/ For each pair @(i,b)@ from the vector of pairs, replace the vector
-- element @a@ at position @i@ by @f a b@.
--
-- > accumulate (+) <5,9,2> <(2,4),(1,6),(0,3),(1,7)> = <5+3, 9+6+7, 2+4>
accumulate :: (Unbox a, Unbox b)
=> (a -> b -> a) -- ^ accumulating function @f@
-> Vector a -- ^ initial vector (of length @m@)
-> Vector (Int,b) -- ^ vector of index/value pairs (of length @n@)
-> Vector a
{-# INLINE accumulate #-}
accumulate = G.accumulate
-- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the
-- corresponding value @b@ from the the value vector,
-- replace the element of the initial vector at
-- position @i@ by @f a b@.
--
-- > accumulate_ (+) <5,9,2> <2,1,0,1> <4,6,3,7> = <5+3, 9+6+7, 2+4>
--
-- The function 'accumulate' provides the same functionality and is usually more
-- convenient.
--
-- @
-- accumulate_ f as is bs = 'accumulate' f as ('zip' is bs)
-- @
accumulate_ :: (Unbox a, Unbox b)
=> (a -> b -> a) -- ^ accumulating function @f@
-> Vector a -- ^ initial vector (of length @m@)
-> Vector Int -- ^ index vector (of length @n1@)
-> Vector b -- ^ value vector (of length @n2@)
-> Vector a
{-# INLINE accumulate_ #-}
accumulate_ = G.accumulate_
-- | Same as 'accum' but without bounds checking.
unsafeAccum :: Unbox a => (a -> b -> a) -> Vector a -> [(Int,b)] -> Vector a
{-# INLINE unsafeAccum #-}
unsafeAccum = G.unsafeAccum
-- | Same as 'accumulate' but without bounds checking.
unsafeAccumulate :: (Unbox a, Unbox b)
=> (a -> b -> a) -> Vector a -> Vector (Int,b) -> Vector a
{-# INLINE unsafeAccumulate #-}
unsafeAccumulate = G.unsafeAccumulate
-- | Same as 'accumulate_' but without bounds checking.
unsafeAccumulate_ :: (Unbox a, Unbox b) =>
(a -> b -> a) -> Vector a -> Vector Int -> Vector b -> Vector a
{-# INLINE unsafeAccumulate_ #-}
unsafeAccumulate_ = G.unsafeAccumulate_
-- Permutations
-- ------------
-- | /O(n)/ Reverse a vector
reverse :: Unbox a => Vector a -> Vector a
{-# INLINE reverse #-}
reverse = G.reverse
-- | /O(n)/ Yield the vector obtained by replacing each element @i@ of the
-- index vector by @xs'!'i@. This is equivalent to @'map' (xs'!') is@ but is
-- often much more efficient.
--
-- > backpermute <a,b,c,d> <0,3,2,3,1,0> = <a,d,c,d,b,a>
backpermute :: Unbox a => Vector a -> Vector Int -> Vector a
{-# INLINE backpermute #-}
backpermute = G.backpermute
-- | Same as 'backpermute' but without bounds checking.
unsafeBackpermute :: Unbox a => Vector a -> Vector Int -> Vector a
{-# INLINE unsafeBackpermute #-}
unsafeBackpermute = G.unsafeBackpermute
-- Safe destructive updates
-- ------------------------
-- | Apply a destructive operation to a vector. The operation will be
-- performed in place if it is safe to do so and will modify a copy of the
-- vector otherwise.
--
-- @
-- modify (\\v -> write v 0 \'x\') ('replicate' 3 \'a\') = \<\'x\',\'a\',\'a\'\>
-- @
modify :: Unbox a => (forall s. MVector s a -> ST s ()) -> Vector a -> Vector a
{-# INLINE modify #-}
modify p = G.modify p
-- Indexing
-- --------
-- | /O(n)/ Pair each element in a vector with its index
indexed :: Unbox a => Vector a -> Vector (Int,a)
{-# INLINE indexed #-}
indexed = G.indexed
-- Mapping
-- -------
-- | /O(n)/ Map a function over a vector
map :: (Unbox a, Unbox b) => (a -> b) -> Vector a -> Vector b
{-# INLINE map #-}
map = G.map
-- | /O(n)/ Apply a function to every element of a vector and its index
imap :: (Unbox a, Unbox b) => (Int -> a -> b) -> Vector a -> Vector b
{-# INLINE imap #-}
imap = G.imap
-- | Map a function over a vector and concatenate the results.
concatMap :: (Unbox a, Unbox b) => (a -> Vector b) -> Vector a -> Vector b
{-# INLINE concatMap #-}
concatMap = G.concatMap
-- Monadic mapping
-- ---------------
-- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a
-- vector of results
mapM :: (Monad m, Unbox a, Unbox b) => (a -> m b) -> Vector a -> m (Vector b)
{-# INLINE mapM #-}
mapM = G.mapM
-- | /O(n)/ Apply the monadic action to every element of a vector and its
-- index, yielding a vector of results
imapM :: (Monad m, Unbox a, Unbox b)
=> (Int -> a -> m b) -> Vector a -> m (Vector b)
{-# INLINE imapM #-}
imapM = G.imapM
-- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the
-- results
mapM_ :: (Monad m, Unbox a) => (a -> m b) -> Vector a -> m ()
{-# INLINE mapM_ #-}
mapM_ = G.mapM_
-- | /O(n)/ Apply the monadic action to every element of a vector and its
-- index, ignoring the results
imapM_ :: (Monad m, Unbox a) => (Int -> a -> m b) -> Vector a -> m ()
{-# INLINE imapM_ #-}
imapM_ = G.imapM_
-- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a
-- vector of results. Equvalent to @flip 'mapM'@.
forM :: (Monad m, Unbox a, Unbox b) => Vector a -> (a -> m b) -> m (Vector b)
{-# INLINE forM #-}
forM = G.forM
-- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the
-- results. Equivalent to @flip 'mapM_'@.
forM_ :: (Monad m, Unbox a) => Vector a -> (a -> m b) -> m ()
{-# INLINE forM_ #-}
forM_ = G.forM_
-- Zipping
-- -------
-- | /O(min(m,n))/ Zip two vectors with the given function.
zipWith :: (Unbox a, Unbox b, Unbox c)
=> (a -> b -> c) -> Vector a -> Vector b -> Vector c
{-# INLINE zipWith #-}
zipWith = G.zipWith
-- | Zip three vectors with the given function.
zipWith3 :: (Unbox a, Unbox b, Unbox c, Unbox d)
=> (a -> b -> c -> d) -> Vector a -> Vector b -> Vector c -> Vector d
{-# INLINE zipWith3 #-}
zipWith3 = G.zipWith3
zipWith4 :: (Unbox a, Unbox b, Unbox c, Unbox d, Unbox e)
=> (a -> b -> c -> d -> e)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
{-# INLINE zipWith4 #-}
zipWith4 = G.zipWith4
zipWith5 :: (Unbox a, Unbox b, Unbox c, Unbox d, Unbox e, Unbox f)
=> (a -> b -> c -> d -> e -> f)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f
{-# INLINE zipWith5 #-}
zipWith5 = G.zipWith5
zipWith6 :: (Unbox a, Unbox b, Unbox c, Unbox d, Unbox e, Unbox f, Unbox g)
=> (a -> b -> c -> d -> e -> f -> g)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f -> Vector g
{-# INLINE zipWith6 #-}
zipWith6 = G.zipWith6
-- | /O(min(m,n))/ Zip two vectors with a function that also takes the
-- elements' indices.
izipWith :: (Unbox a, Unbox b, Unbox c)
=> (Int -> a -> b -> c) -> Vector a -> Vector b -> Vector c
{-# INLINE izipWith #-}
izipWith = G.izipWith
-- | Zip three vectors and their indices with the given function.
izipWith3 :: (Unbox a, Unbox b, Unbox c, Unbox d)
=> (Int -> a -> b -> c -> d)
-> Vector a -> Vector b -> Vector c -> Vector d
{-# INLINE izipWith3 #-}
izipWith3 = G.izipWith3
izipWith4 :: (Unbox a, Unbox b, Unbox c, Unbox d, Unbox e)
=> (Int -> a -> b -> c -> d -> e)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
{-# INLINE izipWith4 #-}
izipWith4 = G.izipWith4
izipWith5 :: (Unbox a, Unbox b, Unbox c, Unbox d, Unbox e, Unbox f)
=> (Int -> a -> b -> c -> d -> e -> f)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f
{-# INLINE izipWith5 #-}
izipWith5 = G.izipWith5
izipWith6 :: (Unbox a, Unbox b, Unbox c, Unbox d, Unbox e, Unbox f, Unbox g)
=> (Int -> a -> b -> c -> d -> e -> f -> g)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f -> Vector g
{-# INLINE izipWith6 #-}
izipWith6 = G.izipWith6
-- Monadic zipping
-- ---------------
-- | /O(min(m,n))/ Zip the two vectors with the monadic action and yield a
-- vector of results
zipWithM :: (Monad m, Unbox a, Unbox b, Unbox c)
=> (a -> b -> m c) -> Vector a -> Vector b -> m (Vector c)
{-# INLINE zipWithM #-}
zipWithM = G.zipWithM
-- | /O(min(m,n))/ Zip the two vectors with a monadic action that also takes
-- the element index and yield a vector of results
izipWithM :: (Monad m, Unbox a, Unbox b, Unbox c)
=> (Int -> a -> b -> m c) -> Vector a -> Vector b -> m (Vector c)
{-# INLINE izipWithM #-}
izipWithM = G.izipWithM
-- | /O(min(m,n))/ Zip the two vectors with the monadic action and ignore the
-- results
zipWithM_ :: (Monad m, Unbox a, Unbox b)
=> (a -> b -> m c) -> Vector a -> Vector b -> m ()
{-# INLINE zipWithM_ #-}
zipWithM_ = G.zipWithM_
-- | /O(min(m,n))/ Zip the two vectors with a monadic action that also takes
-- the element index and ignore the results
izipWithM_ :: (Monad m, Unbox a, Unbox b)
=> (Int -> a -> b -> m c) -> Vector a -> Vector b -> m ()
{-# INLINE izipWithM_ #-}
izipWithM_ = G.izipWithM_
-- Filtering
-- ---------
-- | /O(n)/ Drop elements that do not satisfy the predicate
filter :: Unbox a => (a -> Bool) -> Vector a -> Vector a
{-# INLINE filter #-}
filter = G.filter
-- | /O(n)/ Drop elements that do not satisfy the predicate which is applied to
-- values and their indices
ifilter :: Unbox a => (Int -> a -> Bool) -> Vector a -> Vector a
{-# INLINE ifilter #-}
ifilter = G.ifilter
-- | /O(n)/ Drop elements that do not satisfy the monadic predicate
filterM :: (Monad m, Unbox a) => (a -> m Bool) -> Vector a -> m (Vector a)
{-# INLINE filterM #-}
filterM = G.filterM
-- | /O(n)/ Yield the longest prefix of elements satisfying the predicate
-- without copying.
takeWhile :: Unbox a => (a -> Bool) -> Vector a -> Vector a
{-# INLINE takeWhile #-}
takeWhile = G.takeWhile
-- | /O(n)/ Drop the longest prefix of elements that satisfy the predicate
-- without copying.
dropWhile :: Unbox a => (a -> Bool) -> Vector a -> Vector a
{-# INLINE dropWhile #-}
dropWhile = G.dropWhile
-- Parititioning
-- -------------
-- | /O(n)/ Split the vector in two parts, the first one containing those
-- elements that satisfy the predicate and the second one those that don't. The
-- relative order of the elements is preserved at the cost of a sometimes
-- reduced performance compared to 'unstablePartition'.
partition :: Unbox a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE partition #-}
partition = G.partition
-- | /O(n)/ Split the vector in two parts, the first one containing those
-- elements that satisfy the predicate and the second one those that don't.
-- The order of the elements is not preserved but the operation is often
-- faster than 'partition'.
unstablePartition :: Unbox a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE unstablePartition #-}
unstablePartition = G.unstablePartition
-- | /O(n)/ Split the vector into the longest prefix of elements that satisfy
-- the predicate and the rest without copying.
span :: Unbox a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE span #-}
span = G.span
-- | /O(n)/ Split the vector into the longest prefix of elements that do not
-- satisfy the predicate and the rest without copying.
break :: Unbox a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE break #-}
break = G.break
-- Searching
-- ---------
infix 4 `elem`
-- | /O(n)/ Check if the vector contains an element
elem :: (Unbox a, Eq a) => a -> Vector a -> Bool
{-# INLINE elem #-}
elem = G.elem
infix 4 `notElem`
-- | /O(n)/ Check if the vector does not contain an element (inverse of 'elem')
notElem :: (Unbox a, Eq a) => a -> Vector a -> Bool
{-# INLINE notElem #-}
notElem = G.notElem
-- | /O(n)/ Yield 'Just' the first element matching the predicate or 'Nothing'
-- if no such element exists.
find :: Unbox a => (a -> Bool) -> Vector a -> Maybe a
{-# INLINE find #-}
find = G.find
-- | /O(n)/ Yield 'Just' the index of the first element matching the predicate
-- or 'Nothing' if no such element exists.
findIndex :: Unbox a => (a -> Bool) -> Vector a -> Maybe Int
{-# INLINE findIndex #-}
findIndex = G.findIndex
-- | /O(n)/ Yield the indices of elements satisfying the predicate in ascending
-- order.
findIndices :: Unbox a => (a -> Bool) -> Vector a -> Vector Int
{-# INLINE findIndices #-}
findIndices = G.findIndices
-- | /O(n)/ Yield 'Just' the index of the first occurence of the given element or
-- 'Nothing' if the vector does not contain the element. This is a specialised
-- version of 'findIndex'.
elemIndex :: (Unbox a, Eq a) => a -> Vector a -> Maybe Int
{-# INLINE elemIndex #-}
elemIndex = G.elemIndex
-- | /O(n)/ Yield the indices of all occurences of the given element in
-- ascending order. This is a specialised version of 'findIndices'.
elemIndices :: (Unbox a, Eq a) => a -> Vector a -> Vector Int
{-# INLINE elemIndices #-}
elemIndices = G.elemIndices
-- Folding
-- -------
-- | /O(n)/ Left fold
foldl :: Unbox b => (a -> b -> a) -> a -> Vector b -> a
{-# INLINE foldl #-}
foldl = G.foldl
-- | /O(n)/ Left fold on non-empty vectors
foldl1 :: Unbox a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldl1 #-}
foldl1 = G.foldl1
-- | /O(n)/ Left fold with strict accumulator
foldl' :: Unbox b => (a -> b -> a) -> a -> Vector b -> a
{-# INLINE foldl' #-}
foldl' = G.foldl'
-- | /O(n)/ Left fold on non-empty vectors with strict accumulator
foldl1' :: Unbox a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldl1' #-}
foldl1' = G.foldl1'
-- | /O(n)/ Right fold
foldr :: Unbox a => (a -> b -> b) -> b -> Vector a -> b
{-# INLINE foldr #-}
foldr = G.foldr
-- | /O(n)/ Right fold on non-empty vectors
foldr1 :: Unbox a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldr1 #-}
foldr1 = G.foldr1
-- | /O(n)/ Right fold with a strict accumulator
foldr' :: Unbox a => (a -> b -> b) -> b -> Vector a -> b
{-# INLINE foldr' #-}
foldr' = G.foldr'
-- | /O(n)/ Right fold on non-empty vectors with strict accumulator
foldr1' :: Unbox a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldr1' #-}
foldr1' = G.foldr1'
-- | /O(n)/ Left fold (function applied to each element and its index)
ifoldl :: Unbox b => (a -> Int -> b -> a) -> a -> Vector b -> a
{-# INLINE ifoldl #-}
ifoldl = G.ifoldl
-- | /O(n)/ Left fold with strict accumulator (function applied to each element
-- and its index)
ifoldl' :: Unbox b => (a -> Int -> b -> a) -> a -> Vector b -> a
{-# INLINE ifoldl' #-}
ifoldl' = G.ifoldl'
-- | /O(n)/ Right fold (function applied to each element and its index)
ifoldr :: Unbox a => (Int -> a -> b -> b) -> b -> Vector a -> b
{-# INLINE ifoldr #-}
ifoldr = G.ifoldr
-- | /O(n)/ Right fold with strict accumulator (function applied to each
-- element and its index)
ifoldr' :: Unbox a => (Int -> a -> b -> b) -> b -> Vector a -> b
{-# INLINE ifoldr' #-}
ifoldr' = G.ifoldr'
-- Specialised folds
-- -----------------
-- | /O(n)/ Check if all elements satisfy the predicate.
all :: Unbox a => (a -> Bool) -> Vector a -> Bool
{-# INLINE all #-}
all = G.all
-- | /O(n)/ Check if any element satisfies the predicate.
any :: Unbox a => (a -> Bool) -> Vector a -> Bool
{-# INLINE any #-}
any = G.any
-- | /O(n)/ Check if all elements are 'True'
and :: Vector Bool -> Bool
{-# INLINE and #-}
and = G.and
-- | /O(n)/ Check if any element is 'True'
or :: Vector Bool -> Bool
{-# INLINE or #-}
or = G.or
-- | /O(n)/ Compute the sum of the elements
sum :: (Unbox a, Num a) => Vector a -> a
{-# INLINE sum #-}
sum = G.sum
-- | /O(n)/ Compute the produce of the elements
product :: (Unbox a, Num a) => Vector a -> a
{-# INLINE product #-}
product = G.product
-- | /O(n)/ Yield the maximum element of the vector. The vector may not be
-- empty.
maximum :: (Unbox a, Ord a) => Vector a -> a
{-# INLINE maximum #-}
maximum = G.maximum
-- | /O(n)/ Yield the maximum element of the vector according to the given
-- comparison function. The vector may not be empty.
maximumBy :: Unbox a => (a -> a -> Ordering) -> Vector a -> a
{-# INLINE maximumBy #-}
maximumBy = G.maximumBy
-- | /O(n)/ Yield the minimum element of the vector. The vector may not be
-- empty.
minimum :: (Unbox a, Ord a) => Vector a -> a
{-# INLINE minimum #-}
minimum = G.minimum
-- | /O(n)/ Yield the minimum element of the vector according to the given
-- comparison function. The vector may not be empty.
minimumBy :: Unbox a => (a -> a -> Ordering) -> Vector a -> a
{-# INLINE minimumBy #-}
minimumBy = G.minimumBy
-- | /O(n)/ Yield the index of the maximum element of the vector. The vector
-- may not be empty.
maxIndex :: (Unbox a, Ord a) => Vector a -> Int
{-# INLINE maxIndex #-}
maxIndex = G.maxIndex
-- | /O(n)/ Yield the index of the maximum element of the vector according to
-- the given comparison function. The vector may not be empty.
maxIndexBy :: Unbox a => (a -> a -> Ordering) -> Vector a -> Int
{-# INLINE maxIndexBy #-}
maxIndexBy = G.maxIndexBy
-- | /O(n)/ Yield the index of the minimum element of the vector. The vector
-- may not be empty.
minIndex :: (Unbox a, Ord a) => Vector a -> Int
{-# INLINE minIndex #-}
minIndex = G.minIndex
-- | /O(n)/ Yield the index of the minimum element of the vector according to
-- the given comparison function. The vector may not be empty.
minIndexBy :: Unbox a => (a -> a -> Ordering) -> Vector a -> Int
{-# INLINE minIndexBy #-}
minIndexBy = G.minIndexBy
-- Monadic folds
-- -------------
-- | /O(n)/ Monadic fold
foldM :: (Monad m, Unbox b) => (a -> b -> m a) -> a -> Vector b -> m a
{-# INLINE foldM #-}
foldM = G.foldM
-- | /O(n)/ Monadic fold (action applied to each element and its index)
ifoldM :: (Monad m, Unbox b) => (a -> Int -> b -> m a) -> a -> Vector b -> m a
{-# INLINE ifoldM #-}
ifoldM = G.ifoldM
-- | /O(n)/ Monadic fold over non-empty vectors
fold1M :: (Monad m, Unbox a) => (a -> a -> m a) -> Vector a -> m a
{-# INLINE fold1M #-}
fold1M = G.fold1M
-- | /O(n)/ Monadic fold with strict accumulator
foldM' :: (Monad m, Unbox b) => (a -> b -> m a) -> a -> Vector b -> m a
{-# INLINE foldM' #-}
foldM' = G.foldM'
-- | /O(n)/ Monadic fold with strict accumulator (action applied to each
-- element and its index)
ifoldM' :: (Monad m, Unbox b) => (a -> Int -> b -> m a) -> a -> Vector b -> m a
{-# INLINE ifoldM' #-}
ifoldM' = G.ifoldM'
-- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator
fold1M' :: (Monad m, Unbox a) => (a -> a -> m a) -> Vector a -> m a
{-# INLINE fold1M' #-}
fold1M' = G.fold1M'
-- | /O(n)/ Monadic fold that discards the result
foldM_ :: (Monad m, Unbox b) => (a -> b -> m a) -> a -> Vector b -> m ()
{-# INLINE foldM_ #-}
foldM_ = G.foldM_
-- | /O(n)/ Monadic fold that discards the result (action applied to each
-- element and its index)
ifoldM_ :: (Monad m, Unbox b) => (a -> Int -> b -> m a) -> a -> Vector b -> m ()
{-# INLINE ifoldM_ #-}
ifoldM_ = G.ifoldM_
-- | /O(n)/ Monadic fold over non-empty vectors that discards the result
fold1M_ :: (Monad m, Unbox a) => (a -> a -> m a) -> Vector a -> m ()
{-# INLINE fold1M_ #-}
fold1M_ = G.fold1M_
-- | /O(n)/ Monadic fold with strict accumulator that discards the result
foldM'_ :: (Monad m, Unbox b) => (a -> b -> m a) -> a -> Vector b -> m ()
{-# INLINE foldM'_ #-}
foldM'_ = G.foldM'_
-- | /O(n)/ Monadic fold with strict accumulator that discards the result
-- (action applied to each element and its index)
ifoldM'_ :: (Monad m, Unbox b)
=> (a -> Int -> b -> m a) -> a -> Vector b -> m ()
{-# INLINE ifoldM'_ #-}
ifoldM'_ = G.ifoldM'_
-- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator
-- that discards the result
fold1M'_ :: (Monad m, Unbox a) => (a -> a -> m a) -> Vector a -> m ()
{-# INLINE fold1M'_ #-}
fold1M'_ = G.fold1M'_
-- Prefix sums (scans)
-- -------------------
-- | /O(n)/ Prescan
--
-- @
-- prescanl f z = 'init' . 'scanl' f z
-- @
--
-- Example: @prescanl (+) 0 \<1,2,3,4\> = \<0,1,3,6\>@
--
prescanl :: (Unbox a, Unbox b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE prescanl #-}
prescanl = G.prescanl
-- | /O(n)/ Prescan with strict accumulator
prescanl' :: (Unbox a, Unbox b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE prescanl' #-}
prescanl' = G.prescanl'
-- | /O(n)/ Scan
--
-- @
-- postscanl f z = 'tail' . 'scanl' f z
-- @
--
-- Example: @postscanl (+) 0 \<1,2,3,4\> = \<1,3,6,10\>@
--
postscanl :: (Unbox a, Unbox b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE postscanl #-}
postscanl = G.postscanl
-- | /O(n)/ Scan with strict accumulator
postscanl' :: (Unbox a, Unbox b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE postscanl' #-}
postscanl' = G.postscanl'
-- | /O(n)/ Haskell-style scan
--
-- > scanl f z <x1,...,xn> = <y1,...,y(n+1)>
-- > where y1 = z
-- > yi = f y(i-1) x(i-1)
--
-- Example: @scanl (+) 0 \<1,2,3,4\> = \<0,1,3,6,10\>@
--
scanl :: (Unbox a, Unbox b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE scanl #-}
scanl = G.scanl
-- | /O(n)/ Haskell-style scan with strict accumulator
scanl' :: (Unbox a, Unbox b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE scanl' #-}
scanl' = G.scanl'
-- | /O(n)/ Scan over a non-empty vector
--
-- > scanl f <x1,...,xn> = <y1,...,yn>
-- > where y1 = x1
-- > yi = f y(i-1) xi
--
scanl1 :: Unbox a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanl1 #-}
scanl1 = G.scanl1
-- | /O(n)/ Scan over a non-empty vector with a strict accumulator
scanl1' :: Unbox a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanl1' #-}
scanl1' = G.scanl1'
-- | /O(n)/ Right-to-left prescan
--
-- @
-- prescanr f z = 'reverse' . 'prescanl' (flip f) z . 'reverse'
-- @
--
prescanr :: (Unbox a, Unbox b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE prescanr #-}
prescanr = G.prescanr
-- | /O(n)/ Right-to-left prescan with strict accumulator
prescanr' :: (Unbox a, Unbox b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE prescanr' #-}
prescanr' = G.prescanr'
-- | /O(n)/ Right-to-left scan
postscanr :: (Unbox a, Unbox b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE postscanr #-}
postscanr = G.postscanr
-- | /O(n)/ Right-to-left scan with strict accumulator
postscanr' :: (Unbox a, Unbox b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE postscanr' #-}
postscanr' = G.postscanr'
-- | /O(n)/ Right-to-left Haskell-style scan
scanr :: (Unbox a, Unbox b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE scanr #-}
scanr = G.scanr
-- | /O(n)/ Right-to-left Haskell-style scan with strict accumulator
scanr' :: (Unbox a, Unbox b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE scanr' #-}
scanr' = G.scanr'
-- | /O(n)/ Right-to-left scan over a non-empty vector
scanr1 :: Unbox a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanr1 #-}
scanr1 = G.scanr1
-- | /O(n)/ Right-to-left scan over a non-empty vector with a strict
-- accumulator
scanr1' :: Unbox a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanr1' #-}
scanr1' = G.scanr1'
-- Conversions - Lists
-- ------------------------
-- | /O(n)/ Convert a vector to a list
toList :: Unbox a => Vector a -> [a]
{-# INLINE toList #-}
toList = G.toList
-- | /O(n)/ Convert a list to a vector
fromList :: Unbox a => [a] -> Vector a
{-# INLINE fromList #-}
fromList = G.fromList
-- | /O(n)/ Convert the first @n@ elements of a list to a vector
--
-- @
-- fromListN n xs = 'fromList' ('take' n xs)
-- @
fromListN :: Unbox a => Int -> [a] -> Vector a
{-# INLINE fromListN #-}
fromListN = G.fromListN
-- Conversions - Mutable vectors
-- -----------------------------
-- | /O(1)/ Unsafe convert a mutable vector to an immutable one without
-- copying. The mutable vector may not be used after this operation.
unsafeFreeze :: (Unbox a, PrimMonad m) => MVector (PrimState m) a -> m (Vector a)
{-# INLINE unsafeFreeze #-}
unsafeFreeze = G.unsafeFreeze
-- | /O(1)/ Unsafely convert an immutable vector to a mutable one without
-- copying. The immutable vector may not be used after this operation.
unsafeThaw :: (Unbox a, PrimMonad m) => Vector a -> m (MVector (PrimState m) a)
{-# INLINE unsafeThaw #-}
unsafeThaw = G.unsafeThaw
-- | /O(n)/ Yield a mutable copy of the immutable vector.
thaw :: (Unbox a, PrimMonad m) => Vector a -> m (MVector (PrimState m) a)
{-# INLINE thaw #-}
thaw = G.thaw
-- | /O(n)/ Yield an immutable copy of the mutable vector.
freeze :: (Unbox a, PrimMonad m) => MVector (PrimState m) a -> m (Vector a)
{-# INLINE freeze #-}
freeze = G.freeze
-- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must
-- have the same length. This is not checked.
unsafeCopy
:: (Unbox a, PrimMonad m) => MVector (PrimState m) a -> Vector a -> m ()
{-# INLINE unsafeCopy #-}
unsafeCopy = G.unsafeCopy
-- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must
-- have the same length.
copy :: (Unbox a, PrimMonad m) => MVector (PrimState m) a -> Vector a -> m ()
{-# INLINE copy #-}
copy = G.copy
#define DEFINE_IMMUTABLE
#include "unbox-tuple-instances"
| seckcoder/vector | Data/Vector/Unboxed.hs | bsd-3-clause | 44,965 | 0 | 14 | 9,780 | 10,047 | 5,584 | 4,463 | -1 | -1 |
module PackageTests.BuildDeps.InternalLibrary0.Check where
import Control.Monad
import Data.Version
import PackageTests.PackageTester
import System.FilePath
import Test.HUnit
suite :: Version -> FilePath -> Test
suite cabalVersion ghcPath = TestCase $ do
let spec = PackageSpec ("PackageTests" </> "BuildDeps" </> "InternalLibrary0") []
result <- cabal_build spec ghcPath
assertBuildFailed result
when (cabalVersion >= Version [1, 7] []) $ do
let sb = "library which is defined within the same package."
-- In 1.7 it should tell you how to enable the desired behaviour.
assertOutputContains sb result
| jwiegley/ghc-release | libraries/Cabal/cabal/tests/PackageTests/BuildDeps/InternalLibrary0/Check.hs | gpl-3.0 | 644 | 0 | 14 | 123 | 153 | 78 | 75 | 14 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Handy path information.
module Stack.Path
( path
, pathParser
) where
import Stack.Prelude
import Data.List (intercalate)
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Lens.Micro (lens)
import qualified Options.Applicative as OA
import Path
import Path.Extra
import Stack.Constants
import Stack.Constants.Config
import Stack.GhcPkg as GhcPkg
import Stack.PackageIndex (HasCabalLoader (..))
import Stack.Types.Config
import Stack.Types.Runner
import qualified System.FilePath as FP
import System.IO (stderr)
import RIO.Process (EnvOverride(eoPath), HasEnvOverride (..))
-- | Print out useful path information in a human-readable format (and
-- support others later).
path
:: HasEnvConfig env
=> [Text]
-> RIO env ()
path keys =
do -- We must use a BuildConfig from an EnvConfig to ensure that it contains the
-- full environment info including GHC paths etc.
bc <- view $ envConfigL.buildConfigL
-- This is the modified 'bin-path',
-- including the local GHC or MSYS if not configured to operate on
-- global GHC.
-- It was set up in 'withBuildConfigAndLock -> withBuildConfigExt -> setupEnv'.
-- So it's not the *minimal* override path.
snap <- packageDatabaseDeps
plocal <- packageDatabaseLocal
extra <- packageDatabaseExtra
whichCompiler <- view $ actualCompilerVersionL.whichCompilerL
global <- GhcPkg.getGlobalDB whichCompiler
snaproot <- installationRootDeps
localroot <- installationRootLocal
toolsDir <- bindirCompilerTools
distDir <- distRelativeDir
hpcDir <- hpcReportDir
compiler <- getCompilerPath whichCompiler
let deprecated = filter ((`elem` keys) . fst) deprecatedPathKeys
liftIO $ forM_ deprecated $ \(oldOption, newOption) -> T.hPutStrLn stderr $ T.unlines
[ ""
, "'--" <> oldOption <> "' will be removed in a future release."
, "Please use '--" <> newOption <> "' instead."
, ""
]
forM_
-- filter the chosen paths in flags (keys),
-- or show all of them if no specific paths chosen.
(filter
(\(_,key,_) ->
(null keys && key /= T.pack deprecatedStackRootOptionName) || elem key keys)
paths)
(\(_,key,path') ->
liftIO $ T.putStrLn
-- If a single path type is requested, output it directly.
-- Otherwise, name all the paths.
((if length keys == 1
then ""
else key <> ": ") <>
path'
(PathInfo
bc
snap
plocal
global
snaproot
localroot
toolsDir
distDir
hpcDir
extra
compiler)))
pathParser :: OA.Parser [Text]
pathParser =
mapMaybeA
(\(desc,name,_) ->
OA.flag Nothing
(Just name)
(OA.long (T.unpack name) <>
OA.help desc))
paths
-- | Passed to all the path printers as a source of info.
data PathInfo = PathInfo
{ piBuildConfig :: BuildConfig
, piSnapDb :: Path Abs Dir
, piLocalDb :: Path Abs Dir
, piGlobalDb :: Path Abs Dir
, piSnapRoot :: Path Abs Dir
, piLocalRoot :: Path Abs Dir
, piToolsDir :: Path Abs Dir
, piDistDir :: Path Rel Dir
, piHpcDir :: Path Abs Dir
, piExtraDbs :: [Path Abs Dir]
, piCompiler :: Path Abs File
}
instance HasPlatform PathInfo
instance HasLogFunc PathInfo where
logFuncL = configL.logFuncL
instance HasRunner PathInfo where
runnerL = configL.runnerL
instance HasConfig PathInfo
instance HasCabalLoader PathInfo where
cabalLoaderL = configL.cabalLoaderL
instance HasEnvOverride PathInfo where
envOverrideL = configL.envOverrideL
instance HasBuildConfig PathInfo where
buildConfigL = lens piBuildConfig (\x y -> x { piBuildConfig = y })
. buildConfigL
-- | The paths of interest to a user. The first tuple string is used
-- for a description that the optparse flag uses, and the second
-- string as a machine-readable key and also for @--foo@ flags. The user
-- can choose a specific path to list like @--stack-root@. But
-- really it's mainly for the documentation aspect.
--
-- When printing output we generate @PathInfo@ and pass it to the
-- function to generate an appropriate string. Trailing slashes are
-- removed, see #506
paths :: [(String, Text, PathInfo -> Text)]
paths =
[ ( "Global stack root directory"
, T.pack stackRootOptionName
, view $ stackRootL.to toFilePathNoTrailingSep.to T.pack)
, ( "Project root (derived from stack.yaml file)"
, "project-root"
, view $ projectRootL.to toFilePathNoTrailingSep.to T.pack)
, ( "Configuration location (where the stack.yaml file is)"
, "config-location"
, view $ stackYamlL.to toFilePath.to T.pack)
, ( "PATH environment variable"
, "bin-path"
, T.pack . intercalate [FP.searchPathSeparator] . eoPath . view envOverrideL )
, ( "Install location for GHC and other core tools"
, "programs"
, view $ configL.to configLocalPrograms.to toFilePathNoTrailingSep.to T.pack)
, ( "Compiler binary (e.g. ghc)"
, "compiler-exe"
, T.pack . toFilePath . piCompiler )
, ( "Directory containing the compiler binary (e.g. ghc)"
, "compiler-bin"
, T.pack . toFilePathNoTrailingSep . parent . piCompiler )
, ( "Directory containing binaries specific to a particular compiler (e.g. intero)"
, "compiler-tools-bin"
, T.pack . toFilePathNoTrailingSep . piToolsDir )
, ( "Local bin dir where stack installs executables (e.g. ~/.local/bin)"
, "local-bin"
, view $ configL.to configLocalBin.to toFilePathNoTrailingSep.to T.pack)
, ( "Extra include directories"
, "extra-include-dirs"
, T.intercalate ", " . map T.pack . Set.elems . configExtraIncludeDirs . view configL )
, ( "Extra library directories"
, "extra-library-dirs"
, T.intercalate ", " . map T.pack . Set.elems . configExtraLibDirs . view configL )
, ( "Snapshot package database"
, "snapshot-pkg-db"
, T.pack . toFilePathNoTrailingSep . piSnapDb )
, ( "Local project package database"
, "local-pkg-db"
, T.pack . toFilePathNoTrailingSep . piLocalDb )
, ( "Global package database"
, "global-pkg-db"
, T.pack . toFilePathNoTrailingSep . piGlobalDb )
, ( "GHC_PACKAGE_PATH environment variable"
, "ghc-package-path"
, \pi' -> mkGhcPackagePath True (piLocalDb pi') (piSnapDb pi') (piExtraDbs pi') (piGlobalDb pi'))
, ( "Snapshot installation root"
, "snapshot-install-root"
, T.pack . toFilePathNoTrailingSep . piSnapRoot )
, ( "Local project installation root"
, "local-install-root"
, T.pack . toFilePathNoTrailingSep . piLocalRoot )
, ( "Snapshot documentation root"
, "snapshot-doc-root"
, \pi' -> T.pack (toFilePathNoTrailingSep (piSnapRoot pi' </> docDirSuffix)))
, ( "Local project documentation root"
, "local-doc-root"
, \pi' -> T.pack (toFilePathNoTrailingSep (piLocalRoot pi' </> docDirSuffix)))
, ( "Dist work directory, relative to package directory"
, "dist-dir"
, T.pack . toFilePathNoTrailingSep . piDistDir )
, ( "Where HPC reports and tix files are stored"
, "local-hpc-root"
, T.pack . toFilePathNoTrailingSep . piHpcDir )
, ( "DEPRECATED: Use '--local-bin' instead"
, "local-bin-path"
, T.pack . toFilePathNoTrailingSep . configLocalBin . view configL )
, ( "DEPRECATED: Use '--programs' instead"
, "ghc-paths"
, T.pack . toFilePathNoTrailingSep . configLocalPrograms . view configL )
, ( "DEPRECATED: Use '--" <> stackRootOptionName <> "' instead"
, T.pack deprecatedStackRootOptionName
, T.pack . toFilePathNoTrailingSep . view stackRootL )
]
deprecatedPathKeys :: [(Text, Text)]
deprecatedPathKeys =
[ (T.pack deprecatedStackRootOptionName, T.pack stackRootOptionName)
, ("ghc-paths", "programs")
, ("local-bin-path", "local-bin")
]
| anton-dessiatov/stack | src/Stack/Path.hs | bsd-3-clause | 8,884 | 0 | 17 | 2,666 | 1,690 | 946 | 744 | 184 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Wreq.Internal.Link
(
links
) where
import Control.Applicative ((<$>), (<*>), (*>), (<*), many)
import Data.Attoparsec.ByteString.Char8 as A8
import Data.ByteString (ByteString)
import Network.Wreq.Types (Link(..))
import qualified Data.Attoparsec.ByteString as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
links :: B.ByteString -> [Link]
links hdr = case parseOnly f hdr of
Left _ -> []
Right xs -> xs
where f = sepBy1 (link <* skipSpace) (char8 ',' *> skipSpace) <* endOfInput
link :: Parser Link
link = Link <$> url <*> many (char8 ';' *> skipSpace *> param)
where url = char8 '<' *> A8.takeTill (=='>') <* char8 '>' <* skipSpace
param :: Parser (ByteString, ByteString)
param = do
name <- paramName
skipSpace *> "=" *> skipSpace
c <- peekChar'
let isTokenChar = A.inClass "!#$%&'()*+./0-9:<=>?@a-zA-Z[]^_`{|}~-"
val <- case c of
'"' -> quotedString
_ -> A.takeWhile isTokenChar
skipSpace
return (name, val)
data Quot = Literal | Backslash
quotedString :: Parser ByteString
quotedString = char '"' *> (fixup <$> body) <* char '"'
where body = A8.scan Literal $ \s c ->
case (s,c) of
(Literal, '\\') -> backslash
(Literal, '"') -> Nothing
_ -> literal
literal = Just Literal
backslash = Just Backslash
fixup = B8.pack . go . B8.unpack
where go ('\\' : x@'\\' : xs) = x : go xs
go ('\\' : x@'"' : xs) = x : go xs
go (x : xs) = x : go xs
go xs = xs
paramName :: Parser ByteString
paramName = do
name <- A.takeWhile1 $ A.inClass "a-zA-Z0-9!#$&+-.^_`|~"
c <- peekChar
return $ case c of
Just '*' -> B8.snoc name '*'
_ -> name
| bitemyapp/wreq | Network/Wreq/Internal/Link.hs | bsd-3-clause | 1,936 | 0 | 13 | 594 | 662 | 355 | 307 | 52 | 6 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Heist.Interpreted.Tests
( tests
, quickRender
) where
------------------------------------------------------------------------------
import Blaze.ByteString.Builder
import Control.Error
import Control.Monad.State
import Data.Aeson
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.HashMap.Strict as Map
import Data.Map.Syntax
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import System.IO.Unsafe
import Test.Framework (Test)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import qualified Test.HUnit as H
import Test.QuickCheck
import Test.QuickCheck.Monadic
------------------------------------------------------------------------------
import Heist
import Heist.Common
import Heist.Internal.Types
import Heist.Interpreted.Internal
import Heist.Splices.Apply
import Heist.Splices.Ignore
import Heist.Splices.Json
import Heist.Splices.Markdown
import Heist.TestCommon
import qualified Text.XmlHtml as X
import qualified Text.XmlHtml.Cursor as X
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testProperty "heist/simpleBind" simpleBindTest
, testProperty "heist/simpleApply" simpleApplyTest
, testCase "heist/templateAdd" addTest
, testCase "heist/hasTemplate" hasTemplateTest
, testCase "heist/getDoc" getDocTest
, testCase "heist/load" loadTest
, testCase "heist/fsLoad" fsLoadTest
, testCase "heist/renderNoName" renderNoNameTest
, testCase "heist/doctype" doctypeTest
, testCase "heist/attributeSubstitution" attrSubstTest
, testCase "heist/bindAttribute" bindAttrTest
, testCase "heist/markdown" markdownTest
, testCase "heist/pandoc" pandocTest
, testCase "heist/pandoc_div" pandocDivTest
, testCase "heist/title_expansion" titleExpansion
, testCase "heist/textarea_expansion" textareaExpansion
, testCase "heist/div_expansion" divExpansion
, testCase "heist/bind_param" bindParam
, testCase "heist/markdownText" markdownTextTest
, testCase "heist/apply" applyTest
, testCase "heist/ignore" ignoreTest
, testCase "heist/lookupTemplateContext" lookupTemplateTest
, testCase "heist/attrSpliceContext" attrSpliceContext
, testCase "heist/json/values" jsonValueTest
, testCase "heist/json/object" jsonObjectTest
, testCase "heist/renderXML" xmlNotHtmlTest
]
------------------------------------------------------------------------------
simpleBindTest :: Property
simpleBindTest = monadicIO $ forAllM arbitrary prop
where
prop :: Bind -> PropertyM IO ()
prop bind = do
let template = buildBindTemplate bind
let result = buildResult bind
spliceResult <- run $ do
hs <- loadEmpty defaultLoadTimeSplices mempty mempty mempty
evalHeistT (runNodeList template)
(X.TextNode "") hs
assert $ result == spliceResult
------------------------------------------------------------------------------
simpleApplyTest :: Property
simpleApplyTest = monadicIO $ forAllM arbitrary prop
where
prop :: Apply -> PropertyM IO ()
prop apply = do
let correct = calcCorrect apply
result <- run $ calcResult apply
assert $ correct == result
------------------------------------------------------------------------------
addTest :: IO ()
addTest = do
es <- loadEmpty mempty mempty mempty mempty
let hs = addTemplate "aoeu" [] Nothing es
H.assertEqual "lookup test" (Just []) $
fmap (X.docContent . dfDoc . fst) $
lookupTemplate "aoeu" hs _templateMap
------------------------------------------------------------------------------
hasTemplateTest :: H.Assertion
hasTemplateTest = do
ets <- loadIO "templates" mempty mempty mempty mempty
let tm = either (error . unlines) _templateMap ets
hs <- loadEmpty mempty mempty mempty mempty
let hs's = setTemplates tm hs
H.assertBool "hasTemplate hs's" (hasTemplate "index" hs's)
------------------------------------------------------------------------------
getDocTest :: H.Assertion
getDocTest = do
d <- getDoc "bkteoar"
H.assertBool "non-existent doc" $ isLeft d
f <- getDoc "templates/index.tpl"
H.assertBool "index doc" $ not $ isLeft f
------------------------------------------------------------------------------
loadTest :: H.Assertion
loadTest = do
ets <- loadIO "templates" mempty mempty mempty mempty
either (error "Error loading templates")
(\ts -> do let tm = _templateMap ts
H.assertEqual "loadTest size" 40 $ Map.size tm
) ets
------------------------------------------------------------------------------
fsLoadTest :: H.Assertion
fsLoadTest = do
ets <- loadIO "templates" mempty mempty mempty mempty
let tm = either (error "Error loading templates") _templateMap ets
es <- loadEmpty mempty mempty mempty mempty
let hs = setTemplates tm es
let f = g hs
f isNothing "abc/def/xyz"
f isJust "a"
f isJust "bar/a"
f isJust "/bar/a"
where
g ts p n = H.assertBool ("loading template " ++ n) $ p $
lookupTemplate (B.pack n) ts _templateMap
------------------------------------------------------------------------------
renderNoNameTest :: H.Assertion
renderNoNameTest = do
ets <- loadT "templates" mempty mempty mempty mempty
either (error "Error loading templates")
(\ts -> do t <- renderTemplate ts ""
H.assertBool "renderNoName" $ isNothing t
) ets
------------------------------------------------------------------------------
doctypeTest :: H.Assertion
doctypeTest = do
ets <- loadT "templates" mempty mempty mempty mempty
let ts = either (error "Error loading templates") id ets
Just (indexDoc, _) <- renderTemplate ts "index"
H.assertEqual "index doctype test" indexRes $ toByteString $ indexDoc
Just (_, _) <- renderTemplate ts "ioc"
H.assertEqual "ioc doctype test" indexRes $ toByteString $ indexDoc
where
indexRes = B.concat
[doctype
,"\n <html>\n<div id='pre_{att}_post'>\n/index\n</div>\n</html>\n"
]
------------------------------------------------------------------------------
attrSubstTest :: H.Assertion
attrSubstTest = do
ets <- loadT "templates" mempty mempty mempty mempty
let ts = either (error "Error loading templates") id ets
check "attr subst 1" (bindSplices splices ts) out1
check "attr subst 2" ts out2
where
splices = defaultLoadTimeSplices `mappend`
("foo" ## return [X.TextNode "meaning_of_everything"])
check str ts expected = do
Just (resDoc, _) <- renderTemplate ts "attrs"
H.assertEqual str expected $ toByteString $ resDoc
out1 = B.unlines
["<mytag flag>Empty attribute</mytag>"
,"<mytag flag='abc${bar}'>No ident capture</mytag>"
,"<div id='pre_meaning_of_everything_post'></div>"
]
out2 = B.unlines
["<mytag flag>Empty attribute</mytag>"
,"<mytag flag='abc${bar}'>No ident capture</mytag>"
,"<div id='pre_${foo}_post'></div>"
]
------------------------------------------------------------------------------
bindAttrTest :: H.Assertion
bindAttrTest = do
ets <- loadT "templates" mempty mempty mempty mempty
let ts = either (error "Error loading templates") id ets
check ts "<div id=\'zzzzz\'"
where
check ts str = do
Just (resDoc, _) <- renderTemplate ts "bind-attrs"
H.assertBool ("attr subst " ++ (show str)) $ not $ B.null $
snd $ B.breakSubstring str $ toByteString $ resDoc
H.assertBool ("attr subst bar") $ B.null $
snd $ B.breakSubstring "${bar}" $ toByteString $ resDoc
------------------------------------------------------------------------------
markdownHtmlExpected :: ByteString
markdownHtmlExpected =
"<div class='markdown'><p>This <em>is</em> a test.</p></div>"
------------------------------------------------------------------------------
-- | Markdown test on a file
markdownTest :: H.Assertion
markdownTest = renderTest "markdown" markdownHtmlExpected
-----------------------------------------------------------------------------
-- | Pandoc test on a file
pandocTest :: H.Assertion
pandocTest = renderTest "pandoc" pandocNoDivHtmlExpected
pandocDivTest :: H.Assertion
pandocDivTest = renderTest "pandocdiv" pandocDivHtmlExpected
pandocNoDivHtmlExpected :: ByteString
pandocNoDivHtmlExpected = "<p>This <em>is</em> a test.</p>"
pandocDivHtmlExpected :: ByteString
pandocDivHtmlExpected =
"<div class='foo test' id='pandoc'><p>This <em>is</em> a test.</p></div>"
-- Implementaton dependent. Class is prepended in current implementation,
-- it will be first attribute
pandocTestSplices :: Splices (Splice IO)
pandocTestSplices = do
"pandocnodiv" ## pandocSplice optsNoDiv
"pandocdiv" ## pandocSplice optsDiv
where
optsNoDiv = setPandocWrapDiv Nothing defaultPandocOptions
optsDiv = setPandocWrapDiv (Just "test") defaultPandocOptions
------------------------------------------------------------------------------
jsonValueTest :: H.Assertion
jsonValueTest = do
renderTest "json" jsonExpected1
renderTest "json_snippet" jsonExpected2
where
jsonExpected1 = B.concat [ "<i><b>ok</b></i><i>1</i>"
, "<i></i><i>false</i><i>foo</i>" ]
jsonExpected2 = "<i><b>ok</b></i><i>1</i><i></i><i>false</i><i>foo</i>"
------------------------------------------------------------------------------
jsonObjectTest :: H.Assertion
jsonObjectTest = do
renderTest "json_object" jsonExpected
where
jsonExpected = "<i>1</i><i><b>ok</b></i>12quuxquux1<b>ok</b>"
------------------------------------------------------------------------------
-- | Render a template and assert that it matches an expected result
renderTest :: ByteString -- ^ template name
-> ByteString -- ^ expected result
-> H.Assertion
renderTest templateName expectedResult = do
ets <- loadT "templates" mempty pandocTestSplices mempty mempty
let ts = either (error "Error loading templates") id ets
check ts expectedResult
where
bind txt = bindJson v
where
v :: Value
v = fromJust $ decode txt
check ts0 str = do
let splices = do
"json" ## bind "[\"<b>ok</b>\", 1, null, false, \"foo\"]"
"jsonObject" ##
(bind $ mconcat [
"{\"foo\": 1, \"bar\": \"<b>ok</b>\", "
, "\"baz\": { \"baz1\": 1, \"baz2\": 2 }, "
, "\"quux\": \"quux\" }"
])
let ts = bindSplices splices ts0
Just (doc, _) <- renderTemplate ts templateName
let result = B.filter (/= '\n') (toByteString doc)
H.assertEqual ("Should match " ++ (show str)) str result
------------------------------------------------------------------------------
-- | Expansion of a bound name inside a title-tag
titleExpansion :: H.Assertion
titleExpansion = renderTest "title_expansion" expected
where
expected = "<title>foo</title>"
------------------------------------------------------------------------------
-- | Expansion of a bound name inside a textarea-tag
textareaExpansion :: H.Assertion
textareaExpansion = renderTest "textarea_expansion" expected
where
expected = B.concat
[ "<textarea>foo</textarea>" ]
------------------------------------------------------------------------------
-- | Expansion of a bound name inside a div-tag
divExpansion :: H.Assertion
divExpansion = renderTest "div_expansion" expected
where
expected = "<div>foo</div>"
------------------------------------------------------------------------------
-- | Handling of <content> and bound parameters in a bound tag.
bindParam :: H.Assertion
bindParam = renderTest "bind_param" "<li>Hi there world</li>"
------------------------------------------------------------------------------
-- | Handling of <content> and bound parameters in a bound tag.
attrSpliceContext :: H.Assertion
attrSpliceContext = renderTest "attrsubtest2"
"<a href='asdf'>link</a><a href='before$after'>foo</a>"
------------------------------------------------------------------------------
-- | Markdown test on supplied text
markdownTextTest :: H.Assertion
markdownTextTest = do
hs <- loadEmpty mempty mempty mempty mempty
result <- evalHeistT markdownSplice
(X.TextNode "This *is* a test.")
hs
H.assertEqual "Markdown text" markdownHtmlExpected
(B.filter (/= '\n') $ toByteString $
X.render (X.HtmlDocument X.UTF8 Nothing result))
------------------------------------------------------------------------------
applyTest :: H.Assertion
applyTest = do
es <- loadEmpty mempty mempty mempty mempty
res <- evalHeistT applyImpl
(X.Element "apply" [("template", "nonexistant")] []) es
H.assertEqual "apply nothing" [] res
------------------------------------------------------------------------------
ignoreTest :: H.Assertion
ignoreTest = do
es <- loadEmpty mempty mempty mempty mempty
res <- evalHeistT ignoreImpl
(X.Element "ignore" [("tag", "ignorable")]
[X.TextNode "This should be ignored"]) es
H.assertEqual "<ignore> tag" [] res
lookupTemplateTest :: IO ()
lookupTemplateTest = do
hs <- loadHS "templates"
let k = do
modifyHS (\st -> st { _curContext = ["foo"] })
getsHS $ (\hs' -> lookupTemplate "/user/menu" hs' _templateMap)
res <- runHeistT k (X.TextNode "") hs
H.assertBool "lookup context test" $ isJust $ fst res
------------------------------------------------------------------------------
xmlNotHtmlTest :: H.Assertion
xmlNotHtmlTest = renderTest "rss" expected where
expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss><channel><link>http://www.devalot.com/</link></channel></rss>"
------------------------------------------------------------------------------
identStartChar :: [Char]
identStartChar = ['a'..'z']
------------------------------------------------------------------------------
identChar :: [Char]
identChar = '_' : identStartChar
------------------------------------------------------------------------------
textGen :: Gen [Char]
textGen = listOf $ elements ((replicate 5 ' ') ++ identStartChar)
------------------------------------------------------------------------------
limitedDepth :: Int -> Gen X.Node
limitedDepth 0 = liftM (X.TextNode . T.pack) textGen
limitedDepth n =
oneof [ liftM (X.TextNode . T.pack) textGen
, liftM3 X.Element arbitrary
(liftM (take 2) arbitrary)
(liftM (take 3) $ listOf $ limitedDepth (n - 1))
]
------------------------------------------------------------------------------
-- | Returns the number of unique insertion points in the tree.
-- If h = insertAt f n g", the following property holds:
-- insSize h == (insSize f) + (insSize g) - 1
insSize :: [X.Node] -> Int
insSize ns = 1 + (sum $ map nodeSize ns)
where nodeSize (X.Element _ _ c) = 1 + (insSize c)
nodeSize _ = 1
------------------------------------------------------------------------------
insertAt :: [X.Node] -> Int -> [X.Node] -> [X.Node]
insertAt elems 0 ns = elems ++ ns
insertAt elems _ [] = elems
insertAt elems n list = maybe [] X.topNodes $
evalState (processNode elems $ fromJust $ X.fromNodes list) n
------------------------------------------------------------------------------
move :: Insert ()
move = modify (\x -> x - 1)
------------------------------------------------------------------------------
processNode :: [X.Node] -> X.Cursor -> Insert (Maybe X.Cursor)
processNode elems loc =
liftM2 mplus (move >> goDown loc) (move >> goRight loc)
where
goDown l =
case X.current l of
X.TextNode _ -> modify (+1) >> return Nothing
X.Element _ _ _ -> doneCheck (X.insertManyFirstChild elems)
X.firstChild
l
X.Comment _ -> return Nothing
goRight = doneCheck (Just . X.insertManyRight elems) X.right
doneCheck insertFunc next l = do
s <- get
if s == 0
then return $ insertFunc l
else maybe (return Nothing) (processNode elems) $ next l
------------------------------------------------------------------------------
newtype Name = Name { unName :: Text } deriving (Show)
instance Arbitrary Name where
arbitrary = do
x <- elements identStartChar
n <- choose (4,10)
rest <- vectorOf n $ elements identChar
return $ Name $ T.pack (x:rest)
instance Arbitrary X.Node where
arbitrary = limitedDepth 3
shrink (X.Element _ [] []) = []
shrink (X.Element n [] (_:cs)) = [X.Element n [] cs]
shrink (X.Element n (_:as) []) = [X.Element n as []]
shrink (X.Element n as cs) = [X.Element n as (tail cs), X.Element n (tail as) cs]
shrink _ = []
instance Arbitrary T.Text where
arbitrary = liftM unName arbitrary
--
-- Code for inserting nodes into any point of a tree
--
type Insert a = State Int a
------------------------------------------------------------------------------
-- <bind> tests
-- Data type encapsulating the parameters for a bind operation
data Bind = Bind
{ _bindElemName :: Name
, _bindChildren :: [X.Node]
, _bindDoc :: [X.Node]
, _bindPos :: Int
, _bindRefPos :: Int
} -- deriving (Show)
instance Arbitrary Bind where
arbitrary = do
name <- arbitrary
kids <- liftM (take 3) arbitrary
doc <- liftM (take 5) arbitrary
let s = insSize doc
loc <- choose (0, s - 1)
loc2 <- choose (0, s - loc - 1)
return $ Bind name kids doc loc loc2
shrink (Bind e [c] (_:ds) p r) = [Bind e [c] ds p r]
shrink (Bind e (_:cs) d p r) = [Bind e cs d p r]
shrink _ = []
instance Show Bind where
show b@(Bind e c d p r) = unlines
[ "\n"
, "Bind element name: " ++ (show e)
, "Bind pos: " ++ (show p)
, "Bind ref pos: " ++ (show r)
, "Bind document:"
, L.unpack $ L.concat $ map formatNode d
, "Bind children:"
, L.unpack $ L.concat $ map formatNode c
, "Result:"
, L.unpack $ L.concat $ map formatNode $ buildResult b
, "Splice result:"
, L.unpack $ L.concat $ map formatNode $ unsafePerformIO $ do
hs <- loadEmpty mempty mempty mempty mempty
evalHeistT (runNodeList $ buildBindTemplate b)
(X.TextNode "") hs
, "Template:"
, L.unpack $ L.concat $ map formatNode $ buildBindTemplate b
]
where
formatNode n = toLazyByteString $ X.render
$ X.HtmlDocument X.UTF8 Nothing [n]
------------------------------------------------------------------------------
buildNode :: Text -> Text -> Bind -> X.Node
buildNode tag attr (Bind s c _ _ _) = X.Element tag [(attr, unName s)] c
------------------------------------------------------------------------------
buildBind :: Bind -> X.Node
buildBind = buildNode "bind" "tag"
------------------------------------------------------------------------------
empty :: Text -> X.Node
empty n = X.Element n [] []
------------------------------------------------------------------------------
buildBindTemplate :: Bind -> [X.Node]
buildBindTemplate s@(Bind n _ d b r) =
insertAt [empty $ unName $ n] pos $ withBind
where bind = [buildBind s]
bindSize = insSize bind
withBind = insertAt bind b d
pos = b + bindSize - 1 + r
------------------------------------------------------------------------------
buildResult :: Bind -> [X.Node]
buildResult (Bind _ c d b r) = insertAt c (b + r) d
------------------------------------------------------------------------------
-- <apply> tests
data Apply = Apply
{ _applyName :: Name
, _applyCaller :: [X.Node]
, _applyCallee :: Template
, _applyChildren :: [X.Node]
, _applyPos :: Int
} deriving (Show)
instance Arbitrary Apply where
arbitrary = do
name <- arbitrary
kids <- liftM (take 3) $ listOf $ limitedDepth 2
caller <- liftM (take 5) arbitrary
callee <- liftM (take 1) $ listOf $ limitedDepth 3
let s = insSize caller
loc <- choose (0, s - 1)
return $ Apply name caller callee kids loc
------------------------------------------------------------------------------
buildApplyCaller :: Apply -> [X.Node]
buildApplyCaller (Apply name caller _ kids pos) =
insertAt [X.Element "apply" [("template", unName name)] kids] pos caller
------------------------------------------------------------------------------
calcCorrect :: Apply -> [X.Node]
calcCorrect (Apply _ caller callee _ pos) = insertAt callee pos caller
------------------------------------------------------------------------------
calcResult :: Apply -> IO [X.Node]
calcResult apply@(Apply name _ callee _ _) = do
hs <- loadEmpty defaultLoadTimeSplices mempty mempty mempty
let hs' = setTemplates (Map.singleton [T.encodeUtf8 $ unName name]
(DocumentFile (X.HtmlDocument X.UTF8 Nothing callee)
Nothing)) hs
evalHeistT (runNodeList $ buildApplyCaller apply)
(X.TextNode "") hs'
{-
- Convenience code for manual ghci experimentation
-}
--html :: [Node] -> Node
--html c = X.Element "html" [] [hhead, body c]
--hhead :: Node
--hhead = X.Element "head" [] [title, X.Element "script" [] []]
--title :: Node
--title = X.Element "title" [] [X.Text "Test Page"]
--body :: [Node] -> Node
--body = X.Element "body" []
--
--para :: Int -> Node
--para n = X.Element "p" [] [X.Text $ B.pack $ "This is paragraph " ++ show n]
--para2 :: B.ByteString -> Node
--para2 c = X.Element "p" [] [X.Text c]
--para3 :: Node
--para3 = X.Element "p" [] [X.Text "AHA!"]
--
--foo :: Int -> [Node]
--foo n = insertAt [X.Element "NEW" [] []] n [html [para 1, para 2]]
--
--tdoc :: [Node]
--tdoc = [para 1, para 2, para 3, para 4]
--
--bindElem :: [Node] -> Int -> Int -> Bind
--bindElem = Bind (Name "mytag") [para2 "bound paragraph"]
--
--addBind :: Bind -> [Node] -> [Node]
--addBind b = insertAt [buildBind b] 0 . insertAt [empty $ unName $ _bindElemName b] 2
--
--prn :: Node -> IO ()
--prn = L.putStrLn . formatNode
--runTests :: IO ()
--runTests = defaultMain tests
| sopvop/heist | test/suite/Heist/Interpreted/Tests.hs | bsd-3-clause | 23,890 | 0 | 19 | 5,634 | 5,203 | 2,679 | 2,524 | 414 | 4 |
module HAD.Y2014.M03.D18.Solution where
-- $setup
-- >>> import Data.Maybe
-- >>> let backPartner = (>>= partner) . (>>= partner)
data Person a = Single a | Married a (Person a)
partner :: Person a -> Maybe (Person a)
partner (Married _ p) = Just p
partner _ = Nothing
get :: Person a -> a
get (Single x) = x
get (Married x _) = x
-- | wedding
-- Marray single people, linking them together
-- Nothing if one is married
--
-- Examples:
--
-- >>> isNothing $ wedding (Married "foo" (Single "foobar")) (Single "bar")
-- True
--
-- prop> \(x,y) -> (fmap get . backPartner . fmap fst $ wedding (Single x) (Single y)) == Just (x :: String)
-- prop> \(x,y) -> (fmap get . backPartner . fmap snd $ wedding (Single x) (Single y)) == Just (y :: String)
wedding :: Person a -> Person a -> Maybe (Person a, Person a)
wedding (Single x) (Single y) = let
x' = Married x y'
y' = Married y x'
in return (x',y')
wedding _ _ = Nothing
| Madsn/1HAD | exercises/HAD/Y2014/M03/D18/Solution.hs | mit | 933 | 0 | 9 | 197 | 237 | 127 | 110 | 14 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns#-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -ddump-splices #-}
import Test.Hspec
import Test.HUnit ((@?=))
import Data.Text (Text, pack, unpack, singleton)
import Yesod.Routes.Class hiding (Route)
import qualified Yesod.Routes.Class as YRC
import Yesod.Routes.Parse (parseRoutesNoCheck, parseTypeTree, TypeTree (..))
import Yesod.Routes.Overlap (findOverlapNames)
import Yesod.Routes.TH hiding (Dispatch)
import Language.Haskell.TH.Syntax
import Hierarchy
import qualified Data.ByteString.Char8 as S8
import qualified Data.Set as Set
data MyApp = MyApp
data MySub = MySub
instance RenderRoute MySub where
data
#if MIN_VERSION_base(4,5,0)
Route
#else
YRC.Route
#endif
MySub = MySubRoute ([Text], [(Text, Text)])
deriving (Show, Eq, Read)
renderRoute (MySubRoute x) = x
instance ParseRoute MySub where
parseRoute = Just . MySubRoute
getMySub :: MyApp -> MySub
getMySub MyApp = MySub
data MySubParam = MySubParam Int
instance RenderRoute MySubParam where
data
#if MIN_VERSION_base(4,5,0)
Route
#else
YRC.Route
#endif
MySubParam = ParamRoute Char
deriving (Show, Eq, Read)
renderRoute (ParamRoute x) = ([singleton x], [])
instance ParseRoute MySubParam where
parseRoute ([unpack -> [x]], _) = Just $ ParamRoute x
parseRoute _ = Nothing
getMySubParam :: MyApp -> Int -> MySubParam
getMySubParam _ = MySubParam
do
texts <- [t|[Text]|]
let resLeaves = map ResourceLeaf
[ Resource "RootR" [] (Methods Nothing ["GET"]) ["foo", "bar"] True
, Resource "BlogPostR" [Static "blog", Dynamic $ ConT ''Text] (Methods Nothing ["GET", "POST"]) [] True
, Resource "WikiR" [Static "wiki"] (Methods (Just texts) []) [] True
, Resource "SubsiteR" [Static "subsite"] (Subsite (ConT ''MySub) "getMySub") [] True
, Resource "SubparamR" [Static "subparam", Dynamic $ ConT ''Int] (Subsite (ConT ''MySubParam) "getMySubParam") [] True
]
resParent = ResourceParent
"ParentR"
True
[ Static "foo"
, Dynamic $ ConT ''Text
]
[ ResourceLeaf $ Resource "ChildR" [] (Methods Nothing ["GET"]) ["child"] True
]
ress = resParent : resLeaves
rrinst <- mkRenderRouteInstance (ConT ''MyApp) ress
rainst <- mkRouteAttrsInstance (ConT ''MyApp) ress
prinst <- mkParseRouteInstance (ConT ''MyApp) ress
dispatch <- mkDispatchClause MkDispatchSettings
{ mdsRunHandler = [|runHandler|]
, mdsSubDispatcher = [|subDispatch dispatcher|]
, mdsGetPathInfo = [|fst|]
, mdsMethod = [|snd|]
, mdsSetPathInfo = [|\p (_, m) -> (p, m)|]
, mds404 = [|pack "404"|]
, mds405 = [|pack "405"|]
, mdsGetHandler = defaultGetHandler
} ress
return
$ InstanceD
[]
(ConT ''Dispatcher
`AppT` ConT ''MyApp
`AppT` ConT ''MyApp)
[FunD (mkName "dispatcher") [dispatch]]
: prinst
: rainst
: rrinst
instance Dispatcher MySub master where
dispatcher env (pieces, _method) =
( pack $ "subsite: " ++ show pieces
, Just $ envToMaster env route
)
where
route = MySubRoute (pieces, [])
instance Dispatcher MySubParam master where
dispatcher env (pieces, method) =
case map unpack pieces of
[[c]] ->
let route = ParamRoute c
toMaster = envToMaster env
MySubParam i = envSub env
in ( pack $ "subparam " ++ show i ++ ' ' : [c]
, Just $ toMaster route
)
_ -> (pack "404", Nothing)
{-
thDispatchAlias
:: (master ~ MyApp, sub ~ MyApp, handler ~ String, app ~ (String, Maybe (YRC.Route MyApp)))
=> master
-> sub
-> (YRC.Route sub -> YRC.Route master)
-> app -- ^ 404 page
-> handler -- ^ 405 page
-> Text -- ^ method
-> [Text]
-> app
--thDispatchAlias = thDispatch
thDispatchAlias master sub toMaster app404 handler405 method0 pieces0 =
case dispatch pieces0 of
Just f -> f master sub toMaster app404 handler405 method0
Nothing -> app404
where
dispatch = toDispatch
[ Route [] False $ \pieces ->
case pieces of
[] -> do
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsRootR of
Just f -> f
Nothing -> handler405'
in runHandler handler master' sub' RootR toMaster'
_ -> error "Invariant violated"
, Route [D.Static "blog", D.Dynamic] False $ \pieces ->
case pieces of
[_, x2] -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsBlogPostR of
Just f -> f y2
Nothing -> handler405'
in runHandler handler master' sub' (BlogPostR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "wiki"] True $ \pieces ->
case pieces of
_:x2 -> do
y2 <- fromPathMultiPiece x2
Just $ \master' sub' toMaster' _app404' _handler405' _method ->
let handler = handleWikiR y2
in runHandler handler master' sub' (WikiR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "subsite"] True $ \pieces ->
case pieces of
_:x2 -> do
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySub sub') (toMaster' . SubsiteR) app404' handler405' method x2
_ -> error "Invariant violated"
, Route [D.Static "subparam", D.Dynamic] True $ \pieces ->
case pieces of
_:x2:x3 -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySubParam sub' y2) (toMaster' . SubparamR y2) app404' handler405' method x3
_ -> error "Invariant violated"
]
methodsRootR = Map.fromList [("GET", getRootR)]
methodsBlogPostR = Map.fromList [("GET", getBlogPostR), ("POST", postBlogPostR)]
-}
main :: IO ()
main = hspec $ do
describe "RenderRoute instance" $ do
it "renders root correctly" $ renderRoute RootR @?= ([], [])
it "renders blog post correctly" $ renderRoute (BlogPostR $ pack "foo") @?= (map pack ["blog", "foo"], [])
it "renders wiki correctly" $ renderRoute (WikiR $ map pack ["foo", "bar"]) @?= (map pack ["wiki", "foo", "bar"], [])
it "renders subsite correctly" $ renderRoute (SubsiteR $ MySubRoute (map pack ["foo", "bar"], [(pack "baz", pack "bin")]))
@?= (map pack ["subsite", "foo", "bar"], [(pack "baz", pack "bin")])
it "renders subsite param correctly" $ renderRoute (SubparamR 6 $ ParamRoute 'c')
@?= (map pack ["subparam", "6", "c"], [])
describe "thDispatch" $ do
let disp m ps = dispatcher
(Env
{ envToMaster = id
, envMaster = MyApp
, envSub = MyApp
})
(map pack ps, S8.pack m)
it "routes to root" $ disp "GET" [] @?= (pack "this is the root", Just RootR)
it "POST root is 405" $ disp "POST" [] @?= (pack "405", Just RootR)
it "invalid page is a 404" $ disp "GET" ["not-found"] @?= (pack "404", Nothing :: Maybe (YRC.Route MyApp))
it "routes to blog post" $ disp "GET" ["blog", "somepost"]
@?= (pack "some blog post: somepost", Just $ BlogPostR $ pack "somepost")
it "routes to blog post, POST method" $ disp "POST" ["blog", "somepost2"]
@?= (pack "POST some blog post: somepost2", Just $ BlogPostR $ pack "somepost2")
it "routes to wiki" $ disp "DELETE" ["wiki", "foo", "bar"]
@?= (pack "the wiki: [\"foo\",\"bar\"]", Just $ WikiR $ map pack ["foo", "bar"])
it "routes to subsite" $ disp "PUT" ["subsite", "baz"]
@?= (pack "subsite: [\"baz\"]", Just $ SubsiteR $ MySubRoute ([pack "baz"], []))
it "routes to subparam" $ disp "PUT" ["subparam", "6", "q"]
@?= (pack "subparam 6 q", Just $ SubparamR 6 $ ParamRoute 'q')
describe "parsing" $ do
it "subsites work" $ do
parseRoute ([pack "subsite", pack "foo"], [(pack "bar", pack "baz")]) @?=
Just (SubsiteR $ MySubRoute ([pack "foo"], [(pack "bar", pack "baz")]))
describe "overlap checking" $ do
it "catches overlapping statics" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping dynamics" $ do
let routes = [parseRoutesNoCheck|
/#Int Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping statics and dynamics" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping multi" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/##*Strings Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping subsite" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2 Subsite getSubsite
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "no false positives" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/bar/#String Foo2
|]
findOverlapNames routes @?= []
it "obeys ignore rules" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/#!String Foo2
/!foo Foo3
|]
findOverlapNames routes @?= []
it "obeys multipiece ignore rules #779" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/+![String] Foo2
|]
findOverlapNames routes @?= []
it "ignore rules for entire route #779" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
!/+[String] Foo2
!/#String Foo3
!/foo Foo4
|]
findOverlapNames routes @?= []
it "ignore rules for hierarchy" $ do
let routes = [parseRoutesNoCheck|
/+[String] Foo1
!/foo Foo2:
/foo Foo3
/foo Foo4:
/!#foo Foo5
|]
findOverlapNames routes @?= []
it "proper boolean logic" $ do
let routes = [parseRoutesNoCheck|
/foo/bar Foo1
/foo/baz Foo2
/bar/baz Foo3
|]
findOverlapNames routes @?= []
describe "routeAttrs" $ do
it "works" $ do
routeAttrs RootR @?= Set.fromList [pack "foo", pack "bar"]
it "hierarchy" $ do
routeAttrs (ParentR (pack "ignored") ChildR) @?= Set.singleton (pack "child")
hierarchy
describe "parseRouteTyoe" $ do
let success s t = it s $ parseTypeTree s @?= Just t
failure s = it s $ parseTypeTree s @?= Nothing
success "Int" $ TTTerm "Int"
success "(Int)" $ TTTerm "Int"
failure "(Int"
failure "(Int))"
failure "[Int"
failure "[Int]]"
success "[Int]" $ TTList $ TTTerm "Int"
success "Foo-Bar" $ TTApp (TTTerm "Foo") (TTTerm "Bar")
success "Foo-Bar-Baz" $ TTApp (TTTerm "Foo") (TTTerm "Bar") `TTApp` TTTerm "Baz"
getRootR :: Text
getRootR = pack "this is the root"
getBlogPostR :: Text -> String
getBlogPostR t = "some blog post: " ++ unpack t
postBlogPostR :: Text -> Text
postBlogPostR t = pack $ "POST some blog post: " ++ unpack t
handleWikiR :: [Text] -> String
handleWikiR ts = "the wiki: " ++ show ts
getChildR :: Text -> Text
getChildR = id
| ygale/yesod | yesod-core/test/RouteSpec.hs | mit | 12,619 | 0 | 22 | 3,995 | 2,803 | 1,446 | 1,357 | 199 | 1 |
module ShouldCompile where
foldPair :: (a->a->a,b->b->b) -> (a,b) -> [(a,b)] -> (a,b)
foldPair fg ab [] = ab
foldPair fg@(f,g) ab ((a,b):abs) = (f a u,g b v)
where (u,v) = foldPair fg ab abs
| ghc-android/ghc | testsuite/tests/deSugar/should_compile/ds031.hs | bsd-3-clause | 222 | 0 | 9 | 66 | 149 | 84 | 65 | 5 | 1 |
Vamodule Language.Rowling.Definitions (
module Language.Rowling.Definitions.Types,
module Language.Rowling.Definitions.Expressions,
module Language.Rowling.Definitions.Values
) where
import Language.Rowling.Definitions.Types
import Language.Rowling.Definitions.Expressions
import Language.Rowling.Definitions.Values
| thinkpad20/rowling | src/Language/Rowling/Definitions.hs | mit | 331 | 0 | 8 | 32 | 65 | 39 | 26 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ConstraintKinds #-}
-------------------------------------------
-- |
-- Module : Pinboard.Api
-- Copyright : (c) Jon Schoning, 2015
-- Maintainer : jonschoning@gmail.com
-- Stability : experimental
-- Portability : POSIX
--
-- < https://pinboard.in/api/ >
--
-- Provides Pinboard Api Access (deserializes into Haskell data structures)
module Pinboard.Api
( -- ** Posts
getPostsRecent
, getPostsForDate
, getPostsAll
, getPostsDates
, getPostsMRUTime
, getSuggestedTags
, addPost
, addPostRec
, deletePost
-- ** Tags
, getTags
, renameTag
, deleteTag
-- ** User
, getUserSecretRssKey
, getUserApiToken
-- ** Notes
, getNoteList
, getNote
) where
import Pinboard.Client (pinboardJson)
import Data.Text (Text)
import Data.Time (UTCTime)
import Pinboard.Types (MonadPinboard, ResultFormatType(..))
import Pinboard.ApiTypes
import Pinboard.ApiRequest
import Pinboard.Error
import Control.Applicative
import Prelude
-- POSTS ---------------------------------------------------------------------
-- | posts/recent : Returns a list of the user's most recent posts, filtered by tag.
getPostsRecent
:: MonadPinboard m
=> Maybe [Tag] -- ^ filter by up to three tags
-> Maybe Count -- ^ number of results to return. Default is 15, max is 100
-> m (Either PinboardError Posts)
getPostsRecent tags count =
pinboardJson $ getPostsRecentRequest FormatJson tags count
-- | posts/all : Returns all bookmarks in the user's account.
getPostsAll
:: MonadPinboard m
=> Maybe [Tag] -- ^ filter by up to three tags
-> Maybe StartOffset -- ^ offset value (default is 0)
-> Maybe NumResults -- ^ number of results to return. Default is all
-> Maybe FromDateTime -- ^ return only bookmarks created after this time
-> Maybe ToDateTime -- ^ return only bookmarks created before this time
-> Maybe Meta -- ^ include a change detection signature for each bookmark
-> m (Either PinboardError [Post])
getPostsAll tags start results fromdt todt meta =
pinboardJson $ getPostsAllRequest FormatJson tags start results fromdt todt meta
-- | posts/get : Returns one or more posts on a single day matching the arguments.
-- If no date or url is given, date of most recent bookmark will be used.
getPostsForDate
:: MonadPinboard m
=> Maybe [Tag] -- ^ filter by up to three tags
-> Maybe Date -- ^ return results bookmarked on this day
-> Maybe Url -- ^ return bookmark for this URL
-> m (Either PinboardError Posts)
getPostsForDate tags date url =
pinboardJson $ getPostsForDateRequest FormatJson tags date url
-- | posts/dates : Returns a list of dates with the number of posts at each date.
getPostsDates
:: MonadPinboard m
=> Maybe [Tag] -- ^ filter by up to three tags
-> m (Either PinboardError PostDates)
getPostsDates tags = pinboardJson $ getPostsDatesRequest FormatJson tags
-- | posts/update : Returns the most recent time a bookmark was added, updated or deleted.
getPostsMRUTime
:: MonadPinboard m
=> m (Either PinboardError UTCTime)
getPostsMRUTime =
fmap fromUpdateTime <$> pinboardJson (getPostsMRUTimeRequest FormatJson)
-- | posts/suggest : Returns a list of popular tags and recommended tags for a given URL.
-- Popular tags are tags used site-wide for the url;
-- Recommended tags are drawn from the user's own tags.
getSuggestedTags
:: MonadPinboard m
=> Url -> m (Either PinboardError [Suggested])
getSuggestedTags url = pinboardJson $ getSuggestedTagsRequest FormatJson url
-- | posts/delete : Delete an existing bookmark.
deletePost
:: MonadPinboard m
=> Url -> m (Either PinboardError ())
deletePost url =
fmap fromDoneResult <$> pinboardJson (deletePostRequest FormatJson url)
-- | posts/add : Add or Update a bookmark
addPost
:: MonadPinboard m
=> Url -- ^ the URL of the item
-> Description -- ^ Title of the item. This field is unfortunately named 'description' for backwards compatibility with the delicious API
-> Maybe Extended -- ^ Description of the item. Called 'extended' for backwards compatibility with delicious API
-> Maybe [Tag] -- ^ List of up to 100 tags
-> Maybe DateTime -- ^ creation time for this bookmark. Defaults to current time. Datestamps more than 10 minutes ahead of server time will be reset to current server time
-> Maybe Replace -- ^ Replace any existing bookmark with this URL. Default is yes. If set to no, will fail if bookmark exists
-> Maybe Shared -- ^ Make bookmark public. Default is "yes" unless user has enabled the "save all bookmarks as private" user setting, in which case default is "no"
-> Maybe ToRead -- ^ Marks the bookmark as unread. Default is "no"
-> m (Either PinboardError ())
addPost url descr ext tags ctime repl shared toread =
fmap fromDoneResult <$>
pinboardJson
(addPostRequest FormatJson url descr ext tags ctime repl shared toread)
-- | posts/add : Add or Update a bookmark, from a Post record
addPostRec
:: MonadPinboard m
=> Post -- ^ a Post record
-> Replace -- ^ Replace any existing bookmark with the Posts URL. If set to no, will fail if bookmark exists
-> m (Either PinboardError ())
addPostRec post replace =
fmap fromDoneResult <$> pinboardJson (addPostRecRequest FormatJson post replace)
-- TAGS ----------------------------------------------------------------------
-- | tags/get : Returns a full list of the user's tags along with the number of
-- times they were used.
getTags
:: MonadPinboard m
=> m (Either PinboardError TagMap)
getTags = fmap fromJsonTagMap <$> pinboardJson (getTagsRequest FormatJson)
-- | tags/delete : Delete an existing tag.
deleteTag
:: MonadPinboard m
=> Tag -> m (Either PinboardError ())
deleteTag tag =
fmap fromDoneResult <$> pinboardJson (deleteTagRequest FormatJson tag)
-- | tags/rename : Rename an tag, or fold it in to an existing tag
renameTag
:: MonadPinboard m
=> Old -- ^ note: match is not case sensitive
-> New -- ^ if empty, nothing will happen
-> m (Either PinboardError ())
renameTag old new =
fmap fromDoneResult <$> pinboardJson (renameTagRequest FormatJson old new)
-- USER ----------------------------------------------------------------------
-- | user/secret : Returns the user's secret RSS key (for viewing private feeds)
getUserSecretRssKey
:: MonadPinboard m
=> m (Either PinboardError Text)
getUserSecretRssKey =
fmap fromTextResult <$> pinboardJson (getUserSecretRssKeyRequest FormatJson)
-- | user/api_token : Returns the user's API token (for making API calls without a password)
getUserApiToken
:: MonadPinboard m
=> m (Either PinboardError Text)
getUserApiToken =
fmap fromTextResult <$> pinboardJson (getUserApiTokenRequest FormatJson)
-- NOTES ---------------------------------------------------------------------
-- | notes/list : Returns a list of the user's notes (note text detail is not included)
getNoteList
:: MonadPinboard m
=> m (Either PinboardError NoteList)
getNoteList = pinboardJson (getNoteListRequest FormatJson)
-- | notes/id : Returns an individual user note. The hash property is a 20 character long sha1 hash of the note text.
getNote
:: MonadPinboard m
=> NoteId -> m (Either PinboardError Note)
getNote noteid = pinboardJson (getNoteRequest FormatJson noteid)
| jonschoning/pinboard | src/Pinboard/Api.hs | mit | 7,344 | 0 | 17 | 1,302 | 1,158 | 606 | 552 | 132 | 1 |
module Main where
import Data.List
data Disc = Disc
{ initial :: Int
, size :: Int
}
positions :: [Disc] -> [[Int]]
positions = map positions'
where positions' (Disc i s) = cycle ([i..s-1] ++ [0..i-1])
discs :: [Disc]
discs =
[ Disc 1 17
, Disc 0 7
, Disc 2 19
, Disc 0 5
, Disc 0 3
, Disc 5 13
]
discs2 :: [Disc]
discs2 = discs ++ [Disc 0 11]
example :: [Disc]
example =
[ Disc 4 5
, Disc 1 2
]
machine :: [[Int]] -> Bool
machine = machine' 1
where machine' time' (p:ps) = p !! time' == 0 && machine' (time' + 1) ps
machine' _ [] = True
main :: IO ()
main = do
print $ machine (map (drop 5) (positions example))
print . findIndex machine $ iterate (map tail) (positions example)
print . findIndex machine $ iterate (map tail) (positions discs)
print . findIndex machine $ iterate (map tail) (positions discs2)
| mithrandi/advent2016 | Day15.hs | mit | 865 | 0 | 12 | 220 | 433 | 225 | 208 | 32 | 2 |
module GHCJS.DOM.DataTransferItemList (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/DataTransferItemList.hs | mit | 50 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
module HTMLEntities.Builder (char, text) where
import HTMLEntities.Prelude
import qualified Data.Text as Text
import qualified Data.Text.Lazy.Builder as Text (Builder)
import qualified Data.Text.Lazy.Builder as Text.Builder
-- |
-- HTML-encodes the given char into a text builder.
char :: Char -> Text.Builder
char c =
fromMaybe (Text.Builder.singleton c) $
lookup c entitiesTable
-- |
-- HTML-encodes the given text into a text builder.
--
-- >>> Data.Text.Lazy.IO.putStrLn $ Data.Text.Lazy.Builder.toLazyText $ text "<a href=\"\">"
-- <a href="">
--
text :: Text -> Text.Builder
text =
Text.foldr (\c b -> char c <> b) mempty
{-# NOINLINE entitiesTable #-}
entitiesTable :: [(Char, Text.Builder)]
entitiesTable =
[
('<', "<"),
('>', ">"),
('&', "&"),
('"', """),
('\'', "'")
]
| nikita-volkov/html-entities | library/HTMLEntities/Builder.hs | mit | 851 | 0 | 9 | 149 | 209 | 131 | 78 | 21 | 1 |
module Y2016.M06.D21.Exercise where
{--
So what happens when things become Complex?
With the Quadratic type, enhance solver in such a way that it gives all
solutions, whether they be Real or Complex.
This exercise is an elaboration of yesterday's that solved quadratic equations
with Real roots with the quadratic formula:
-b +/- sqrt (b^2 - 4ac)
x = -----------------------
2a
for the quadratic equation
ax^2 + bx + c = 0
--}
import Data.Complex
data QuadraticEq = Q { a,b,c :: Float }
solver :: QuadraticEq -> [Complex Float]
solver = undefined
-- with the new solver, solve the below quadratic equations represented by
-- the coefficients (a,b,c):
eqs :: [(Float, Float, Float)]
eqs = [(1,-6,25), (1,10,29), (1,-6,13), (2,6,29)]
{-- BONUS ------------------------------------------------------------------
The default Show-instance for QuadraticEq 'leaves something to be desired.'
Write your own Show-instance for QuadraticEq that for (Q 2 3 4) shows:
"2x^2 + 3x + 4 = 0"
--}
instance Show QuadraticEq where show = undefined
| geophf/1HaskellADay | exercises/HAD/Y2016/M06/D21/Exercise.hs | mit | 1,063 | 0 | 8 | 194 | 143 | 92 | 51 | 8 | 1 |
{-# LANGUAGE TemplateHaskell, TypeFamilies, OverloadedLists #-}
{-# OPTIONS_GHC -ddump-splices #-} -- for debugging
module Build.Derive.List.HigherKind where
import Derive.List
import Data.Semigroup
import GHC.Exts (IsList (..))
data Elisp a
= ElispAtom a
| ElispSexp [Elisp a]
deriving (Show)
deriveList ''Elisp 'ElispSexp
main = do
putStrLn ""
print$ (emptyElisp :: Elisp Bool)
print$ toElispList (ElispAtom True)
print$ ElispSexp [ElispAtom (Left "&&"), ElispAtom (Right True), ElispAtom (Right True)] <> mempty <> ElispAtom (Right False)
| sboosali/derive-monoid | test/Build/Derive/List/HigherKind.hs | mit | 558 | 0 | 14 | 86 | 180 | 95 | 85 | 16 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
module ALaCarteDSL where
import ALaCarte
import Control.Monad
import Control.Monad.Reader (MonadReader, ReaderT)
import qualified Control.Monad.Reader as R
import Control.Monad.State
import Data.Maybe
import Data.Functor.Identity
import Prelude hiding (lookup)
import qualified Prelude as P
-- |a language for modelling a calculator memory
-- We can increment the memory, recall it, or clear it.
data Calculator' a where
Incr' :: Int -> Calculator' ()
Recall' :: Calculator' Int
Clear' :: Calculator' ()
-- the same, but CPS transformed
data Calculator'' a -- implement
instance Functor Calculator'' where
fmap = undefined
-- broken up into parts
data Incr a -- implement
data Recall a --implement
data Clear a -- implement
-- and put back together again
type Calculator = Incr :+: Recall :+: Clear
instance Functor Incr where
fmap = undefined
instance Functor Recall where
fmap = undefined
instance Functor Clear where
fmap = undefined
-- smart constructors
incr :: (Incr :<: f) => Int -> Free f ()
incr i = undefined
recall :: (Recall :<: f) => Free f Int
recall = undefined
clear :: (Clear :<: f) => Free f ()
clear = undefined
-- a simple language for user interaction
data Ask a -- implement
data Tell a -- implement
instance Functor Ask where
fmap = undefined
instance Functor Tell where
fmap = undefined
type Console = Ask :+: Tell
ask :: (Ask :<: f) => String -> Free f String
ask = undefined
tell :: (Tell :<: f) => String -> Free f ()
tell = undefined
-- adder: like the calculator, but increment can overflow
data Adder k = Increment Int (Bool -> k)
| Reset k
| Total (Int -> k)
instance Functor Adder where
fmap = undefined
increment :: (Adder :<: f) => Int -> Free f Bool
increment = undefined
reset :: (Adder :<: f) => Free f ()
reset = undefined
total :: (Adder :<: f) => Free f Int
total = undefined
-- key value lookup
data Lookup k v a = Lookup k (Maybe v -> a)
instance Functor (Lookup k v) where
fmap = undefined
lookup :: ((Lookup k v) :<: f) => k -> Free f (Maybe v)
lookup = undefined
-- test programs
sayHelloProg :: (Ask :<: f, Tell :<: f) => Free f ()
sayHelloProg = do
name <- ask "What's your name?"
tell $ "Hello " ++ name
lookupProg :: Free (Ask :+: Lookup String Int :+: Tell) ()
lookupProg = do
name <- ask "What's your name?"
quota <- fromMaybe (0 :: Int) <$> lookup name
tell $ "Hi " ++ name ++ ", your quota is " ++ show quota
tick :: (Recall :<: f, Incr :<: f) => Free f Int
tick = do
y <- recall
incr 1
return y
-- findLimit should return the limit, i.e. the number of times you
-- can increment an adder initialized at 0 before getting an overflow
--
-- hint: use execStateT :: Monad m => StateT s m a -> s -> m s
findLimit :: (Adder :<: f) => Free f Int
findLimit = undefined
-- helper function
findLimit' :: (Adder :<: f) => StateT Int (Free f) ()
findLimit' = undefined
tellLimit :: (Adder :<: f, Tell :<: f) => Free f ()
tellLimit = undefined | mjhopkins/StopPayingForFreeMonads | ALaCarteDSL.hs | mit | 3,530 | 0 | 10 | 837 | 932 | 521 | 411 | -1 | -1 |
foldQs :: Ord a => [a] -> [a]
foldQs [] = []
foldQs (x:xs) = foldQs (foldFilter (<=x) xs) ++ [x] ++ foldQs (foldFilter (>x) xs)
--foldQs (x:xs) = foldr ()
foldFilter p = foldr (\x acc -> if p x then x : acc else acc) []
foldlFilter p = foldl (\acc x -> if p x then acc++[x] else acc) []
| RAFIRAF/HASKELL | foldQs.hs | mit | 289 | 0 | 10 | 65 | 175 | 93 | 82 | 5 | 2 |
-- Copyright (c) 2015-16 Nicola Bonelli <nicola@pfq.io>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE LambdaCase #-}
module Main where
import Data.Semigroup
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Either
import Data.Char
import Data.Time.Clock
import qualified Data.ByteString as B (ByteString, readFile)
import qualified Data.Yaml as Y
import Data.Yaml (FromJSON(..), (.:), (.:?))
import Control.Applicative
import Control.Monad
import Control.Monad.State
import Control.Concurrent (threadDelay)
import Control.Exception
import Data.Data
import System.Console.ANSI
import System.Console.CmdArgs
import System.Directory (getHomeDirectory, doesFileExist, getModificationTime)
import System.IO.Unsafe
import System.IO.Error
import System.Process
import System.Exit
import System.FilePath
import System.Posix.Signals
import System.Posix.Types
import qualified Network.PFQ as Q (version)
proc_cpuinfo, proc_modules, tmp_pfq :: String
proc_cpuinfo = "/proc/cpuinfo"
proc_modules = "/proc/modules"
tmp_pfq = "/tmp/pfq.opt"
dmesg, pidof, ethtool, setpci, cpufreq_set, rmmod, insmod, modprobe, lsmod, ifconfig :: String
dmesg = "/bin/dmesg"
pidof = "/bin/pidof"
ethtool = "/sbin/ethtool"
setpci = "/usr/bin/setpci"
cpufreq_set = "/usr/bin/cpufreq-set"
rmmod = "/sbin/rmmod"
insmod = "/sbin/insmod"
modprobe = "/sbin/modprobe"
lsmod = "/sbin/lsmod"
ifconfig = "/sbin/ifconfig"
bold = setSGRCode [SetConsoleIntensity BoldIntensity]
red = setSGRCode [SetColor Foreground Vivid Red]
blue = setSGRCode [SetColor Foreground Vivid Blue]
reset = setSGRCode []
configFiles = [ "/etc/pfq.conf.yaml"
, "/root/.pfq.conf.yaml"
, "/root/pfq.conf.yaml"
, "/etc/pfq.conf"
, "/root/.pfq.conf"
, "/root/pfq.conf"
]
defaultDelay = 200000
newtype OptString = OptString { getOptString :: String }
deriving (Show, Read, Eq)
newtype OptList a = OptList { getOptList :: [a] }
deriving (Show, Read, Eq)
instance Semigroup OptString where
a <> OptString "" = a
_ <> b = b
instance Semigroup (OptList a) where
a <> OptList [] = a
_ <> b = b
data SystemError = SystemError String ExitCode
deriving (Show, Typeable)
instance Exception SystemError
data Device =
Device
{ devname :: String
, devspeed :: Maybe Int
, channels :: Maybe Int
, flowctrl :: Maybe Bool
, ethopt :: [(String, String)]
} deriving (Show, Read, Eq)
instance FromJSON Device where
parseJSON (Y.Object v) =
Device <$>
v .: "devname" <*>
v .:? "devspeed" <*>
v .:? "channels" <*>
v .:? "flowctrl" <*>
v .: "ethopt"
parseJSON _ = fail "Expected Object for Device value"
data Driver =
Driver
{ drvmod :: String
, drvopt :: [String]
, pci :: [(String, String)]
, instances :: Int
, devices :: [Device]
} deriving (Show, Read, Eq)
instance FromJSON Driver where
parseJSON (Y.Object v) =
Driver <$>
v .: "drvmod" <*>
v .: "drvopt" <*>
v .: "pci" <*>
v .: "instances" <*>
v .: "devices"
parseJSON _ = fail "Expected Object for Driver value"
data Config = Config
{ pfq_module :: String
, pfq_options :: [String]
, exclude_core :: [Int]
, irq_affinity :: [String]
, cpu_governor :: String
, drivers :: [Driver]
} deriving (Show, Read, Eq)
instance FromJSON Config where
parseJSON (Y.Object v) =
Config <$>
v .: "pfq_module" <*>
v .: "pfq_options" <*>
v .: "exclude_core" <*>
v .: "irq_affinity" <*>
v .: "cpu_governor" <*>
v .: "drivers"
parseJSON _ = fail "Expected Object for Config value"
instance Semigroup Config where
(Config mod1 opt1 excl1 algo1 gov1 drvs1) <> (Config mod2 opt2 excl2 algo2 gov2 drvs2) =
Config
{ pfq_module = getOptString $ OptString mod1 <> OptString mod2
, pfq_options = getOptList $ OptList opt1 <> OptList opt2
, exclude_core = excl1 <> excl2
, irq_affinity = algo1 <> algo2
, cpu_governor = getOptString $ OptString gov1 <> OptString gov2
, drivers = drvs1 <> drvs2
}
data Options = Options
{ config :: Maybe String
, kmodule :: String
, algorithm :: String
, governor :: String
, first_core :: Int
, exclude :: [Int]
, queues :: Maybe Int
, force :: Bool
, others :: [String]
} deriving (Show, Read, Data, Typeable)
options :: Mode (CmdArgs Options)
options = cmdArgsMode $ Options
{ config = Nothing &= typ "FILE" &= help "Specify config file (default ~/.pfq.conf)"
, kmodule = "" &= help "Override the kmodule specified in config file"
, queues = Nothing &= help "Specify hardware channels (i.e. Intel RSS)"
, algorithm = "" &= help "Irq affinity algorithm: naive, round-robin, even, odd, all-in:id, comb:id"
, governor = "" &= help "Set cpufreq governor"
, first_core = 0 &= typ "NUM" &= help "First core used for irq affinity"
, exclude = [] &= typ "CORE" &= help "Exclude core from irq affinity"
, force = False &= help "Force PFQ reload!"
, others = [] &= args
} &= summary ("pfq-load (PFQ " ++ Q.version ++ ")") &= program "pfq-load"
-------------------------------------------------------------------------------------------
main :: IO ()
main = handle (\(SystemError msg code) -> putStrBoldLn msg *> exitWith code) $ do
-- load options...
home <- getHomeDirectory
opt <- cmdArgsRun options
conf <- (<> mkConfig opt) <$> loadConfig (catMaybes (config opt : map Just configFiles)) opt
pmod <- getProcModules
core <- getNumberOfPhyCores
bal <- getProcessID "irqbalance"
frd <- getProcessID "cpufreqd"
-- compute the command to load pfq...
let pfqLoadCmd = if null (pfq_module conf)
then mkLoadModuleCmd ProbeMod "pfq" (pfq_options conf)
else mkLoadModuleCmd InsertMod (pfq_module conf) (pfq_options conf)
-- determine whether pfq load is required...
tstamp <- if null (pfq_module conf)
then getCurrentTime
else getModificationTime $ pfq_module conf
pfqForceLoad <- or <$> sequence [ return $ force opt
, not <$> isLoaded "pfq"
, (/= (pfqLoadCmd ++ " " ++ show tstamp)) <$> possiblyReadFile tmp_pfq
]
writeFile tmp_pfq pfqLoadCmd
appendFile tmp_pfq (" " ++ show tstamp)
-- check queues
when (maybe False (> core) (queues opt)) $ errorWithoutStackTrace "queues number is too big!"
-- unload pfq and drivers that depend on it...
evalStateT (unloadDependencies pfqForceLoad "pfq") pmod
-- check irqbalance deaemon
unless (null bal) $
putStrBoldLn ("Irqbalance daemon detected @pid " ++ show bal ++ ". Sending SIGKILL...") *> forM_ bal (signalProcess sigKILL)
-- check cpufreqd deaemon
unless (null frd) $
putStrBoldLn ("Cpufreqd daemon detected @pid " ++ show frd ++ ". Sending SIGKILL...") *> forM_ frd (signalProcess sigKILL)
-- set cpufreq governor...
unless (null (cpu_governor conf)) $
forM_ [0.. core-1] $ \n ->
runSystem (cpufreq_set ++ " -g " ++ cpu_governor conf ++ " -c " ++ show n) "*** cpufreq-set error! Make sure you have cpufrequtils installed! ***"
-- load PFQ (if required)...
if pfqForceLoad
then do
putStrBoldLn (blue ++ "Loading pfq [" ++ pfqLoadCmd ++ "]")
system $ dmesg ++ " --clear"
runSystem pfqLoadCmd (red ++ "load pfq.ko error!")
xs <- lines <$> readProcess dmesg ["-t"] []
forM_ xs $ \x -> when ("pfq: unknown parameter" `isInfixOf` x) (throw $ SystemError (red ++ "load pfq.ko: " ++ x ++ "!") (ExitFailure 42))
else putStrBoldLn $ red ++ "Using pfq.ko module already loaded (use --force to reload it)..."
-- update current loaded proc/modules
pmod2 <- getProcModules
-- unload drivers...
unless (null (drivers conf)) $
putStrBoldLn "Unloading vanilla/standard drivers..." *>
evalStateT (forM_ (drivers conf) $ unloadDependencies True . takeBaseName . drvmod) pmod2
-- load and configure device drivers...
forM_ (drivers conf) $ \drv -> do
let rss = maybe [] (mkRssOption (drvmod drv) (instances drv)) (queues opt)
unless (null $ drvmod drv) $
loadModule InsertMod (drvmod drv) (drvopt drv ++ rss)
threadDelay defaultDelay
forM_ (devices drv) $ setupDevice (queues opt)
-- setup per-driver pci options..
forM_ (drivers conf) $ setupPCI . pci
-- set interrupt affinity...
putStrBoldLn "Setting irq affinity..."
setupIRQAffinity (first_core opt) (exclude_core conf) (irq_affinity conf) (getDevices conf)
putStrBoldLn "PFQ ready."
mkRssOption :: String -> Int -> Int -> [String]
mkRssOption driver ndev nqueue
| "ixgbe.ko" `isSuffixOf` driver = [ "RSS=" ++ intercalate "," (replicate ndev (show nqueue)) ]
| "igb.ko" `isSuffixOf` driver = [ "RSS=" ++ intercalate "," (replicate ndev (show nqueue)) ]
| otherwise = []
mkConfig :: Options -> Config
mkConfig
Options
{ config = _
, kmodule = mod
, algorithm = algo
, exclude = excl
, governor = gov
, others = opt } =
Config
{ pfq_module = mod
, pfq_options = opt
, exclude_core = excl
, irq_affinity = [algo | not (null algo)]
, cpu_governor = gov
, drivers = []
}
getFirstConfig :: [FilePath] -> IO (Maybe FilePath)
getFirstConfig xs = filterM doesFileExist xs >>= \case
[ ] -> return Nothing
(x:_) -> return $ Just x
clean :: String -> String
clean = unlines . filter notComment . lines
where notComment = (not . ("#" `isPrefixOf`)) . dropWhile isSpace
loadConfig :: [FilePath] -> Options -> IO Config
loadConfig confs opt =
getFirstConfig confs >>= \case
Nothing -> putStrBoldLn "Using default config..." >> return (mkConfig opt)
Just conf ->
putStrBoldLn ("Using " ++ conf ++ " config...") *>
if "yaml" `isInfixOf` conf
then do
conf' <- Y.decodeFileEither conf
case conf' of
Right x -> return x
Left x -> throw $ SystemError (Y.prettyPrintParseException x) (ExitFailure 42)
else read . clean <$> readFile conf
{-# NOINLINE getNumberOfPhyCores #-}
getNumberOfPhyCores :: IO Int
getNumberOfPhyCores = readFile proc_cpuinfo >>= \file ->
return $ (length . filter (isInfixOf "processor") . lines) file
type ProcModules = [ (String, [String]) ]
type ModStateT = StateT ProcModules
getProcModules :: IO ProcModules
getProcModules =
readFile proc_modules >>= \file ->
return $ map (\l -> let ts = words l in (head ts, filter (\s -> (not . null) s && s /= "-") $
splitOn "," (ts !! 3))) $ lines file
rmmodFromProcMOdules :: String -> ProcModules -> ProcModules
rmmodFromProcMOdules name = filter (\(m,ds) -> m /= name )
getProcessID :: String -> IO [ProcessID]
getProcessID name = map read . words <$> catchIOError (readProcess pidof [name] "") (\_-> return [])
moduleDependencies :: String -> ProcModules -> [String]
moduleDependencies name =
concatMap (\(m,ds) -> if m == name then ds else [])
unloadDependencies :: Bool -- unload the given module as well
-> String -- kernel module name
-> ModStateT IO ()
unloadDependencies rm name = do
proc_mods <- get
mapM_ (unloadDependencies True) (moduleDependencies name proc_mods)
when (rm && isModuleLoaded name proc_mods) $ do
liftIO $ rmmod' name
put $ rmmodFromProcMOdules name proc_mods
where rmmod' name = putStrBoldLn ("Unloading " ++ name ++ "...") *>
runSystem (rmmod ++ " " ++ name) ("rmmod " ++ name ++ " error.")
isModuleLoaded name = any (\(mod,_) -> mod == name)
data LoadMode = InsertMod | ProbeMod
deriving Eq
isLoaded :: String -> IO Bool
isLoaded mod = getProcModules >>= (\pmod -> return $ mod `elem` fmap fst pmod)
-- putStrBoldLn $ "Loading " ++ name ++ " " ++ show opts
mkLoadModuleCmd :: LoadMode -> String -> [String] -> String
mkLoadModuleCmd mode name opts =
tool ++ " " ++ name ++ " " ++ unwords opts
where tool = if mode == InsertMod then insmod
else modprobe
loadModule :: LoadMode -> String -> [String] -> IO ()
loadModule mode name opts = putStrBoldLn ("Loading " ++ name ++ " " ++ show opts) *>
runSystem (mkLoadModuleCmd mode name opts) ("insmod " ++ name ++ " error.")
setupDevice :: Maybe Int -> Device -> IO ()
setupDevice queues (Device dev speed channels fctrl opts) = do
putStrBoldLn $ "Activating " ++ dev ++ "..."
runSystem (ifconfig ++ " " ++ dev ++ " up") "ifconfig error!"
threadDelay defaultDelay
if isJust speed
then do
let s = fromJust speed
putStrBoldLn $ "Setting speed (" ++ show s ++ ") for " ++ dev ++ "..."
runSystem (ethtool ++ " -s " ++ dev ++ " speed " ++ show s ++ " duplex full autoneg off") "ethtool: set speed error!"
else
putStrBoldLn ("Auto-negotiating speed for " ++ dev ++ "...") *>
runSystem (ethtool ++ " -s " ++ dev ++ " duplex full autoneg off") "ethtool: auto-negotiation error!"
threadDelay defaultDelay
when (isJust fctrl) $ do
let t = fromJust fctrl
if t then putStrBoldLn ("Disabling flow control for " ++ dev ++ "...") *>
runSystem (ethtool ++ " -A " ++ dev ++ " rx on tx on") "ethtool: enabling flow-ctrl error!"
else putStrBoldLn ("Enabling flow control for " ++ dev ++ "...") *>
runSystem (ethtool ++ " -A " ++ dev ++ " autoneg off rx off tx off") "ethtool: disabling flow-ctrl error!"
threadDelay defaultDelay
when (isJust queues || isJust channels) $ do
let c = fromJust (channels <|> queues)
putStrBoldLn $ "Setting channels to " ++ show c ++ "..."
runSystem (ethtool ++ " -L " ++ dev ++ " combined " ++ show c) ""
forM_ opts $ \(opt, arg) ->
threadDelay defaultDelay *>
runSystem (ethtool ++ " " ++ opt ++ " " ++ dev ++ " " ++ arg) ("ethtool:" ++ opt ++ " error!")
setupPCI :: [(String, String)] -> IO ()
setupPCI = mapM_ (\(a, v) -> runSystem (setpci ++ " -v -d " ++ show a ++ " " ++ show v) (setpci ++ ": error!"))
getDevices :: Config -> [String]
getDevices conf =
map devname (concatMap devices (drivers conf))
setupIRQAffinity :: Int -> [Int] -> [String] -> [String] -> IO ()
setupIRQAffinity fc excl algs devs = do
let excl_opt = unwords (map (\n -> " -e " ++ show n) excl)
let affinity = zip algs (tails devs)
unless (null affinity) $
forM_ affinity $ \(alg, devs') ->
runSystem ("pfq-affinity -f " ++ show fc ++ " " ++ excl_opt ++ " -a " ++ alg ++ " -m TxRx " ++ unwords devs') "pfq-affinity error!"
runSystem :: String -> String -> IO ()
runSystem cmd errmsg =
putStrLn ("-> " ++ cmd) *>
system cmd >>= \ec -> unless (null errmsg || ec == ExitSuccess) $ throw (SystemError (red ++ errmsg ++ reset) ec)
putStrBoldLn :: String -> IO ()
putStrBoldLn msg = putStrLn $ bold ++ msg ++ reset
possiblyReadFile :: FilePath -> IO String
possiblyReadFile file = do
res <- tryIOError $ readFile file
case res of
Left _ -> return ""
Right str -> length str `seq` return str
| pfq/PFQ | user/pfq-load/pfq-load.hs | gpl-2.0 | 16,878 | 0 | 23 | 4,741 | 4,729 | 2,462 | 2,267 | 339 | 4 |
module SneakyBeaky.Matrix where
type Matrix2D a = (a, a, a, a)
mMultiply :: RealFrac a => Matrix2D a -> (Int, Int) -> (Int, Int)
mMultiply (a00,a10,a01,a11) (x, y) = let xf = fromIntegral x
yf = fromIntegral y
in (floor (a00 * xf + a01 * yf), floor (a10 * xf + a11 * yf))
mRotationMatrix :: Floating a => a -> Matrix2D a
mRotationMatrix a = (cos a, -(sin a), sin a, cos a)
| pmiddend/sneakybeaky | src/SneakyBeaky/Matrix.hs | gpl-3.0 | 455 | 0 | 12 | 157 | 208 | 113 | 95 | 8 | 1 |
module Bot where
import Network.SimpleIRC hiding (Command,parse)
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import Data.List
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Char
import BotCommand
import Logger
import Config
import Categorize
import Control.Exception
-- | onMessage Event handler. According the RFC 2812 , PrivMsg is used to send
-- message to a user, a channel and a user in the channel.
-- type EventFunc = MIrc -> IrcMessage -> IO ()
onMessage :: EventFunc
onMessage s m = case categorize m of
(msgType, False) -> logMsg msgType m
(ChanMsg, True) -> reply s m False
(ChanMsgtoBot, True) -> reply s m True
(PrivMsg, True) -> reply s m False
logMsg :: IrcMsgType -> IrcMessage -> IO ()
logMsg PrivMsg m = return ()
logMsg _ m = defaultLogger m
reply :: MIrc -> IrcMessage -> Bool -> IO ()
reply s m b = (process b $ mMsg m) >>= sendMsg s (fromJust $ mOrigin m)
-- | Process a message and return a response
--
process :: Bool -> B.ByteString -> IO B.ByteString
process True b = (process2 . stripBotName . B.unpack) b >>= return . B.pack
process False b = (process2 . B.unpack) b >>= return . B.pack
process2 :: String -> IO String
process2 m = case commandParser m of
Left error -> return $ show error
Right (Msg onlyMsg) -> return onlyMsg
Right (Cmd cmd args) -> runCommand cmd args
-- | Parse the message which contains either a command starting with ! or
-- anything
commandParser :: String -> Either ParseError (ChatMsg)
commandParser = parse parseCmd ""
-- | Process a command and return a response
runCommand :: Command -> [String] -> IO String
runCommand (Command f g u) args = do
res <- evaluate (f args) `catch` excepHandler
case res of
Left InvalidNumber -> return (showNumberError ++ u)
Left InvalidType -> return (showTypeError ++ u)
Right arg -> return (g arg)
excepHandler :: SomeException -> IO (Either ArgError a)
excepHandler _ = return (Left InvalidType)
-------------------------Tests--------------------------------------------------
-- | Test function without the IRC communication
-- >>>test "hi"
-- hi
-- >>>test "!hi"
-- Hello!
-- >>>test "!neg 3"
-- -3
-- >>>test "!add 3 4"
-- 7
test :: String -> IO ()
test msg = do case commandParser (msg) of
Left error -> putStrLn $ show error
Right (Msg onlyMsg) -> putStrLn onlyMsg
Right (Cmd cmd args) -> runCommand cmd args >>= putStrLn
-- | 1. Define a test IRC message to the channel for testing
msg :: IrcMessage
msg = IrcMessage {mNick = Just $ B.pack "maxking",
mUser = Just $ B.pack "~phoenix",
mHost = Just $ B.pack "104.131.128.74",
mServer = Nothing,
mCode = B.pack "PRIVMSG",
mMsg = B.pack "hi",
mChan = Just $ B.pack "##maxking",
mOrigin = Just $ B.pack "##maxking",
mOther = Nothing,
mRaw = B.pack ":maxking!~phoenix@104.131.128.74 PRIVMSG ##maxking :hi"}
-- | 2. A test IRC message to channel highlighting the bot
msg2 :: IrcMessage
msg2 = IrcMessage {mNick = Just $ B.pack "maxking",
mUser = Just $ B.pack "~phoenix",
mHost = Just $ B.pack "104.131.128.74",
mServer = Nothing,
mCode = B.pack "PRIVMSG",
mMsg = B.pack "hasbot: How you you man?",
mChan = Just $ B.pack "##maxking",
mOrigin = Just $ B.pack "##maxking",
mOther = Nothing,
mRaw = B.pack ":maxking!~phoenix@104.131.128.74 PRIVMSG ##maxking :hasbot: How you you man?"}
-- | 3. A test IRC message to bot as private message
msg3 :: IrcMessage
msg3 = IrcMessage {mNick = Just $ B.pack "maxking",
mUser = Just $ B.pack "~phoenix",
mHost = Just $ B.pack "104.131.128.74",
mServer = Nothing,
mCode = B.pack "PRIVMSG",
mMsg = B.pack "Hi Man!",
mChan = Just $ B.pack "hasbot",
mOrigin = Just $ B.pack "maxking",
mOther = Nothing,
mRaw = B.pack ":maxking!~phoenix@104.131.128.74 PRIVMSG hasbot :Hi Man!"}
| maxking/cs583-project | src/Bot.hs | gpl-3.0 | 4,508 | 0 | 12 | 1,398 | 1,154 | 613 | 541 | 81 | 4 |
module Service(trade,record,query,pay,sign) where
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.Trans(liftIO)
import Type
import Utils
import Config
record :: TradeRecord
record = TradeRecord {
tradeNo = "20170214372419268805",
tradeAmount = 10,
tradeType = ORDER,
tradePayMethod = WX,
tradePayChannel = TERMINAL,
tradeRefundNo = Nothing,
tradeDate = 1400678
}
order :: Trade PayResponse
order = do
record <- ask
put SUCCESS
return UnifiedOrderResponse
refund :: OrderId -> Amount -> IO PayResponse
refund orderId amount = do
record <- findPaidRecord orderId
let resp = request.unifiedRefund $ ["out_trade_no" .- (tradeNo record)
,"out_refund_no" .- "2017lll"
,"total_fee" .- (show $ tradeAmount record)
,"refund_fee" .- (show amount)
,wxOpUserId]
return $ WxRefundResponse resp
charge :: Trade PayResponse
charge = do
put FAIL
return ChargeResponse
route :: TradeType -> Trade ServiceResponse
route ORDER = do
resp <- order
return (ServiceResponse OK Nothing Nothing Nothing)
route _ = return $ ServiceResponse ERR (Just 1002) (Just "Not Ready!") Nothing
pay :: Trade ServiceResponse
pay = route =<< (\record -> return (tradeType record)) =<< ask
query :: String -> IO ServiceResponse
query tradeNo = do
let resp = request.orderQuery $ ["out_trade_no" .- tradeNo]
case resp of
Nothing -> return $ ServiceResponse ERR (Just 1005) (Just "Network Timeout") Nothing
Just r -> return $ ServiceResponse OK Nothing Nothing resp
trade :: TradeRecord -> Trade a -> (a,TradeState)
trade r t = runState (runReaderT t r) APPLY
findPaidRecord :: String -> IO TradeRecord
findPaidRecord no = return (TradeRecord {
tradeNo = no,
tradeAmount = 10,
tradeType = ORDER,
tradePayMethod = WX,
tradePayChannel = TERMINAL,
tradeRefundNo = Nothing,
tradeDate = 1400678
}) | koerriva/paygate | src/Service.hs | gpl-3.0 | 2,092 | 0 | 15 | 541 | 617 | 327 | 290 | 59 | 2 |
{-# OPTIONS -fno-warn-orphans #-}
module Foreign.C.Types.Instances () where
import Data.Aeson (ToJSON(..), FromJSON(..))
import Foreign.C.Types (CDouble)
instance FromJSON CDouble where
parseJSON = fmap (realToFrac :: Double -> CDouble) . parseJSON
instance ToJSON CDouble where
toJSON = toJSON . (realToFrac :: CDouble -> Double)
| da-x/lamdu | bottlelib/Foreign/C/Types/Instances.hs | gpl-3.0 | 341 | 0 | 9 | 52 | 101 | 61 | 40 | 8 | 0 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.LevelPuzzleMode.Do
(
doPlay,
doComplete,
--doSpecialComplete,
doFailure,
) where
import MyPrelude
import Game
import Game.Grid.Helpers
import Game.LevelPuzzleMode.LevelPuzzleWorld
import Game.LevelPuzzleMode.Iteration.State
import Game.LevelPuzzleMode.Helpers
import Game.LevelPuzzleMode.Do.Grid
import Game.LevelPuzzleMode.Do.Input
import Game.Run.RunWorld
import Graphics.UI.GLFW
--------------------------------------------------------------------------------
--
beginLevelPuzzleWorld lvl = do
let lvl' = levelpuzzleClearEvents $ levelpuzzleModifyCamera lvl $ \cam ->
cameraToPath cam (levelpuzzlePath lvl)
keysKeyOnce (CharKey ' ') >>= \bool -> case bool of
False -> return lvl'
True -> return $ if levelpuzzleIsPuzzle lvl'
then levelpuzzleModifyGrid (lvl { levelpuzzleIsPuzzle = False }) gridPathStart
else lvl' { levelpuzzleIsPuzzle = True }
doPlay :: s -> LevelPuzzleWorld -> b -> MEnv' (s, LevelPuzzleWorld, b)
doPlay s lvl b = do
lvl' <- beginLevelPuzzleWorld lvl
-- Grid
(s', grid', lvl'') <- doGridPlay s (levelpuzzleGrid lvl') lvl'
let lvl''' = levelpuzzleModifyContent lvl'' $ \cnt -> cnt { contentGrid = grid' }
return (s', lvl''', b)
doFailure :: s -> LevelPuzzleWorld -> b -> MEnv' (s, LevelPuzzleWorld, b)
doFailure s lvl b = do
lvl' <- beginLevelPuzzleWorld lvl
-- Grid
(s', grid', lvl'') <- doGridFailure s (levelpuzzleGrid lvl') lvl'
let lvl''' = levelpuzzleModifyContent lvl'' $ \cnt -> cnt { contentGrid = grid' }
return (s', lvl''', b)
doComplete :: s -> LevelPuzzleWorld -> b -> MEnv' (s, LevelPuzzleWorld, b)
doComplete s lvl b = do
lvl' <- beginLevelPuzzleWorld lvl
-- do Grid
(s', grid', lvl'') <- doGridComplete s (levelpuzzleGrid lvl') lvl'
let lvl''' = levelpuzzleModifyContent lvl'' $ \cnt -> cnt { contentGrid = grid' }
return (s', lvl''', b)
| karamellpelle/grid | designer/source/Game/LevelPuzzleMode/Do.hs | gpl-3.0 | 2,794 | 0 | 17 | 634 | 595 | 330 | 265 | 41 | 3 |
{-# 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.AccessApproval.Organizations.UpdateAccessApprovalSettings
-- 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)
--
-- Updates the settings associated with a project, folder, or organization.
-- Settings to update are determined by the value of field_mask.
--
-- /See:/ <https://cloud.google.com/access-approval/docs Access Approval API Reference> for @accessapproval.organizations.updateAccessApprovalSettings@.
module Network.Google.Resource.AccessApproval.Organizations.UpdateAccessApprovalSettings
(
-- * REST Resource
OrganizationsUpdateAccessApprovalSettingsResource
-- * Creating a Request
, organizationsUpdateAccessApprovalSettings
, OrganizationsUpdateAccessApprovalSettings
-- * Request Lenses
, ouaasXgafv
, ouaasUploadProtocol
, ouaasUpdateMask
, ouaasAccessToken
, ouaasUploadType
, ouaasPayload
, ouaasName
, ouaasCallback
) where
import Network.Google.AccessApproval.Types
import Network.Google.Prelude
-- | A resource alias for @accessapproval.organizations.updateAccessApprovalSettings@ method which the
-- 'OrganizationsUpdateAccessApprovalSettings' request conforms to.
type OrganizationsUpdateAccessApprovalSettingsResource
=
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AccessApprovalSettings :>
Patch '[JSON] AccessApprovalSettings
-- | Updates the settings associated with a project, folder, or organization.
-- Settings to update are determined by the value of field_mask.
--
-- /See:/ 'organizationsUpdateAccessApprovalSettings' smart constructor.
data OrganizationsUpdateAccessApprovalSettings =
OrganizationsUpdateAccessApprovalSettings'
{ _ouaasXgafv :: !(Maybe Xgafv)
, _ouaasUploadProtocol :: !(Maybe Text)
, _ouaasUpdateMask :: !(Maybe GFieldMask)
, _ouaasAccessToken :: !(Maybe Text)
, _ouaasUploadType :: !(Maybe Text)
, _ouaasPayload :: !AccessApprovalSettings
, _ouaasName :: !Text
, _ouaasCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsUpdateAccessApprovalSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ouaasXgafv'
--
-- * 'ouaasUploadProtocol'
--
-- * 'ouaasUpdateMask'
--
-- * 'ouaasAccessToken'
--
-- * 'ouaasUploadType'
--
-- * 'ouaasPayload'
--
-- * 'ouaasName'
--
-- * 'ouaasCallback'
organizationsUpdateAccessApprovalSettings
:: AccessApprovalSettings -- ^ 'ouaasPayload'
-> Text -- ^ 'ouaasName'
-> OrganizationsUpdateAccessApprovalSettings
organizationsUpdateAccessApprovalSettings pOuaasPayload_ pOuaasName_ =
OrganizationsUpdateAccessApprovalSettings'
{ _ouaasXgafv = Nothing
, _ouaasUploadProtocol = Nothing
, _ouaasUpdateMask = Nothing
, _ouaasAccessToken = Nothing
, _ouaasUploadType = Nothing
, _ouaasPayload = pOuaasPayload_
, _ouaasName = pOuaasName_
, _ouaasCallback = Nothing
}
-- | V1 error format.
ouaasXgafv :: Lens' OrganizationsUpdateAccessApprovalSettings (Maybe Xgafv)
ouaasXgafv
= lens _ouaasXgafv (\ s a -> s{_ouaasXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ouaasUploadProtocol :: Lens' OrganizationsUpdateAccessApprovalSettings (Maybe Text)
ouaasUploadProtocol
= lens _ouaasUploadProtocol
(\ s a -> s{_ouaasUploadProtocol = a})
-- | The update mask applies to the settings. Only the top level fields of
-- AccessApprovalSettings (notification_emails & enrolled_services) are
-- supported. For each field, if it is included, the currently stored value
-- will be entirely overwritten with the value of the field passed in this
-- request. For the \`FieldMask\` definition, see
-- https:\/\/developers.google.com\/protocol-buffers\/docs\/reference\/google.protobuf#fieldmask
-- If this field is left unset, only the notification_emails field will be
-- updated.
ouaasUpdateMask :: Lens' OrganizationsUpdateAccessApprovalSettings (Maybe GFieldMask)
ouaasUpdateMask
= lens _ouaasUpdateMask
(\ s a -> s{_ouaasUpdateMask = a})
-- | OAuth access token.
ouaasAccessToken :: Lens' OrganizationsUpdateAccessApprovalSettings (Maybe Text)
ouaasAccessToken
= lens _ouaasAccessToken
(\ s a -> s{_ouaasAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ouaasUploadType :: Lens' OrganizationsUpdateAccessApprovalSettings (Maybe Text)
ouaasUploadType
= lens _ouaasUploadType
(\ s a -> s{_ouaasUploadType = a})
-- | Multipart request metadata.
ouaasPayload :: Lens' OrganizationsUpdateAccessApprovalSettings AccessApprovalSettings
ouaasPayload
= lens _ouaasPayload (\ s a -> s{_ouaasPayload = a})
-- | The resource name of the settings. Format is one of: *
-- \"projects\/{project}\/accessApprovalSettings\" *
-- \"folders\/{folder}\/accessApprovalSettings\" *
-- \"organizations\/{organization}\/accessApprovalSettings\"
ouaasName :: Lens' OrganizationsUpdateAccessApprovalSettings Text
ouaasName
= lens _ouaasName (\ s a -> s{_ouaasName = a})
-- | JSONP
ouaasCallback :: Lens' OrganizationsUpdateAccessApprovalSettings (Maybe Text)
ouaasCallback
= lens _ouaasCallback
(\ s a -> s{_ouaasCallback = a})
instance GoogleRequest
OrganizationsUpdateAccessApprovalSettings
where
type Rs OrganizationsUpdateAccessApprovalSettings =
AccessApprovalSettings
type Scopes OrganizationsUpdateAccessApprovalSettings
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
OrganizationsUpdateAccessApprovalSettings'{..}
= go _ouaasName _ouaasXgafv _ouaasUploadProtocol
_ouaasUpdateMask
_ouaasAccessToken
_ouaasUploadType
_ouaasCallback
(Just AltJSON)
_ouaasPayload
accessApprovalService
where go
= buildClient
(Proxy ::
Proxy
OrganizationsUpdateAccessApprovalSettingsResource)
mempty
| brendanhay/gogol | gogol-accessapproval/gen/Network/Google/Resource/AccessApproval/Organizations/UpdateAccessApprovalSettings.hs | mpl-2.0 | 7,179 | 0 | 17 | 1,469 | 866 | 508 | 358 | 131 | 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.DataFusion.Projects.Locations.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)
--
-- Gets information about a location.
--
-- /See:/ <https://cloud.google.com/data-fusion/docs Cloud Data Fusion API Reference> for @datafusion.projects.locations.get@.
module Network.Google.Resource.DataFusion.Projects.Locations.Get
(
-- * REST Resource
ProjectsLocationsGetResource
-- * Creating a Request
, projectsLocationsGet
, ProjectsLocationsGet
-- * Request Lenses
, plgXgafv
, plgUploadProtocol
, plgAccessToken
, plgUploadType
, plgName
, plgCallback
) where
import Network.Google.DataFusion.Types
import Network.Google.Prelude
-- | A resource alias for @datafusion.projects.locations.get@ method which the
-- 'ProjectsLocationsGet' request conforms to.
type ProjectsLocationsGetResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Location
-- | Gets information about a location.
--
-- /See:/ 'projectsLocationsGet' smart constructor.
data ProjectsLocationsGet =
ProjectsLocationsGet'
{ _plgXgafv :: !(Maybe Xgafv)
, _plgUploadProtocol :: !(Maybe Text)
, _plgAccessToken :: !(Maybe Text)
, _plgUploadType :: !(Maybe Text)
, _plgName :: !Text
, _plgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plgXgafv'
--
-- * 'plgUploadProtocol'
--
-- * 'plgAccessToken'
--
-- * 'plgUploadType'
--
-- * 'plgName'
--
-- * 'plgCallback'
projectsLocationsGet
:: Text -- ^ 'plgName'
-> ProjectsLocationsGet
projectsLocationsGet pPlgName_ =
ProjectsLocationsGet'
{ _plgXgafv = Nothing
, _plgUploadProtocol = Nothing
, _plgAccessToken = Nothing
, _plgUploadType = Nothing
, _plgName = pPlgName_
, _plgCallback = Nothing
}
-- | V1 error format.
plgXgafv :: Lens' ProjectsLocationsGet (Maybe Xgafv)
plgXgafv = lens _plgXgafv (\ s a -> s{_plgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plgUploadProtocol :: Lens' ProjectsLocationsGet (Maybe Text)
plgUploadProtocol
= lens _plgUploadProtocol
(\ s a -> s{_plgUploadProtocol = a})
-- | OAuth access token.
plgAccessToken :: Lens' ProjectsLocationsGet (Maybe Text)
plgAccessToken
= lens _plgAccessToken
(\ s a -> s{_plgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plgUploadType :: Lens' ProjectsLocationsGet (Maybe Text)
plgUploadType
= lens _plgUploadType
(\ s a -> s{_plgUploadType = a})
-- | Resource name for the location.
plgName :: Lens' ProjectsLocationsGet Text
plgName = lens _plgName (\ s a -> s{_plgName = a})
-- | JSONP
plgCallback :: Lens' ProjectsLocationsGet (Maybe Text)
plgCallback
= lens _plgCallback (\ s a -> s{_plgCallback = a})
instance GoogleRequest ProjectsLocationsGet where
type Rs ProjectsLocationsGet = Location
type Scopes ProjectsLocationsGet =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsGet'{..}
= go _plgName _plgXgafv _plgUploadProtocol
_plgAccessToken
_plgUploadType
_plgCallback
(Just AltJSON)
dataFusionService
where go
= buildClient
(Proxy :: Proxy ProjectsLocationsGetResource)
mempty
| brendanhay/gogol | gogol-datafusion/gen/Network/Google/Resource/DataFusion/Projects/Locations/Get.hs | mpl-2.0 | 4,504 | 0 | 15 | 1,022 | 695 | 406 | 289 | 100 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.OperatingSystemVersions.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)
--
-- Retrieves a list of operating system versions.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.operatingSystemVersions.list@.
module Network.Google.Resource.DFAReporting.OperatingSystemVersions.List
(
-- * REST Resource
OperatingSystemVersionsListResource
-- * Creating a Request
, operatingSystemVersionsList
, OperatingSystemVersionsList
-- * Request Lenses
, osvlXgafv
, osvlUploadProtocol
, osvlAccessToken
, osvlUploadType
, osvlProFileId
, osvlCallback
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.operatingSystemVersions.list@ method which the
-- 'OperatingSystemVersionsList' request conforms to.
type OperatingSystemVersionsListResource =
"dfareporting" :>
"v3.5" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"operatingSystemVersions" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] OperatingSystemVersionsListResponse
-- | Retrieves a list of operating system versions.
--
-- /See:/ 'operatingSystemVersionsList' smart constructor.
data OperatingSystemVersionsList =
OperatingSystemVersionsList'
{ _osvlXgafv :: !(Maybe Xgafv)
, _osvlUploadProtocol :: !(Maybe Text)
, _osvlAccessToken :: !(Maybe Text)
, _osvlUploadType :: !(Maybe Text)
, _osvlProFileId :: !(Textual Int64)
, _osvlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperatingSystemVersionsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'osvlXgafv'
--
-- * 'osvlUploadProtocol'
--
-- * 'osvlAccessToken'
--
-- * 'osvlUploadType'
--
-- * 'osvlProFileId'
--
-- * 'osvlCallback'
operatingSystemVersionsList
:: Int64 -- ^ 'osvlProFileId'
-> OperatingSystemVersionsList
operatingSystemVersionsList pOsvlProFileId_ =
OperatingSystemVersionsList'
{ _osvlXgafv = Nothing
, _osvlUploadProtocol = Nothing
, _osvlAccessToken = Nothing
, _osvlUploadType = Nothing
, _osvlProFileId = _Coerce # pOsvlProFileId_
, _osvlCallback = Nothing
}
-- | V1 error format.
osvlXgafv :: Lens' OperatingSystemVersionsList (Maybe Xgafv)
osvlXgafv
= lens _osvlXgafv (\ s a -> s{_osvlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
osvlUploadProtocol :: Lens' OperatingSystemVersionsList (Maybe Text)
osvlUploadProtocol
= lens _osvlUploadProtocol
(\ s a -> s{_osvlUploadProtocol = a})
-- | OAuth access token.
osvlAccessToken :: Lens' OperatingSystemVersionsList (Maybe Text)
osvlAccessToken
= lens _osvlAccessToken
(\ s a -> s{_osvlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
osvlUploadType :: Lens' OperatingSystemVersionsList (Maybe Text)
osvlUploadType
= lens _osvlUploadType
(\ s a -> s{_osvlUploadType = a})
-- | User profile ID associated with this request.
osvlProFileId :: Lens' OperatingSystemVersionsList Int64
osvlProFileId
= lens _osvlProFileId
(\ s a -> s{_osvlProFileId = a})
. _Coerce
-- | JSONP
osvlCallback :: Lens' OperatingSystemVersionsList (Maybe Text)
osvlCallback
= lens _osvlCallback (\ s a -> s{_osvlCallback = a})
instance GoogleRequest OperatingSystemVersionsList
where
type Rs OperatingSystemVersionsList =
OperatingSystemVersionsListResponse
type Scopes OperatingSystemVersionsList =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient OperatingSystemVersionsList'{..}
= go _osvlProFileId _osvlXgafv _osvlUploadProtocol
_osvlAccessToken
_osvlUploadType
_osvlCallback
(Just AltJSON)
dFAReportingService
where go
= buildClient
(Proxy :: Proxy OperatingSystemVersionsListResource)
mempty
| brendanhay/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/OperatingSystemVersions/List.hs | mpl-2.0 | 5,183 | 0 | 18 | 1,174 | 726 | 421 | 305 | 109 | 1 |
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module XSpec where
import Gauge
import GaugeUse
import MissionControl
import MissionControlUse
import ScratchPad.FuelLevel
import ScratchPad.Sorted
------------------------------------------------------------------------------
import Test.Hspec
spec :: Spec
spec = describe "xx" $ do
chkMF1
chkMF2
chkD
chkDMF
fl0t
fl1t
fl2t
g1t
gc1t
s0t
gaugeUse
rocket
gaugeUse :: Spec
gaugeUse = describe "gauge use" $ do
mkGood "l1g" l1g 10.0
mkBad "l1ge" l1ge "ExceedsMaxFlow"
--mkBad "l2b" l2b "NotDecr" -- infinite loop
mkBad "l2ge" l2ge "NotDecr"
mkBad "ldslb" ldslb "Prelude.head: empty list"
mkGood "ldsneg" ldsneg 10.0
mkBad "ldsnebb" ldsnebb "NotDecr"
mkGood "lNTg" lNTg 10.0
mkGood "lPTg" lPTg 10.0
mkGood "lRTg" lRTg 10.0
mkGood "lRTwSg" lRTwSg (10.0, 0.33521595799981796)
mkGood "lOOPg1" lOOPg1 (10.0, 0.33521595799981796)
mkGood "lOOPg2" lOOPg2 (10.0, 110.79432945026694)
where
mkGood :: (Show a, Eq a) => String -> IO a -> a -> Spec
mkGood name f v = do x <- runIO f; it name $ x `shouldBe` v
mkBad :: String -> IO a -> String -> Spec
mkBad name f e = it name $ f `shouldThrow` errorCall e
rocket :: Spec
rocket = describe "rocket" $
it "countdown" $ countdown mkMissionControl `shouldBe` "Rocket Launched!"
| haroldcarr/learn-haskell-coq-ml-etc | haskell/playpen/2020-07-07-harold-carr-phantom-existential-scratchpad/test/XSpec.hs | unlicense | 1,521 | 0 | 11 | 395 | 401 | 194 | 207 | 46 | 1 |
{-# OPTIONS -cpp #-}
------------------------------------------------------------------------------
-- Copyright 2012 Microsoft Corporation.
--
-- This is free software; you can redistribute it and/or modify it under the
-- terms of the Apache License, Version 2.0. A copy of the License can be
-- found in the file "license.txt" at the root of this distribution.
-----------------------------------------------------------------------------
{-
Reading file times
-}
-----------------------------------------------------------------------------
module Platform.Filetime( FileTime
, getCurrentTime
, getFileTime
, getFileTimeOrCurrent
, fileTime0
) where
import System.Directory( getModificationTime )
import Platform.Runtime( exCatch )
#if __GLASGOW_HASKELL__ >= 706
import qualified Data.Time as T
type FileTime = T.UTCTime
getCurrentTime :: IO FileTime
getCurrentTime
= T.getCurrentTime
fileTime0 :: FileTime
fileTime0
= T.UTCTime (T.ModifiedJulianDay 0) (T.secondsToDiffTime 0)
#else
import qualified System.Time as T
type FileTime = T.ClockTime
getCurrentTime :: IO FileTime
getCurrentTime
= T.getClockTime
fileTime0 :: FileTime
fileTime0
= T.TOD 0 0
#endif
-- | Returns the file modification time or 0 if it does not exist.
getFileTime :: FilePath -> IO FileTime
getFileTime fname
= do getModificationTime fname
`exCatch` \_ -> do -- putStrLn $ "filetime: 0 for : " ++ fname
return fileTime0
-- | returns the file modification time or the current time if it does not exist.
getFileTimeOrCurrent :: FilePath -> IO FileTime
getFileTimeOrCurrent fname
= do getModificationTime fname
`exCatch` \_ -> getCurrentTime
| lpeterse/koka | src/Platform/Filetime.hs | apache-2.0 | 1,822 | 0 | 9 | 416 | 203 | 119 | 84 | 25 | 1 |
import Math.NumberTheory.Primes.Sieve
import Math.NumberTheory.Primes.Testing
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
triangle n = (n*(n+1)) `div` 2
pentagonal n = (n*((3*n)-1)) `div` 2
hexagonal n = n*((2*n)-1)
main = do
let base = [1..100000]
let triangles = IntSet.fromList $ map triangle base
let pentagonals = IntSet.fromList $ map pentagonal base
let hexagonals = IntSet.fromList $ map hexagonal base
let intersect = IntSet.intersection pentagonals $ IntSet.intersection hexagonals triangles
print $ take 1 $ dropWhile (<= 40755) $ IntSet.toList $ intersect | ulikoehler/ProjectEuler | Euler45.hs | apache-2.0 | 621 | 0 | 12 | 110 | 257 | 135 | 122 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Texts where
import Prelude
import Data.Monoid ((<>))
import Config.Config (staticURL)
bookLabelTxt :: String -> String
bookLabelTxt ref =
"<div class='book-banner'>\
\ <img class='book-clipart' src='" <> staticURL <> "img/book.png' alt='book clipart'/>\
\ <div class='book-title'>\
\ <a href='https://www.crcpress.com/Data-Stewardship-for-Discovery-A-Practical-Guide-for-Data-Experts/Mons/p/book/9781498753173' target='_blank'>\
\ Data Stewardship for Discovery\
\ </a>\
\ : Chapter " <> ref <> "\
\ </div>\
\ <div class='book-acknowledgement'>\
\ <div class='book-permission'>\
\ With kind permission of\
\ </div>\
\ <div class='crc-log'>\
\ <a href='http://taylorandfrancis.com/' target='_blank'><img src='" <> staticURL <> "img/crc-logo.png' alt='CRC logo'/></a>\
\ </div>\
\ </div>\
\</div>"
| DataStewardshipPortal/ds-wizard | src/Texts.hs | apache-2.0 | 919 | 0 | 10 | 172 | 71 | 41 | 30 | 11 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
----------------------------------------------------------------------------
-- |
-- Module : Web.Skroutz.Model.Base.FilterGroup
-- Copyright : (c) 2016 Remous-Aris Koutsiamanis
-- License : Apache License 2.0
-- Maintainer : Remous-Aris Koutsiamanis <ariskou@gmail.com>
-- Stability : alpha
-- Portability : non-portable
--
-- Provides the 'FilterGroup' type.
----------------------------------------------------------------------------
module Web.Skroutz.Model.Base.FilterGroup
where
import Control.DeepSeq (NFData)
import Data.Data (Data, Typeable)
import Data.Text (Text)
import GHC.Generics (Generic)
import Web.Skroutz.Model.Base.FilterGroupType
import Web.Skroutz.Model.Base.ISO8601Time
import Web.Skroutz.TH
data FilterGroup = FilterGroup {
_filterGroupId :: Int
, _filterGroupName :: Text
, _filterGroupActive :: Bool
, _filterGroupCategoryId :: Int
, _filterGroupCreatedAt :: Maybe ISO8601Time
, _filterGroupUpdatedAt :: ISO8601Time
, _filterGroupHint :: Text
, _filterGroupCombined :: Bool
, _filterGroupFilterType :: FilterGroupType
} deriving (Eq, Ord, Typeable, Data, Generic, Show, NFData)
makeLensesAndJSON ''FilterGroup "_filterGroup"
| ariskou/skroutz-haskell-api | src/Web/Skroutz/Model/Base/FilterGroup.hs | apache-2.0 | 1,546 | 0 | 9 | 394 | 196 | 126 | 70 | 24 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStandardItem_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:21
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStandardItem_h where
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QStandardItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QStandardItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QStandardItem_unSetUserMethod" qtc_QStandardItem_unSetUserMethod :: Ptr (TQStandardItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QStandardItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QStandardItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QStandardItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QStandardItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QStandardItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QStandardItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QStandardItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QStandardItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QStandardItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QStandardItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QStandardItem ()) (QStandardItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QStandardItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QStandardItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QStandardItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QStandardItem_setUserMethod" qtc_QStandardItem_setUserMethod :: Ptr (TQStandardItem a) -> CInt -> Ptr (Ptr (TQStandardItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QStandardItem :: (Ptr (TQStandardItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQStandardItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QStandardItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QStandardItemSc a) (QStandardItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QStandardItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QStandardItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QStandardItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QStandardItem ()) (QStandardItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QStandardItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QStandardItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QStandardItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QStandardItem_setUserMethodVariant" qtc_QStandardItem_setUserMethodVariant :: Ptr (TQStandardItem a) -> CInt -> Ptr (Ptr (TQStandardItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QStandardItem :: (Ptr (TQStandardItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQStandardItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QStandardItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QStandardItemSc a) (QStandardItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QStandardItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QStandardItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QStandardItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QStandardItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QStandardItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QStandardItem_unSetHandler" qtc_QStandardItem_unSetHandler :: Ptr (TQStandardItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QStandardItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QStandardItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QStandardItem ()) (QStandardItem x0 -> IO (QStandardItem t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> IO (Ptr (TQStandardItem t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QStandardItem_setHandler1" qtc_QStandardItem_setHandler1 :: Ptr (TQStandardItem a) -> CWString -> Ptr (Ptr (TQStandardItem x0) -> IO (Ptr (TQStandardItem t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QStandardItem1 :: (Ptr (TQStandardItem x0) -> IO (Ptr (TQStandardItem t0))) -> IO (FunPtr (Ptr (TQStandardItem x0) -> IO (Ptr (TQStandardItem t0))))
foreign import ccall "wrapper" wrapSetHandler_QStandardItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QStandardItemSc a) (QStandardItem x0 -> IO (QStandardItem t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> IO (Ptr (TQStandardItem t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qclone_h (QStandardItem ()) (()) (IO (QStandardItem ())) where
clone_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStandardItem_clone cobj_x0
foreign import ccall "qtc_QStandardItem_clone" qtc_QStandardItem_clone :: Ptr (TQStandardItem a) -> IO (Ptr (TQStandardItem ()))
instance Qclone_h (QStandardItemSc a) (()) (IO (QStandardItem ())) where
clone_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStandardItem_clone cobj_x0
instance QsetHandler (QStandardItem ()) (QStandardItem x0 -> Int -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> CInt -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1int
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QStandardItem_setHandler2" qtc_QStandardItem_setHandler2 :: Ptr (TQStandardItem a) -> CWString -> Ptr (Ptr (TQStandardItem x0) -> CInt -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QStandardItem2 :: (Ptr (TQStandardItem x0) -> CInt -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQStandardItem x0) -> CInt -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QStandardItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QStandardItemSc a) (QStandardItem x0 -> Int -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> CInt -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1int
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqdata_h (QStandardItem ()) ((Int)) where
qdata_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStandardItem_data1 cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStandardItem_data1" qtc_QStandardItem_data1 :: Ptr (TQStandardItem a) -> CInt -> IO (Ptr (TQVariant ()))
instance Qqdata_h (QStandardItemSc a) ((Int)) where
qdata_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStandardItem_data1 cobj_x0 (toCInt x1)
instance QsetHandler (QStandardItem ()) (QStandardItem x0 -> QVariant t1 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> Ptr (TQVariant t1) -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QStandardItem_setHandler3" qtc_QStandardItem_setHandler3 :: Ptr (TQStandardItem a) -> CWString -> Ptr (Ptr (TQStandardItem x0) -> Ptr (TQVariant t1) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QStandardItem3 :: (Ptr (TQStandardItem x0) -> Ptr (TQVariant t1) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQStandardItem x0) -> Ptr (TQVariant t1) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QStandardItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QStandardItemSc a) (QStandardItem x0 -> QVariant t1 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> Ptr (TQVariant t1) -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetData_h (QStandardItem ()) ((QVariant t1, Int)) (IO ()) where
setData_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStandardItem_setData1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QStandardItem_setData1" qtc_QStandardItem_setData1 :: Ptr (TQStandardItem a) -> Ptr (TQVariant t1) -> CInt -> IO ()
instance QsetData_h (QStandardItemSc a) ((QVariant t1, Int)) (IO ()) where
setData_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStandardItem_setData1 cobj_x0 cobj_x1 (toCInt x2)
instance QsetHandler (QStandardItem ()) (QStandardItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QStandardItem_setHandler4" qtc_QStandardItem_setHandler4 :: Ptr (TQStandardItem a) -> CWString -> Ptr (Ptr (TQStandardItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QStandardItem4 :: (Ptr (TQStandardItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQStandardItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QStandardItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QStandardItemSc a) (QStandardItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QStandardItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QStandardItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QStandardItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQStandardItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqtype_h (QStandardItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStandardItem_type cobj_x0
foreign import ccall "qtc_QStandardItem_type" qtc_QStandardItem_type :: Ptr (TQStandardItem a) -> IO CInt
instance Qqtype_h (QStandardItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStandardItem_type cobj_x0
| uduki/hsQt | Qtc/Gui/QStandardItem_h.hs | bsd-2-clause | 23,810 | 0 | 18 | 5,388 | 7,783 | 3,708 | 4,075 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.