code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Exercises where import Lab3.Lecture3 import Data.String.Utils import Data.List -- Define Main -- main = do putStrLn $ "====================" putStrLn $ "Assignment 3 / Lab 3" putStrLn $ "====================" putStrLn $ "> Exercise 1" exercise1 putStrLn $ "> Exercise 2" exercise2 putStrLn $ "> Exercise 3" exercise3 putStrLn $ "> Exercise 4" -- exercise4 putStrLn $ "> Exercise 5" exercise5 -- ============================================================================= -- Exercise 1 :: Time spent: +- 180 min -- ============================================================================= exercise1 = do putStrLn "Contradiction:" print $ contradiction form1 print $ contradiction form2 print $ contradiction form3 putStrLn "Tautology:" print $ tautology form1 print $ tautology form2 print $ tautology form3 putStrLn "Entails:" print $ entails form1 form1 print $ entails form1 form2 print $ entails form1 form3 print $ entails form2 form2 print $ entails form2 form1 print $ entails form2 form3 print $ entails form3 form3 print $ entails form3 form1 print $ entails form3 form2 putStrLn "Equivalance:" print $ equiv form1 form1 print $ equiv form1 form2 print $ equiv form1 form3 print $ equiv form2 form2 print $ equiv form2 form1 print $ equiv form2 form3 print $ equiv form3 form3 print $ equiv form3 form1 print $ equiv form3 form2 -- contradiction :: check contradiction :: Form -> Bool contradiction f = all (\ v -> not $ evl v f) (allVals f) -- tautology :: check tautology :: Form -> Bool tautology f = all (\ v -> evl v f) (allVals f) showIssue = doEntail "*(1 2)" "+(*(1 2) 3)" showIssue2 = doEntail "*(1 2)" "*(3 4)" doEntail :: String -> String -> Bool doEntail f1 f2 = entails (doParse f1) (doParse f2) doParse :: String -> Form doParse = head . parse -- logical entailment :: check entails :: Form -> Form -> Bool entails x y = entailment (allResults x) (allResults y) entailment :: [Bool] -> [Bool] -> Bool entailment [] [] = True entailment [] (y:ys) = entailment [True] ys entailment (x:xs) [] = False entailment (x:xs) (y:ys) | x && not y = False | otherwise = entailment xs ys allResults :: Form -> [Bool] allResults x = map (flip evl x) (allVals x) -- logical equivalence :: check equiv :: Form -> Form -> Bool equiv x y = equivalent (allResults x) (allResults y) equivalent :: [Bool] -> [Bool] -> Bool equivalent [] [] = True equivalent [] (y:ys) = False equivalent (x:xs) [] = False equivalent (x:xs) (y:ys) | x /= y = False | otherwise = equivalent xs ys -- ============================================================================= -- Exercise 2 :: Time spent +- 150 min -- ============================================================================= exercise2 = do -- test stuff print $ parse "*(1 + (2 -3))" print $ parse "+(1 + (2 -3))" print $ parse "*(1 + (-2 -3))" -- Check all tests print $ and $ map (uncurry propositional_test) tests propositional_test :: [Char] -> [Form] -> Bool propositional_test s f = parse s == f tests = [ -- empty ("", []), -- single value ("1", [(Prop 1)]), -- parenthesis (empty) ("(1)", []), -- conjunction (empty) ("*", []), -- disjunction (empty) ("+", []), -- negation (empty) ("-", []), -- implication (empty) ("==>", []), -- conjunction ("*(1 2)", [Cnj [Prop 1, Prop 2]]), -- disjunction ("+(1 2)", [Dsj [Prop 1, Prop 2]]), -- negation ("-1", [(Neg (Prop 1))]), -- implication ("(1==>2)", [Impl (Prop 1) (Prop 2)]), -- equivalence ("(1<=>1)", [Equiv (Prop 1) (Prop 1)]), -- complex tests ("((1==>2) ==> (1==>3))", [Impl (Impl (Prop 1) (Prop 2)) (Impl (Prop 1) (Prop 3))]), ("(-(1==>2) ==> (1==>3))", [Impl (Neg (Impl (Prop 1) (Prop 2))) (Impl (Prop 1) (Prop 3))]), ("(-(1==>2) <=> (1==>3))", [Equiv (Neg (Impl (Prop 1) (Prop 2))) (Impl (Prop 1) (Prop 3))]), ("((1<=>2) ==> (1==>3))", [Impl (Equiv (Prop 1) (Prop 2)) (Impl (Prop 1) (Prop 3))]) ] -- ============================================================================= -- Exercise 3 :: Time spent +- 360 min -- ============================================================================= exercise3 = do -- Step #1 :: Remove arrows -- Step #2 :: Conversion to negation normal form -- Step #3 :: Generate Truth Table -- Step #4 :: Every result that is false, negate the literal -- Step #5 :: Use the literals to construct the CNF -- print $ convertToCNF $ getNonTruths $ nnf $ arrowfree prop -- print $ invertLiterals $ getNonTruths $ nnf $ arrowfree prop print $ convertToCNF $ invertLiterals $ getNonTruths $ nnf $ arrowfree prop2 print $ parse $ convertToCNF $ invertLiterals $ getNonTruths $ nnf $ arrowfree prop2 convertToCNF :: [Valuation] -> String convertToCNF v = andCNF (map ordCNF v) andCNF :: [String] -> String andCNF (x:xs) | length xs == 0 = x | length xs < 2 = "*(" ++ x ++ " " ++ xs !! 0 ++ ")" | otherwise = "*(" ++ x ++ " " ++ andCNF xs ++ ")" ordCNF :: Valuation -> String ordCNF (x:xs) | length xs < 2 && snd x == True && snd (xs !! 0) == True = "+(" ++ show (fst x) ++ " " ++ show (fst (xs !! 0)) ++ ")" | length xs < 2 && snd x == False && snd (xs !! 0) == True = "+(-" ++ show (fst x) ++ " " ++ show (fst (xs !! 0)) ++ ")" | length xs < 2 && snd x == True && snd (xs !! 0) == False = "+(" ++ show (fst x) ++ " -" ++ show (fst (xs !! 0)) ++ ")" | length xs < 2 && snd x == False && snd (xs !! 0) == False = "+(-" ++ show (fst x) ++ " -" ++ show (fst (xs !! 0)) ++ ")" | length xs >= 2 && snd x == False = "+(-" ++ show (fst x) ++ " " ++ ordCNF xs ++ ")" | otherwise = "+(" ++ show (fst x) ++ " " ++ ordCNF xs ++ ")" invertLiterals :: [Valuation] -> [Valuation] invertLiterals v = map invertLiteral v invertLiteral :: Valuation -> Valuation invertLiteral v = map revert v -- Revert Valuations revert :: (Name,Bool) -> (Name,Bool) revert (k,v) = if v == True then (k,False) else (k,True) -- This actually returns all valuations for False getNonTruths :: Form -> [Valuation] getNonTruths f = filter (\ v -> not $ evl v f) (allVals f) -- Define base env x = Prop 1 y = Prop 2 z = Prop 3 prop = Cnj [(Dsj [x,y]),(Neg z)] prop2 = Dsj [Cnj [x,y], z] -- +(*(1 2) 3) -- prop0 = (Neg (Prop 1)) -- prop1 = (Impl (Prop 1) (Prop 2)) -- prop2 = (Impl (Equiv (Prop 1) (Prop 2)) (Impl (Prop 1) (Prop 3))) -- ============================================================================= -- Exercise 4 -- ============================================================================= -- ============================================================================= -- Exercise 5 -- ============================================================================= type Clauses = [Clause] type Clause = [Int] exercise5 = do print $ smashCL $ convertToCl $ show $ convertToCls $ cnf $ nnf $ arrowfree wiki1Input print $ smashCL $ convertToCl $ show $ convertToCls $ cnf $ nnf $ arrowfree wiki2Input print $ smashCL $ convertToCl $ show $ convertToCls $ cnf $ nnf $ arrowfree wiki3Input wiki1Input, wiki2Input, wiki3Input :: Form wiki1Input = doParse "+(-2 -3)" wiki2Input = doParse "*(+(1 3) +(2 3))" wiki3Input = doParse "*(1 *(+(2 4) +(2 5)))" wiki1Result, wiki2Result, wiki3Result :: Clauses wiki1Result = [[-2, -3]] wiki2Result = [[1, 3], [2, 3]] wiki3Result = [[1], [2, 4], [2, 5]] convertToCl :: String -> String convertToCl s = replace ")" "]" $ replace "+(" "[" $ replace "*(" "[" $ replace " " "," s smashCL :: String -> String smashCL s = if (isInfixOf "[[" s == True) || (isInfixOf "]]" s == True) then do smashCL ( replace "[[" "[" $ (replace "]]" "]" s)) else "[" ++ s ++ "]" convertToCls :: Form -> Form convertToCls = cls . nnf . arrowfree cls :: Form -> Form cls = cls' . nnf . arrowfree cls' :: Form -> Form cls' (Prop x) = Prop x cls' (Neg (Prop x)) = Neg (Prop x) cls' (Cnj fs) = Cnj (map cls' fs) cls' (Dsj fs) | not.null $ filter (filterDsj) fs = cls' $ Dsj ((liftDsj fs) ++ (filter (not.filterDsj) fs)) | not.null $ filter (filterCnj) fs = cls' (distribute (uniqueMap cls' fs)) | otherwise = Dsj (uniqueMap cls' fs) where liftDsj fs = nub $ concatMap (\(Dsj xs) -> map (\y -> y ) xs) (filter (filterDsj) fs) -- Borrowed the below from our group-deliverable cnf :: Form -> Form cnf = cnf' . nnf . arrowfree cnf' :: Form -> Form cnf' (Prop x) = Prop x cnf' (Neg (Prop x)) = Neg (Prop x) cnf' (Cnj fs) = Cnj (map cnf' fs) cnf' (Dsj fs) | not.null $ filter (filterDsj) fs = cnf' $ Dsj ((liftDsj fs) ++ (filter (not.filterDsj) fs)) | not.null $ filter (filterCnj) fs = cnf' (distribute (uniqueMap cnf' fs)) | otherwise = Dsj (uniqueMap cnf' fs) where liftDsj fs = nub $ concatMap (\(Dsj xs) -> map (\y -> y ) xs) (filter (filterDsj) fs) filterDsj :: Form -> Bool filterDsj (Dsj x) = True filterDsj _ = False filterCnj :: Form -> Bool filterCnj (Cnj x) = True filterCnj _ = False filterProps :: Form -> Bool filterProps (Prop x) = True filterProps _ = False distribute :: [Form] -> Form distribute fs = Cnj expand' where cnjs = (filter filterCnj fs) notConj = (filter (not.filterCnj)) fs combineCnj = sequence (map (\(Cnj x) -> x) cnjs) expand' = map (\cnjList -> Dsj (nub (notConj ++ cnjList))) combineCnj uniqueMap :: Eq a => (a1 -> a) -> [a1] -> [a] uniqueMap f xs = ys where ys = nub $ map f xs
vdweegen/UvA-Software_Testing
Lab3/Cas/Exercises.hs
gpl-3.0
9,415
0
14
1,966
3,672
1,877
1,795
192
2
-- Sortable Test -- Copyright (C) 2015 Jonathan Lamothe -- <jonathan@jlamothe.net> -- 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/>. module Daily (dailySummary, process, encode, headersFor) where import Common import Common.Types import Daily.Types import Data.List (transpose) import Data.Map (Map) import qualified Data.Map as Map import Data.Time.Calendar (Day) import Text.CSV (CSV, Record, Field, printCSV) dailySummary :: String -> String dailySummary rawInput = printCSV $ encode $ process $ decode rawInput process :: InputData -> ProcessedData process input = ProcessedData (inputFields input) $ Map.map buildRecord $ sortByDate $ inputRecords input encode :: ProcessedData -> CSV encode input = encodeHeader input : encodeBody input buildRecord :: [InputRecord] -> ProcessedRecord buildRecord = map buildStats . transpose . map inputRecordValues buildStats :: [Double] -> Stats buildStats xs = Stats { statSum = sum xs , statMax = max' xs , statMin = min' xs , statAvg = avg xs , statStdDev = stdDev xs } max' :: [Double] -> Double max' (x : xs) = foldl max x xs min' :: [Double] -> Double min' (x : xs) = foldl min x xs avg :: [Double] -> Double avg xs = sum xs / (fromIntegral . length) xs stdDev :: [Double] -> Double stdDev xs = sqrt (sum $ map (\x -> (x - avg xs) ^ 2) xs) / (fromIntegral . length) xs sortByDate :: [InputRecord] -> Map Day [InputRecord] sortByDate = foldr addToMap Map.empty addToMap :: InputRecord -> Map Day [InputRecord] -> Map Day [InputRecord] addToMap x s = Map.insert day (x : Map.findWithDefault [] day s) s where day = inputRecordDate x encodeHeader :: ProcessedData -> Record encodeHeader input = "Date" : concatMap headersFor fields where fields = processedFields input encodeBody :: ProcessedData -> CSV encodeBody input = map encodeRecord recordList where recordList = Map.toList $ processedRecords input headersFor :: Field -> Record headersFor field = [ "Total " ++ field , "Max " ++ field , "Min " ++ field , "Avg " ++ field , field ++ " Std Dev" ] encodeRecord :: (Day, ProcessedRecord) -> Record encodeRecord (day, record) = show day : concatMap encodeStats record encodeStats :: Stats -> Record encodeStats stats = map show [ statSum stats , statMax stats , statMin stats , statAvg stats , statStdDev stats ] -- jl
jlamothe/sortable-test
Daily.hs
gpl-3.0
3,076
0
15
694
810
437
373
60
1
{-# LANGUAGE OverloadedStrings #-} import Control.Monad (void) import Data.Graph.Builder.GraphViz import Data.GraphViz import Data.GraphViz.Attributes.Complete import Data.GraphViz.Helpers mytasks :: Graph mytasks = digraph [RankDir FromLeft] $ do t1 <- node [ htmlLabel [ formatBold "Lorem ipsum dolor sit amet,", newlineLeft , "consectetur adipisicing elit,", newlineLeft , "sed do eiusmod tempor incididunt", newlineLeft , "ut labore et dolore magna aliqua.", newlineLeft ] ] t2 <- node [ htmlLabel [ formatBold "Ut enim ad minim veniam,", newlineLeft , "quis nostrud exercitation ullamco", newlineLeft , "laboris nisi ut aliquip", newlineLeft , "ex ea commodo consequat.", newlineLeft ] ] t3 <- node [ htmlLabel [ formatBold "Duis aute irure dolor", newlineLeft , "in reprehenderit in voluptate", newlineLeft , "velit esse cillum dolore", newlineLeft , "eu fugiat nulla pariatur.", newlineLeft ] ] t4 <- node [ htmlLabel [ formatBold "Excepteur sint occaecat", newlineLeft , "cupidatat non proident,", newlineLeft , "sunt in culpa qui officia deserunt", newlineLeft , "mollit anim id est laborum.", newlineLeft ] ] void $ edges' [t1, t2, t4] void $ edges' [t1, t3, t4] p <- node [textLabel "Lorem ipsum"] t4 --> p t5 <- node [textLabel "dolor sit amet"] t5 --> p t6 <- node [textLabel "consectetur adipisicing elit"] t6 --> p t7 <- node [textLabel "sed do eiusmod tempor incididunt"] t7 --> p t8 <- node [textLabel "ut labore et dolore magna aliqua"] t8 --> p t9 <- node [textLabel "Ut enim ad minim veniam"] t9 --> p t10 <- node [textLabel "quis nostrud exercitation ullamco"] t10 --> p main :: IO () main = void $ runGraphviz mytasks Svg "/dev/stdout"
cblp/graph-dsl-graphviz
examples/FirstTry.hs
gpl-3.0
2,098
0
13
699
457
235
222
46
1
module TypeBug8 where infixl 6 <*!> infixl 7 <$!> type Parser symbol result = [symbol] -> [(result,[symbol])] (<*!>) :: Parser s (a -> b) -> Parser s a -> Parser s b (<$!>) :: (a -> b) -> Parser s a -> Parser s b (<*!>) = undefined (<$!>) = undefined many :: Parser s a -> Parser s [a] many = undefined --------------------------- chainr :: Parser s a -> Parser s (a -> a -> a) -> Parser s a chainr pe po = h <$!> many (j <$!> pe <*!> po) <*!> pe where j x op = (x `op`) h :: [a -> a] -> a -> a h fs x = foldr ($) fs x
Helium4Haskell/helium
test/typeerrors/Examples/TypeBug8.hs
gpl-3.0
554
0
10
154
280
155
125
15
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------------------- -- | -- Module : Dhek.Widget.BlankDocument -- -- -------------------------------------------------------------------------------- module Dhek.Widget.BlankDocument ( BlankDocumentEvent(..) , OpenInput(..) , PageDimension(..) , PageCount(..) , newBlankDocumentWidget ) where -------------------------------------------------------------------------------- import Control.Monad.Trans import Data.Text (unpack) import qualified Graphics.UI.Gtk as Gtk import System.FilePath import Text.Shakespeare.I18N -------------------------------------------------------------------------------- import Dhek.I18N import Dhek.PDF.Type import Dhek.Widget.Type -------------------------------------------------------------------------------- data BlankDocument = BlankDocument -------------------------------------------------------------------------------- data BlankDocumentEvent a where BlankDocumentOpen :: BlankDocumentEvent OpenInput -------------------------------------------------------------------------------- data OpenInput = OpenInput PageDimension PageCount -------------------------------------------------------------------------------- mkMessage "BlankDocument" (joinPath ["messages", "widget", "blank-document"]) "en" -------------------------------------------------------------------------------- mkBlankDocI18n :: IO (BlankDocumentMessage -> String) mkBlankDocI18n = fmap (\l -> unpack . renderMessage BlankDocument [l]) determineLang -------------------------------------------------------------------------------- newBlankDocumentWidget :: (DhekMessage -> String) -> Gtk.Window -> IO (Widget BlankDocumentEvent) newBlankDocumentWidget msgStr parent = do bdMsgStr <- mkBlankDocI18n win <- Gtk.dialogNew table <- Gtk.tableNew 3 3 False spin <- Gtk.spinButtonNewWithRange 1 200 1 store <- Gtk.listStoreNew [A2_P .. A5_L] combo <- Gtk.comboBoxNewWithModel store render <- Gtk.cellRendererTextNew label <- Gtk.labelNew $ Just $ bdMsgStr MsgDescription plbl <- Gtk.labelNew $ Just $ bdMsgStr MsgPageDimension nlbl <- Gtk.labelNew $ Just $ bdMsgStr MsgNumberPage l1align <- Gtk.alignmentNew 0 0 0 0 l2align <- Gtk.alignmentNew 0 0 0 0 l3align <- Gtk.alignmentNew 0 0 0 0 salign <- Gtk.alignmentNew 0 0 0 0 calign <- Gtk.alignmentNew 0 0 0 0 talign <- Gtk.alignmentNew 0 0 1 0 Gtk.set win [ Gtk.windowTitle Gtk.:= msgStr MsgOpenBlank , Gtk.windowResizable Gtk.:= False ] Gtk.windowSetModal win True Gtk.windowSetTransientFor win parent Gtk.cellLayoutPackStart combo render False Gtk.cellLayoutSetAttributes combo render store (layoutMapping $ dimStr bdMsgStr) Gtk.comboBoxSetActive combo 0 ob <- Gtk.dialogAddButton win (msgStr MsgOpen) Gtk.ResponseOk cl <- Gtk.dialogAddButton win (msgStr MsgCancel) Gtk.ResponseClose Gtk.labelSetLineWrap label True Gtk.labelSetJustify label Gtk.JustifyFill Gtk.alignmentSetPadding talign 20 20 20 20 Gtk.containerAdd salign spin Gtk.containerAdd calign combo Gtk.containerAdd l1align label Gtk.containerAdd l2align plbl Gtk.containerAdd l3align nlbl Gtk.containerAdd talign table Gtk.tableAttachDefaults table l1align 0 3 0 1 Gtk.tableAttachDefaults table l2align 0 1 1 2 Gtk.tableAttachDefaults table calign 1 2 1 2 Gtk.tableAttachDefaults table l3align 0 1 2 3 Gtk.tableAttachDefaults table salign 1 2 2 3 Gtk.tableSetRowSpacings table 10 Gtk.widgetShowAll talign box <- Gtk.dialogGetUpper win Gtk.containerAdd box talign -- Close handler _ <- Gtk.on cl Gtk.buttonActivated $ Gtk.widgetHide win _ <- Gtk.on win Gtk.deleteEvent $ liftIO $ do Gtk.widgetHide win return True let widget = Widget { widgetRegister = blankDocumentRegister ob win combo spin store , widgetShow = blankDocumentShow win , widgetHide = Gtk.widgetHide win } return widget -------------------------------------------------------------------------------- blankDocumentRegister :: Gtk.Button -> Gtk.Dialog -> Gtk.ComboBox -> Gtk.SpinButton -> Gtk.ListStore PageDimension -> BlankDocumentEvent a -> (a -> IO ()) -> IO Release blankDocumentRegister btn dialog cb spin store BlankDocumentOpen handler = do cid <- Gtk.on btn Gtk.buttonActivated $ do Gtk.widgetHide dialog idx <- Gtk.comboBoxGetActive cb val <- Gtk.listStoreGetValue store idx cnt <- Gtk.spinButtonGetValueAsInt spin handler $ OpenInput val (PageCount cnt) return $ Gtk.signalDisconnect cid -------------------------------------------------------------------------------- blankDocumentShow :: Gtk.Dialog -> IO () blankDocumentShow win = do Gtk.widgetShowAll win _ <- Gtk.dialogRun win return () -------------------------------------------------------------------------------- dimStr :: (BlankDocumentMessage -> String) -> PageDimension -> String dimStr msgStr pd = msgStr $ case pd of A2_P -> MsgA2_P A2_L -> MsgA2_L A3_P -> MsgA3_P A3_L -> MsgA3_L A4_P -> MsgA4_P A4_L -> MsgA4_L A5_P -> MsgA5_P A5_L -> MsgA5_L -------------------------------------------------------------------------------- layoutMapping :: (PageDimension -> String) -> PageDimension -> [Gtk.AttrOp Gtk.CellRendererText] layoutMapping msgStr pd = [Gtk.cellText Gtk.:= msgStr pd]
cchantep/dhek
Dhek/Widget/BlankDocument.hs
gpl-3.0
6,507
0
15
1,855
1,378
669
709
-1
-1
elementAt :: (Num b, Eq b) => [a] -> b -> a elementAt [] _ = error "Element out of range" elementAt (x:xs) 1 = x elementAt (x:xs) y = elementAt xs (y-1)
carlosavieira/self-study
programming/Haskell/99 problems/solutions/03.hs
gpl-3.0
152
0
7
32
93
48
45
4
1
module Ledger.Main where import Ledger.Application (application, defaultState, middleware) import Ledger.Config (getConfig) import Ledger.Settings (getSettings) import Ledger.State (getState) import Network.Wai.Handler.Warp (Settings, getHost, getPort, runSettings) main :: IO () main = do config <- getConfig settings <- getSettings config state <- getState config defaultState let fullApplication = middleware (application state) putStrLn (message settings) runSettings settings fullApplication message :: Settings -> String message settings = concat [ show (getHost settings) , ":" , show (getPort settings) ]
asm-products/ledger-backend
library/Ledger/Main.hs
agpl-3.0
657
0
12
118
202
106
96
19
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Control.Lens {-- Snap --} import Snap.Http.Server (defaultConfig) import Snap.Util.FileServe (serveDirectory) {-- Snaplets --} import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.PostgresqlSimple import Snap.Snaplet.Session import Snap.Snaplet.Session.Backends.CookieSession import Snap.Snaplet.PostgresqlSimple import Snap.Snaplet.Heist import Snap.Snaplet.JobBoard (JobBoard, jobBoardInit) -- | We need all of these for the Job Board snaplet. data App = App { _sess :: Snaplet SessionManager , _db :: Snaplet Postgres , _auth :: Snaplet (AuthManager App) , _heist :: Snaplet (Heist App) , _board :: Snaplet (JobBoard App) } makeLenses ''App -- | This is needed so the JobBoard snaplet can use splices instance HasHeist App where heistLens = subSnaplet heist appInit :: SnapletInit App App appInit = makeSnaplet "App" "App" Nothing $ do s <- nestSnaplet "" sess $ initCookieSessionManager "site_key.txt" "_cookie" Nothing d <- nestSnaplet "db" db pgsInit a <- nestSnaplet "auth" auth $ initPostgresAuth sess d h <- nestSnaplet "" heist $ heistInit "templates" b <- nestSnaplet "" board $ jobBoardInit auth (subSnaplet db) d -- Serve static files. addRoutes [("", serveDirectory "static")] return $ App s d a h b main :: IO () main = serveSnaplet defaultConfig appInit
statusfailed/snaplet-job-board
src/Main.hs
agpl-3.0
1,446
0
12
249
381
203
178
36
1
{-# LANGUAGE BangPatterns, OverloadedStrings #-} module Util (BString, joinWith, joinWithBS, pack, unpack, bsNull, dropSpaces, mapFst, mapSnd, listEscape, ifFails, commaList, downCase, slurpFile, utilTests ) where import qualified Data.ByteString.Char8 as B -- import Control.Monad.Error import Control.Monad.Except import Data.List(intersperse) import Test.HUnit import Data.Char (toLower) import Control.Exception.Base import Control.Monad.Trans.Except import Control.Applicative -- import TclErr type BString = B.ByteString joinWithBS bsl bs = B.concat (intersperse bs bsl) joinWith bsl c = B.concat (intersperse (B.singleton c) bsl) {-# INLINE joinWith #-} pack = B.pack {-# INLINE pack #-} unpack = B.unpack bsNull = B.null {-# INLINE bsNull #-} dropSpaces = B.dropWhile (\x -> x == ' ' || x == '\t') {-# INLINE dropSpaces #-} mapSnd f = map (\(a,b) -> (a, f b)) {-# INLINE mapSnd #-} mapFst f = map (\(a,b) -> (f a, b)) -- catchAny :: TclM -> (SomeException -> IO a) -> TclM a -- catchAny = catch -- ifFails :: MonadError e m => m a -> a -> m a ifFails f v = f `catchError` (\_ -> return v) -- ifFails f v = (f <|> return v) -- `catchIOError` (const (return v) ) {-# INLINE ifFails #-} slurpFile fname = do dat <- B.readFile fname B.length dat `seq` return dat listEscape s = if (B.elem ' ' s && not hasBracks) || B.null s then B.concat [B.singleton '{', s, B.singleton '}'] else if hasBracks then B.concat (escapeStr s) else s where hasBracks = (brackDepth s) /= 0 downCase = B.map toLower brackDepth s = match 0 0 False where match i c esc = if i >= B.length s then c else let ni = i+1 in if esc then match ni c False else case B.index s i of '{' -> match ni (c+1) False '}' -> match ni (c-1) False '\\' -> match ni c True _ -> match ni c False escapeStr s = case B.findIndex (`B.elem` " \n\t{}") s of Nothing -> [s] Just i -> let (b,a) = B.splitAt i s in b : handle (B.head a) : escapeStr (B.drop 1 a) where handle '\n' = "\\n" handle ' ' = "\\ " handle '{' = "\\{" handle '}' = "\\}" handle _ = error "The impossible happened in handle" commaList :: String -> [String] -> String commaList _ [] = "" commaList _ [a] = a commaList conj lst = (intercalate ", " (init lst)) ++ " " ++ conj ++ " " ++ last lst intercalate :: String -> [String] -> String intercalate xs xss = concat (intersperse xs xss) utilTests = TestList [joinWithTests, listEscapeTests] where joinWithTests = TestList [ ([""],'!') `joinsTo` "" ,(["one"],'!') `joinsTo` "one" ,(["one", "two"],',') `joinsTo` "one,two" ] where joinsTo (a,s) r = pack r ~=? ((map pack a) `joinWith` s) listEscapeTests = TestList [ noEscape "one" ,noEscape "[andkda]" ,"" `escapesAs` "{}" ,"a b" `escapesAs` "{a b}" ,"a { b" `escapesAs` "a\\ \\{\\ b" ,"a } b" `escapesAs` "a\\ \\}\\ b" ,"a {b} c" `escapesAs` "{a {b} c}" ," { " `escapesAs` "\\ \\{\\ " ] where escapesAs a b = pack b ~=? listEscape (pack a) noEscape a = pack a ~=? listEscape (pack a)
tolysz/hiccup
Util.hs
lgpl-2.1
3,605
0
16
1,220
1,150
626
524
79
6
import Data.List import Data.Maybe (fromJust) import Numeric.LinearAlgebra import Numeric.LinearAlgebra.NIPALS import Foreign.Storable import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck hiding ((><)) main = defaultMain tests tests = [ testGroup "Accuracy" [ testProperty "sameFirstPCAsSVD" prop_sameFirstPCAsSVD , testProperty "scoreGuessStable" prop_scoreGuessStable ] , testGroup "Correctness" [ testProperty "resultCanRecoverInput" prop_recoverInput , testProperty "monadSameAnswer" prop_monadSameAnswer ] ] prop_sameFirstPCAsSVD m = relErr <= svdThreshold where relErrP = relativeDifference expPC actPC relErrN = relativeDifference expPC (-actPC) relErr = min relErrP relErrN expPC = head $ toColumns lSV (lSV,_) = leftSV $ trans m (actPC,_,_) = firstPC m svdThreshold = 10 * sqrt (fromIntegral (rows m * cols m) * eps) prop_recoverInput m = relErr <= eps where (p,t,r) = firstPC m m' = (t `outer` p) `add` r relErr = relativeDifference m m' prop_scoreGuessStable m = tRelErr <= th .&&. pRelErr <= th where (p,t,_) = firstPC m (p',t',_) = firstPCFromScores m t tRelErr = relativeDifference t t' pRelErr = relativeDifference p p' th = sqrt $ fromIntegral (cols m * rows m) * eps prop_monadSameAnswer m = tRelErr <= th .&&. pRelErr <= th .&&. rRelErr <= th where guess = head $ toColumns m samplesM = return $ toRows m (p,t,r) = firstPCFromScores m guess (p',t') = fromJust $ firstPCFromScoresM samplesM guess r' = fromRows $ residual (toRows m) p' t' tRelErr = relativeDifference t t' pRelErr = relativeDifference p p' rRelErr = if rank m > 2 then relativeDifference r r' else 0 th = 1e-7 relativeDifference :: (Normed c t, Container c t) => c t -> c t -> Double relativeDifference x y = realToFrac (norm (x `sub` y) / (peps + norm x + norm y)) where norm = pnorm Infinity instance (Arbitrary t, Storable t) => Arbitrary (Matrix t) where arbitrary = sized $ \n -> do r <- choose (1,n+1) c <- choose (1,n+1) vals <- vector (r*c) return $ (r><c) vals
alanfalloon/hmatrix-nipals
test/tests.hs
lgpl-2.1
2,329
0
14
613
816
428
388
-1
-1
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, TypeFamilies #-} module Vision.Image.Grey.Type ( Grey, GreyPixel (..), GreyDelayed ) where import Data.Bits import Data.Word import Foreign.Storable (Storable) import Vision.Image.Interpolate (Interpolable (..)) import Vision.Image.Type (Pixel (..), Manifest, Delayed) newtype GreyPixel = GreyPixel Word8 deriving (Bits, Bounded, Enum, Eq, Integral, Num, Ord, Real, Read, Show , Storable) type Grey = Manifest GreyPixel type GreyDelayed = Delayed GreyPixel instance Pixel GreyPixel where type PixelChannel GreyPixel = Word8 pixNChannels _ = 1 {-# INLINE pixNChannels #-} pixIndex !(GreyPixel v) _ = v {-# INLINE pixIndex #-} instance Interpolable GreyPixel where interpol f (GreyPixel a) (GreyPixel b) = GreyPixel $ f a b {-# INLINE interpol #-}
TomMD/friday
src/Vision/Image/Grey/Type.hs
lgpl-3.0
865
0
9
171
239
136
103
22
0
module Calculator where import CLaSH.Prelude import CalculatorTypes (.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d (f .: g) a b = f (g a b) infixr 9 .: alu :: Num a => OPC a -> a -> a -> Maybe a alu ADD = Just .: (+) alu MUL = Just .: (*) alu (Imm i) = const . const (Just i) alu _ = const . const Nothing pu :: (Num a, Num b) => (OPC a -> a -> a -> Maybe a) -> (a, a, b) -- Current state -> (a, OPC a) -- Input -> ( (a, a, b) -- New state , (b, Maybe a) -- Output ) pu alu (op1,op2,cnt) (dmem,Pop) = ((dmem,op1,cnt-1),(cnt,Nothing)) pu alu (op1,op2,cnt) (dmem,Push) = ((op1,op2,cnt+1) ,(cnt,Nothing)) pu alu (op1,op2,cnt) (dmem,opc) = ((op1,op2,cnt) ,(cnt,alu opc op1 op2)) datamem :: (KnownNat n, Integral i) => Vec n a -- Current state -> (i, Maybe a) -- Input -> (Vec n a, a) -- (New state, Output) datamem mem (addr,Nothing) = (mem ,mem !! addr) datamem mem (addr,Just val) = (replace mem addr val,mem !! addr) topEntity :: Signal (OPC Word) -> Signal (Maybe Word) topEntity i = val where (addr,val) = (pu alu <^> (0,0,0 :: Unsigned 3)) (mem,i) mem = (datamem <^> initMem) (addr,val) initMem = replicate (snat :: SNat 8) 0 testInput :: Signal (OPC Word) testInput = stimuliGenerator $(v [Imm 1::OPC Word,Push,Imm 2,Push,Pop,Pop,Pop,ADD]) expectedOutput :: Signal (Maybe Word) -> Signal Bool expectedOutput = outputVerifier $(v [Just 1 :: Maybe Word,Nothing,Just 2,Nothing,Nothing,Nothing,Nothing,Just 3])
christiaanb/clash-compiler
examples/Calculator.hs
bsd-2-clause
1,552
0
12
403
827
457
370
-1
-1
{-# LANGUAGE OverloadedStrings #-} import System.IO import System.Environment import System.Directory import Control.Monad import qualified Data.ByteString.Lazy.Char8 as L import Data.Text.Encoding import Network.HTTP.Conduit import qualified Data.Text as T import Text.HTML.DOM (parseLBS) import Text.XML.Cursor (Cursor, attributeIs, content, element, fromDocument, child, ($//), (&|), (&//), (&/), (>=>)) import Network (withSocketsDo) -- почтовый адрес email = "" cursorFor :: String -> IO Cursor cursorFor u = do page <- withSocketsDo $ simpleHttp u return $ fromDocument $ parseLBS page lab3 :: IO [T.Text] lab3 = do cursor <- cursorFor "http://mipt.ru/diht/bases/" return $ cursor $// element "ul" >=> attributeIs "class" "right-menu" &// element "a" >=> child &| T.concat . content main :: IO() main = withSocketsDo $ do nodes <- lab3 dir <- getCurrentDirectory initReq <- parseUrl "http://91.239.142.110:13666/lab3" handle <- openFile (dir ++ "/Lab3.hs") ReadMode hSetEncoding handle utf8_bom content <- hGetContents handle let req = urlEncodedBody [("email", email), ("result", encodeUtf8 $ T.concat $ nodes), ("content", encodeUtf8 $ T.pack content) ] $ initReq { method = "POST" } response <- withManager $ httpLbs req hClose handle L.putStrLn $ responseBody response
shevkunov/workout
fsharp/lab3/Lab3.hs
bsd-3-clause
1,332
0
17
212
430
232
198
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE StandaloneDeriving #-} -- | -- Types for working with integers modulo some constant. module Data.Modular ( -- $doc -- * Preliminaries -- $setup -- * Modular arithmetic Mod, unMod, unMod', toMod, toMod', toMod'', inv, (/)(), ℤ, modVal, SomeMod, someModVal, Unsign ) where import Control.Arrow (first) import Data.Proxy (Proxy (..)) import Data.Ratio ((%)) import Data.Int import Data.Word import GHC.TypeLits import Numeric.Natural -- $setup -- -- To use type level numeric literals you need to enable -- the @DataKinds@ extension: -- -- >>> :set -XDataKinds -- -- To use infix syntax for @'Mod'@ or the @/@ synonym, -- enable @TypeOperators@: -- -- >>> :set -XTypeOperators -- $doc -- -- @'Mod'@ and its synonym @/@ let you wrap arbitrary numeric types -- in a modulus. To work with integers (mod 7) backed by @'Integer'@, -- you could use one of the following equivalent types: -- -- > Mod Integer 7 -- > Integer `Mod` 7 -- > Integer/7 -- > ℤ/7 -- -- (@'ℤ'@ is a synonym for @'Integer'@ provided by this library. In -- Emacs, you can use the TeX input mode to type it with @\\Bbb{Z}@.) -- -- The usual numeric typeclasses are defined for these types. You can -- always extract the underlying value with @'unMod'@. -- -- Here is a quick example: -- -- >>> 10 * 11 :: ℤ/7 -- 5 -- -- It also works correctly with negative numeric literals: -- -- >>> (-10) * 11 :: ℤ/7 -- 2 -- -- Modular division is an inverse of modular multiplication. -- It is defined when divisor is coprime to modulus: -- -- >>> 7 `div` 3 :: ℤ/16 -- 13 -- >>> 3 * 13 :: ℤ/16 -- 7 -- -- To use type level numeric literals you need to enable the -- @DataKinds@ extension and to use infix syntax for @Mod@ or the @/@ -- synonym, you need @TypeOperators@. type family Unsign (i :: *) :: * -- = (u :: *) where u -> i type instance Unsign Int = Word type instance Unsign Int8 = Word8 type instance Unsign Int16 = Word16 type instance Unsign Int32 = Word32 type instance Unsign Int64 = Word64 type instance Unsign Integer = Natural -- | Wraps an underlying @Integeral@ type @i@ in a newtype annotated -- with the bound @n@. newtype i `Mod` (n :: Nat) = Mod (Unsign i) deriving instance Eq (Unsign i) => Eq (Mod i n) deriving instance Ord (Unsign i) => Ord (Mod i n) -- | Extract the underlying natural value from a modular value. unMod :: i `Mod` n -> Unsign i unMod (Mod i) = i -- | Extract the unquotiented intergral value from a modular value. unMod' :: (Integral (Unsign i), Num i) => i `Mod` n -> i unMod' (Mod i) = fromIntegral i -- | A synonym for @Mod@, inspired by the ℤ/n syntax from mathematics. type (/) = Mod -- | A synonym for Integer, also inspired by the ℤ/n syntax. type ℤ = Integer -- | Injects a value of the quotiented type into the modulus type, -- wrapping as appropriate. toMod :: forall n i. (Integral i, Num (Unsign i), KnownNat n) => i -> i `Mod` n toMod i = Mod $ fromIntegral $ i `mod` fromInteger (natVal (Proxy :: Proxy n)) -- | Wraps an integral number, converting between integral types. toMod' :: forall n i j. (Integral i, Integral j, Num (Unsign j), KnownNat n) => i -> j `Mod` n toMod' i = toMod . fromIntegral $ i `mod` (fromInteger $ natVal (Proxy :: Proxy n)) -- | Injects a value of the underlying type into the modulus type, -- wrapping as appropriate. toMod'' :: forall n i. (Integral (Unsign i), KnownNat n) => Unsign i -> i `Mod` n toMod'' i = Mod $ fromIntegral $ i `mod` fromInteger (natVal (Proxy :: Proxy n)) instance Show (Unsign i) => Show (i `Mod` n) where show (Mod i) = show i instance (Read (Unsign i), Integral (Unsign i), KnownNat n) => Read (i `Mod` n) where readsPrec prec = map (first toMod'') . readsPrec prec instance (Integral i, Integral (Unsign i), KnownNat n) => Num (i `Mod` n) where fromInteger = toMod'' . fromInteger Mod i₁ + Mod i₂ = toMod'' $ i₁ + i₂ Mod i₁ * Mod i₂ = toMod'' $ i₁ * i₂ abs (Mod i) = toMod'' $ abs i signum (Mod i) = toMod'' $ signum i negate i = toMod $ negate $ unMod' i instance (Integral i, Integral (Unsign i), KnownNat n) => Enum (i `Mod` n) where toEnum = fromInteger . toInteger fromEnum = fromInteger . toInteger . unMod enumFrom x = enumFromTo x maxBound enumFromThen x y = enumFromThenTo x y bound where bound | fromEnum y >= fromEnum x = maxBound | otherwise = minBound instance (Integral i, Integral (Unsign i), KnownNat n) => Bounded (i `Mod` n) where maxBound = -1 minBound = 0 instance (Integral i, Integral (Unsign i), KnownNat n) => Real (i `Mod` n) where toRational (Mod i) = toInteger i % 1 -- | Integer division uses modular inverse @'inv'@, so it is possible -- to divide only by numbers coprime to @n@ and the remainder is -- always @0@. instance (Integral i, Integral (Unsign i), KnownNat n, Show (Unsign i)) => Integral (i `Mod` n) where toInteger (Mod i) = toInteger i i₁ `quotRem` i₂ = (i₁ * inv i₂, 0) -- | The modular inverse. -- -- >>> inv 3 :: ℤ/7 -- 5 -- >>> 3 * 5 :: ℤ/7 -- 1 -- -- Note that only numbers coprime to @n@ have an inverse modulo @n@: -- -- >>> inv 6 :: ℤ/15 -- *** Exception: divide by 6 (mod 15), non-coprime to modulus -- inv :: forall n i. (KnownNat n, Integral (Unsign i), Integral i, Show (Unsign i)) => Mod i n -> Mod i n inv divisor = toMod $ snd $ inv' modulus' divisor' where modulus :: Unsign i modulus = fromInteger $ natVal (Proxy :: Proxy n) modulus', divisor' :: i modulus' = fromIntegral modulus divisor' = unMod' divisor -- backwards Euclidean algorithm inv' :: i -> i -> (i , i) inv' _ 0 = error $ "divide by " ++ show divisor ++ " (mod " ++ show modulus ++ "), non-coprime to modulus" inv' _ 1 = (0, 1) inv' n x = (r', q' - r' * q) where (q, r) = n `quotRem` x (q', r') = inv' x r -- | A modular number with an unknown bound. data SomeMod i where SomeMod :: forall i (n :: Nat). KnownNat n => Mod i n -> SomeMod i instance Show (Unsign i) => Show (SomeMod i) where showsPrec p (SomeMod x) = showsPrec p x -- | Convert an integral number @i@ into a @'Mod'@ value given modular -- bound @n@ at type level. modVal :: forall i proxy n. (Integral i, Integral (Unsign i), KnownNat n) => i -> proxy n -> Mod i n modVal i _ = toMod i -- | Convert an integral number @i@ into a @'Mod'@ value with an -- unknown modulus. someModVal :: (Integral i, Integral (Unsign i)) => i -> Integer -> Maybe (SomeMod i) someModVal i n = case someNatVal n of Nothing -> Nothing Just (SomeNat proxy) -> Just (SomeMod (modVal i proxy))
Ericson2314/modular-arithmetic
src/Data/Modular.hs
bsd-3-clause
7,047
22
12
1,644
1,905
1,060
845
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TupleSections #-} import Plots import Plots.Axis import Plots.Types hiding (B) import Plots.Themes import Plots.Utils import Data.List import Diagrams.Prelude import Diagrams.Backend.Rasterific import Diagrams.Backend.CmdLine import Diagrams.Coordinates.Polar import Data.Array import Data.Monoid.Recommend import Dataset data1 = [(2.0,(1/3 @@ turn)),(3.0,(1/2 @@ turn)),(5.0,(4/5 @@ turn)),(6.0,(2/3 @@ turn)),(7.0,(1/6 @@ turn)),(8.0,(1/3 @@ turn)),(5.4,(2/3 @@ turn)),(7.1,(4/6 @@ turn)),(8.2,(3/5 @@ turn)),(9.0,(1/3 @@ turn))] data2 = [ (x/2.0, y)| (x,y) <- data1] myaxis :: Axis B Polar Double myaxis = polarAxis &~ do pointsPlot data1 pointsPlot data2 make :: Diagram B -> IO () make = renderRasterific "test.png" (mkWidth 1000) . frame 20 main :: IO () main = make $ renderAxis myaxis
bergey/plots
examples/points.hs
bsd-3-clause
873
0
9
141
406
234
172
25
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE DeriveDataTypeable , DeriveGeneric , TemplateHaskell , TypeFamilies #-} module Type.Invoice where import Data.Aeson import Data.JSON.Schema import Data.Text (Text) import Data.Time (UTCTime) import Data.Typeable import GHC.Generics import Generics.Regular import Generics.Regular.XmlPickler import Text.XML.HXT.Arrow.Pickle import qualified Type.Customer as Customer type Id = Int type Title = Text data Invoice = Invoice { id :: Id , author :: Customer.Name , createdTime :: UTCTime , title :: Title , content :: Text } deriving (Eq, Generic, Ord, Show, Typeable) deriveAll ''Invoice "PFInvoice" type instance PF Invoice = PFInvoice instance XmlPickler Invoice where xpickle = gxpickle instance JSONSchema Invoice where schema = gSchema instance ToJSON Invoice instance FromJSON Invoice instance XmlPickler UTCTime where xpickle = xpPrim
tinkerthaler/basic-invoice-rest
example-api/Type/Invoice.hs
bsd-3-clause
951
0
9
178
225
133
92
33
0
{-| Module : Ralgebra Description : Implements basic raltional algebra operators and operations. Copyright : (c) Nikos KAragiannidis, 2016 License : GPL-3 Maintainer : nkarag@gmail.com Stability : experimental Portability : POSIX Here is a longer description of this module, containing some commentary with @some markup@. -} {-# LANGUAGE OverloadedStrings #-} module Ralgebra ( -- Relation(..) RTable (..) ,RTuple (..) ,RPredicate (..) ,ColumnName ,RDataType (..) ,ROperation (..) ) where -- Vector import qualified Data.Vector as V -- HashMap -- https://hackage.haskell.org/package/unordered-containers-0.2.7.2/docs/Data-HashMap-Strict.html import Data.HashMap.Strict as HM --import qualified Data.Map.Strict as Map -- Data.Map.Strict https://www.stackage.org/haddock/lts-7.4/containers-0.5.7.1/Data-Map-Strict.html --import qualified Data.Set as Set -- https://www.stackage.org/haddock/lts-7.4/containers-0.5.7.1/Data-Set.html#t:Set --import qualified Data.ByteString as BS -- Data.ByteString https://www.stackage.org/haddock/lts-7.4/bytestring-0.10.8.1/Data-ByteString.html {-- -- | Definition of the Relation entity data Relation -- = RelToBeDefined deriving (Show) = Relation -- ^ A Relation is essentially a set of tuples { relname :: String -- ^ The name of the Relation (metadata) ,fields :: [RelationField] -- ^ The list of fields (i.e., attributes) of the relation (metadata) ,tuples :: Set.Set Rtuple -- ^ A relation is essentially a set o tuples (data) } | EmptyRel -- ^ An empty relation deriving Show --} -- * ########## Data Types ############## -- | Definition of the Relational Table entity data RTable = Vector RTuple deriving (Show, Eq) -- | Definiiton of the Relational Tuple data RTuple = HashMap ColumnName RDataType deriving (Show, Eq) -- | Definition of the Column Name type ColumnName = String -- | Definition of the Relational Data Types -- These will be the data types supported by the RTable data RDataType = RInteger | RChar | RText | RDate | RNumber deriving (Show, Eq) {-- -- | Definition of a relational tuple data Rtuple -- = TupToBeDefined deriving (Show) = Rtuple { fieldMap :: Map.Map RelationField Int -- ^ provides a key,value mapping between the field and the Index (i.e., the offset) in the bytestring ,fieldValues :: BS.ByteString -- ^ tuple values are stored in a bytestring } deriving Show --} {-- -- | Definition of a relation's field data RelationField = RelationField { fldname :: String ,dataType :: DataType } deriving Show -- | Definition of a data type data DataType = Rinteger -- ^ an integer data type | Rstring -- ^ a string data type | Rdate -- ^ a date data type deriving Show -- | Definition of a predicate type Predicate a = a -> Bool -- ^ a predicate is a polymorphic type, which is a function that evaluates an expression over an 'a' -- (e.g., a can be an Rtuple, thus Predicate Rtuple) and returns either true or false. -- | The selection operator. -- It filters the tuples of a relation based on a predicate -- and returns a new relation with the tuple that satisfy the predicate selection :: Relation -- ^ input relation -> Predicate Rtuple -- ^ input predicate -> Relation -- ^ output relation selection r p = undefined --} -- | Definition of a Predicate type RPredicate = RTuple -> Bool -- | Definition of Relational Algebra operations. -- These are the valid operations between RTables data ROperation = RUnion | RIntersection | RDifference | RProjection | RRestriction | RJoin | RFieldRenaming | RAggregation | RExtension
nkarag/haskell-CSVDB
src/Obsolete/Ralgebra.hs
bsd-3-clause
4,241
0
6
1,287
199
134
65
32
0
{-# OPTIONS -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.Marshal -- Copyright : (c) The FFI task force 2003 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : portable -- -- Marshalling support -- ----------------------------------------------------------------------------- module Foreign.Marshal ( module Foreign.Marshal.Alloc , module Foreign.Marshal.Array , module Foreign.Marshal.Error , module Foreign.Marshal.Pool , module Foreign.Marshal.Utils ) where import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Foreign.Marshal.Error import Foreign.Marshal.Pool import Foreign.Marshal.Utils
OS2World/DEV-UTIL-HUGS
libraries/Foreign/Marshal.hs
bsd-3-clause
848
0
5
147
87
64
23
12
0
module System.Posix.Daemonize ( -- * Simple daemonization daemonize, -- * Building system services serviced, CreateDaemon(..), simpleDaemon -- * An example -- -- | Here is an example of a full program which writes a message to -- syslog once a second proclaiming its continued existance, and -- which installs its own SIGHUP handler. Note that you won't -- actually see the message once a second in the log on most -- systems. @syslogd@ detects repeated messages and prints the -- first one, then delays for the rest and eventually writes a line -- about how many times it has seen it. -- -- > module Main where -- > -- > import System.Posix.Daemonize (CreateDaemon(..), serviced, simpleDaemon) -- > import System.Posix.Signals (installHandler, Handler(Catch), sigHUP, fullSignalSet) -- > import System.Posix.Syslog (syslog, Priority(Notice)) -- > import Control.Concurrent (threadDelay) -- > import Control.Monad (forever) -- > -- > main :: IO () -- > main = serviced stillAlive -- > -- > stillAlive :: CreateDaemon -- > stillAlive = simpleDaemon { program = stillAliveMain } -- > -- > stillAliveMain :: IO () -- > stillAliveMain = do -- > installHandler sigHUP (Catch taunt) (Just fullSignalSet) -- > forever $ do threadDelay (10^6) -- > syslog Notice "I'm still alive!" -- > -- > taunt :: IO () -- > taunt = syslog Notice "I sneeze in your general direction, you and your SIGHUP." ) where {- originally based on code from http://sneakymustard.com/2008/12/11/haskell-daemons -} import Control.Concurrent import Control.Exception.Extensible import qualified Control.Monad as M (forever) import Prelude hiding (catch) import System import System.Exit import System.Posix import System.Posix.Syslog (withSyslog,Option(..),Priority(..),Facility(..),syslog) import System.Posix.Types (UserID, GroupID) import System.FilePath.Posix (FilePath,joinPath) import Data.Maybe (isNothing, fromMaybe, fromJust) -- | Turning a process into a daemon involves a fixed set of -- operations on unix systems, described in section 13.3 of Stevens -- and Rago, "Advanced Programming in the Unix Environment." Since -- they are fixed, they can be written as a single function, -- 'daemonize' taking an 'IO' action which represents the daemon's -- actual activity. -- -- Briefly, 'daemonize' sets the file creation mask to 0, forks twice, -- changed the working directory to @/@, closes stdin, stdout, and -- stderr, blocks 'sigHUP', and runs its argument. Strictly, it -- should close all open file descriptors, but this is not possible in -- a sensible way in Haskell. -- -- The most trivial daemon would be -- -- > daemonize (forever $ return ()) -- -- which does nothing until killed. daemonize :: IO () -> IO () daemonize program = do setFileCreationMask 0 forkProcess p exitImmediately ExitSuccess where p = do createSession forkProcess p' exitImmediately ExitSuccess p' = do changeWorkingDirectory "/" closeFileDescriptors blockSignal sigHUP program -- | 'serviced' turns a program into a UNIX daemon (system service) -- ready to be deployed to /etc/rc.d or similar startup folder. It -- is meant to be used in the @main@ function of a program, such as -- -- > serviced simpleDaemon -- -- The resulting program takes one of three argments: @start@, -- @stop@, and @restart@. All control the status of a daemon by -- looking for a file containing a text string holding the PID of -- any running instance. Conventionally, this file is in -- @/var/run/$name.pid@, where $name is the executable's name. For -- obvious reasons, this file is known as a PID file. -- -- @start@ makes the program write a PID file. If the file already -- exists, it refuses to start, guaranteeing there is only one -- instance of the daemon at any time. -- -- @stop@ read the PID file, and terminates the process whose pid is -- written therein. First it does a soft kill, SIGTERM, giving the -- daemon a chance to shut down cleanly, then three seconds later a -- hard kill which the daemon cannot catch or escape. -- -- @restart@ is simple @stop@ followed by @start@. -- -- 'serviced' also tries to drop privileges. If you don't specify a -- user the daemon should run as, it will try to switch to a user -- with the same name as the daemon, and otherwise to user @daemon@. -- It goes through the same sequence for group. Just to complicate -- matters, the name of the daemon is by default the name of the -- executable file, but can again be set to something else in the -- 'CreateDaemon' record. -- -- Finally, exceptions in the program are caught, logged to syslog, -- and the program restarted. serviced :: CreateDaemon -> IO () serviced daemon = do systemName <- getProgName let daemon' = daemon { name = if isNothing (name daemon) then Just systemName else name daemon } args <- getArgs process daemon' args where program' daemon = withSyslog (fromJust $ name daemon) (syslogOptions daemon) DAEMON $ do let log = syslog Notice log "starting" pidWrite daemon dropPrivileges daemon forever (program daemon) process daemon ["start"] = pidExists daemon >>= f where f True = do error "PID file exists. Process already running?" exitImmediately (ExitFailure 1) f False = daemonize (program' daemon) process daemon ["stop"] = do pid <- pidRead daemon let ifdo x f = x >>= \x -> if x then f else pass case pid of Nothing -> pass Just pid -> (do signalProcess sigTERM pid usleep (10^6) ifdo (pidLive pid) $ do usleep (3*10^6) ifdo (pidLive pid) (signalProcess sigKILL pid)) `finally` removeLink (pidFile daemon) process daemon ["restart"] = do process daemon ["stop"] process daemon ["start"] process daemon _ = getProgName >>= \pname -> putStrLn $ "usage: " ++ pname ++ " {start|stop|restart}" -- | The details of any given daemon are fixed by the 'CreateDaemon' -- record passed to 'serviced'. You can also take a predefined form -- of 'CreateDaemon', such as 'simpleDaemon' below, and set what -- options you want, rather than defining the whole record yourself. data CreateDaemon = CreateDaemon { program :: IO (), -- ^ The actual guts of the daemon, more or less -- the @main@ function. name :: Maybe String, -- ^ The name of the daemon, which is used as -- the name for the PID file, as the name that -- appears in the system logs, and as the user -- and group the daemon tries to run as if -- none are explicitly specified. In general, -- this should be 'Nothing', in which case the -- system defaults to the name of the -- executable file containing the daemon. user :: Maybe String, -- ^ Most daemons are initially run as root, -- and try to change to another user so they -- have fewer privileges and represent less of -- a security threat. This field specifies -- which user it should try to run as. If it -- is 'Nothing', or if the user does not exist -- on the system, it next tries to become a -- user with the same name as the daemon, and -- if that fails, the user @daemon@. group :: Maybe String, -- ^ 'group' is the group the daemon should -- try to run as, and works the same way as -- the user field. syslogOptions :: [Option], -- ^ The options the daemon should set on -- syslog. You can safely leave this as @[]@. pidfileDirectory :: Maybe FilePath -- ^ The directory where the -- daemon should write and look -- for the PID file. 'Nothing' -- means @/var/run@. Unless you -- have a good reason to do -- otherwise, leave this as -- 'Nothing'. } -- | The simplest possible instance of 'CreateDaemon' is -- -- > CreateDaemon { -- > program = forever $ return () -- > name = Nothing, -- > user = Nothing, -- > group = Nothing, -- > syslogOptions = [], -- > pidfileDirectory = Nothing, -- > } -- -- which does nothing forever with all default settings. We give it a -- name, 'simpleDaemon', since you may want to use it as a template -- and modify only the fields that you need. simpleDaemon :: CreateDaemon simpleDaemon = CreateDaemon { name = Nothing, user = Nothing, group = Nothing, syslogOptions = [], pidfileDirectory = Nothing, program = M.forever $ return () } {- implementation -} forever :: IO () -> IO () forever program = program `catch` restart where restart :: SomeException -> IO () restart e = do syslog Error ("unexpected exception: " ++ show e) syslog Error "restarting in 5 seconds" usleep (5 * 10^6) forever program closeFileDescriptors :: IO () closeFileDescriptors = do null <- openFd "/dev/null" ReadWrite Nothing defaultFileFlags let sendTo fd' fd = closeFd fd >> dupTo fd' fd mapM_ (sendTo null) $ [stdInput, stdOutput, stdError] blockSignal :: Signal -> IO () blockSignal sig = installHandler sig Ignore Nothing >> pass getGroupID :: String -> IO (Maybe GroupID) getGroupID group = try (fmap groupID (getGroupEntryForName group)) >>= return . f where f :: Either IOException GroupID -> Maybe GroupID f (Left e) = Nothing f (Right gid) = Just gid getUserID :: String -> IO (Maybe UserID) getUserID user = try (fmap userID (getUserEntryForName user)) >>= return . f where f :: Either IOException UserID -> Maybe UserID f (Left e) = Nothing f (Right uid) = Just uid dropPrivileges :: CreateDaemon -> IO () dropPrivileges daemon = do Just ud <- getUserID "daemon" Just gd <- getGroupID "daemon" let targetUser = fromMaybe (fromJust $ name daemon) (user daemon) targetGroup = fromMaybe (fromJust $ name daemon) (group daemon) u <- fmap (maybe ud id) $ getUserID targetUser g <- fmap (maybe gd id) $ getGroupID targetGroup setGroupID g setUserID u pidFile:: CreateDaemon -> String pidFile daemon = joinPath [dir, (fromJust $ name daemon) ++ ".pid"] where dir = fromMaybe "/var/run" (pidfileDirectory daemon) pidExists :: CreateDaemon -> IO Bool pidExists daemon = fileExist (pidFile daemon) pidRead :: CreateDaemon -> IO (Maybe CPid) pidRead daemon = pidExists daemon >>= choose where choose True = fmap (Just . read) $ readFile (pidFile daemon) choose False = return Nothing pidWrite :: CreateDaemon -> IO () pidWrite daemon = getProcessID >>= \pid -> writeFile (pidFile daemon) (show pid) pidLive :: CPid -> IO Bool pidLive pid = (getProcessPriority pid >> return True) `catch` f where f :: IOException -> IO Bool f _ = return False pass :: IO () pass = return ()
t0yv0/hdaemonize
System/Posix/Daemonize.hs
bsd-3-clause
12,084
0
22
3,735
1,852
989
863
133
8
{-# LANGUAGE TypeOperators, StandaloneDeriving, FlexibleInstances #-} module Compiler.LiftDefinitions ( DefinitionA (..) , Definition , DefinitionsA (..) , Definitions , lift , eliminiateDoubles , dump ) where import Compiler.Generics import Compiler.Expression import Control.Arrow hiding (app) import Data.List (intercalate, nubBy) data DefinitionA a = Def { defName :: String , defExpr :: FixA a ExpressionF } newtype DefinitionsA a = Defs { unDefs :: [DefinitionA a] } type Definition = DefinitionA Id type Definitions = DefinitionsA Id deriving instance Eq (DefinitionA Id) deriving instance Eq (DefinitionsA Id) -- All named sub-expressions will be replaces by a variables that references -- the definition that will be created. All named sub-expression MUST NOT -- contain any free variables. inline :: Expression -> Expression inline = foldId (In . Id . fmap defs) where defs (In (Id (Name n _))) = var n defs e = e -- Collect all definitions from an expression tree and return a map with -- name/definition pairs. Because of the Map datatype all duplicate definitions -- will be joined to a single one. collect :: Expression -> [Definition] collect = reduce defs where defs (Name n d) = [Def n d] defs _ = [] -- Lift all definitions to the top-level and inline all references to these -- definitions in the main expression. lift :: Arrow (~>) => Expression ~> Definitions lift = arr (\e -> Defs (collect e ++ [Def "__main" (inline e)])) eliminiateDoubles :: Arrow (~>) => Definitions ~> Definitions eliminiateDoubles = arr (Defs . nubBy (\a b -> defName a == defName b) . unDefs) dump :: Arrow (~>) => Definitions ~> String dump = arr (intercalate "\n" . map one . unDefs) where one (Def d e) = "var " ++ d ++ " = " ++ rec e tr (App f e ) = rec f ++ "(" ++ rec e ++ ")" tr (Con c ) = c tr (Prim s vf) = s vf tr (Lam as e) = "function (" ++ intercalate ", " as ++ ") { return " ++ rec e ++ ";" ++ " }" tr (Var v ) = v tr (Name n e ) = "/* " ++ n ++ " */ " ++ rec e rec = tr . unId . out
sebastiaanvisser/AwesomePrelude
src/Compiler/LiftDefinitions.hs
bsd-3-clause
2,106
0
14
489
667
356
311
-1
-1
{-| Module : TypeSafeRoute.HTTP Description : Statically checked HTTP handlers. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE Arrows #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveFunctor #-} module TypeSafeRoute.HTTP where import GHC.TypeLits (Symbol, KnownSymbol, symbolVal) import Data.Void import Data.Proxy import Data.Profunctor import Data.Functor.Identity import Data.String (fromString) import Data.Char (isAlphaNum) import Control.Freedom.Construction import Control.Applicative import Control.Arrow import TypeSafeRoute.Server import qualified Network.HTTP.Types as H import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as B8 import qualified Data.Text as T import Data.Text.Encoding import qualified Data.Map as M import qualified Data.Attoparsec.Text as PT import qualified Data.Attoparsec.ByteString as PB import qualified Data.Attoparsec.ByteString.Char8 as PB8 import qualified Network.Wai as Wai import qualified Network.Wai.Internal as Wai.Internal import qualified Blaze.ByteString.Builder.ByteString as BSBuilder type QueryMap = M.Map T.Text (Maybe T.Text) data HTTPRequest t = HTTPRequest { httpRequestMethod :: H.Method , httpRequestHeaders :: H.RequestHeaders , httpRequestPath :: [T.Text] , httpRequestQuery :: QueryMap , httpRequestBody :: t } deriving instance Functor HTTPRequest deriving instance Show t => Show (HTTPRequest t) data HTTPResponse t = HTTPResponse { httpResponseStatus :: H.Status , httpResponseHeaders :: H.ResponseHeaders , httpResponseBody :: t } deriving instance Functor HTTPResponse deriving instance Show t => Show (HTTPResponse t) response200 :: t -> HTTPResponse t response200 = HTTPResponse H.status200 [] data HTTPMethod where GET :: HTTPMethod PUT :: HTTPMethod POST :: HTTPMethod DELETE :: HTTPMethod data RoutePieceT where RoutePieceSymbolT :: RoutePieceT RoutePieceSingleT :: RoutePieceT data RoutePiece t where RoutePieceSymbol :: RoutePiece '(RoutePieceSymbolT, sym, Void) RoutePieceSingle :: t -> RoutePiece '(RoutePieceSingleT, sym, t) type family RoutePieceOverlap piece route where RoutePieceOverlap piece '[] = False RoutePieceOverlap '(RoutePieceSymbolT, sym, s) rs = False RoutePieceOverlap '(RoutePieceSingleT, sym, s) ( '(RoutePieceSingleT, sym, t) ': rs ) = True RoutePieceOverlap '(RoutePieceSingleT, sym, s) ( '(pieceType, sym', t) ': rs) = RoutePieceOverlap '(RoutePieceSingleT, sym, s) rs type family InvalidRoute route where InvalidRoute '[] = False InvalidRoute (r ': rs) = Or (RoutePieceOverlap r rs) (InvalidRoute rs) data Route route where Root :: Route '[] Route :: RoutePiece t -> Route ts -> Route (t ': ts) data QueryPieceT where QueryPieceSingleT :: QueryPieceT data QueryPiece t where QueryPieceSingle :: t -> QueryPiece '(QueryPieceSingleT, sym, t) type family QueryPieceOverlap piece query where QueryPieceOverlap piece '[] = False QueryPieceOverlap '(any1, sym, s) ( '(any2, sym, t) ': qs ) = True QueryPieceOverlap '(any1, sym1, s) ( '(any2, sym2, t) ': qs ) = QueryPieceOverlap '(any1, sym1, s) qs type family InvalidQuery query where InvalidQuery '[] = False InvalidQuery (q ': qs) = Or (QueryPieceOverlap q qs) (InvalidQuery qs) data Query query where EndQuery :: Query '[] Query :: QueryPiece t -> Query ts -> Query (t ': ts) data Body body where Body :: body -> Body body data HTTP (method :: HTTPMethod) route query body where HTTP :: Route route -> Query query -> Body body -> HTTP method route query body routeValue :: InRoute sym route => HTTP method route query body -> Proxy sym -> InRouteType sym route routeValue http proxy = case http of HTTP route _ _ -> inRouteLookup proxy route queryValue :: InQuery sym query => HTTP method route query body -> Proxy sym -> InQueryType sym query queryValue http proxy = case http of HTTP _ query _ -> inQueryLookup proxy query requestBody :: HTTP method route query body -> body requestBody http = case http of HTTP _ _ (Body b) -> b httpNoData :: HTTP method '[] '[] () httpNoData = HTTP Root EndQuery (Body ()) type HTTPHandler a method route query body output = a (HTTP method route query body) (HTTPResponse output) noRoute :: Arrow a => HTTPHandler a method '[] '[] () () noRoute = arr (\_ -> HTTPResponse H.status404 [] ()) noMethod :: Arrow a => HTTPHandler a method '[] '[] () () noMethod = arr (\_ -> HTTPResponse H.status405 [] ()) -- TODO would be cool if we could throw in a reason, like which parameter -- failed to parse. badRequest :: Arrow a => HTTPHandler a method '[] '[] () () badRequest = arr (\_ -> HTTPResponse H.status403 [] ()) data HTTPHandlers a resources where NoHandlers :: HTTPHandlers a '[] AddHandler -- It's here where we check that the type parameters are sane. -- You can construct bogus @HTTPHandler@s, but you cannot use them -- in an @HTTPHandlers@ value. :: ( ResourceOverlap '(method, route) rs ~ False , InvalidRoute route ~ False , InvalidQuery query ~ False , MatchMethod method , MatchRoute route , MatchQuery query , HTTPBody body , HTTPBody output ) => HTTPHandler a method route query body output -> HTTPHandlers a rs -> HTTPHandlers a ( '(method, route, query, body, output) ': rs ) type family Or (a :: Bool) (b :: Bool) :: Bool where Or False False = False Or a b = True -- Two routes overlap precisely when they are of equal length and all of their -- corresponding symbolic components (strings between the slashes) are the same. type family RouteOverlap q r where RouteOverlap '[] '[] = True RouteOverlap ( '(RoutePieceSymbolT, sym, t) ': qs ) ( '(RoutePieceSymbolT, sym, s) ': rs ) = RouteOverlap qs rs -- Two distinct symbols encountered; we know there's no overlap. RouteOverlap ( '(RoutePieceSymbolT, sym1, t) ': qs ) ( '(RoutePieceSymbolT, sym2, s) ': rs) = False -- If we encounter any two non-symbolic pieces (RoutePieceSymbolT already -- covered above) then the route may still overlap. RouteOverlap ( '(piece1, sym1, t) ': qs ) ( '(piece2, sym2, s) ': rs ) = RouteOverlap qs rs RouteOverlap qs '[] = False RouteOverlap '[] rs = False -- Identify if some resource overlaps with any of a list of resources. -- -- 1. /foo/<bar>/baz -- 2. /<foo>/bar/baz -- 3. /bar/foo -- -- <x> means that part of the route is a variable binding. -- Here, 1 and 2 overlap if they have the same method, because there's no way -- to distinguish the two; either could be interpreted as the other. -- But 3 overlaps with neither, since the first route piece differs from that -- of 1, and the second route piece differs from that of 2. -- -- The rule: two resources overlap if they have the same method, and their -- routes are of the same length and do not contain one pair of distinct symbols -- (non-bindings) at the same index. type family ResourceOverlap r rs where ResourceOverlap r '[] = False ResourceOverlap '(method, route1) ( '(method, route2, query, body, output) ': rs ) = Or (RouteOverlap route1 route2) (ResourceOverlap '(method, route1) rs) ResourceOverlap '(method1, route1) ( '(method2, route2, query, body, output) ': rs ) = ResourceOverlap '(method1, route1) rs type family InRouteType (t :: Symbol) (ts :: [(RoutePieceT, Symbol, *)]) :: * where InRouteType sym ( '(RoutePieceSingleT, sym, t) ': ts ) = t InRouteType sym ( s ': ts ) = InRouteType sym ts InRouteType sym '[] = Void class InRoute (sym :: Symbol) (ts :: [(RoutePieceT, Symbol, *)]) where inRouteLookup :: Proxy sym -> Route ts -> InRouteType sym ts instance {-# OVERLAPPING #-} InRoute sym ( '(RoutePieceSingleT, sym, t) ': ts ) where inRouteLookup _ rd = case rd of Route (RoutePieceSingle x) _ -> x instance {-# OVERLAPPABLE #-} ( InRoute sym ts , InRouteType sym (s ': ts) ~ InRouteType sym ts ) => InRoute sym (s ': ts) where inRouteLookup proxy rd = case rd of Route _ rest -> inRouteLookup proxy rest type family InQueryType (q :: Symbol) (qs :: [(QueryPieceT, Symbol, *)]) :: * where InQueryType sym ( '(QueryPieceSingleT, sym, t) ': qs ) = t InQueryType sym ( q ': qs ) = InQueryType sym qs InQueryType sym '[] = Void class InQuery (sym :: Symbol) (qs :: [(QueryPieceT, Symbol, *)]) where inQueryLookup :: Proxy sym -> Query qs -> InQueryType sym qs instance {-# OVERLAPPING #-} InQuery sym ( '(QueryPieceSingleT, sym, t) ': qs ) where inQueryLookup _ q = case q of Query (QueryPieceSingle x) _ -> x instance {-# OVERLAPPABLE #-} ( InQuery sym qs , InQueryType sym (q ': qs) ~ InQueryType sym qs ) => InQuery sym (q ': qs) where inQueryLookup proxy q = case q of Query _ rest -> inQueryLookup proxy rest class MatchMethod method where matchMethod :: Proxy method -> H.Method -> Bool instance MatchMethod GET where matchMethod _ = (==) H.methodGet instance MatchMethod PUT where matchMethod _ = (==) H.methodPut instance MatchMethod POST where matchMethod _ = (==) H.methodPost instance MatchMethod DELETE where matchMethod _ = (==) H.methodDelete class MatchRoute route where matchRoute :: [T.Text] -> Either () (Route route) instance MatchRoute '[] where matchRoute texts = case texts of (_ : _) -> Left () [] -> Right Root instance ( KnownSymbol sym , MatchRoute ts ) => MatchRoute ( '(RoutePieceSymbolT, sym, Void) ': ts ) where matchRoute texts = case texts of (text : rest) -> case text == T.pack (symbolVal (Proxy :: Proxy sym)) of True -> Route <$> Right RoutePieceSymbol <*> matchRoute rest False -> Left () [] -> Left () instance ( HTTPParameter t , MatchRoute ts ) => MatchRoute ( '(RoutePieceSingleT, sym, t) ': ts ) where matchRoute texts = case texts of (text : rest) -> (\x y -> Route (RoutePieceSingle x) y) <$> parsed <*> matchRoute rest where parsed = case PT.parseOnly parseHttpParameter text of Right x -> Right x Left _ -> Left () [] -> Left () class MatchQuery query where matchQuery :: QueryMap -> Either () (Query query) instance MatchQuery '[] where matchQuery queryMap = Right EndQuery instance ( QueryParameter t , MatchQuery ts , KnownSymbol sym ) => MatchQuery ( '(QueryPieceSingleT, sym, t) ': ts ) where matchQuery queryMap = (\x y -> Query (QueryPieceSingle x) y) <$> parsed <*> matchQuery restOfMap where key = T.pack (symbolVal (Proxy :: Proxy sym)) restOfMap = M.delete key queryMap value = M.lookup key queryMap parsed = parseQueryParameter value class QueryParameter t where parseQueryParameter :: Maybe (Maybe T.Text) -> Either () t printQueryParameter :: t -> Maybe T.Text instance QueryParameter Bool where parseQueryParameter bs = case bs of Just (Just bs') -> Right True _ -> Right False printQueryParameter = Just . T.pack . show instance HTTPParameter t => QueryParameter (Identity t) where parseQueryParameter ts = case ts of Just (Just ts) -> case PT.parseOnly parseHttpParameter ts of Right x -> Right (Identity x) Left _ -> Left () _ -> Left () printQueryParameter = Just . printHttpParameter . runIdentity instance HTTPParameter t => QueryParameter (Maybe t) where parseQueryParameter ts = case ts of Nothing -> Right Nothing Just Nothing -> Right Nothing Just (Just ts') -> case PT.parseOnly parseHttpParameter ts' of Right x -> Right (Just x) Left _ -> Left () printQueryParameter = fmap printHttpParameter instance HTTPParameter t => QueryParameter [t] where parseQueryParameter ts = case ts of Just (Just tss) -> case PT.parseOnly (PT.sepBy1 (parseHttpParameter) (PT.char ',')) tss of Right xs -> Right xs Left _ -> Left () _ -> Left () printQueryParameter = Just . T.intercalate (T.pack ",") . fmap printHttpParameter class HTTPParameter t where parseHttpParameter :: PT.Parser t printHttpParameter :: t -> T.Text instance HTTPParameter Integer where parseHttpParameter = do x <- PT.number case x of PT.I int -> pure int _ -> empty printHttpParameter = T.pack . show instance HTTPParameter T.Text where parseHttpParameter = PT.takeWhile isAlphaNum printHttpParameter = id instance HTTPParameter t => HTTPParameter [t] where parseHttpParameter = PT.sepBy parseHttpParameter (PT.char ',') printHttpParameter = T.intercalate (T.pack ",") . fmap printHttpParameter -- Any HTTPBody must have an injection into ByteString, which we express as -- a parser rather than a straight up function. class HTTPBody t where parseHttpBody :: PB.Parser t printHttpBody :: t -> BS.ByteString instance HTTPBody () where parseHttpBody = pure () printHttpBody = const BS.empty instance HTTPBody BS.ByteString where parseHttpBody = PB.takeByteString printHttpBody = id instance HTTPBody T.Text where parseHttpBody = do bs <- PB.takeByteString case decodeUtf8' bs of Left _ -> empty Right x -> pure x printHttpBody = encodeUtf8 instance HTTPBody t => HTTPBody [t] where parseHttpBody = PB.sepBy1 parseHttpBody (PB8.char ',') printHttpBody = BS.intercalate (B8.pack ",") . fmap printHttpBody instance HTTPBody t => HTTPBody (Maybe t) where parseHttpBody = (PB8.string "Just " *> (Just <$> parseHttpBody)) <|> (PB8.string "Nothing" *> pure Nothing) printHttpBody x = case x of Nothing -> "Nothing" Just x' -> BS.append (B8.pack "Just ") (printHttpBody x') type family TermSymbol t where TermSymbol '(sym, t) = sym type family TermType t where TermType '(sym, t) = t type family Snoc t ts where Snoc t '[] = '[t] Snoc t (u ': ts) = u ': (Snoc t ts) infixl 8 -/ type route -/ symbol = Snoc '(RoutePieceSymbolT, symbol, Void) route infixl 8 =/ type route =/ (term :: (Symbol, *)) = Snoc '(RoutePieceSingleT, TermSymbol term, TermType term) route type Root = '[] infixl 8 -? type query -? term = Snoc '(QueryPieceSingleT, TermSymbol term, TermType term) query type Q = '[] -- Take the HTTPRequest, match a handler, and run it. handle :: ArrowApply a => HTTPHandlers a routes -> a (HTTPRequest BS.ByteString) (HTTPResponse BS.ByteString) handle httpHandlers = proc httpRequest -> do httpResponse <- app -< handleSomeHandler (matchHandler httpRequest httpHandlers) returnA -< httpResponse data SomeHandler a where SomeHandler :: (a (HTTP method route query body) (HTTPResponse BS.ByteString), HTTP method route query body) -> SomeHandler a handleSomeHandler :: (Arrow a) => SomeHandler a -> (a () (HTTPResponse BS.ByteString), ()) handleSomeHandler someHandler = case someHandler of SomeHandler (arrow, input) -> (arr (const input) >>> arrow, ()) matchHandler :: forall routes method route query body a . ( Arrow a ) => (HTTPRequest BS.ByteString) -> HTTPHandlers a routes -> SomeHandler a matchHandler httpRequest handlers = case handlers of NoHandlers -> SomeHandler (noRoute >>> arr (fmap printHttpBody), httpNoData) AddHandler (handler :: HTTPHandler a thisMethod thisRoute thisQuery thisBody thisOutput) rest -> case matchMethod (Proxy :: Proxy thisMethod) (httpRequestMethod httpRequest) :: Bool of False -> matchHandler httpRequest rest True -> case matchRoute (httpRequestPath httpRequest) :: Either () (Route thisRoute) of Left () -> matchHandler httpRequest rest Right route -> case matchQuery (httpRequestQuery httpRequest) :: Either () (Query thisQuery) of -- Do not recurse! The route matches, but the query parameters -- don't; that counts as a bad request. Left () -> SomeHandler (badRequest >>> arr (fmap printHttpBody), httpNoData) Right query -> case PB.parseOnly parseHttpBody (httpRequestBody httpRequest) :: Either String thisBody of Left _ -> SomeHandler (badRequest >>> arr (fmap printHttpBody), httpNoData) Right body -> SomeHandler (handler >>> arr (fmap printHttpBody), HTTP route query (Body body)) httpServer :: ArrowApply a => (req -> HTTPRequest BS.ByteString) -> (HTTPResponse BS.ByteString -> res) -> HTTPHandlers a router -> Server a req res httpServer makeRequest makeResponse handlers = Server $ proc req -> do httpResponse <- handle handlers -< makeRequest req returnA -< makeResponse httpResponse waiApplication :: (forall s t . a s t -> Kleisli IO s t) -> Server a (HTTPRequest BS.ByteString) (HTTPResponse BS.ByteString) -> Wai.Application waiApplication makeIO server req response = do httpRequest <- waiRequestToHTTPRequest req out <- runKleisli (makeIO (runServer server)) httpRequest let waiResponse = httpResponseToWaiResponse out response waiResponse waiRequestToHTTPRequest :: Wai.Internal.Request -> IO (HTTPRequest BS.ByteString) waiRequestToHTTPRequest req = do let method = Wai.Internal.requestMethod req let path = Wai.Internal.pathInfo req let headers = Wai.Internal.requestHeaders req let query = Wai.Internal.queryString req let queryMap = makeQueryMap (H.queryToQueryText query) body <- waiForceRequestBody req return (HTTPRequest method headers path queryMap body) where makeQueryMap = M.fromList waiForceRequestBody req = do chunk <- Wai.Internal.requestBody req if chunk == BS.empty then return chunk else BS.append chunk <$> waiForceRequestBody req httpResponseToWaiResponse :: HTTPResponse BS.ByteString -> Wai.Internal.Response httpResponseToWaiResponse httpResponse = let status = httpResponseStatus httpResponse headers = httpResponseHeaders httpResponse body = httpResponseBody httpResponse in Wai.Internal.ResponseBuilder status headers (BSBuilder.fromByteString body) type family RouteTypes (r :: [(RoutePieceT, Symbol, *)]) :: [*] where RouteTypes '[] = '[] RouteTypes ( '(RoutePieceSymbolT, sym, Void) ': rest ) = RouteTypes rest RouteTypes ( '(RoutePieceSingleT, sym, t) ': rest ) = t ': RouteTypes rest type family QueryTypes (q :: [(QueryPieceT, Symbol, *)]) :: [*] where QueryTypes '[] = '[] QueryTypes ( '(QueryPieceSingleT, sym, t) ': rest ) = t ': QueryTypes rest data HList (ts :: [*]) where HNil :: HList '[] HCons :: t -> HList ts -> HList (t ': ts) -- We can use a route type to make a path suitable for use in a URL. -- The texts will not be escaped; use encodePathSegments from -- Network.HTTP.Types.URI to obtain a Builder for the path. class MakePath (r :: [(RoutePieceT, Symbol, *)]) where makePath :: Proxy r -> HList (RouteTypes r) -> [T.Text] instance MakePath '[] where makePath _ _ = [] instance ( KnownSymbol sym , MakePath ts ) => MakePath ( '(RoutePieceSymbolT, sym, Void) ': ts ) where -- It's right to put this portion in the LHS of the list cons, because -- the type-list representation of routes is in the "higher-levels to the -- right style" just like the way we usually write domain-names: google.com -- rather than com.google; subresource/resource/ rather than -- /resource/subresource. -- Note that the type synonyms -/, =/, and +/ allow us to write the -- routes in the familiar web-browsing style, by reverse-consing the -- RHS onto the LHS. makePath _ list = T.pack (symbolVal (Proxy :: Proxy sym)) : makePath (Proxy :: Proxy ts) list instance ( MakePath ts , HTTPParameter t ) => MakePath ( '(RoutePieceSingleT, sym, t) ': ts ) where makePath _ hlist = case hlist of HCons x rest -> printHttpParameter x : makePath (Proxy :: Proxy ts) rest -- Use renderQueryText from Network.HTTP.Types.URI to get a Builder for the -- actual text. class MakeQuery (q :: [(QueryPieceT, Symbol, *)]) where makeQuery :: Proxy q -> HList (QueryTypes q) -> [(T.Text, Maybe T.Text)] instance MakeQuery '[] where makeQuery _ _ = [] instance ( KnownSymbol sym , MakeQuery qs , QueryParameter t ) => MakeQuery ( '(QueryPieceSingleT, sym, t) ': qs ) where makeQuery _ hlist = case hlist of HCons x rest -> (T.pack (symbolVal (Proxy :: Proxy sym)), printQueryParameter x) : makeQuery (Proxy :: Proxy qs) rest
avieth/TypeSafeRoute
Network/TypeSafeRoute/HTTP.hs
bsd-3-clause
21,440
68
22
4,863
6,476
3,450
3,026
421
6
module Environment where import Control.Monad.Except import Data.IORef import Data.Maybe import Syntax type Env = IORef [(String, IORef LispVal)] nullEnv :: IO Env nullEnv = newIORef [] type IOThrowsError = ExceptT LispError IO liftThrows :: ThrowsError a -> IOThrowsError a liftThrows (Left err) = throwError err liftThrows (Right val) = return val runIOThrows :: IOThrowsError String -> IO String runIOThrows action = extractValue <$> runExceptT (trapError action) -- isBound busca si una variable esta definida en el Env. isBound :: Env -> String -> IO Bool isBound envRef var = isJust . lookup var <$> readIORef envRef getVar :: Env -> String -> IOThrowsError LispVal getVar envRef var = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Getting an unbound variable" var ) (liftIO . readIORef) (lookup var env) setVar :: Env -> String -> LispVal -> IOThrowsError LispVal setVar envRef var value = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Setting an unbound variable" var) (liftIO . flip writeIORef value) (lookup var env) return value defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal defineVar envRef var value = do alreadyDefined <- liftIO $ isBound envRef var if alreadyDefined then setVar envRef var value >> return value else liftIO $ do valueRef <- newIORef value env <- readIORef envRef writeIORef envRef ((var, valueRef) : env) return value bindVars :: Env -> [(String, LispVal)] -> IO Env bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef where extendEnv bindings env = (++ env) <$> mapM addBinding bindings addBinding (var, value) = do ref <- newIORef value return (var, ref)
juanbono/my-scheme
src/Environment.hs
bsd-3-clause
1,850
0
14
440
604
297
307
44
2
{-# OPTIONS_GHC -F -pgmF htfpp #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Text.HSmarty.Parser.SmartyTest where import Data.Attoparsec.Text import Paths_HSmarty import Test.Framework import Text.HSmarty.Parser.Smarty import Text.HSmarty.Types import qualified Data.Aeson as A import qualified Data.Text as T import qualified Data.Text.IO as T parserTest :: forall b. (Eq b, Show b) => Parser b -> T.Text -> b -> IO () parserTest parser input expected = either fail comp $ parseOnly parser input where comp x = assertEqual x expected readDataFile :: String -> IO T.Text readDataFile name = do fp <- getDataFileName name T.readFile fp test_complex :: IO () test_complex = do testData <- readDataFile "test.tpl" case parseOnly pRoot testData of Left errMsg -> fail errMsg Right _ -> return () test_literalParser :: IO () test_literalParser = parserTest pLiteral "{literal}abc{/literal}" "abc" test_commentParser :: IO () test_commentParser = parserTest pComment "{* some comment *}" " some comment " test_varParser :: IO () test_varParser = do parserTest pVar "$hallo.sub@prop" (Variable "hallo" ["sub"] Nothing (Just "prop")) parserTest pVar "$hallo.foo_bar" (Variable "hallo" ["foo_bar"] Nothing Nothing) test_capture :: IO () test_capture = do parserTest pCapture "{capture name='foo'}Bye{/capture}" expect1 parserTest pCapture "{capture name='foo' assign=bar}Bye{/capture}" expect2 where expect1 = Capture "foo" Nothing [SmartyText "Bye"] expect2 = Capture "foo" (Just "bar") [SmartyText "Bye"] test_if :: IO () test_if = do parserTest pIf "{if $var@last}Bye{/if}" expect parserTest pIf "{if ($var@last)}Bye{/if}" expect where expect = If { if_cases = [( ExprVar (Variable "var" [] Nothing (Just "last")) , [SmartyText "Bye"] ) ] , if_else = Nothing } test_rootParser :: IO () test_rootParser = parserTest pRoot "{if true}{include file='hallo.tpl' var1=23}{else}Nothing{/if}" expect where expect = [SmartyIf (If{if_cases = [(ExprLit (A.Bool True), [SmartyPrint (ExprFun (FunctionCall{f_name = "include", f_args = [("file", ExprLit (A.String "hallo.tpl")), ("var1", ExprLit (A.Number 23))]})) []])], if_else = Just [SmartyText "Nothing"]})]
agrafix/HSmarty
test/Text/HSmarty/Parser/SmartyTest.hs
bsd-3-clause
2,869
0
26
988
696
364
332
70
2
module ThreadsLang.EvaluatorSuite ( tests ) where import Control.Monad.Except import Control.Monad.Trans.State.Lazy (evalStateT) import Data.List (stripPrefix) import Test.HUnit import Text.Megaparsec import ThreadsLang.Data import ThreadsLang.Evaluator import ThreadsLang.Parser (expression) tests :: Test tests = TestList [ testBasic , testOps , testLet , testCond , testProc , testRef , testSpawn , testMutex ] testBasic :: Test testBasic = TestList [ testEq "Eval const" (ExprNum 3) "3" , testEq "Eval bounded var" (ExprNum 5) "let v = 5 in v" , testErr "Eval no-bounded var" (UnboundVar "y") "let x = 5 in y" ] testOps :: Test testOps = TestList [ testEq "Eval binary num-to-num operator 1" (ExprNum 5) "-(10, 5)" , testEq "Eval binary num-to-num operator 2" (ExprNum 15) "+(10, 5)" , testEq "Eval binary num-to-bool operator (true case)" (ExprBool True) "greater?(4, 3)" , testEq "Eval binary num-to-bool operator (false case)" (ExprBool False) "less?(5,2)" , testEq "Eval unary operator" (ExprNum (-1)) "minus(1)" ] testLet :: Test testLet = TestList [ testEq "Eval let expression" (ExprNum 2) $ unlines [ "let x = 30" , "in let y = -(x,2)" , " in -(x,y)" ] , testEq "Eval let with multi bindings 1" (ExprNum 1) $ unlines [ "let x = 1" , " y = 2" , " z = 3" , "in x" ] , testEq "Eval let with multi bindings 2" (ExprNum 3) $ unlines [ "let x = 1" , " y = 2" , " z = 3" , "in z" ] , testEq "Eval let expression with variable shadowing" (ExprNum 2) $ unlines [ "let x = 1" , "in let x = 2" , " in x" ] , testEq "Eval letrec with recursion" (ExprNum 12) $ unlines [ "letrec double(x)" , " = if zero?(x) then 0 else -((double -(x,1)), -2)" , "in (double 6)" ] , testEq "Eval letrec with co-recursion" (ExprNum 1) $ unlines [ "letrec" , " even(x) = if zero?(x) then 1 else (odd -(x,1))" , " odd(x) = if zero?(x) then 0 else (even -(x,1))" , "in (odd 13)" ] , testEq "Eval let and begin expression" (ExprNum 12) $ unlines [ "let times4 = 0" , "in begin" , " set times4 = proc (x)" , " if zero?(x)" , " then 0" , " else -((times4 -(x,1)), -4);" , " (times4 3)" , " end" ] ] testCond :: Test testCond = TestList [ testEq "Eval true branch of if expression" (ExprNum 3) "if zero? (0) then 3 else 4" , testEq "Eval false branch of if expression" (ExprNum 4) "if zero? (5) then 3 else 4" ] testProc :: Test testProc = TestList [ testEq "Eval proc and call expression (no parameter)" (ExprNum 1) "(proc () 1)" , testEq "Eval proc and call expression (1 parameter)" (ExprNum 2) "(proc (x) + (x, x) 1)" , testEq "Eval proc and call expression (many parameters)" (ExprNum 7) "(proc (x y z) + (x, * (y, z)) 1 2 3)" , testEq "Eval named proc" (ExprNum 7) "let f = proc (x y z) + (x, * (y, z)) in (f 1 2 3)" , testErr "Too many parameters" (ArgNumMismatch 0 [ExprNum 1]) "(proc () 1 1)" , testErr "Too many arguments" (ArgNumMismatch 2 [ExprNum 1]) "(proc (x y) +(x, y) 1)" ] testRef :: Test testRef = TestList [ testEq "Set value of a parameter should not affect the original variable." (ExprNum 3) $ unlines [ "let p = proc (x) set x = 4" , "in let a = 3" , " in begin (p a); a end" ] , testEq ("Parameters of nested function call should " `mappend` "not refer to the same variable.") (ExprNum 55) $ unlines [ "let f = proc (x) set x = 44" , "in let g = proc (y) (f y)" , " in let z = 55" , " in begin (g z); z end" ] , testEq "Test implicit ref" (ExprNum 3) $ unlines [ "let x = 4" , "in begin set x = 3;" , " x" , " end" ] ] testSpawn :: Test testSpawn = TestList [ testEq "Test spawn 1" (ExprNum 1) $ unlines [ "let x = 0 in" , "let incX = proc() set x = + (x, 1) in" , "letrec buzyWait(n) = if zero?(n) then 1 else (buzyWait -(n, 1)) in" , "begin spawn(incX);" , " (buzyWait 100);" , " x" , "end" ] , testEq "Test spawn 2" (ExprNum 3) $ unlines [ "let x = 0 in" , "let incX = proc() set x = + (x, 1) in" , "letrec buzyWait(n) = if zero?(n) then 1 else (buzyWait -(n, 1)) in" , "begin spawn(incX);" , " spawn(incX);" , " spawn(incX);" , " (buzyWait 100);" , " x" , "end" ] ] testMutex :: Test testMutex = TestList [ testEq "Test mutex 1" (ExprNum 1) $ unlines [ "let x = 0 in" , "let m = mutex() in" , "let incX = proc()" , " begin" , " wait(m);" , " set x = + (x, 1);" , " signal(m)" , " end in" , "letrec buzyWait(n) = if zero?(n) then 1 else (buzyWait -(n, 1)) in" , "begin spawn(incX);" , " (buzyWait 100);" , " wait(m);" , " signal(m);" , " x" , "end" ] , testEq "Test mutex 2" (ExprNum 3) $ unlines [ "let x = 0 in" , "let m = mutex() in" , "let incX = proc()" , " begin" , " wait(m);" , " set x = + (x, 1);" , " signal(m)" , " end in" , "letrec buzyWait(n) = if zero?(n) then 1 else (buzyWait -(n, 1)) in" , "begin spawn(incX);" , " spawn(incX);" , " spawn(incX);" , " (buzyWait 100);" , " wait(m);" , " signal(m);" , " x" , "end" ] , testEq "Test yield" (ExprNum 3) $ unlines [ "let x = 0 in" , "let m = mutex() in" , "let incX = proc()" , " begin" , " wait(m);" , " set x = + (x, 1);" , " signal(m)" , " end in" , "letrec buzyWait(n) = if zero?(n) then 1 else (buzyWait -(n, 1)) in" , "begin spawn(incX);" , " spawn(incX);" , " spawn(incX);" , " yield();" , " wait(m);" , " signal(m);" , " x" , "end" ] ] testEq :: String -> ExpressedValue -> String -> Test testEq msg expect input = TestCase $ do evalRes <- run input assertEqual msg (Right expect) evalRes testErr :: String -> LangError -> String -> Test testErr msg expect input = TestCase $ do evalRes <- run input assertEqual msg (Left expect) evalRes
li-zhirui/EoplLangs
test/ThreadsLang/EvaluatorSuite.hs
bsd-3-clause
7,998
0
11
3,685
1,245
684
561
229
1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE OverloadedStrings #-} module Repl where import Prelude hiding (lines, read) import Control.Applicative ((<|>)) import Control.Monad.RWS (lift, liftIO) import qualified Control.Monad.RWS as RWS import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.List as List import qualified Data.Map as Map import Data.Monoid ((<>)) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified System.Console.Haskeline as Repl import qualified System.Directory as Dir import qualified System.Exit as Exit import System.FilePath ((</>)) import qualified System.IO as IO import qualified System.Process as Proc import qualified Elm.Compiler as Elm (version) import qualified Elm.Name as N import qualified Elm.Project as Project import qualified Elm.Package as Pkg import qualified Elm.PerUserCache as PerUserCache import qualified Elm.Utils as Elm import qualified Reporting.Task as Task import qualified Reporting.Progress.Repl as Repl import qualified CommandLine.Args as Args -- RUN run :: Args.ReplFlags -> IO () run (Args.ReplFlags maybeAlternateInterpreter) = do interpreter <- getInterpreter maybeAlternateInterpreter _ <- Project.getRootWithReplFallback putStrLn welcomeMessage settings <- initSettings let manager = Repl.runInputT settings (Repl.withInterrupt loop) (exitCode,_,_) <- RWS.runRWST manager interpreter initalState Exit.exitWith exitCode type Runner = RWS.RWST FilePath () State IO -- LOOP loop :: Repl.InputT Runner Exit.ExitCode loop = do input <- Repl.handleInterrupt (return Skip) read maybe loop return =<< lift (eval input) -- READ read :: Repl.InputT Runner Input read = readHelp "> " [] readHelp :: String -> [String] -> Repl.InputT Runner Input readHelp starter lines = do input <- Repl.getInputLine starter case input of Nothing -> return Exit Just line -> if not (null line) && last line == '\\' then readHelp "| " (init line : lines) else return $ toInput $ List.intercalate "\n" $ reverse (line : lines) -- EVAL eval :: Input -> Runner (Maybe Exit.ExitCode) eval input = case input of Skip -> return Nothing Exit -> return (Just Exit.ExitSuccess) Reset -> do RWS.put initalState report "<reset>" Help info -> report (helpMessage info) Code entry -> Repl.handleInterrupt (report "<cancelled>") $ do state@(State _ imports types defs tricks) <- RWS.get case entry of Elm.Import name src -> interpret None $ state { _imports = Map.insert name src imports } Elm.Type name src -> interpret None $ state { _types = Map.insert name src types } Elm.Def (Just name) src -> interpret (Def name) $ state { _defs = Map.insert name src defs } Elm.Def Nothing src -> interpret None $ state { _tricks = src : tricks } Elm.Other src -> interpret (Expr src) state Elm.Annotation -> report "I cannot handle type annotations." Elm.Port -> report "I cannot handle port declarations." toUtf8 :: String -> BS.ByteString toUtf8 string = LBS.toStrict (B.toLazyByteString (B.stringUtf8 string)) report :: String -> Runner (Maybe a) report msg = do liftIO (putStrLn msg) return Nothing data Output = None | Def N.Name | Expr Text.Text interpret :: Output -> State -> Runner (Maybe a) interpret def state = do reporter <- liftIO $ Repl.create result <- liftIO $ Task.run reporter $ compile def state case result of Nothing -> return () Just maybePath -> do RWS.put (state { _count = _count state + 1 }) maybe (return ()) interpretHelp maybePath return Nothing interpretHelp :: FilePath -> Runner () interpretHelp path = do interpreter <- RWS.ask let proc = (Proc.proc interpreter [path]) { Proc.std_in = Proc.CreatePipe } liftIO $ Proc.withCreateProcess proc $ \_ _ _ handle -> do _ <- Proc.waitForProcess handle Dir.removeFile path -- INPUT data Input = Skip | Exit | Reset | Help (Maybe String) | Code Elm.Entry toInput :: String -> Input toInput string = case dropWhile (==' ') string of ":exit" -> Exit ":help" -> Help Nothing ":reset" -> Reset ':' : rest -> Help (Just (takeWhile (/=' ') rest)) "" -> Skip _ -> Code (Elm.parseEntry string) -- STATE data State = State { _count :: !Int , _imports :: Map.Map N.Name Text.Text , _types :: Map.Map N.Name Text.Text , _defs :: Map.Map N.Name Text.Text , _tricks :: [Text.Text] } initalState :: State initalState = State 0 Map.empty Map.empty Map.empty [] compile :: Output -> State -> Task.Task (Maybe FilePath) compile output (State count imports types defs tricks) = let elmSourceCode = (<>) "module ElmRepl exposing (..)\n\n" $ addLines imports $ addLines types $ addLines defs $ List.foldr (<>) mempty (map Text.encodeUtf8Builder tricks) in case output of None -> if Map.null types && Map.null defs && null tricks then evaluate (elmSourceCode <> "unit = ()") Nothing else evaluate elmSourceCode Nothing Def name -> evaluate elmSourceCode (Just name) Expr expr -> let name = N.addIndex "repl_value_" count text = Text.replace "\n" "\n " expr def = N.toBuilder name <> " =\n " <> Text.encodeUtf8Builder text <> "\n" in evaluate (elmSourceCode <> def) (Just name) addLines :: Map.Map N.Name Text.Text -> B.Builder -> B.Builder addLines dict builder = Map.foldr (\text b -> Text.encodeUtf8Builder text <> b) builder dict evaluate :: B.Builder -> Maybe N.Name -> Task.Task (Maybe FilePath) evaluate builder maybeName = Project.compileForRepl (LBS.toStrict (B.toLazyByteString builder)) maybeName -- SETTINGS initSettings :: IO (Repl.Settings Runner) initSettings = do cache <- PerUserCache.getReplRoot return $ Repl.Settings { Repl.historyFile = Just (cache </> "history") , Repl.autoAddHistory = True , Repl.complete = Repl.completeWord Nothing " \n" lookupCompletions } lookupCompletions :: String -> Runner [Repl.Completion] lookupCompletions string = do (State _ imports types defs _) <- RWS.get return $ addMatches string False defs $ addMatches string False types $ addMatches string True imports $ addMatches string False commands [] commands :: Map.Map N.Name () commands = Map.fromList [ (":exit", ()), (":quit", ()), (":reset", ()), (":help", ()) ] addMatches :: String -> Bool -> Map.Map N.Name v -> [Repl.Completion] -> [Repl.Completion] addMatches string isFinished dict completions = Map.foldrWithKey (addMatch string isFinished) completions dict addMatch :: String -> Bool -> N.Name -> v -> [Repl.Completion] -> [Repl.Completion] addMatch string isFinished name _ completions = let suggestion = N.toString name in if List.isPrefixOf string suggestion then Repl.Completion (drop (length string) suggestion) suggestion isFinished : completions else completions -- WELCOME welcomeMessage :: String welcomeMessage = let starter = "---- Elm " ++ elmVersion ++ " " in starter ++ replicate (80 - length starter) '-' ++ "\n" ++ " :help for help, :exit to exit, more at <https://github.com/elm-lang/elm-repl>\n" ++ "--------------------------------------------------------------------------------" elmVersion :: String elmVersion = Pkg.versionToString Elm.version -- HELP MESSAGES helpMessage :: Maybe String -> String helpMessage maybeBadCommand = case maybeBadCommand of Nothing -> genericHelpMessage Just command -> "I do not recognize the :" ++ command ++ " command. " ++ genericHelpMessage genericHelpMessage :: String genericHelpMessage = "Valid commands include:\n\ \\n\ \ :exit Exit the REPL\n\ \ :help Show this information\n\ \ :reset Clear all previous imports and definitions\n\ \\n\ \More info at <https://github.com/elm-lang/elm/blob/" ++ elmVersion ++ "/help/repl.md>\n" -- GET INTERPRETER getInterpreter :: Maybe String -> IO FilePath getInterpreter maybeName = case maybeName of Just name -> getInterpreterHelp name (Dir.findExecutable name) Nothing -> getInterpreterHelp "node` or `nodejs" $ do exe1 <- Dir.findExecutable "node" exe2 <- Dir.findExecutable "nodejs" return (exe1 <|> exe2) getInterpreterHelp :: String -> IO (Maybe FilePath) -> IO FilePath getInterpreterHelp name findExe = do maybePath <- findExe case maybePath of Just path -> return path Nothing -> do IO.hPutStrLn IO.stderr (exeNotFound name) Exit.exitFailure exeNotFound :: String -> String exeNotFound name = "The REPL relies on node.js to execute JavaScript code outside the browser.\n" ++ "I could not find executable `" ++ name ++ "` on your PATH though!\n\n" ++ "You can install node.js from <http://nodejs.org/>. If it is already installed\n" ++ "but has a different name, use the --interpreter flag."
evancz/cli
src/Repl.hs
bsd-3-clause
9,658
0
18
2,469
2,798
1,439
1,359
248
11
module Cauterize.ErlangRef.Options ( runWithOptions , ErlangOpts(..) ) where import Options.Applicative runWithOptions :: (ErlangOpts -> IO ()) -> IO () runWithOptions fn = execParser options >>= fn data ErlangOpts = ErlangOpts { specFile :: FilePath , outputDirectory :: FilePath } deriving (Show) options :: ParserInfo ErlangOpts options = info (optParser <**> helper) ( fullDesc <> progDesc "Process Cauterize schema files." ) optParser :: Parser ErlangOpts optParser = ErlangOpts <$> strOption ( long "spec" <> short 's' <> metavar "FILE_PATH" <> help "Input Cauterize specification file." ) <*> strOption ( long "output" <> short 'o' <> metavar "DIRECTORY_PATH" <> help "Output Cauterize directory." )
cauterize-tools/caut-erl-ref
app/Cauterize/ErlangRef/Options.hs
bsd-3-clause
797
0
12
192
209
108
101
26
1
module Main where import Control.Exception (try, SomeException) import System.Environment (getArgs) import Network.HTTP.Conduit as C import Network.HTTP.Types as C main = do url <- (!! 0) `fmap` getArgs eresp <- try (loadWebsite url) case eresp of Left e -> putStrLn ("Falsch: " ++ show (e :: SomeException)) Right r -> putStrLn ("All Cool: " ++ r) loadWebsite :: String -> IO String loadWebsite rawUrl = do resp <- C.withManager $ \m -> C.parseUrl rawUrl >>= flip C.httpLbs m >>= \t -> return ( show (C.responseHeaders t)) return (show resp)
rethab/tagger
src/Tagger/Conduit.hs
bsd-3-clause
651
0
17
196
227
119
108
16
2
{-# LINE 1 "System.Posix.Types.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , NoImplicitPrelude , MagicHash , GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : System.Posix.Types -- Copyright : (c) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : non-portable (requires POSIX) -- -- POSIX data types: Haskell equivalents of the types defined by the -- @\<sys\/types.h>@ C header on a POSIX system. -- ----------------------------------------------------------------------------- module System.Posix.Types ( -- * POSIX data types -- ** Platform differences -- | This module contains platform specific information about types. -- __/As such the types presented on this page reflect the platform -- on which the documentation was generated and may not coincide with -- the types on your platform./__ CDev(..), CIno(..), CMode(..), COff(..), CPid(..), CSsize(..), CGid(..), CNlink(..), CUid(..), CCc(..), CSpeed(..), CTcflag(..), CRLim(..), Fd(..), LinkCount, UserID, GroupID, ByteCount, ClockTick, EpochTime, FileOffset, ProcessID, ProcessGroupID, DeviceID, FileID, FileMode, Limit ) where import Foreign import Foreign.C -- import Data.Bits import GHC.Base import GHC.Enum import GHC.Num import GHC.Real -- import GHC.Prim import GHC.Read import GHC.Show {- -------------------------------------------------------------------------- // Dirty CPP hackery for CTypes/CTypesISO // // (c) The FFI task force, 2000 // -------------------------------------------------------------------------- -} {- // As long as there is no automatic derivation of classes for newtypes we resort // to extremely dirty cpp-hackery. :-P Some care has to be taken when the // macros below are modified, otherwise the layout rule will bite you. -} -- // GHC can derive any class for a newtype, so we make use of that here... newtype CDev = CDev Word64 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CDev where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word64); readList = unsafeCoerce# (readList :: ReadS [Word64]); }; instance Show CDev where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word64 -> ShowS); show = unsafeCoerce# (show :: Word64 -> String); showList = unsafeCoerce# (showList :: [Word64] -> ShowS); }; newtype CIno = CIno Word64 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CIno where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word64); readList = unsafeCoerce# (readList :: ReadS [Word64]); }; instance Show CIno where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word64 -> ShowS); show = unsafeCoerce# (show :: Word64 -> String); showList = unsafeCoerce# (showList :: [Word64] -> ShowS); }; newtype {-# CTYPE "mode_t" #-} CMode = CMode Word32 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CMode where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word32); readList = unsafeCoerce# (readList :: ReadS [Word32]); }; instance Show CMode where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word32 -> ShowS); show = unsafeCoerce# (show :: Word32 -> String); showList = unsafeCoerce# (showList :: [Word32] -> ShowS); }; newtype COff = COff Int64 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read COff where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Int64); readList = unsafeCoerce# (readList :: ReadS [Int64]); }; instance Show COff where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Int64 -> ShowS); show = unsafeCoerce# (show :: Int64 -> String); showList = unsafeCoerce# (showList :: [Int64] -> ShowS); }; newtype CPid = CPid Int32 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CPid where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Int32); readList = unsafeCoerce# (readList :: ReadS [Int32]); }; instance Show CPid where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Int32 -> ShowS); show = unsafeCoerce# (show :: Int32 -> String); showList = unsafeCoerce# (showList :: [Int32] -> ShowS); }; newtype CSsize = CSsize Int64 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CSsize where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Int64); readList = unsafeCoerce# (readList :: ReadS [Int64]); }; instance Show CSsize where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Int64 -> ShowS); show = unsafeCoerce# (show :: Int64 -> String); showList = unsafeCoerce# (showList :: [Int64] -> ShowS); }; newtype CGid = CGid Word32 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CGid where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word32); readList = unsafeCoerce# (readList :: ReadS [Word32]); }; instance Show CGid where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word32 -> ShowS); show = unsafeCoerce# (show :: Word32 -> String); showList = unsafeCoerce# (showList :: [Word32] -> ShowS); }; newtype CNlink = CNlink Word64 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CNlink where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word64); readList = unsafeCoerce# (readList :: ReadS [Word64]); }; instance Show CNlink where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word64 -> ShowS); show = unsafeCoerce# (show :: Word64 -> String); showList = unsafeCoerce# (showList :: [Word64] -> ShowS); }; newtype CUid = CUid Word32 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CUid where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word32); readList = unsafeCoerce# (readList :: ReadS [Word32]); }; instance Show CUid where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word32 -> ShowS); show = unsafeCoerce# (show :: Word32 -> String); showList = unsafeCoerce# (showList :: [Word32] -> ShowS); }; newtype CCc = CCc Word8 deriving (Eq,Ord,Num,Enum,Storable,Real); instance Read CCc where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word8); readList = unsafeCoerce# (readList :: ReadS [Word8]); }; instance Show CCc where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word8 -> ShowS); show = unsafeCoerce# (show :: Word8 -> String); showList = unsafeCoerce# (showList :: [Word8] -> ShowS); }; newtype CSpeed = CSpeed Word32 deriving (Eq,Ord,Num,Enum,Storable,Real); instance Read CSpeed where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word32); readList = unsafeCoerce# (readList :: ReadS [Word32]); }; instance Show CSpeed where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word32 -> ShowS); show = unsafeCoerce# (show :: Word32 -> String); showList = unsafeCoerce# (showList :: [Word32] -> ShowS); }; newtype CTcflag = CTcflag Word32 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CTcflag where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word32); readList = unsafeCoerce# (readList :: ReadS [Word32]); }; instance Show CTcflag where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word32 -> ShowS); show = unsafeCoerce# (show :: Word32 -> String); showList = unsafeCoerce# (showList :: [Word32] -> ShowS); }; newtype CRLim = CRLim Word64 deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read CRLim where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS Word64); readList = unsafeCoerce# (readList :: ReadS [Word64]); }; instance Show CRLim where { showsPrec = unsafeCoerce# (showsPrec :: Int -> Word64 -> ShowS); show = unsafeCoerce# (show :: Word64 -> String); showList = unsafeCoerce# (showList :: [Word64] -> ShowS); }; -- ToDo: blksize_t, clockid_t, blkcnt_t, fsblkcnt_t, fsfilcnt_t, id_t, key_t -- suseconds_t, timer_t, useconds_t -- Make an Fd type rather than using CInt everywhere newtype Fd = Fd CInt deriving (Eq,Ord,Num,Enum,Storable,Real, Bounded,Integral,Bits,FiniteBits); instance Read Fd where { readsPrec = unsafeCoerce# (readsPrec :: Int -> ReadS CInt); readList = unsafeCoerce# (readList :: ReadS [CInt]); }; instance Show Fd where { showsPrec = unsafeCoerce# (showsPrec :: Int -> CInt -> ShowS); show = unsafeCoerce# (show :: CInt -> String); showList = unsafeCoerce# (showList :: [CInt] -> ShowS); }; -- nicer names, and backwards compatibility with POSIX library: type LinkCount = CNlink type UserID = CUid type GroupID = CGid type ByteCount = CSize type ClockTick = CClock type EpochTime = CTime type DeviceID = CDev type FileID = CIno type FileMode = CMode type ProcessID = CPid type FileOffset = COff type ProcessGroupID = CPid type Limit = CLong
phischu/fragnix
builtins/base/System.Posix.Types.hs
bsd-3-clause
10,661
0
9
3,040
2,798
1,637
1,161
69
0
{-# LANGUAGE DataKinds, PolyKinds, TypeFamilies, TypeOperators, OverloadedStrings #-} module Database.Edis.Command.ZSet where import Database.Edis.Type import Database.Edis.Helper import Data.Proxy (Proxy) import Data.Serialize (Serialize, encode) import Data.Type.Bool import Database.Redis as Redis hiding (decode) import GHC.TypeLits -------------------------------------------------------------------------------- -- Sorted Sets -------------------------------------------------------------------------------- zadd :: (KnownSymbol s, Serialize x, ZSetOrNX xs s) => Proxy s -> Double -> x -> Edis xs (If (Member xs s) xs (Set xs s (ZSetOf x))) (Either Reply Integer) zadd key score val = Edis $ Redis.zadd (encodeKey key) [(score, encode val)] zcard :: (KnownSymbol s, SetOrNX xs s) => Proxy s -> Edis xs xs (Either Reply Integer) zcard key = Edis $ Redis.zcard (encodeKey key) zcount :: (KnownSymbol s, SetOrNX xs s) => Proxy s -> Double -> Double -> Edis xs xs (Either Reply Integer) zcount key min' max' = Edis $ Redis.zcount (encodeKey key) min' max' zincrby :: (KnownSymbol s, Serialize x, ZSetOrNX xs s) => Proxy s -> Integer -> x -> Edis xs (If (Member xs s) xs (Set xs s (ZSetOf x))) (Either Reply Double) zincrby key score val = Edis $ Redis.zincrby (encodeKey key) score (encode val) zrange :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Integer -> Integer -> Edis xs xs (Either Reply [x]) zrange key from to = Edis $ Redis.zrange (encodeKey key) from to >>= decodeAsList zrangeWithscores :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Integer -> Integer -> Edis xs xs (Either Reply [(x, Double)]) zrangeWithscores key from to = Edis $ Redis.zrangeWithscores (encodeKey key) from to >>= decodeAsListWithScores zrangebyscore :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Edis xs xs (Either Reply [x]) zrangebyscore key min' max' = Edis $ Redis.zrangebyscore (encodeKey key) min' max' >>= decodeAsList zrangebyscoreWithscores :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Edis xs xs (Either Reply [(x, Double)]) zrangebyscoreWithscores key min' max' = Edis $ Redis.zrangebyscoreWithscores (encodeKey key) min' max' >>= decodeAsListWithScores zrangebyscoreLimit :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Integer -> Integer -> Edis xs xs (Either Reply [x]) zrangebyscoreLimit key min' max' offset count = Edis $ Redis.zrangebyscoreLimit (encodeKey key) min' max' offset count >>= decodeAsList zrangebyscoreWithscoresLimit :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Integer -> Integer -> Edis xs xs (Either Reply [(x, Double)]) zrangebyscoreWithscoresLimit key min' max' offset count = Edis $ Redis.zrangebyscoreWithscoresLimit (encodeKey key) min' max' offset count >>= decodeAsListWithScores zrank :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> x -> Edis xs xs (Either Reply (Maybe Integer)) zrank key val = Edis $ Redis.zrank (encodeKey key) (encode val) zremrangebyrank :: (KnownSymbol s, ZSetOrNX xs s) => Proxy s -> Integer -> Integer -> Edis xs xs (Either Reply Integer) zremrangebyrank key from to = Edis $ Redis.zremrangebyrank (encodeKey key) from to zremrangebyscore :: (KnownSymbol s, ZSetOrNX xs s) => Proxy s -> Double -> Double -> Edis xs xs (Either Reply Integer) zremrangebyscore key min' max' = Edis $ Redis.zremrangebyscore (encodeKey key) min' max' zrevrange :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Integer -> Integer -> Edis xs xs (Either Reply [x]) zrevrange key from to = Edis $ Redis.zrevrange (encodeKey key) from to >>= decodeAsList zrevrangeWithscores :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Integer -> Integer -> Edis xs xs (Either Reply [(x, Double)]) zrevrangeWithscores key from to = Edis $ Redis.zrevrangeWithscores (encodeKey key) from to >>= decodeAsListWithScores zrevrangebyscore :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Edis xs xs (Either Reply [x]) zrevrangebyscore key min' max' = Edis $ Redis.zrevrangebyscore (encodeKey key) min' max' >>= decodeAsList zrevrangebyscoreWithscores :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Edis xs xs (Either Reply [(x, Double)]) zrevrangebyscoreWithscores key min' max' = Edis $ Redis.zrevrangebyscoreWithscores (encodeKey key) min' max' >>= decodeAsListWithScores zrevrangebyscoreLimit :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Integer -> Integer -> Edis xs xs (Either Reply [x]) zrevrangebyscoreLimit key min' max' offset count = Edis $ Redis.zrevrangebyscoreLimit (encodeKey key) min' max' offset count >>= decodeAsList zrevrangebyscoreWithscoresLimit :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> Double -> Double -> Integer -> Integer -> Edis xs xs (Either Reply [(x, Double)]) zrevrangebyscoreWithscoresLimit key min' max' offset count = Edis $ Redis.zrevrangebyscoreWithscoresLimit (encodeKey key) min' max' offset count >>= decodeAsListWithScores zrevrank :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> x -> Edis xs xs (Either Reply (Maybe Integer)) zrevrank key val = Edis $ Redis.zrevrank (encodeKey key) (encode val) zscore :: (KnownSymbol s, Serialize x , 'Just (ZSetOf x) ~ Get xs s) => Proxy s -> x -> Edis xs xs (Either Reply (Maybe Double)) zscore key val = Edis $ Redis.zscore (encodeKey key) (encode val)
banacorn/tredis
src/Database/Edis/Command/ZSet.hs
mit
6,239
0
15
1,454
2,420
1,210
1,210
118
1
{-# LANGUAGE DeriveDataTypeable #-} {- Abstract syntax for Events -} module EVT.AS ( EVTQualId (..) , Sentence , ACTION (..) , GUARD (..) , EVENT (..) , MACHINE (..) , EVENT_NAME --, mapQualId --, getSignature ) where import Data.Data import Common.Id import CASL.AS_Basic_CASL import CASL.ATC_CASL () -- DrIFT command {-! global: GetRange !-} type GUARD_NAME = Id type ACTION_NAME = Id type EVENT_NAME = Id -- | Machines are sets of events. data MACHINE = MACHINE [EVENT] --Range deriving (Show, Eq, Ord, Typeable, Data) data EVENT = EVENT { name :: EVENT_NAME , guards :: [GUARD] , actions :: [ACTION] } deriving (Show, Eq, Ord, Typeable, Data) data GUARD = GUARD { gnum :: GUARD_NAME , predicate :: (FORMULA ()) } deriving (Show, Eq, Ord, Typeable, Data) data ACTION = ACTION { anum :: ACTION_NAME , statement :: (FORMULA ()) } deriving (Show, Eq, Ord, Typeable, Data) data EVTQualId = EVTQualId { eventid :: Id } deriving (Eq, Ord, Show, Typeable, Data) -- Sentences are machines type Sentence = EVENT {- map_qualId :: EVTMorphism -> EVTQualId -> Result EVTQualId map_qualId mor qid = let (eid, rid, rn) = case qid of EVTQualId i1 i2 rn1 -> (i1, i2, rn1) return $ EVTQualId mtid mrid rn -} {- ^ oo-style getter function for signatures getSignature :: RSScheme -> EVTEvents getSignature spec = case spec of RSScheme tb _ _ -> tb-} -- Generated by DrIFT, look but don't touch! instance GetRange MACHINE where getRange = const nullRange rangeSpan x = case x of MACHINE a -> joinRanges [rangeSpan a] instance GetRange EVENT where getRange = const nullRange rangeSpan x = case x of EVENT a b c -> joinRanges [rangeSpan a, rangeSpan b, rangeSpan c] instance GetRange GUARD where getRange = const nullRange rangeSpan x = case x of GUARD a b -> joinRanges [rangeSpan a, rangeSpan b] instance GetRange ACTION where getRange = const nullRange rangeSpan x = case x of ACTION a b -> joinRanges [rangeSpan a, rangeSpan b] instance GetRange EVTQualId where getRange = const nullRange rangeSpan x = case x of EVTQualId a -> joinRanges [rangeSpan a]
keithodulaigh/Hets
EVT/AS.hs
gpl-2.0
2,753
0
11
1,065
603
333
270
55
0
{-# LANGUAGE DeriveDataTypeable #-} -- | -- Module : Args -- Copyright : [2011] The Accelerate Team -- License : BSD3 -- -- Maintainer : Trevor L. McDonell <tmcdonell@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-partable (GHC extensions) -- module Args where import Data.Version import Paths_accelerate_buildbot import System.Console.CmdArgs data Args = Args { accelerate_repo :: String , daily_at :: Maybe String , with_ghc :: String , output :: Maybe FilePath , with_timestamp :: Bool , upload_to :: Maybe String , compare_to :: Maybe FilePath , compare_swing :: Maybe Double , mail_from :: Maybe String , mail_to :: [String] , mail_fail_to :: [String] , mail_banner :: Maybe FilePath , history :: Maybe FilePath , send_test_email :: Bool } deriving (Show, Data, Typeable) defaultArgs :: Args defaultArgs = Args { accelerate_repo = "http://code.haskell.org/accelerate" &= name "r" &= help "The Accelerate repository to test" &= typ "DARCS_PATH" , with_ghc = "ghc" &= name "w" &= help "Give path to a particular compiler" &= typ "PATH" , daily_at = def &= name "a" &= help "Run every day at this time, else once now" &= typ "HH:MM:SS" , output = def &= help "Write results to this file" &= typFile , with_timestamp = def &= name "t" &= help "Append time stamp to result files" , upload_to = def &= help "Upload result files to this address" &= typ "SCP_PATH" , compare_to = def &= name "c" &= help "Compare to results in this file" &= typFile , compare_swing = def &= name "s" &= help "Treat this fractional swing as interesting" &= typ "DOUBLE" , mail_from = def &= help "Send test results from this address" &= typ "ADDRESS" , mail_to = def &= help "Send test results to this address" &= typ "ADDRESS" , mail_fail_to = def &= help "Send failure notifications to this address" &= typ "ADDRESS" , mail_banner = def &= help "Append a banner to the result email" &= typFile , history = def &= explicit &= name "history" &= help "Where to stash the buildbot history" &= typFile , send_test_email = def &= help "Test the mailer configuration" } &= program "accelerate-buildbot" &= summary "accelerate-buildbot (c) 2011 The Accelerate Team" &= versionArg [summary $ "accelerate-buildbot-" ++ showVersion version] &= verbosityArgs [help "Verbose logging of build commands"] [ignore]
wilbowma/accelerate
accelerate-buildbot/src/Args.hs
bsd-3-clause
2,848
0
14
929
538
288
250
89
1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Network/Wai/Handler/Warp/Conduit.hs" #-} {-# LANGUAGE CPP #-} module Network.Wai.Handler.Warp.Conduit where import Control.Exception import Control.Monad (when, unless) import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.IORef as I import Data.Word (Word8) import Network.Wai.Handler.Warp.Types ---------------------------------------------------------------- -- | Contains a @Source@ and a byte count that is still to be read in. data ISource = ISource !Source !(I.IORef Int) mkISource :: Source -> Int -> IO ISource mkISource src cnt = do ref <- I.newIORef cnt return $! ISource src ref -- | Given an @IsolatedBSSource@ provide a @Source@ that only allows up to the -- specified number of bytes to be passed downstream. All leftovers should be -- retained within the @Source@. If there are not enough bytes available, -- throws a @ConnectionClosedByPeer@ exception. readISource :: ISource -> IO ByteString readISource (ISource src ref) = do count <- I.readIORef ref if count == 0 then return S.empty else do bs <- readSource src -- If no chunk available, then there aren't enough bytes in the -- stream. Throw a ConnectionClosedByPeer when (S.null bs) $ throwIO ConnectionClosedByPeer let -- How many of the bytes in this chunk to send downstream toSend = min count (S.length bs) -- How many bytes will still remain to be sent downstream count' = count - toSend case () of () -- The expected count is greater than the size of the -- chunk we just read. Send the entire chunk -- downstream, and then loop on this function for the -- next chunk. | count' > 0 -> do I.writeIORef ref count' return bs -- Some of the bytes in this chunk should not be sent -- downstream. Split up the chunk into the sent and -- not-sent parts, add the not-sent parts onto the new -- source, and send the rest of the chunk downstream. | otherwise -> do let (x, y) = S.splitAt toSend bs leftoverSource src y assert (count' == 0) $ I.writeIORef ref count' return x ---------------------------------------------------------------- data CSource = CSource !Source !(I.IORef ChunkState) data ChunkState = NeedLen | NeedLenNewline | HaveLen Word | DoneChunking deriving Show mkCSource :: Source -> IO CSource mkCSource src = do ref <- I.newIORef NeedLen return $! CSource src ref readCSource :: CSource -> IO ByteString readCSource (CSource src ref) = do mlen <- I.readIORef ref go mlen where withLen 0 bs = do leftoverSource src bs dropCRLF yield' S.empty DoneChunking withLen len bs | S.null bs = do -- FIXME should this throw an exception if len > 0? I.writeIORef ref DoneChunking return S.empty | otherwise = case S.length bs `compare` fromIntegral len of EQ -> yield' bs NeedLenNewline LT -> yield' bs $ HaveLen $ len - fromIntegral (S.length bs) GT -> do let (x, y) = S.splitAt (fromIntegral len) bs leftoverSource src y yield' x NeedLenNewline yield' bs mlen = do I.writeIORef ref mlen return bs dropCRLF = do bs <- readSource src case S.uncons bs of Nothing -> return () Just (13, bs') -> dropLF bs' Just (10, bs') -> leftoverSource src bs' Just _ -> leftoverSource src bs dropLF bs = case S.uncons bs of Nothing -> do bs2 <- readSource' src unless (S.null bs2) $ dropLF bs2 Just (10, bs') -> leftoverSource src bs' Just _ -> leftoverSource src bs go NeedLen = getLen go NeedLenNewline = dropCRLF >> getLen go (HaveLen 0) = do -- Drop the final CRLF dropCRLF I.writeIORef ref DoneChunking return S.empty go (HaveLen len) = do bs <- readSource src withLen len bs go DoneChunking = return S.empty -- Get the length from the source, and then pass off control to withLen getLen = do bs <- readSource src if S.null bs then do I.writeIORef ref $ assert False $ HaveLen 0 return S.empty else do (x, y) <- case S.break (== 10) bs of (x, y) | S.null y -> do bs2 <- readSource' src return $ if S.null bs2 then (x, y) else S.break (== 10) $ bs `S.append` bs2 | otherwise -> return (x, y) let w = S.foldl' (\i c -> i * 16 + fromIntegral (hexToWord c)) 0 $ S.takeWhile isHexDigit x let y' = S.drop 1 y y'' <- if S.null y' then readSource src else return y' withLen w y'' hexToWord w | w < 58 = w - 48 | w < 71 = w - 55 | otherwise = w - 87 isHexDigit :: Word8 -> Bool isHexDigit w = w >= 48 && w <= 57 || w >= 65 && w <= 70 || w >= 97 && w <= 102
phischu/fragnix
tests/packages/scotty/Network.Wai.Handler.Warp.Conduit.hs
bsd-3-clause
5,920
26
23
2,387
1,330
665
665
135
16
{-# OPTIONS_GHC -fno-warn-type-defaults #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Triplet (isPythagorean, mkTriplet, pythagoreanTriplets) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = do describe "isPythagorean" $ for_ isPythagoreanCases isPythagoreanTest describe "pythagoreanTriplets" $ for_ pythagoreanTripletsCases pythagoreanTripletsTest where isPythagoreanTest ((a, b, c), expected) = it description assertion where description = unwords $ show <$> [a, b, c] assertion = isPythagorean (mkTriplet a b c) `shouldBe` expected pythagoreanTripletsTest (x, y, ts) = it description assertion where description = unwords $ show <$> [x, y] assertion = pythagoreanTriplets x y `shouldBe` uncurry3 mkTriplet <$> ts uncurry3 f (x, y, z) = f x y z isPythagoreanCases = [ ( (3, 4, 5), True ) , ( (3, 5, 4), True ) , ( (4, 3, 5), True ) , ( (4, 5, 3), True ) , ( (5, 3, 4), True ) , ( (5, 4, 3), True ) , ( (3, 3, 3), False) , ( (5, 6, 7), False) ] pythagoreanTripletsCases = [ (1 , 10, [ ( 3, 4, 5), ( 6, 8, 10) ]) , (11, 20, [ (12, 16, 20) ]) , (56, 95, [ (57, 76, 95), (60, 63, 87) ]) ]
c19/Exercism-Haskell
pythagorean-triplet/test/Tests.hs
mit
1,622
3
9
588
564
333
231
29
1
{-# language NamedFieldPuns, DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable #-} module Base.Grounds where import Safe import Data.Indexable as I import Data.Data import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Data.Initial import Data.Accessor import Graphics.Qt import Utils -- | Multiple backgrounds, one main Layer, multiple foregrounds -- if backgrounds (or foregrounds) have zero distance to the main layer, -- the don't move wrt the main layer, but are rendered before (after) -- the main layer. data Grounds a = Grounds { backgrounds_ :: Indexable (Layer a), mainLayer_ :: Layer a, foregrounds_ :: Indexable (Layer a) } deriving (Show, Read, Data, Typeable, Functor, Foldable, Traversable) backgrounds, foregrounds :: Accessor (Grounds a) (Indexable (Layer a)) backgrounds = accessor backgrounds_ (\ a r -> r{backgrounds_ = a}) foregrounds = accessor foregrounds_ (\ a r -> r{foregrounds_ = a}) mainLayer :: Accessor (Grounds a) (Layer a) mainLayer = accessor mainLayer_ (\ a r -> r{mainLayer_ = a}) -- | one group of objects, positioned relatively to each other. -- to be refined data Layer a = Layer { content_ :: (Indexable a), xDistance :: Double, yDistance :: Double } deriving (Show, Read, Data, Typeable, Functor, Foldable, Traversable) content :: Accessor (Layer a) (Indexable a) content = accessor content_ (\ a r -> r{content_ = a}) -- | Index for selecting one (Layer a) from a (Grounds a) data GroundsIndex = Backgrounds Index | MainLayer | Foregrounds Index deriving Show -- useful instances instance Initial (Grounds a) where initial = Grounds initial initial initial instance Initial (Layer a) where initial = Layer initial 1 1 -- * construction mkMainLayer :: Indexable a -> Layer a mkMainLayer c = content ^= c $ initial -- * discriminators isGroundsIndexOf :: GroundsIndex -> Grounds a -> Bool isGroundsIndexOf MainLayer _ = True isGroundsIndexOf (Backgrounds i) gs = isIndexOf i (gs ^. backgrounds) isGroundsIndexOf (Foregrounds i) gs = isIndexOf i (gs ^. foregrounds) -- * getter mainLayerIndexable :: Grounds a -> Indexable a mainLayerIndexable = (^. mainLayer .> content) -- | access the indexed Layer layerA :: GroundsIndex -> Accessor (Grounds a) (Layer a) layerA (Backgrounds i) = backgrounds .> indexA i layerA MainLayer = mainLayer layerA (Foregrounds i) = foregrounds .> indexA i -- | returns the number of contained Layers -- PRE: isNormalized numberOfLayers :: Grounds a -> Int numberOfLayers (Grounds backgrounds _ foregrounds) = fromIntegral (I.length backgrounds + 1 + I.length foregrounds) -- | returns all Layers below the selected (excluding the selected) belowSelected :: GroundsIndex -> Grounds a -> [Layer a] belowSelected index grounds = let bgs = grounds ^. backgrounds ml = grounds ^. mainLayer fgs = grounds ^. foregrounds in case index of Backgrounds i -> beforeIndex i bgs MainLayer -> I.toList bgs Foregrounds i -> I.toList bgs ++ [ml] ++ I.toList (beforeIndex i fgs) -- | Returns a textual representation of the indexed layer and its -- place in the Grounds-value, including the render number (which is not the -- same as the index). describeLayer :: Grounds a -> GroundsIndex -> String describeLayer (Grounds bgs ml fgs) gi = case gi of Backgrounds i -> "background " ++ show (succ $ indexableNumber bgs i) MainLayer -> "mainlayer" Foregrounds i -> "foreground " ++ show (succ $ indexableNumber fgs i) -- * setter setXDistance :: Double -> Layer a -> Layer a setXDistance x l = l{xDistance = x} setYDistance :: Double -> Layer a -> Layer a setYDistance y l = l{yDistance = y} -- * modifications -- | returns an index referring to the next element nextGroundsIndex :: Grounds a -> GroundsIndex -> GroundsIndex nextGroundsIndex gs i = case i of Backgrounds i -> maybe MainLayer Backgrounds (nextIndex (gs ^. backgrounds) i) MainLayer -> firstForegroundsIndex Foregrounds i -> maybe firstBackgroundsIndex Foregrounds (nextIndex (gs ^. foregrounds) i) where firstForegroundsIndex = case keys (gs ^. foregrounds) of (a : _) -> Foregrounds a [] -> firstBackgroundsIndex firstBackgroundsIndex = case keys (gs ^. backgrounds) of (a : _) -> Backgrounds a [] -> MainLayer previousGroundsIndex :: Grounds a -> GroundsIndex -> GroundsIndex previousGroundsIndex gs i = case i of Backgrounds i -> maybe lastForegroundsIndex Backgrounds (previousIndex (gs ^. backgrounds) i) MainLayer -> lastBackgroundsIndex Foregrounds i -> maybe MainLayer Foregrounds (previousIndex (gs ^. foregrounds) i) where lastForegroundsIndex = maybe MainLayer Foregrounds (lastMay $ keys (gs ^. foregrounds)) lastBackgroundsIndex = maybe lastForegroundsIndex Backgrounds (lastMay $ keys (gs ^. backgrounds)) -- | modifies the content of one Layer modifyContent :: (Indexable a -> Indexable b) -> Layer a -> Layer b modifyContent f l@Layer{content_} = l{content_ = f content_} -- * maps layerMap :: (Layer a -> Layer b) -> Grounds a -> Grounds b layerMap f (Grounds backgrounds mainLayer foregrounds) = Grounds (fmap f backgrounds) (f mainLayer) (fmap f foregrounds) layerMapM_ :: Monad m => (Layer a -> m b) -> Grounds a -> m () layerMapM_ cmd (Grounds backgrounds mainLayer foregrounds) = do fmapM_ cmd backgrounds _ <- cmd mainLayer fmapM_ cmd foregrounds -- * rendering offset -- | calculates the offset for one Layer. calculateLayerOffset :: Size Double -> Position Double -> (Double, Double) -> Position Double calculateLayerOffset windowSize mainLayerOffset (xDistance, yDistance) = Position xLayerOffset yLayerOffset where xLayerOffset = xMainOffset * xDistance + xWindowOffset * (1 - xDistance) yLayerOffset = yMainOffset * yDistance + yWindowOffset * (1 - yDistance) (Position xMainOffset yMainOffset) = mainLayerOffset (Size width height) = windowSize xWindowOffset = width / 2 yWindowOffset = height / 2 -- | modify the distances of the second given Layer as if the first was the mainLayer correctDistances :: Layer a -> Layer b -> Layer b correctDistances pretendMain l@Layer{xDistance = oldX, yDistance = oldY} = l{ xDistance = inner (xDistance pretendMain) oldX, yDistance = inner (yDistance pretendMain) oldY } where inner 0 _ = 1 inner pretend old = old / pretend
changlinli/nikki
src/Base/Grounds.hs
lgpl-3.0
6,494
0
13
1,300
1,905
987
918
117
5
module Main where import Data.List import Language.C import Language.C.Analysis.AstAnalysis import Language.C.Analysis.TravMonad import Language.C.System.GCC import System.Console.GetOpt import System.Environment import System.Exit import System.IO processFile :: CLanguage -> [String] -> FilePath -> IO () processFile lang cppOpts file = do hPutStr stderr $ file ++ ": " result <- parseCFile (newGCC "gcc") Nothing cppOpts file case result of Left err -> hPutStrLn stderr ('\n' : show err) Right tu -> case runTrav_ (body tu) of Left errs -> hPutStrLn stderr ('\n' : concatMap show errs) Right _ -> hPutStrLn stderr "success" where body tu = do modifyOptions (\opts -> opts { language = lang }) analyseAST tu main :: IO () main = do args <- getArgs let (cppOpts, files) = partition (isPrefixOf "-") args mapM_ (processFile GNU99 cppOpts) files
llelf/language-c
examples/TypeCheck.hs
bsd-3-clause
953
0
16
235
325
164
161
26
3
----------------------------------------------------------------------------- -- | -- Module : Text.PrettyPrint.Leijen -- Copyright : Daan Leijen (c) 2000, http://www.cs.uu.nl/~daan -- License : BSD-style (see the file LICENSE) -- -- Maintainer : otakar.smrz cmu.edu -- Stability : provisional -- Portability : portable -- -- Pretty print module based on Philip Wadler's \"prettier printer\" -- -- @ -- \"A prettier printer\" -- Draft paper, April 1997, revised March 1998. -- <http://cm.bell-labs.com/cm/cs/who/wadler/papers/prettier/prettier.ps> -- @ -- -- PPrint is an implementation of the pretty printing combinators -- described by Philip Wadler (1997). In their bare essence, the -- combinators of Wadler are not expressive enough to describe some -- commonly occurring layouts. The PPrint library adds new primitives -- to describe these layouts and works well in practice. -- -- The library is based on a single way to concatenate documents, -- which is associative and has both a left and right unit. This -- simple design leads to an efficient and short implementation. The -- simplicity is reflected in the predictable behaviour of the -- combinators which make them easy to use in practice. -- -- A thorough description of the primitive combinators and their -- implementation can be found in Philip Wadler's paper -- (1997). Additions and the main differences with his original paper -- are: -- -- * The nil document is called empty. -- -- * The above combinator is called '<$>'. The operator '</>' is used -- for soft line breaks. -- -- * There are three new primitives: 'align', 'fill' and -- 'fillBreak'. These are very useful in practice. -- -- * Lots of other useful combinators, like 'fillSep' and 'list'. -- -- * There are two renderers, 'renderPretty' for pretty printing and -- 'renderCompact' for compact output. The pretty printing algorithm -- also uses a ribbon-width now for even prettier output. -- -- * There are two displayers, 'displayS' for strings and 'displayIO' for -- file based output. -- -- * There is a 'Pretty' class. -- -- * The implementation uses optimised representations and strictness -- annotations. -- -- Full documentation available at <http://www.cs.uu.nl/~daan/download/pprint/pprint.html>. ----------------------------------------------------------- module Text.PrettyPrint.Leijen ( -- * Documents Doc, putDoc, hPutDoc, -- * Basic combinators empty, char, text, (<>), nest, line, linebreak, group, softline, softbreak, -- * Alignment -- -- The combinators in this section can not be described by Wadler's -- original combinators. They align their output relative to the -- current output position - in contrast to @nest@ which always -- aligns to the current nesting level. This deprives these -- combinators from being \`optimal\'. In practice however they -- prove to be very useful. The combinators in this section should -- be used with care, since they are more expensive than the other -- combinators. For example, @align@ shouldn't be used to pretty -- print all top-level declarations of a language, but using @hang@ -- for let expressions is fine. align, hang, indent, encloseSep, list, tupled, semiBraces, -- * Operators (<+>), (<$>), (</>), (<$$>), (<//>), -- * List combinators hsep, vsep, fillSep, sep, hcat, vcat, fillCat, cat, punctuate, -- * Fillers fill, fillBreak, -- * Bracketing combinators enclose, squotes, dquotes, parens, angles, braces, brackets, -- * Character documents lparen, rparen, langle, rangle, lbrace, rbrace, lbracket, rbracket, squote, dquote, semi, colon, comma, space, dot, backslash, equals, -- * Primitive type documents string, int, integer, float, double, rational, -- * Pretty class Pretty(..), -- * Rendering SimpleDoc(..), renderPretty, renderCompact, displayS, displayIO -- * Undocumented , bool , column, nesting, width ) where import System.IO (Handle,hPutStr,hPutChar,stdout) infixr 5 </>,<//>,<$>,<$$> infixr 6 <>,<+> ----------------------------------------------------------- -- list, tupled and semiBraces pretty print a list of -- documents either horizontally or vertically aligned. ----------------------------------------------------------- -- | The document @(list xs)@ comma separates the documents @xs@ and -- encloses them in square brackets. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All comma separators are put in front of the elements. list :: [Doc] -> Doc list = encloseSep lbracket rbracket comma -- | The document @(tupled xs)@ comma separates the documents @xs@ and -- encloses them in parenthesis. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All comma separators are put in front of the elements. tupled :: [Doc] -> Doc tupled = encloseSep lparen rparen comma -- | The document @(semiBraces xs)@ separates the documents @xs@ with -- semi colons and encloses them in braces. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All semi colons are put in front of the elements. semiBraces :: [Doc] -> Doc semiBraces = encloseSep lbrace rbrace semi -- | The document @(encloseSep l r sep xs)@ concatenates the documents -- @xs@ separated by @sep@ and encloses the resulting document by @l@ -- and @r@. The documents are rendered horizontally if that fits the -- page. Otherwise they are aligned vertically. All separators are put -- in front of the elements. For example, the combinator 'list' can be -- defined with @encloseSep@: -- -- > list xs = encloseSep lbracket rbracket comma xs -- > test = text "list" <+> (list (map int [10,200,3000])) -- -- Which is layed out with a page width of 20 as: -- -- @ -- list [10,200,3000] -- @ -- -- But when the page width is 15, it is layed out as: -- -- @ -- list [10 -- ,200 -- ,3000] -- @ encloseSep :: Doc -> Doc -> Doc -> [Doc] -> Doc encloseSep left right sep ds = case ds of [] -> left <> right [d] -> left <> d <> right _ -> align (cat (zipWith (<>) (left : repeat sep) ds) <> right) ----------------------------------------------------------- -- punctuate p [d1,d2,...,dn] => [d1 <> p,d2 <> p, ... ,dn] ----------------------------------------------------------- -- | @(punctuate p xs)@ concatenates all documents in @xs@ with -- document @p@ except for the last document. -- -- > someText = map text ["words","in","a","tuple"] -- > test = parens (align (cat (punctuate comma someText))) -- -- This is layed out on a page width of 20 as: -- -- @ -- (words,in,a,tuple) -- @ -- -- But when the page width is 15, it is layed out as: -- -- @ -- (words, -- in, -- a, -- tuple) -- @ -- -- (If you want put the commas in front of their elements instead of -- at the end, you should use 'tupled' or, in general, 'encloseSep'.) punctuate :: Doc -> [Doc] -> [Doc] punctuate p [] = [] punctuate p [d] = [d] punctuate p (d:ds) = (d <> p) : punctuate p ds ----------------------------------------------------------- -- high-level combinators ----------------------------------------------------------- -- | The document @(sep xs)@ concatenates all documents @xs@ either -- horizontally with @(\<+\>)@, if it fits the page, or vertically with -- @(\<$\>)@. -- -- > sep xs = group (vsep xs) sep :: [Doc] -> Doc sep = group . vsep -- | The document @(fillSep xs)@ concatenates documents @xs@ -- horizontally with @(\<+\>)@ as long as its fits the page, than -- inserts a @line@ and continues doing that for all documents in -- @xs@. -- -- > fillSep xs = foldr (\<\/\>) empty xs fillSep :: [Doc] -> Doc fillSep = fold (</>) -- | The document @(hsep xs)@ concatenates all documents @xs@ -- horizontally with @(\<+\>)@. hsep :: [Doc] -> Doc hsep = fold (<+>) -- | The document @(vsep xs)@ concatenates all documents @xs@ -- vertically with @(\<$\>)@. If a 'group' undoes the line breaks -- inserted by @vsep@, all documents are separated with a space. -- -- > someText = map text (words ("text to lay out")) -- > -- > test = text "some" <+> vsep someText -- -- This is layed out as: -- -- @ -- some text -- to -- lay -- out -- @ -- -- The 'align' combinator can be used to align the documents under -- their first element -- -- > test = text "some" <+> align (vsep someText) -- -- Which is printed as: -- -- @ -- some text -- to -- lay -- out -- @ vsep :: [Doc] -> Doc vsep = fold (<$>) -- | The document @(cat xs)@ concatenates all documents @xs@ either -- horizontally with @(\<\>)@, if it fits the page, or vertically with -- @(\<$$\>)@. -- -- > cat xs = group (vcat xs) cat :: [Doc] -> Doc cat = group . vcat -- | The document @(fillCat xs)@ concatenates documents @xs@ -- horizontally with @(\<\>)@ as long as its fits the page, than inserts -- a @linebreak@ and continues doing that for all documents in @xs@. -- -- > fillCat xs = foldr (\<\/\/\>) empty xs fillCat :: [Doc] -> Doc fillCat = fold (<//>) -- | The document @(hcat xs)@ concatenates all documents @xs@ -- horizontally with @(\<\>)@. hcat :: [Doc] -> Doc hcat = fold (<>) -- | The document @(vcat xs)@ concatenates all documents @xs@ -- vertically with @(\<$$\>)@. If a 'group' undoes the line breaks -- inserted by @vcat@, all documents are directly concatenated. vcat :: [Doc] -> Doc vcat = fold (<$$>) fold f [] = empty fold f ds = foldr1 f ds -- | The document @(x \<\> y)@ concatenates document @x@ and document -- @y@. It is an associative operation having 'empty' as a left and -- right unit. (infixr 6) (<>) :: Doc -> Doc -> Doc x <> y = x `beside` y -- | The document @(x \<+\> y)@ concatenates document @x@ and @y@ with a -- @space@ in between. (infixr 6) (<+>) :: Doc -> Doc -> Doc x <+> y = x <> space <> y -- | The document @(x \<\/\> y)@ concatenates document @x@ and @y@ with a -- 'softline' in between. This effectively puts @x@ and @y@ either -- next to each other (with a @space@ in between) or underneath each -- other. (infixr 5) (</>) :: Doc -> Doc -> Doc x </> y = x <> softline <> y -- | The document @(x \<\/\/\> y)@ concatenates document @x@ and @y@ with -- a 'softbreak' in between. This effectively puts @x@ and @y@ either -- right next to each other or underneath each other. (infixr 5) (<//>) :: Doc -> Doc -> Doc x <//> y = x <> softbreak <> y -- | The document @(x \<$\> y)@ concatenates document @x@ and @y@ with a -- 'line' in between. (infixr 5) (<$>) :: Doc -> Doc -> Doc x <$> y = x <> line <> y -- | The document @(x \<$$\> y)@ concatenates document @x@ and @y@ with -- a @linebreak@ in between. (infixr 5) (<$$>) :: Doc -> Doc -> Doc x <$$> y = x <> linebreak <> y -- | The document @softline@ behaves like 'space' if the resulting -- output fits the page, otherwise it behaves like 'line'. -- -- > softline = group line softline :: Doc softline = group line -- | The document @softbreak@ behaves like 'empty' if the resulting -- output fits the page, otherwise it behaves like 'line'. -- -- > softbreak = group linebreak softbreak :: Doc softbreak = group linebreak -- | Document @(squotes x)@ encloses document @x@ with single quotes -- \"'\". squotes :: Doc -> Doc squotes = enclose squote squote -- | Document @(dquotes x)@ encloses document @x@ with double quotes -- '\"'. dquotes :: Doc -> Doc dquotes = enclose dquote dquote -- | Document @(braces x)@ encloses document @x@ in braces, \"{\" and -- \"}\". braces :: Doc -> Doc braces = enclose lbrace rbrace -- | Document @(parens x)@ encloses document @x@ in parenthesis, \"(\" -- and \")\". parens :: Doc -> Doc parens = enclose lparen rparen -- | Document @(angles x)@ encloses document @x@ in angles, \"\<\" and -- \"\>\". angles :: Doc -> Doc angles = enclose langle rangle -- | Document @(brackets x)@ encloses document @x@ in square brackets, -- \"[\" and \"]\". brackets :: Doc -> Doc brackets = enclose lbracket rbracket -- | The document @(enclose l r x)@ encloses document @x@ between -- documents @l@ and @r@ using @(\<\>)@. -- -- > enclose l r x = l <> x <> r enclose :: Doc -> Doc -> Doc -> Doc enclose l r x = l <> x <> r -- | The document @lparen@ contains a left parenthesis, \"(\". lparen :: Doc lparen = char '(' -- | The document @rparen@ contains a right parenthesis, \")\". rparen :: Doc rparen = char ')' -- | The document @langle@ contains a left angle, \"\<\". langle :: Doc langle = char '<' -- | The document @rangle@ contains a right angle, \">\". rangle :: Doc rangle = char '>' -- | The document @lbrace@ contains a left brace, \"{\". lbrace :: Doc lbrace = char '{' -- | The document @rbrace@ contains a right brace, \"}\". rbrace :: Doc rbrace = char '}' -- | The document @lbracket@ contains a left square bracket, \"[\". lbracket :: Doc lbracket = char '[' -- | The document @rbracket@ contains a right square bracket, \"]\". rbracket :: Doc rbracket = char ']' -- | The document @squote@ contains a single quote, \"'\". squote :: Doc squote = char '\'' -- | The document @dquote@ contains a double quote, '\"'. dquote :: Doc dquote = char '"' -- | The document @semi@ contains a semi colon, \";\". semi :: Doc semi = char ';' -- | The document @colon@ contains a colon, \":\". colon :: Doc colon = char ':' -- | The document @comma@ contains a comma, \",\". comma :: Doc comma = char ',' -- | The document @space@ contains a single space, \" \". -- -- > x <+> y = x <> space <> y space :: Doc space = char ' ' -- | The document @dot@ contains a single dot, \".\". dot :: Doc dot = char '.' -- | The document @backslash@ contains a back slash, \"\\\". backslash :: Doc backslash = char '\\' -- | The document @equals@ contains an equal sign, \"=\". equals :: Doc equals = char '=' ----------------------------------------------------------- -- Combinators for prelude types ----------------------------------------------------------- -- string is like "text" but replaces '\n' by "line" -- | The document @(string s)@ concatenates all characters in @s@ -- using @line@ for newline characters and @char@ for all other -- characters. It is used instead of 'text' whenever the text contains -- newline characters. string :: String -> Doc string "" = empty string ('\n':s) = line <> string s string s = case (span (/='\n') s) of (xs,ys) -> text xs <> string ys bool :: Bool -> Doc bool b = text (show b) -- | The document @(int i)@ shows the literal integer @i@ using -- 'text'. int :: Int -> Doc int i = text (show i) -- | The document @(integer i)@ shows the literal integer @i@ using -- 'text'. integer :: Integer -> Doc integer i = text (show i) -- | The document @(float f)@ shows the literal float @f@ using -- 'text'. float :: Float -> Doc float f = text (show f) -- | The document @(double d)@ shows the literal double @d@ using -- 'text'. double :: Double -> Doc double d = text (show d) -- | The document @(rational r)@ shows the literal rational @r@ using -- 'text'. rational :: Rational -> Doc rational r = text (show r) ----------------------------------------------------------- -- overloading "pretty" ----------------------------------------------------------- -- | The member @prettyList@ is only used to define the @instance Pretty -- a => Pretty [a]@. In normal circumstances only the @pretty@ function -- is used. class Pretty a where pretty :: a -> Doc prettyList :: [a] -> Doc prettyList = list . map pretty instance Pretty a => Pretty [a] where pretty = prettyList instance Pretty Doc where pretty = id instance Pretty () where pretty () = text "()" instance Pretty Bool where pretty b = bool b instance Pretty Char where pretty c = char c prettyList s = string s instance Pretty Int where pretty i = int i instance Pretty Integer where pretty i = integer i instance Pretty Float where pretty f = float f instance Pretty Double where pretty d = double d --instance Pretty Rational where -- pretty r = rational r instance (Pretty a,Pretty b) => Pretty (a,b) where pretty (x,y) = tupled [pretty x, pretty y] instance (Pretty a,Pretty b,Pretty c) => Pretty (a,b,c) where pretty (x,y,z)= tupled [pretty x, pretty y, pretty z] instance Pretty a => Pretty (Maybe a) where pretty Nothing = empty pretty (Just x) = pretty x ----------------------------------------------------------- -- semi primitive: fill and fillBreak ----------------------------------------------------------- -- | The document @(fillBreak i x)@ first renders document @x@. It -- than appends @space@s until the width is equal to @i@. If the -- width of @x@ is already larger than @i@, the nesting level is -- increased by @i@ and a @line@ is appended. When we redefine @ptype@ -- in the previous example to use @fillBreak@, we get a useful -- variation of the previous output: -- -- > ptype (name,tp) -- > = fillBreak 6 (text name) <+> text "::" <+> text tp -- -- The output will now be: -- -- @ -- let empty :: Doc -- nest :: Int -> Doc -> Doc -- linebreak -- :: Doc -- @ fillBreak :: Int -> Doc -> Doc fillBreak f x = width x (\w -> if (w > f) then nest f linebreak else text (spaces (f - w))) -- | The document @(fill i x)@ renders document @x@. It than appends -- @space@s until the width is equal to @i@. If the width of @x@ is -- already larger, nothing is appended. This combinator is quite -- useful in practice to output a list of bindings. The following -- example demonstrates this. -- -- > types = [("empty","Doc") -- > ,("nest","Int -> Doc -> Doc") -- > ,("linebreak","Doc")] -- > -- > ptype (name,tp) -- > = fill 6 (text name) <+> text "::" <+> text tp -- > -- > test = text "let" <+> align (vcat (map ptype types)) -- -- Which is layed out as: -- -- @ -- let empty :: Doc -- nest :: Int -> Doc -> Doc -- linebreak :: Doc -- @ fill :: Int -> Doc -> Doc fill f d = width d (\w -> if (w >= f) then empty else text (spaces (f - w))) width :: Doc -> (Int -> Doc) -> Doc width d f = column (\k1 -> d <> column (\k2 -> f (k2 - k1))) ----------------------------------------------------------- -- semi primitive: Alignment and indentation ----------------------------------------------------------- -- | The document @(indent i x)@ indents document @x@ with @i@ spaces. -- -- > test = indent 4 (fillSep (map text -- > (words "the indent combinator indents these words !"))) -- -- Which lays out with a page width of 20 as: -- -- @ -- the indent -- combinator -- indents these -- words ! -- @ indent :: Int -> Doc -> Doc indent i d = hang i (text (spaces i) <> d) -- | The hang combinator implements hanging indentation. The document -- @(hang i x)@ renders document @x@ with a nesting level set to the -- current column plus @i@. The following example uses hanging -- indentation for some text: -- -- > test = hang 4 (fillSep (map text -- > (words "the hang combinator indents these words !"))) -- -- Which lays out on a page with a width of 20 characters as: -- -- @ -- the hang combinator -- indents these -- words ! -- @ -- -- The @hang@ combinator is implemented as: -- -- > hang i x = align (nest i x) hang :: Int -> Doc -> Doc hang i d = align (nest i d) -- | The document @(align x)@ renders document @x@ with the nesting -- level set to the current column. It is used for example to -- implement 'hang'. -- -- As an example, we will put a document right above another one, -- regardless of the current nesting level: -- -- > x $$ y = align (x <$> y) -- -- > test = text "hi" <+> (text "nice" $$ text "world") -- -- which will be layed out as: -- -- @ -- hi nice -- world -- @ align :: Doc -> Doc align d = column (\k -> nesting (\i -> nest (k - i) d)) --nesting might be negative :-) ----------------------------------------------------------- -- Primitives ----------------------------------------------------------- -- | The abstract data type @Doc@ represents pretty documents. -- -- @Doc@ is an instance of the 'Show' class. @(show doc)@ pretty -- prints document @doc@ with a page width of 100 characters and a -- ribbon width of 40 characters. -- -- > show (text "hello" <$> text "world") -- -- Which would return the string \"hello\\nworld\", i.e. -- -- @ -- hello -- world -- @ data Doc = Empty | Char Char -- invariant: char is not '\n' | Text !Int String -- invariant: text doesn't contain '\n' | Line !Bool -- True <=> when undone by group, do not insert a space | Cat Doc Doc | Nest !Int Doc | Union Doc Doc -- invariant: first lines of first doc longer than the first lines of the second doc | Column (Int -> Doc) | Nesting (Int -> Doc) -- | The data type @SimpleDoc@ represents rendered documents and is -- used by the display functions. -- -- The @Int@ in @SText@ contains the length of the string. The @Int@ -- in @SLine@ contains the indentation for that line. The library -- provides two default display functions 'displayS' and -- 'displayIO'. You can provide your own display function by writing a -- function from a @SimpleDoc@ to your own output format. data SimpleDoc = SEmpty | SChar Char SimpleDoc | SText !Int String SimpleDoc | SLine !Int SimpleDoc -- | The empty document is, indeed, empty. Although @empty@ has no -- content, it does have a \'height\' of 1 and behaves exactly like -- @(text \"\")@ (and is therefore not a unit of @\<$\>@). empty :: Doc empty = Empty -- | The document @(char c)@ contains the literal character @c@. The -- character shouldn't be a newline (@'\n'@), the function 'line' -- should be used for line breaks. char :: Char -> Doc char '\n' = line char c = Char c -- | The document @(text s)@ contains the literal string @s@. The -- string shouldn't contain any newline (@'\n'@) characters. If the -- string contains newline characters, the function 'string' should be -- used. text :: String -> Doc text "" = Empty text s = Text (length s) s -- | The @line@ document advances to the next line and indents to the -- current nesting level. Document @line@ behaves like @(text \" \")@ -- if the line break is undone by 'group'. line :: Doc line = Line False -- | The @linebreak@ document advances to the next line and indents to -- the current nesting level. Document @linebreak@ behaves like -- 'empty' if the line break is undone by 'group'. linebreak :: Doc linebreak = Line True beside x y = Cat x y -- | The document @(nest i x)@ renders document @x@ with the current -- indentation level increased by i (See also 'hang', 'align' and -- 'indent'). -- -- > nest 2 (text "hello" <$> text "world") <$> text "!" -- -- outputs as: -- -- @ -- hello -- world -- ! -- @ nest :: Int -> Doc -> Doc nest i x = Nest i x column, nesting :: (Int -> Doc) -> Doc column f = Column f nesting f = Nesting f -- | The @group@ combinator is used to specify alternative -- layouts. The document @(group x)@ undoes all line breaks in -- document @x@. The resulting line is added to the current line if -- that fits the page. Otherwise, the document @x@ is rendered without -- any changes. group :: Doc -> Doc group x = Union (flatten x) x flatten :: Doc -> Doc flatten (Cat x y) = Cat (flatten x) (flatten y) flatten (Nest i x) = Nest i (flatten x) flatten (Line break) = if break then Empty else Text 1 " " flatten (Union x y) = flatten x flatten (Column f) = Column (flatten . f) flatten (Nesting f) = Nesting (flatten . f) flatten other = other --Empty,Char,Text ----------------------------------------------------------- -- Renderers ----------------------------------------------------------- ----------------------------------------------------------- -- renderPretty: the default pretty printing algorithm ----------------------------------------------------------- -- list of indentation/document pairs; saves an indirection over [(Int,Doc)] data Docs = Nil | Cons !Int Doc Docs -- | This is the default pretty printer which is used by 'show', -- 'putDoc' and 'hPutDoc'. @(renderPretty ribbonfrac width x)@ renders -- document @x@ with a page width of @width@ and a ribbon width of -- @(ribbonfrac * width)@ characters. The ribbon width is the maximal -- amount of non-indentation characters on a line. The parameter -- @ribbonfrac@ should be between @0.0@ and @1.0@. If it is lower or -- higher, the ribbon width will be 0 or @width@ respectively. renderPretty :: Float -> Int -> Doc -> SimpleDoc renderPretty rfrac w x = best 0 0 (Cons 0 x Nil) where -- r :: the ribbon width in characters r = max 0 (min w (round (fromIntegral w * rfrac))) -- best :: n = indentation of current line -- k = current column -- (ie. (k >= n) && (k - n == count of inserted characters) best n k Nil = SEmpty best n k (Cons i d ds) = case d of Empty -> best n k ds Char c -> let k' = k+1 in seq k' (SChar c (best n k' ds)) Text l s -> let k' = k+l in seq k' (SText l s (best n k' ds)) Line _ -> SLine i (best i i ds) Cat x y -> best n k (Cons i x (Cons i y ds)) Nest j x -> let i' = i+j in seq i' (best n k (Cons i' x ds)) Union x y -> nicest n k (best n k (Cons i x ds)) (best n k (Cons i y ds)) Column f -> best n k (Cons i (f k) ds) Nesting f -> best n k (Cons i (f i) ds) --nicest :: r = ribbon width, w = page width, -- n = indentation of current line, k = current column -- x and y, the (simple) documents to chose from. -- precondition: first lines of x are longer than the first lines of y. nicest n k x y | fits width x = x | otherwise = y where width = min (w - k) (r - k + n) fits w x | w < 0 = False fits w SEmpty = True fits w (SChar c x) = fits (w - 1) x fits w (SText l s x) = fits (w - l) x fits w (SLine i x) = True ----------------------------------------------------------- -- renderCompact: renders documents without indentation -- fast and fewer characters output, good for machines ----------------------------------------------------------- -- | @(renderCompact x)@ renders document @x@ without adding any -- indentation. Since no \'pretty\' printing is involved, this -- renderer is very fast. The resulting output contains fewer -- characters than a pretty printed version and can be used for output -- that is read by other programs. renderCompact :: Doc -> SimpleDoc renderCompact x = scan 0 [x] where scan k [] = SEmpty scan k (d:ds) = case d of Empty -> scan k ds Char c -> let k' = k+1 in seq k' (SChar c (scan k' ds)) Text l s -> let k' = k+l in seq k' (SText l s (scan k' ds)) Line _ -> SLine 0 (scan 0 ds) Cat x y -> scan k (x:y:ds) Nest j x -> scan k (x:ds) Union x y -> scan k (y:ds) Column f -> scan k (f k:ds) Nesting f -> scan k (f 0:ds) ----------------------------------------------------------- -- Displayers: displayS and displayIO ----------------------------------------------------------- -- | @(displayS simpleDoc)@ takes the output @simpleDoc@ from a -- rendering function and transforms it to a 'ShowS' type (for use in -- the 'Show' class). -- -- > showWidth :: Int -> Doc -> String -- > showWidth w x = displayS (renderPretty 0.4 w x) "" displayS :: SimpleDoc -> ShowS displayS SEmpty = id displayS (SChar c x) = showChar c . displayS x displayS (SText l s x) = showString s . displayS x displayS (SLine i x) = showString ('\n':indentation i) . displayS x -- | @(displayIO handle simpleDoc)@ writes @simpleDoc@ to the file -- handle @handle@. This function is used for example by 'hPutDoc': -- -- > hPutDoc handle doc = displayIO handle (renderPretty 0.4 100 doc) displayIO :: Handle -> SimpleDoc -> IO () displayIO handle simpleDoc = display simpleDoc where display SEmpty = return () display (SChar c x) = do{ hPutChar handle c; display x} display (SText l s x) = do{ hPutStr handle s; display x} display (SLine i x) = do{ hPutStr handle ('\n':indentation i); display x} ----------------------------------------------------------- -- default pretty printers: show, putDoc and hPutDoc ----------------------------------------------------------- instance Show Doc where showsPrec d doc = displayS (renderPretty 0.4 80 doc) -- | The action @(putDoc doc)@ pretty prints document @doc@ to the -- standard output, with a page width of 100 characters and a ribbon -- width of 40 characters. -- -- > main :: IO () -- > main = do{ putDoc (text "hello" <+> text "world") } -- -- Which would output -- -- @ -- hello world -- @ putDoc :: Doc -> IO () putDoc doc = hPutDoc stdout doc -- | @(hPutDoc handle doc)@ pretty prints document @doc@ to the file -- handle @handle@ with a page width of 100 characters and a ribbon -- width of 40 characters. -- -- > main = do{ handle <- openFile "MyFile" WriteMode -- > ; hPutDoc handle (vcat (map text -- > ["vertical","text"])) -- > ; hClose handle -- > } hPutDoc :: Handle -> Doc -> IO () hPutDoc handle doc = displayIO handle (renderPretty 0.4 80 doc) ----------------------------------------------------------- -- insert spaces -- "indentation" used to insert tabs but tabs seem to cause -- more trouble than they solve :-) ----------------------------------------------------------- spaces n | n <= 0 = "" | otherwise = replicate n ' ' indentation n = spaces n --indentation n | n >= 8 = '\t' : indentation (n-8) -- | otherwise = spaces n -- LocalWords: PPrint combinators Wadler Wadler's encloseSep
hvr/jhc
src/Text/PrettyPrint/Leijen.hs
mit
31,245
0
16
7,756
4,736
2,719
2,017
296
10
{-# LANGUAGE PatternGuards #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.CopyWindow -- Copyright : (c) David Roundy <droundy@darcs.net>, Ivan Veselov <veselov@gmail.com>, Lanny Ripple <lan3ny@gmail.com> -- License : BSD3-style (see LICENSE) -- -- Maintainer : ??? -- Stability : unstable -- Portability : unportable -- -- Provides bindings to duplicate a window on multiple workspaces, -- providing dwm-like tagging functionality. -- ----------------------------------------------------------------------------- module XMonad.Actions.CopyWindow ( -- * Usage -- $usage copy, copyToAll, copyWindow, runOrCopy , killAllOtherCopies, kill1 -- * Highlight workspaces containing copies in logHook -- $logHook , wsContainingCopies ) where import XMonad import Control.Arrow ((&&&)) import qualified Data.List as L import XMonad.Actions.WindowGo import qualified XMonad.StackSet as W -- $usage -- -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file: -- -- > import XMonad.Actions.CopyWindow -- -- Then add something like this to your keybindings: -- -- > -- mod-[1..9] @@ Switch to workspace N -- > -- mod-shift-[1..9] @@ Move client to workspace N -- > -- mod-control-shift-[1..9] @@ Copy client to workspace N -- > [((m .|. modm, k), windows $ f i) -- > | (i, k) <- zip (workspaces x) [xK_1 ..] -- > , (f, m) <- [(W.view, 0), (W.shift, shiftMask), (copy, shiftMask .|. controlMask)]] -- -- To use the above key bindings you need also to import -- "XMonad.StackSet": -- -- > import qualified XMonad.StackSet as W -- -- You may also wish to redefine the binding to kill a window so it only -- removes it from the current workspace, if it's present elsewhere: -- -- > , ((modm .|. shiftMask, xK_c ), kill1) -- @@ Close the focused window -- -- Instead of copying a window from one workspace to another maybe you don't -- want to have to remember where you placed it. For that consider: -- -- > , ((modm, xK_b ), runOrCopy "firefox" (className =? "Firefox")) -- @@ run or copy firefox -- -- Another possibility which this extension provides is 'making window -- always visible' (i.e. always on current workspace), similar to corresponding -- metacity functionality. This behaviour is emulated through copying given -- window to all the workspaces and then removing it when it's unneeded on -- all workspaces any more. -- -- Here is the example of keybindings which provide these actions: -- -- > , ((modm, xK_v ), windows copyToAll) -- @@ Make focused window always visible -- > , ((modm .|. shiftMask, xK_v ), killAllOtherCopies) -- @@ Toggle window state back -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". -- $logHook -- To distinguish workspaces containing copies of the focused window use -- something like: -- -- > sampleLogHook h = do -- > copies <- wsContainingCopies -- > let check ws | ws `elem` copies = pad . xmobarColor "red" "black" $ ws -- > | otherwise = pad ws -- > dynamicLogWithPP myPP {ppHidden = check, ppOutput = hPutStrLn h} -- > -- > main = do -- > h <- spawnPipe "xmobar" -- > xmonad defaultConfig { logHook = sampleLogHook h } -- | Copy the focused window to a workspace. copy :: (Eq s, Eq i, Eq a) => i -> W.StackSet i l a s sd -> W.StackSet i l a s sd copy n s | Just w <- W.peek s = copyWindow w n s | otherwise = s -- | Copy the focused window to all workspaces. copyToAll :: (Eq s, Eq i, Eq a) => W.StackSet i l a s sd -> W.StackSet i l a s sd copyToAll s = foldr copy s $ map W.tag (W.workspaces s) -- | Copy an arbitrary window to a workspace. copyWindow :: (Eq a, Eq i, Eq s) => a -> i -> W.StackSet i l a s sd -> W.StackSet i l a s sd copyWindow w n = copy' where copy' s = if n `W.tagMember` s then W.view (W.currentTag s) $ insertUp' w $ W.view n s else s insertUp' a s = W.modify (Just $ W.Stack a [] []) (\(W.Stack t l r) -> if a `elem` t:l++r then Just $ W.Stack t l r else Just $ W.Stack a (L.delete a l) (L.delete a (t:r))) s -- | runOrCopy will run the provided shell command unless it can -- find a specified window in which case it will copy the window to -- the current workspace. Similar to (i.e., stolen from) "XMonad.Actions.WindowGo". runOrCopy :: String -> Query Bool -> X () runOrCopy = copyMaybe . spawn -- | Copy a window if it exists, run the first argument otherwise. copyMaybe :: X () -> Query Bool -> X () copyMaybe f qry = ifWindow qry copyWin f where copyWin = ask >>= \w -> doF (\ws -> copyWindow w (W.currentTag ws) ws) -- | Remove the focused window from this workspace. If it's present in no -- other workspace, then kill it instead. If we do kill it, we'll get a -- delete notify back from X. -- -- There are two ways to delete a window. Either just kill it, or if it -- supports the delete protocol, send a delete event (e.g. firefox). kill1 :: X () kill1 = do ss <- gets windowset whenJust (W.peek ss) $ \w -> if W.member w $ delete'' w ss then windows $ delete'' w else kill where delete'' w = W.modify Nothing (W.filter (/= w)) -- | Kill all other copies of focused window (if they're present). -- 'All other' means here 'copies which are not on the current workspace'. killAllOtherCopies :: X () killAllOtherCopies = do ss <- gets windowset whenJust (W.peek ss) $ \w -> windows $ W.view (W.currentTag ss) . delFromAllButCurrent w where delFromAllButCurrent w ss = foldr ($) ss $ map (delWinFromWorkspace w . W.tag) $ W.hidden ss ++ map W.workspace (W.visible ss) delWinFromWorkspace w wid = viewing wid $ W.modify Nothing (W.filter (/= w)) viewing wis f ss = W.view (W.currentTag ss) $ f $ W.view wis ss -- | A list of hidden workspaces containing a copy of the focused window. wsContainingCopies :: X [WorkspaceId] wsContainingCopies = do ws <- gets windowset return $ copiesOfOn (W.peek ws) (taggedWindows $ W.hidden ws) -- | Get a list of tuples (tag, [Window]) for each workspace. taggedWindows :: [W.Workspace i l a] -> [(i, [a])] taggedWindows = map $ W.tag &&& W.integrate' . W.stack -- | Get tags with copies of the focused window (if present.) copiesOfOn :: (Eq a) => Maybe a -> [(i, [a])] -> [i] copiesOfOn foc tw = maybe [] hasCopyOf foc where hasCopyOf f = map fst $ filter ((f `elem` ) . snd) tw
markus1189/xmonad-contrib-710
XMonad/Actions/CopyWindow.hs
bsd-3-clause
7,090
0
16
1,965
1,260
688
572
-1
-1
module B where -- Test for refactor of if to case foo x = if (odd x) then "Odd" else "Even" bob x y = x + y foo' x = case (odd x) of True -> "Odd" False -> "Even" main = do putStrLn $ show $ foo 5 mary = [1,2,3] h = bob 1 2 data D = A | B String | C
RefactoringTools/HaRe
old/refactorer/B.hs
bsd-3-clause
265
0
8
82
129
70
59
11
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Db -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This provides a 'ProgramDb' type which holds configured and not-yet -- configured programs. It is the parameter to lots of actions elsewhere in -- Cabal that need to look up and run programs. If we had a Cabal monad, -- the 'ProgramDb' would probably be a reader or state component of it. -- -- One nice thing about using it is that any program that is -- registered with Cabal will get some \"configure\" and \".cabal\" -- helpers like --with-foo-args --foo-path= and extra-foo-args. -- -- There's also a hook for adding programs in a Setup.lhs script. See -- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a -- hook user the ability to get the above flags and such so that they -- don't have to write all the PATH logic inside Setup.lhs. module Distribution.Simple.Program.Db ( -- * The collection of configured programs we can run ProgramDb, emptyProgramDb, defaultProgramDb, restoreProgramDb, -- ** Query and manipulate the program db addKnownProgram, addKnownPrograms, lookupKnownProgram, knownPrograms, getProgramSearchPath, setProgramSearchPath, modifyProgramSearchPath, userSpecifyPath, userSpecifyPaths, userMaybeSpecifyPath, userSpecifyArgs, userSpecifyArgss, userSpecifiedArgs, lookupProgram, updateProgram, configuredPrograms, -- ** Query and manipulate the program db configureProgram, configureAllKnownPrograms, unconfigureProgram, lookupProgramVersion, reconfigurePrograms, requireProgram, requireProgramVersion, ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Simple.Program.Types import Distribution.Simple.Program.Find import Distribution.Simple.Program.Builtin import Distribution.Simple.Utils import Distribution.Version import Distribution.Text import Distribution.Verbosity import Control.Monad (join) import Data.Tuple (swap) import qualified Data.Map as Map -- ------------------------------------------------------------ -- * Programs database -- ------------------------------------------------------------ -- | The configuration is a collection of information about programs. It -- contains information both about configured programs and also about programs -- that we are yet to configure. -- -- The idea is that we start from a collection of unconfigured programs and one -- by one we try to configure them at which point we move them into the -- configured collection. For unconfigured programs we record not just the -- 'Program' but also any user-provided arguments and location for the program. data ProgramDb = ProgramDb { unconfiguredProgs :: UnconfiguredProgs, progSearchPath :: ProgramSearchPath, configuredProgs :: ConfiguredProgs } deriving (Typeable) type UnconfiguredProgram = (Program, Maybe FilePath, [ProgArg]) type UnconfiguredProgs = Map.Map String UnconfiguredProgram type ConfiguredProgs = Map.Map String ConfiguredProgram emptyProgramDb :: ProgramDb emptyProgramDb = ProgramDb Map.empty defaultProgramSearchPath Map.empty defaultProgramDb :: ProgramDb defaultProgramDb = restoreProgramDb builtinPrograms emptyProgramDb -- internal helpers: updateUnconfiguredProgs :: (UnconfiguredProgs -> UnconfiguredProgs) -> ProgramDb -> ProgramDb updateUnconfiguredProgs update progdb = progdb { unconfiguredProgs = update (unconfiguredProgs progdb) } updateConfiguredProgs :: (ConfiguredProgs -> ConfiguredProgs) -> ProgramDb -> ProgramDb updateConfiguredProgs update progdb = progdb { configuredProgs = update (configuredProgs progdb) } -- Read & Show instances are based on listToFM -- | Note that this instance does not preserve the known 'Program's. -- See 'restoreProgramDb' for details. -- instance Show ProgramDb where show = show . Map.toAscList . configuredProgs -- | Note that this instance does not preserve the known 'Program's. -- See 'restoreProgramDb' for details. -- instance Read ProgramDb where readsPrec p s = [ (emptyProgramDb { configuredProgs = Map.fromList s' }, r) | (s', r) <- readsPrec p s ] -- | Note that this instance does not preserve the known 'Program's. -- See 'restoreProgramDb' for details. -- instance Binary ProgramDb where put db = do put (progSearchPath db) put (configuredProgs db) get = do searchpath <- get progs <- get return $! emptyProgramDb { progSearchPath = searchpath, configuredProgs = progs } -- | The 'Read'\/'Show' and 'Binary' instances do not preserve all the -- unconfigured 'Programs' because 'Program' is not in 'Read'\/'Show' because -- it contains functions. So to fully restore a deserialised 'ProgramDb' use -- this function to add back all the known 'Program's. -- -- * It does not add the default programs, but you probably want them, use -- 'builtinPrograms' in addition to any extra you might need. -- restoreProgramDb :: [Program] -> ProgramDb -> ProgramDb restoreProgramDb = addKnownPrograms -- ------------------------------- -- Managing unconfigured programs -- | Add a known program that we may configure later -- addKnownProgram :: Program -> ProgramDb -> ProgramDb addKnownProgram prog = updateUnconfiguredProgs $ Map.insertWith combine (programName prog) (prog, Nothing, []) where combine _ (_, path, args) = (prog, path, args) addKnownPrograms :: [Program] -> ProgramDb -> ProgramDb addKnownPrograms progs progdb = foldl' (flip addKnownProgram) progdb progs lookupKnownProgram :: String -> ProgramDb -> Maybe Program lookupKnownProgram name = fmap (\(p,_,_)->p) . Map.lookup name . unconfiguredProgs knownPrograms :: ProgramDb -> [(Program, Maybe ConfiguredProgram)] knownPrograms progdb = [ (p,p') | (p,_,_) <- Map.elems (unconfiguredProgs progdb) , let p' = Map.lookup (programName p) (configuredProgs progdb) ] -- | Get the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This is the default list of locations where programs are looked for when -- configuring them. This can be overridden for specific programs (with -- 'userSpecifyPath'), and specific known programs can modify or ignore this -- search path in their own configuration code. -- getProgramSearchPath :: ProgramDb -> ProgramSearchPath getProgramSearchPath = progSearchPath -- | Change the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This will affect programs that are configured from here on, so you -- should usually set it before configuring any programs. -- setProgramSearchPath :: ProgramSearchPath -> ProgramDb -> ProgramDb setProgramSearchPath searchpath db = db { progSearchPath = searchpath } -- | Modify the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This will affect programs that are configured from here on, so you -- should usually modify it before configuring any programs. -- modifyProgramSearchPath :: (ProgramSearchPath -> ProgramSearchPath) -> ProgramDb -> ProgramDb modifyProgramSearchPath f db = setProgramSearchPath (f $ getProgramSearchPath db) db -- |User-specify this path. Basically override any path information -- for this program in the configuration. If it's not a known -- program ignore it. -- userSpecifyPath :: String -- ^Program name -> FilePath -- ^user-specified path to the program -> ProgramDb -> ProgramDb userSpecifyPath name path = updateUnconfiguredProgs $ flip Map.update name $ \(prog, _, args) -> Just (prog, Just path, args) userMaybeSpecifyPath :: String -> Maybe FilePath -> ProgramDb -> ProgramDb userMaybeSpecifyPath _ Nothing progdb = progdb userMaybeSpecifyPath name (Just path) progdb = userSpecifyPath name path progdb -- |User-specify the arguments for this program. Basically override -- any args information for this program in the configuration. If it's -- not a known program, ignore it.. userSpecifyArgs :: String -- ^Program name -> [ProgArg] -- ^user-specified args -> ProgramDb -> ProgramDb userSpecifyArgs name args' = updateUnconfiguredProgs (flip Map.update name $ \(prog, path, args) -> Just (prog, path, args ++ args')) . updateConfiguredProgs (flip Map.update name $ \prog -> Just prog { programOverrideArgs = programOverrideArgs prog ++ args' }) -- | Like 'userSpecifyPath' but for a list of progs and their paths. -- userSpecifyPaths :: [(String, FilePath)] -> ProgramDb -> ProgramDb userSpecifyPaths paths progdb = foldl' (\progdb' (prog, path) -> userSpecifyPath prog path progdb') progdb paths -- | Like 'userSpecifyPath' but for a list of progs and their args. -- userSpecifyArgss :: [(String, [ProgArg])] -> ProgramDb -> ProgramDb userSpecifyArgss argss progdb = foldl' (\progdb' (prog, args) -> userSpecifyArgs prog args progdb') progdb argss -- | Get the path that has been previously specified for a program, if any. -- userSpecifiedPath :: Program -> ProgramDb -> Maybe FilePath userSpecifiedPath prog = join . fmap (\(_,p,_)->p) . Map.lookup (programName prog) . unconfiguredProgs -- | Get any extra args that have been previously specified for a program. -- userSpecifiedArgs :: Program -> ProgramDb -> [ProgArg] userSpecifiedArgs prog = maybe [] (\(_,_,as)->as) . Map.lookup (programName prog) . unconfiguredProgs -- ----------------------------- -- Managing configured programs -- | Try to find a configured program lookupProgram :: Program -> ProgramDb -> Maybe ConfiguredProgram lookupProgram prog = Map.lookup (programName prog) . configuredProgs -- | Update a configured program in the database. updateProgram :: ConfiguredProgram -> ProgramDb -> ProgramDb updateProgram prog = updateConfiguredProgs $ Map.insert (programId prog) prog -- | List all configured programs. configuredPrograms :: ProgramDb -> [ConfiguredProgram] configuredPrograms = Map.elems . configuredProgs -- --------------------------- -- Configuring known programs -- | Try to configure a specific program. If the program is already included in -- the collection of unconfigured programs then we use any user-supplied -- location and arguments. If the program gets configured successfully it gets -- added to the configured collection. -- -- Note that it is not a failure if the program cannot be configured. It's only -- a failure if the user supplied a location and the program could not be found -- at that location. -- -- The reason for it not being a failure at this stage is that we don't know up -- front all the programs we will need, so we try to configure them all. -- To verify that a program was actually successfully configured use -- 'requireProgram'. -- configureProgram :: Verbosity -> Program -> ProgramDb -> IO ProgramDb configureProgram verbosity prog progdb = do let name = programName prog maybeLocation <- case userSpecifiedPath prog progdb of Nothing -> programFindLocation prog verbosity (progSearchPath progdb) >>= return . fmap (swap . fmap FoundOnSystem . swap) Just path -> do absolute <- doesExecutableExist path if absolute then return (Just (UserSpecified path, [])) else findProgramOnSearchPath verbosity (progSearchPath progdb) path >>= maybe (die' verbosity notFound) (return . Just . swap . fmap UserSpecified . swap) where notFound = "Cannot find the program '" ++ name ++ "'. User-specified path '" ++ path ++ "' does not refer to an executable and " ++ "the program is not on the system path." case maybeLocation of Nothing -> return progdb Just (location, triedLocations) -> do version <- programFindVersion prog verbosity (locationPath location) newPath <- programSearchPathAsPATHVar (progSearchPath progdb) let configuredProg = ConfiguredProgram { programId = name, programVersion = version, programDefaultArgs = [], programOverrideArgs = userSpecifiedArgs prog progdb, programOverrideEnv = [("PATH", Just newPath)], programProperties = Map.empty, programLocation = location, programMonitorFiles = triedLocations } configuredProg' <- programPostConf prog verbosity configuredProg return (updateConfiguredProgs (Map.insert name configuredProg') progdb) -- | Configure a bunch of programs using 'configureProgram'. Just a 'foldM'. -- configurePrograms :: Verbosity -> [Program] -> ProgramDb -> IO ProgramDb configurePrograms verbosity progs progdb = foldM (flip (configureProgram verbosity)) progdb progs -- | Unconfigure a program. This is basically a hack and you shouldn't -- use it, but it can be handy for making sure a 'requireProgram' -- actually reconfigures. unconfigureProgram :: String -> ProgramDb -> ProgramDb unconfigureProgram progname = updateConfiguredProgs $ Map.delete progname -- | Try to configure all the known programs that have not yet been configured. -- configureAllKnownPrograms :: Verbosity -> ProgramDb -> IO ProgramDb configureAllKnownPrograms verbosity progdb = configurePrograms verbosity [ prog | (prog,_,_) <- Map.elems notYetConfigured ] progdb where notYetConfigured = unconfiguredProgs progdb `Map.difference` configuredProgs progdb -- | reconfigure a bunch of programs given new user-specified args. It takes -- the same inputs as 'userSpecifyPath' and 'userSpecifyArgs' and for all progs -- with a new path it calls 'configureProgram'. -- reconfigurePrograms :: Verbosity -> [(String, FilePath)] -> [(String, [ProgArg])] -> ProgramDb -> IO ProgramDb reconfigurePrograms verbosity paths argss progdb = do configurePrograms verbosity progs . userSpecifyPaths paths . userSpecifyArgss argss $ progdb where progs = catMaybes [ lookupKnownProgram name progdb | (name,_) <- paths ] -- | Check that a program is configured and available to be run. -- -- It raises an exception if the program could not be configured, otherwise -- it returns the configured program. -- requireProgram :: Verbosity -> Program -> ProgramDb -> IO (ConfiguredProgram, ProgramDb) requireProgram verbosity prog progdb = do -- If it's not already been configured, try to configure it now progdb' <- case lookupProgram prog progdb of Nothing -> configureProgram verbosity prog progdb Just _ -> return progdb case lookupProgram prog progdb' of Nothing -> die' verbosity notFound Just configuredProg -> return (configuredProg, progdb') where notFound = "The program '" ++ programName prog ++ "' is required but it could not be found." -- | Check that a program is configured and available to be run. -- -- Additionally check that the program version number is suitable and return -- it. For example you could require 'AnyVersion' or @'orLaterVersion' -- ('Version' [1,0] [])@ -- -- It returns the configured program, its version number and a possibly updated -- 'ProgramDb'. If the program could not be configured or the version is -- unsuitable, it returns an error value. -- lookupProgramVersion :: Verbosity -> Program -> VersionRange -> ProgramDb -> IO (Either String (ConfiguredProgram, Version, ProgramDb)) lookupProgramVersion verbosity prog range programDb = do -- If it's not already been configured, try to configure it now programDb' <- case lookupProgram prog programDb of Nothing -> configureProgram verbosity prog programDb Just _ -> return programDb case lookupProgram prog programDb' of Nothing -> return $! Left notFound Just configuredProg@ConfiguredProgram { programLocation = location } -> case programVersion configuredProg of Just version | withinRange version range -> return $! Right (configuredProg, version ,programDb') | otherwise -> return $! Left (badVersion version location) Nothing -> return $! Left (unknownVersion location) where notFound = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but it could not be found." badVersion v l = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but the version found at " ++ locationPath l ++ " is version " ++ display v unknownVersion l = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but the version of " ++ locationPath l ++ " could not be determined." versionRequirement | isAnyVersion range = "" | otherwise = " version " ++ display range -- | Like 'lookupProgramVersion', but raises an exception in case of error -- instead of returning 'Left errMsg'. -- requireProgramVersion :: Verbosity -> Program -> VersionRange -> ProgramDb -> IO (ConfiguredProgram, Version, ProgramDb) requireProgramVersion verbosity prog range programDb = join $ either (die' verbosity) return `fmap` lookupProgramVersion verbosity prog range programDb
mydaum/cabal
Cabal/Distribution/Simple/Program/Db.hs
bsd-3-clause
18,220
0
20
4,191
2,968
1,623
1,345
262
4
module ParserM ( -- Parser Monad ParserM(..), AlexInput, run_parser, -- Parser state St, StartCode, start_code, set_start_code, inc_brace_depth, dec_brace_depth, -- Tokens Token(..), -- Actions Action, andBegin, mkT, mkTv, -- Positions get_pos, show_pos, -- Input alexGetChar, alexGetByte, alexInputPrevChar, input, position, -- Other happyError ) where import Control.Applicative import Control.Monad (ap, liftM) import Data.Word (Word8) import Data.Char (ord) -- Parser Monad newtype ParserM a = ParserM (AlexInput -> St -> Either String (AlexInput, St, a)) instance Functor ParserM where fmap = liftM instance Applicative ParserM where pure = return (<*>) = ap instance Monad ParserM where ParserM m >>= k = ParserM $ \i s -> case m i s of Right (i', s', x) -> case k x of ParserM y -> y i' s' Left err -> Left err return a = ParserM $ \i s -> Right (i, s, a) fail err = ParserM $ \_ _ -> Left err run_parser :: ParserM a -> (String -> Either String a) run_parser (ParserM f) = \s -> case f (AlexInput init_pos s) init_state of Left es -> Left es Right (_, _, x) -> Right x -- Parser state data St = St { start_code :: !StartCode, brace_depth :: !Int } deriving Show type StartCode = Int init_state :: St init_state = St { start_code = 0, brace_depth = 0 } -- Tokens data Token = TEOF | TArrow | TDArrow | TEquals | TComma | TOpenParen | TCloseParen | TOpenParenHash | THashCloseParen | TOpenBrace | TCloseBrace | TOpenBracket | TCloseBracket | TOpenAngle | TCloseAngle | TSection | TPrimop | TPseudoop | TPrimtype | TWith | TDefaults | TTrue | TFalse | TDyadic | TMonadic | TCompare | TGenPrimOp | TThatsAllFolks | TLowerName String | TUpperName String | TString String | TNoBraces String | TInteger Int | TFixity | TInfixN | TInfixL | TInfixR | TNothing | TVector | TSCALAR | TVECTOR | TVECTUPLE deriving Show -- Actions type Action = String -> ParserM Token set_start_code :: StartCode -> ParserM () set_start_code sc = ParserM $ \i st -> Right (i, st { start_code = sc }, ()) inc_brace_depth :: ParserM () inc_brace_depth = ParserM $ \i st -> Right (i, st { brace_depth = brace_depth st + 1 }, ()) dec_brace_depth :: ParserM () dec_brace_depth = ParserM $ \i st -> let bd = brace_depth st - 1 sc = if bd == 0 then 0 else 1 in Right (i, st { brace_depth = bd, start_code = sc }, ()) andBegin :: Action -> StartCode -> Action (act `andBegin` sc) x = do set_start_code sc act x mkT :: Token -> Action mkT t = mkTv (const t) mkTv :: (String -> Token) -> Action mkTv f str = ParserM (\i st -> Right (i, st, f str)) -- Positions data Pos = Pos !Int{- Line -} !Int{- Column -} get_pos :: ParserM Pos get_pos = ParserM $ \i@(AlexInput p _) st -> Right (i, st, p) alexMove :: Pos -> Char -> Pos alexMove (Pos l _) '\n' = Pos (l+1) 1 alexMove (Pos l c) '\t' = Pos l ((c+8) `div` 8 * 8) alexMove (Pos l c) _ = Pos l (c+1) init_pos :: Pos init_pos = Pos 1 1 show_pos :: Pos -> String show_pos (Pos l c) = "line " ++ show l ++ ", column " ++ show c -- Input data AlexInput = AlexInput {position :: !Pos, input :: String} -- alexGetByte is for Alex >= 3.0, alexGetChar for earlier -- XXX no UTF-8; we should do this properly sometime alexGetByte :: AlexInput -> Maybe (Word8,AlexInput) alexGetByte (AlexInput p (x:xs)) = Just (fromIntegral (ord x), AlexInput (alexMove p x) xs) alexGetByte (AlexInput _ []) = Nothing alexGetChar :: AlexInput -> Maybe (Char,AlexInput) alexGetChar (AlexInput p (x:xs)) = Just (x, AlexInput (alexMove p x) xs) alexGetChar (AlexInput _ []) = Nothing alexInputPrevChar :: AlexInput -> Char alexInputPrevChar _ = error "Lexer doesn't implement alexInputPrevChar" happyError :: ParserM a happyError = do p <- get_pos fail $ "Parse error at " ++ show_pos p
frantisekfarka/ghc-dsi
utils/genprimopcode/ParserM.hs
bsd-3-clause
4,761
1
14
1,755
1,457
805
652
138
2
module Test0 () where import Language.Haskell.Liquid.Prelude x :: Int x = 4
mightymoose/liquidhaskell
tests/pos/profcrasher.hs
bsd-3-clause
78
0
4
14
24
16
8
4
1
module UnitTests.Distribution.Compat.CreatePipe (tests) where import Distribution.Compat.CreatePipe import System.IO (hClose, hGetContents, hPutStr, hSetEncoding, localeEncoding) import Test.Tasty import Test.Tasty.HUnit tests :: [TestTree] tests = [testCase "Locale Encoding" case_Locale_Encoding] case_Locale_Encoding :: Assertion case_Locale_Encoding = assert $ do let str = "\0252" (r, w) <- createPipe hSetEncoding w localeEncoding out <- hGetContents r hPutStr w str hClose w return $! out == str
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/tests/UnitTests/Distribution/Compat/CreatePipe.hs
bsd-3-clause
534
0
10
90
152
82
70
16
1
{-# LANGUAGE MagicHash, TypeOperators, MultiParamTypeClasses, TypeFamilies, DataKinds, FlexibleContexts, OverloadedStrings, ScopedTypeVariables #-} import Java import AkkaStream main :: IO () main = return ()
filippovitale/eta-playground
scala-akka-stream-eta-echoflow/src/main/eta/src/Main.hs
mit
211
1
6
25
31
15
16
5
1
module Main where import Program import Parser import Continuations import LParse doExec :: String -> String -> String doExec pro par = run (pFunc parseProgram pro) (\(p,_) -> printRes $ exec p (parsePar par)) (const "ERR") parsePar :: String -> [Bool] parsePar [] = [] parsePar ('0':ss) = False:parsePar ss parsePar ('1':ss) = True:parsePar ss parsePar _ = [] printRes :: [Bool] -> String printRes [] = [] printRes (False:xs) = '0' : printRes xs printRes (True:xs) = '1' : printRes xs main :: IO () main = do program <- getLine input <- getLine putStrLn (doExec program input)
MarcusVoelker/Smilefuck
Main.hs
mit
586
0
11
107
278
144
134
21
1
import Data.List (nub) main = do contents <- getContents let lns = lines contents print $ length lns - (length . nub) lns
MAPSuio/spring-challenge16
dejavu/larstvei.hs
mit
129
1
10
30
62
28
34
5
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} module Hydrazine.Client.API where import Servant import Servant.Client import Control.Monad.Trans.Either import Network.HTTP.Media.MediaType (MediaType) import Network.HTTP.Client (Response) import Network.HTTP.Types.Method (Method) import qualified Data.Text as T import qualified Data.ByteString.Lazy as BS import qualified Network.HTTP.Types.Header as H (Header) import Hydrazine.Server.API import Hydrazine.JSON getBootInfo :: T.Text -> EitherT ServantError IO BootInfo getImages :: EitherT ServantError IO [ImageInfo] newUpload :: NewImage -> EitherT ServantError IO UploadID uploadKernel :: Int -> _ -> EitherT ServantError IO () uploadCPIO :: Int -> _ -> EitherT ServantError IO () completeUpload :: Int -> EitherT ServantError IO () deleteImage :: T.Text -> EitherT ServantError IO () getMachines :: EitherT ServantError IO [BoxInfo] getMachine :: T.Text -> EitherT ServantError IO BoxInfo newMachine :: T.Text -> NewBox -> EitherT ServantError IO EmptyValue updateMachine :: T.Text -> UpdateBox -> EitherT ServantError IO EmptyValue deleteMachine :: T.Text -> EitherT ServantError IO () staticFiles :: Method -> EitherT ServantError IO (Int, BS.ByteString, MediaType, [H.Header], Response BS.ByteString) getBootInfo :<|> getImages :<|> newUpload :<|> uploadKernel :<|> uploadCPIO :<|> completeUpload :<|> deleteImage :<|> getMachines :<|> getMachine :<|> newMachine :<|> updateMachine :<|> deleteMachine :<|> staticFiles = client hydrazineAPI (BaseUrl Http "localhost" 8081)
dgonyeo/hydrazine
src/Hydrazine/Client/API.hs
mit
1,611
0
16
229
443
245
198
42
1
{-# LANGUAGE CPP, EmptyDataDecls #-} module Melchior.Dom ( -- * Types Dom , Element (unEl) , Node , Document , Input , Div , Span , Canvas , Image , ListItem , ensures , assuredly -- * Typeclasses , DomNode -- * Functions , toElement , toInput , toDiv , document , root , addClass , removeClass , toggle , parentOf , siblings , appendHtml , prependHtml , hack , set , value , setV ) where import Melchior.Data.String import Melchior.Dom.Events import Melchior.Dom.Html import Control.Monad (liftM) #ifdef __UHC_TARGET_JS__ import Language.UHC.JScript.Primitives #else data JSPtr a = JSPtr a #endif data Dom a = Dom (IO a) data Node newtype Element = Element { unEl :: JSPtr Node } newtype Document = Document {unDoc :: JSPtr Node } newtype Input = Input { unIn :: JSPtr Node } newtype Div = Div { unDiv :: JSPtr Node } newtype Span = Span {unSpan :: JSPtr Node} newtype Canvas = Canvas {unCanvas :: JSPtr Node} newtype Image = Image {unImage :: JSPtr Node} newtype ListItem = ListItem {unListItem :: JSPtr Node} ensures :: Maybe a -> a ensures e = case e of Nothing -> error "Assertion Error -- Missing DOM Node" Just x -> x assuredly :: IO (Maybe a) -> IO a assuredly x = x >>= \m -> return $ ensures m #ifdef __UHC_TARGET_JS__ foreign import js "document" document :: Document #else document :: Document document = undefined #endif root :: [Element] root = [toElement document] instance Monad Dom where return = Dom . return (Dom io) >>= k = Dom $ io >>= \x -> let Dom io' = k x in io' class DomNode a where instance DomNode Element where instance DomNode Input where instance DomNode Document where instance DomNode Div where instance DomNode Span where instance DomNode Canvas where instance DomNode ListItem where instance DomNode Image where #ifdef __UHC_TARGET_JS__ foreign import js "id(%2)" toElement :: (DomNode a) => a -> Element #else toElement :: (DomNode a) => a -> Element toElement = undefined #endif #ifdef __UHC_TARGET_JS__ foreign import js "Selectors.toInput(%2)" toInput ::(DomNode a) => a -> Input #else toInput ::(DomNode a) => a -> Input toInput = undefined #endif #ifdef __UHC_TARGET_JS__ foreign import js "Selectors.toDocument(%2)" toDocument ::(DomNode a) => a -> Document #else toDocument ::(DomNode a) => a -> Document toDocument = undefined #endif #ifdef __UHC_TARGET_JS__ foreign import js "Selectors.toDiv(%2)" toDiv :: (DomNode a) => a -> Div #else toDiv :: (DomNode a) => a -> Div toDiv = undefined #endif #ifdef __UHC_TARGET_JS__ foreign import js "Selectors.toSpan(%2)" toSpan :: (DomNode a) => a -> Span #else toSpan :: (DomNode a) => a -> Span toSpan = undefined #endif #ifdef __UHC_TARGET_JS__ foreign import js "%1.parentNode" parentOf :: Element -> Element #else parentOf :: Element -> Element parentOf = undefined #endif #ifdef __UHC_TARGET_JS__ foreign import js "Dom.siblings(%1)" siblings :: Element -> [Element] #else siblings :: Element -> [Element] siblings = undefined #endif addClass :: String -> Element -> JSString addClass s e = primAddClass (stringToJSString s) e #ifdef __UHC_TARGET_JS__ foreign import js "Dom.addClass(%2, %1)" primAddClass :: JSString -> Element -> JSString #else primAddClass :: JSString -> Element -> JSString primAddClass = undefined #endif removeClass :: String -> Element -> JSString removeClass s e = primRemoveClass (stringToJSString s) e #ifdef __UHC_TARGET_JS__ foreign import js "Dom.removeClass(%2, %1)" primRemoveClass :: JSString -> Element -> JSString #else primRemoveClass :: JSString -> Element -> JSString primRemoveClass = undefined #endif toggle :: String -> Element -> IO () toggle s = primToggle (stringToJSString s) #ifdef __UHC_TARGET_JS__ foreign import js "Dom.toggle(%2, %1)" primToggle :: JSString -> Element -> IO () #else primToggle :: JSString -> Element -> IO () primToggle = undefined #endif set :: Element -> String -> a -> () set e s v = primSet e (stringToJSString s) v #ifdef __UHC_TARGET_JS__ foreign import js "Dom.set(%1, %2, %3)" primSet :: Element -> JSString -> a -> () #else primSet :: Element -> JSString -> a -> () primSet = undefined #endif #ifdef __UHC_TARGET_JS__ foreign import js "Dom.hack(%1)" hack :: JSString -> JSString #else hack :: JSString -> JSString hack = undefined #endif value :: Input -> JSString value = primGetValue #ifdef __UHC_TARGET_JS__ foreign import js "Dom.value(%1)" primGetValue :: Input -> JSString #else primGetValue :: Input -> JSString primGetValue = undefined #endif appendHtml :: Element -> Html -> IO () appendHtml = primAppend #ifdef __UHC_TARGET_JS__ foreign import js "Dom.append(%1, %2)" primAppend :: Element -> Html -> IO () #else primAppend :: Element -> Html -> IO () primAppend = undefined #endif prependHtml :: Element -> Html -> IO () prependHtml = primPrepend #ifdef __UHC_TARGET_JS__ foreign import js "Dom.prepend(%1, %2)" primPrepend :: Element -> Html -> IO () #else primPrepend :: Element -> Html -> IO () primPrepend = undefined #endif setV :: Input -> String -> IO () setV i s = primSetValue i (stringToJSString s) #ifdef __UHC_TARGET_JS__ foreign import js "Dom.value(%1, %2)" primSetValue :: Input -> JSString -> IO () #else primSetValue :: Input -> JSString -> IO () primSetValue = undefined #endif
kjgorman/melchior
Melchior/Dom.hs
mit
5,380
12
12
1,032
1,017
620
397
-1
-1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} module Stack where import Language.MSH [state| state Stack a where data stack :: [a] push :: a -> Void push x = do st <- this.!stack stack <: (x : st) pushMany :: [a] -> Void pushMany = mapM_ (\x -> this.!push x) pop :: a pop = do (x:xs) <- this.!stack stack <: xs return x |] instance Show a => Show (Stack a) where show s = show $ result (s.!stack) pattern Stack :: [a] -> Stack a pattern Stack xs <- (extractData -> MkStackState xs) where Stack xs = new xs emptyStack :: Stack a emptyStack = Stack [] isEmptyStack :: Stack a -> Bool isEmptyStack (Stack []) = True isEmptyStack (Stack _) = False
mbg/monadic-state-hierarchies
examples/Stack.hs
mit
1,090
0
9
258
181
99
82
25
1
-- Copyright © 2013 Bart Massey -- [This work is licensed under the "MIT License"] -- Please see the file COPYING in the source -- distribution of this software for license terms. -- Default main for "Genuine Sieve of Eratosthenes" implementations. module DefaultMain (defaultMain) where import Data.List (foldl') import Data.Word import System.Console.ParseArgs data ArgLabel = ArgUseLimit | ArgPrint | ArgLimit deriving (Enum, Ord, Eq, Show) argd :: [Arg ArgLabel] argd = [ Arg { argIndex = ArgUseLimit, argAbbr = Just 'l', argName = Just "use-limit", argData = Nothing, argDesc = "Use the prime size limit to optimize generation." }, Arg { argIndex = ArgPrint, argAbbr = Just 'p', argName = Just "print", argData = Nothing, argDesc = "Print primes instead of counting them." }, Arg { argIndex = ArgLimit, argAbbr = Nothing, argName = Nothing, argData = argDataOptional "limit" ArgtypeInteger, argDesc = "Largest candidate prime to use in count." } ] defaultMain :: (Integral a, Show a) => Maybe [a] -> Maybe (a -> [a]) -> IO () defaultMain primes primesLimit = do argv <- parseArgsIO ArgsComplete argd let limit = case getArg argv ArgLimit :: Maybe Integer of Just l -> fromIntegral l Nothing -> case gotArg argv ArgPrint of True -> 100 False -> 2000000 let ps = case gotArg argv ArgUseLimit of True -> case primesLimit of Nothing -> usageError argv "Use-limit flag unsupported by this sieve." Just pl -> pl limit False -> case primes of Nothing -> usageError argv "Prime stream unsupported by this sieve." Just qs -> takeWhile (<= limit) qs case gotArg argv ArgPrint of True -> print ps False -> do let (n, p) = foldl' next (0 :: Word64, undefined) ps where next (a, _) x = (a + 1, x) putStrLn $ show p ++ " " ++ show n
BartMassey/genuine-sieve
DefaultMain.hs
mit
2,252
0
18
827
540
288
252
55
7
module Tamien.TestUtil where import Test.QuickCheck import Text.Printf check s a = printf "%-25s: " s >> quickCheck a
cpettitt/tamien
Tamien/TestUtil.hs
mit
120
0
6
20
38
20
18
4
1
{-# LANGUAGE OverloadedStrings #-} module Y2020.M12.D09.Solution where {-- Okay! Yesterday we associated aliases to countries, YAY! Now, however, we still have the problem that we have data (alliances) associated to the aliases, not to the countries. We have to do that. Why? So that the USA and UK can be part of NATO, so that our map looks pretty. MAPS LOOKING PRETTY IS WHY WE ARE HERE, PEOPLE! So. 1.a. To which alliances do these aliases belong; accumulate those. 1.b. associate those data to the source country entity. 2. Now, are there other things associated with these aliased countries? 2. answer: yes. Yes, there are: capitals. So, today, let's do 1. above, and tomorrow we'll look at collecting capitals for aliases. --} import Control.Arrow ((&&&)) import Data.Aeson import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe, mapMaybe) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Y2020.M10.D28.Solution hiding (alliance, Alliance) -- for Name import Y2020.M11.D11.Solution -- Member-Edge instance import Y2020.M12.D01.Solution (Country, Country(Country)) import Y2020.M12.D03.Solution -- for Country-Node instance import Data.Relation import Graph.Query import Graph.JSON.Cypher import Graph.JSON.Cypher.Read.Rows (TableRow) import qualified Graph.JSON.Cypher.Read.Rows as RR {-- We also need to filter out, again, countries and aliases that will break queries to upload and to download data ... although downloading data won't be a problem, but uploading a correction to those data will. So we need to report that we don't do certain corrections... also what weirdo Text values we're imp2orting. --} import qualified Y2020.M12.D07.Solution as UniFilterer -- With that, let's query orphaned countries and their associated alliances. data AliasAlliance = AA { alias :: Name, alliance :: Name } deriving (Eq, Ord, Show) fetchAliasedAlliances :: Cypher fetchAliasedAlliances = T.concat ["MATCH p=(c:Country)<-[:MEMBER_OF]-(d) ", "WHERE not (c)-[:IN]->(:Continent) ", "RETURN c.name, d.name"] {-- Our query >>> graphEndpoint >>> let url = it >>> getGraphResponse url [fetchAliasedAlliances] ... >>> let aaq = it returns the JSON of `sampleAliasesAlliances` --} sampleAliasesAlliances :: String sampleAliasesAlliances = concat ["{\"results\":[{\"columns\":[\"c.name\",\"d.name\"],\"data\":", "[{\"row\":[\"USA\",\"Moroccan-American Treaty of Friendship\"],", "\"meta\":[null,null]},{\"row\":[\"USA\",\"U.S.-Afghanistan Stra", "tegic Partnership Agreement\"],\"meta\":[null,null]}]}],", "\"errors\":[]}"] {-- >>> (RR.justRows sampleAliasesAlliances) :: [TableRow [Text]] [TR {row = ["USA","Moroccan-American Treaty of Friendship"]}, TR {row = ["USA","U.S.-Afghanistan Strategic Partnership Agreement"]}] --} -- so, to get from the JSON result to AliasAlliance values we do toAliasAlliance :: [Text] -> AliasAlliance toAliasAlliance = AA . head <*> last {-- >>> map (toAliasAlliance . RR.row) (RR.justRows sampleAliasesAlliances) [AA {alias = "USA", alliance = "Moroccan-American Treaty of Friendship"}, AA {alias = "USA", alliance = "U.S.-Afghanistan Strategic Partnership Agreement"}] --} -- then we collect these result into a map: type Alias = Name type AliasAlliancesMap = Map Alias (Set Name) aliasedAlliances :: [AliasAlliance] -> AliasAlliancesMap aliasedAlliances = foldr inserter Map.empty -- For an aliased country, collect and associate alliances to it in a map. inserter :: AliasAlliance -> AliasAlliancesMap -> AliasAlliancesMap inserter aa m = let namei = alias aa in Map.insert namei (Set.insert (alliance aa) (fromMaybe Set.empty (Map.lookup namei m))) m {-- >>> let aas = aliasedAlliances (map (toAliasAlliance . RR.row) (RR.justRows aaq)) {("USA",{"Moroccan-American Treaty of Friendship", "U.S.-Afghanistan Strategic Partnership Agreement"})} Okay! Now we need to replace the aliases with the source countries. Or, that is to say: we need to lookup the source country from the alias: --} type AliasCountryMap = Map Alias Country toAliasCountry :: [[Text]] -> AliasCountryMap toAliasCountry = Map.fromList . map (head &&& Country . T.unpack . last) -- which we get from aliasesCountriesQuery :: Cypher aliasesCountriesQuery = T.concat ["MATCH (c:Country)<-[:MEMBER_OF]-(d:Alliance) ", "WHERE not (c)-[:IN]->(:Continent) ", "WITH c.name as alias ", "MATCH (c:Country) WHERE alias in c.aliases ", "RETURN alias, c.name as country"] {-- >>> getGraphResponse url [aliasesCountriesQuery] "{\"results\":[{\"columns\":[\"alias\",\"country\"],\"data\":..." >>> let aac = it >>> let acm = toAliasCountry $ map RR.row (RR.justRows aac) >>> acm {("Abyssinia","Ethiopia"),("Al Maghrib","Morocco"),("Bahamas","The Bahamas"), ("Bangladesh1","Bangladesh"),("Cabo Verde","Cape Verde"), ("Cambodia1","Cambodia"),("Iraqi","Iraq"),("Ireland","Republic of Ireland"), ("Misr","Egypt"),("Sao Tome and Principe","S\227o Tom\233 and Pr\237ncipe"), ("Slovenija","Slovenia"),("St. Kitts and Nevis","Saint Kitts and Nevis"), ("St. Lucia","Saint Lucia"), ("St. Vincent and the Grenadines","Saint Vincent and the Grenadines"), ("Tchad","Chad"),("Timor Leste","East Timor"),("UAE","United Arab Emirates"), ("UK","United Kingdom"),("USA","United States of America"), ("United States","United States of America"), ("Zaire","Democratic Republic of the Congo"),("\205sland","Iceland"), ("\922\973\960\961\959\962","Cyprus"), ("\1062\1088\1085\1072 \1043\1086\1088\1072","Montenegro")] Now we match the alliances to the source countries by replacing the alias with the source country name, then we build a set of (new) relations from each alliance to the source country. Use the neo4j countries from Y2020.M12.D01.Solution and Y2020.M12.D03.Solution for country-nodes, and Y2020.M11.D11.Solution for the Member-type. --} data Alliance = Alliance Name deriving (Eq, Ord, Show) instance Node Alliance where asNode (Alliance n) = constr "Alliance" [("name", n)] type CountryAllianceRel = Relation Alliance Member Country mkCountryAlliances :: AliasCountryMap -> Alias -> Set Name -> [CountryAllianceRel] mkCountryAlliances acm alias = mapMaybe mkCountryAlliance . Set.toList where mkCountryAlliance alliance = Rel (Alliance alliance) MEMBER_OF <$> Map.lookup alias acm -- from a row in the alias-alliance map, create a set of relations for uploading {-- >>> let cas = concat $ map (uncurry (mkCountryAlliances acm)) $ Map.toList ... to show the relations we need a Show instance for Member instance Show Member where show _ = "MEMBER_OF" ... moving this to the Member type-declaration module. So we can do this: >>> cas [Rel (Alliance "African Union") MEMBER_OF (Country {country = "Ethiopia"}), Rel (Alliance "African Union") MEMBER_OF (Country {country = "Morocco"}),...] Now upload this to your graph data-store using cyphIt >>> cyphIt url cas "{\"results\":[{\"columns\":[],\"data\":[]},... ... "Neo.ClientError.Statement.SyntaxError\",\"message\":\"Invalid input... Oops! Tomorrow, we'll remove unicode-y relations (noting which ones we remove) and delete the alliance MEMBER_OF relations to the aliases. --}
geophf/1HaskellADay
exercises/HAD/Y2020/M12/D09/Solution.hs
mit
7,428
0
14
1,227
685
405
280
-1
-1
module Interface.General ( MenueState(..) ) where data MenueState = Done | Redo instance Eq MenueState where Done == Done = True Redo == Redo = True x == y = False
DevWurm/numeric-sequences-haskell
src/Interface/General.hs
mit
183
0
6
50
66
35
31
7
0
-- author : Lukasz Wolochowski (l.wolochowski@students.mimuw.edu.pl) module Letter where import Data.Set (Set) import qualified Data.Set as Set import Data.Map ((!)) import qualified Data.Map as Map import qualified Data.List as List import Math.Algebra.Group.PermutationGroup(Permutation, (.^)) import qualified Math.Algebra.Group.PermutationGroup as PermutationGroup newtype Atom = Atom Int deriving (Ord, Eq) instance Show Atom where show (Atom a) = show a type Partition = [[Atom]] type AutomorphismGroup = ([Atom], [Permutation Atom]) type Alphabet = [AutomorphismGroup] data Letter = LSet (Set Letter) | LAtom Atom deriving (Show, Ord, Eq) setL :: [Letter] -> Letter setL letters = LSet (Set.fromList letters) setA :: [Atom] -> Letter setA ats = setL (map LAtom ats) letterAtoms :: Letter -> Set Atom letterAtoms (LAtom a) = Set.singleton a letterAtoms (LSet set) = Set.unions (map letterAtoms (Set.toList set)) isAutomorphism :: Letter -> Permutation Atom -> Bool isAutomorphism letter f = applyAutomorphism f letter == letter where applyAutomorphism f' (LAtom a) = LAtom (a .^ f') applyAutomorphism f' (LSet set) = LSet (Set.map (applyAutomorphism f') set) letterAutomorphisms :: Letter -> AutomorphismGroup letterAutomorphisms letter = (atoms, filter (isAutomorphism letter) allPermutations) where atoms = Set.toList (letterAtoms letter) allPermutations = map (\perm -> PermutationGroup.fromPairs (zip atoms perm)) (List.permutations atoms) letterAutomorphismGroup :: Letter -> AutomorphismGroup letterAutomorphismGroup letter = (atoms, filter (isAutomorphism letter) allPermutations) where atoms = Set.toList (letterAtoms letter) allPermutations = map (\perm -> PermutationGroup.fromPairs (zip atoms perm)) (List.permutations atoms) mapAtoms :: (Atom -> Atom) -> Letter -> Letter mapAtoms f (LAtom a) = LAtom (f a) mapAtoms f (LSet set) = LSet (Set.map (mapAtoms f) set) resetAtoms :: Letter -> Letter resetAtoms letter = mapAtoms (\a -> atomMap!a) letter where atomList = Set.toList $ letterAtoms letter atomMap = Map.fromList $ zip atomList (map Atom [1..List.length atomList]) alphabetFromLetters :: [Letter] -> Alphabet alphabetFromLetters letters = map letterAutomorphismGroup letters dimension :: Alphabet -> Int dimension alph = maximum $ map (\(atoms, _) -> List.length atoms) alph
luke725/alphabets
src/Letter.hs
mit
2,466
163
11
475
931
514
417
57
2
{-# LANGUAGE TypeFamilies #-} module Data.Summary.Bool (BoolSumm, Summary(..), boolSumm) where import Data.Result (Result(..)) import Data.Summary (Summary(..)) import Data.List (foldl') import Control.DeepSeq (NFData(..)) -- | A 'BoolSumm' counts the number of True and all events observed. data BoolSumm = BoolSumm { _noSuccess :: !Int , _noTotal :: !Int } deriving (Show) instance NFData BoolSumm boolSumm :: [Bool] -> BoolSumm boolSumm = foldl' addObs rzero instance Result BoolSumm where type Obs BoolSumm = Bool addObs (BoolSumm s t) True = BoolSumm (s+1) (t+1) addObs (BoolSumm s t) False = BoolSumm s (t+1) rjoin (BoolSumm s t) (BoolSumm s' t') = BoolSumm (s+s') (t+t') rzero = BoolSumm 0 0 instance Summary BoolSumm where sampleMean (BoolSumm s t) = fromIntegral s / fromIntegral t sampleSE s = sqrt (p * (1 - p) / n) where p = sampleMean s n = fromIntegral $ sampleSize s sampleSize (BoolSumm _ t) = t sampleSD = error ("sampleSD" ++ undefBinObs) sampleVar = error ("sampleVar" ++ undefBinObs) undefBinObs :: String undefBinObs = " is undefined for binary observations. Please contact" ++ " the package maintainer if you can define it."
fffej/hs-carbon
src/Data/Summary/Bool.hs
mit
1,286
0
11
322
419
227
192
35
1
module Y2016.M11.D16.Exercise where {-- Today we focus on the important things: coffee and chocolate. So, we have two chemicals: caffeine and theobromine (chocolate), if we look at their chemical compositions, see caffeine.png and chocolate.jpeg here in this directory or at the URLs: https://github.com/geophf/1HaskellADay/blob/master/exercises/HAD/Y2016/M11/D16/caffeine.png and https://github.com/geophf/1HaskellADay/blob/master/exercises/HAD/Y2016/M11/D16/chocolate.jpeg Looking at these diagrams we see the commonality of them, the importance of the carbon-bond. Today's Haskell problem. We are NOT going to model caffeine nor chocholate, ... today. Nor are we going to see how caffeine breaks down into three compounds in the liver, one of them being chocolate ... today. So, today we are going to be looking at chemical bonding. If we have the atom, C, that 'wants' four chemical bonds, and H, 1 N, 3 and O, 2 We get neat things like ... water, where H wants 1 electron each, and O wants to give away 2 of them, so what do you have? Water. Or water-reactants.png and water-properties.png And there we have it: O has 2δ- and each H as 1δ+ and together they stabilize ... if you look at this planet, there is a WHOLE LOT of stabilization going on! Let's model this chemical valence or stability. Given: --} data Atom = C | H | O | N deriving (Eq, Show) -- define the valence for each of these atoms (look it up. I know you can) -- or, better, their δ or oxidation state: oxidationState :: Atom -> Int oxidationState atom = undefined -- Now, given that water and chocolate have the chemical compositions: type Count = Int theobromine, water :: [(Atom, Count)] water = [(H, 2), (O, 1)] theobromine = [(C, 7), (H, 8), (N, 4), (O, 2)] -- theobromine, chocolate, is written: C7H8N4O2 -- Are these compounds stable? Show their net oxidation states. stable :: [(Atom, Count)] -> Bool stable compound = undefined -- Of course, listing the atoms of a compound is one thing. We'll be looking -- at chemical bonds in another exercise.
geophf/1HaskellADay
exercises/HAD/Y2016/M11/D16/Exercise.hs
mit
2,063
0
7
362
172
111
61
11
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE CPP #-} ---------------------------------------------------------------------- -- | -- Module: Web.Slack.Classy -- Description: For compatibility with Web.Slack prior to v0.4.0.0. -- -- -- ---------------------------------------------------------------------- module Web.Slack.Classy ( SlackConfig(..) , mkSlackConfig , apiTest , authTest , chatPostMessage , conversationsList , conversationsHistory , conversationsHistoryAll , conversationsReplies , repliesFetchAll , getUserDesc , usersList , userLookupByEmail , authenticateReq , Response , LoadPage , HasManager(..) , HasToken(..) ) where -- base import Control.Arrow ((&&&)) import Data.Maybe -- containers import qualified Data.Map as Map -- http-client import Network.HTTP.Client (Manager) -- mtl import Control.Monad.Reader -- slack-web import qualified Web.Slack.Api as Api import qualified Web.Slack.Auth as Auth import qualified Web.Slack.Conversation as Conversation import qualified Web.Slack.Chat as Chat import qualified Web.Slack.Common as Common import qualified Web.Slack.User as User import Web.Slack.Pager import qualified Web.Slack as NonClassy import Web.Slack (SlackConfig (..), authenticateReq, mkSlackConfig) -- text import Data.Text (Text) #if !MIN_VERSION_servant(0,13,0) mkClientEnv :: Manager -> BaseUrl -> ClientEnv mkClientEnv = ClientEnv #endif -- | Implemented by 'SlackConfig' class HasManager a where getManager :: a -> Manager -- | Implemented by 'SlackConfig' class HasToken a where getToken :: a -> Text instance HasManager SlackConfig where getManager = slackConfigManager instance HasToken SlackConfig where getToken = slackConfigToken -- | -- -- Check API calling code. -- -- <https://api.slack.com/methods/api.test> apiTest :: (MonadReader env m, HasManager env, MonadIO m) => Api.TestReq -> m (Response Api.TestRsp) apiTest = liftToReader . flip (NonClassy.apiTest . getManager) -- | -- -- Check authentication and identity. -- -- <https://api.slack.com/methods/auth.test> authTest :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => m (Response Auth.TestRsp) authTest = liftNonClassy NonClassy.authTest -- | -- -- Retrieve conversations list. -- -- <https://api.slack.com/methods/conversations.list> conversationsList :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => Conversation.ListReq -> m (Response Conversation.ListRsp) conversationsList = liftNonClassy . flip NonClassy.conversationsList -- | -- -- Retrieve ceonversation history. -- Consider using 'historyFetchAll' in combination with this function. -- -- <https://api.slack.com/methods/conversations.history> conversationsHistory :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => Conversation.HistoryReq -> m (Response Conversation.HistoryRsp) conversationsHistory = liftNonClassy . flip NonClassy.conversationsHistory -- | -- -- Retrieve replies of a conversation. -- Consider using 'repliesFetchAll' if you want to get entire replies -- of a conversation. -- -- <https://api.slack.com/methods/conversations.replies> conversationsReplies :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => Conversation.RepliesReq -> m (Response Conversation.HistoryRsp) conversationsReplies = liftNonClassy . flip NonClassy.conversationsReplies -- | -- -- Send a message to a channel. -- -- <https://api.slack.com/methods/chat.postMessage> chatPostMessage :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => Chat.PostMsgReq -> m (Response Chat.PostMsgRsp) chatPostMessage = liftNonClassy . flip NonClassy.chatPostMessage -- | -- -- This method returns a list of all users in the team. -- This includes deleted/deactivated users. -- -- <https://api.slack.com/methods/users.list> usersList :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => m (Response User.ListRsp) usersList = liftNonClassy NonClassy.usersList -- | -- -- This method returns a list of all users in the team. -- This includes deleted/deactivated users. -- -- <https://api.slack.com/methods/users.lookupByEmail> userLookupByEmail :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => User.Email -> m (Response User.UserRsp) userLookupByEmail = liftNonClassy . flip NonClassy.userLookupByEmail -- | Returns a function to get a username from a 'Common.UserId'. -- Comes in handy to use 'Web.Slack.MessageParser.messageToHtml' getUserDesc :: (Common.UserId -> Text) -- ^ A function to give a default username in case the username is unknown -> User.ListRsp -- ^ List of users as known by the slack server. See 'usersList'. -> (Common.UserId -> Text) -- ^ A function from 'Common.UserId' to username. getUserDesc unknownUserFn users = let userMap = Map.fromList $ (User.userId &&& User.userName) <$> User.listRspMembers users in \userId -> fromMaybe (unknownUserFn userId) $ Map.lookup userId userMap -- | Returns an action to send a request to get the history of a conversation. -- -- To fetch all messages in the conversation, run the returned 'LoadPage' action -- repeatedly until it returns an empty list. conversationsHistoryAll :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => Conversation.HistoryReq -- ^ The first request to send. _NOTE_: 'Conversation.historyReqCursor' is silently ignored. -> m (LoadPage m Common.Message) -- ^ An action which returns a new page of messages every time called. -- If there are no pages anymore, it returns an empty list. conversationsHistoryAll = conversationsHistoryAllBy conversationsHistory -- | Returns an action to send a request to get the replies of a conversation. -- -- To fetch all replies in the conversation, run the returned 'LoadPage' action -- repeatedly until it returns an empty list. -- -- *NOTE*: The conversations.replies endpoint always returns the first message -- of the thread. So every page returned by the 'LoadPage' action includes -- the first message of the thread. You should drop it if you want to -- collect messages in a thread without duplicates. repliesFetchAll :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => Conversation.RepliesReq -- ^ The first request to send. _NOTE_: 'Conversation.repliesReqCursor' is silently ignored. -> m (LoadPage m Common.Message) -- ^ An action which returns a new page of messages every time called. -- If there are no pages anymore, it returns an empty list. repliesFetchAll = repliesFetchAllBy conversationsReplies liftNonClassy :: (MonadReader env m, HasManager env, HasToken env, MonadIO m) => (SlackConfig -> IO a) -> m a liftNonClassy f = liftToReader $ \env -> f $ SlackConfig (getManager env) (getToken env) liftToReader :: (MonadReader env m, MonadIO m) => (env -> IO a) -> m a liftToReader f = do env <- ask liftIO $ f env
jpvillaisaza/slack-web
src/Web/Slack/Classy.hs
mit
7,062
0
13
1,179
1,267
729
538
114
1
module StabilizationNum where import Types newStbNum :: StabilizationNum newStbNum = 0 isNone :: StabilizationNum -> Bool isNone = (==) none isSome :: StabilizationNum -> Bool isSome = (>= 0) add1 :: StabilizationNum -> StabilizationNum add1 = (+ 1)
JenniferWang/incremental-haskell
src/StabilizationNum.hs
mit
257
0
5
45
72
44
28
10
1
-- test/Mataskell/Base64Spec.hs module Mataskell.Base64Spec (spec) where import Mataskell.Base64 (encode64, decode64) import Test.Hspec import Test.Hspec.QuickCheck spec :: Spec spec = do describe "Mataskell.Base64" $ do context "plaintext decoding" $ do it "decodes hex values" $ do let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d" let expected = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t" decode64 hex `shouldBe` expected
tylerjl/mataskell
test/Mataskell/Base64Spec.hs
gpl-2.0
583
0
18
122
106
55
51
12
1
{- Copyright (C) 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.Actions.Mod where import Prelude hiding (mod) import Control.Monad import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (NoLoggingT) import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Trans.Resource (ResourceT) import Data.List (inits, intercalate, partition, sort, sortBy) import Data.Maybe import Data.Monoid import Data.Time (TimeZone, UTCTime, getCurrentTime, getCurrentTimeZone) import Data.Time.ISO8601 import Database.Persist (insert) import Database.Persist.Sqlite import Debug.Trace import System.Console.ANSI import System.Console.CmdArgs.Explicit import System.Environment import System.FilePath.Posix (joinPath, splitDirectories) import System.IO import Text.Read (readMaybe) import qualified Data.ByteString as BS import qualified Data.Map as M import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.UUID as U import qualified Data.UUID.V4 as U4 import qualified Data.Yaml as Yaml import Args import DatabaseTables import DatabaseUtils import Utils import OnTopOfThings.Parsers.NumberList import OnTopOfThings.Actions.Action import OnTopOfThings.Actions.Env import OnTopOfThings.Actions.Utils (lookupItem) --import OnTopOfThings.Data.DatabaseJson import OnTopOfThings.Data.FileJson import OnTopOfThings.Data.Patch import OnTopOfThings.Data.PatchDatabase import OnTopOfThings.Data.Time import OnTopOfThings.Data.Types instance Action ActionMod where runAction env action | trace ("runAction") False = undefined runAction env action = mod env action >>= \result -> return (env, result) actionFromOptions env opts | trace ("actionFromOptions "++(show opts)) False = undefined actionFromOptions env opts = do tz <- liftIO $ getCurrentTimeZone items_ <- case optionsArgs opts of [] -> return (Left ["mod: missing file operand", "Try 'mod --help' for more information."]) args -> do case concatEithersN (map parseNumberList args) of Left msgs -> return (Left msgs) Right refs' -> do let refs = concat refs' uuids_ <- mapM (lookupItem env) refs case concatEithersN uuids_ of Left msgs -> return (Left msgs) Right uuids -> return (Right uuids) parentItem_ <- case M.lookup "parent" (optionsParams1 opts) of Nothing -> return (Right Nothing) Just ref -> do item_ <- lookupItem env ref case item_ of Left msgs -> return (Left msgs) Right item -> return (Right (Just item)) return $ do items <- items_ let uuids = map itemUuid items parentItem <- parentItem_ let parentUuid = parentItem >>= \item -> Just (itemUuid item) closed <- getMaybeDate "closed" tz start <- getMaybeDate "start" tz end <- getMaybeDate "end" tz due <- getMaybeDate "due" tz estimate <- getMaybeDuration "estimate" return (ActionMod { modUuids = uuids , modType = M.lookup "type" (optionsParams1 opts) , modStatus = M.lookup "status" (optionsParams1 opts) , modParentUuid = parentUuid , modName = M.lookup "name" (optionsParams1 opts) , modTitle = M.lookup "title" (optionsParams1 opts) , modContent = M.lookup "content" (optionsParams1 opts) , modStage = M.lookup "stage" (optionsParams1 opts) , modClosed = closed , modStart = start , modEnd = end , modDue = due , modEstimate = estimate , modTag = M.lookup "tag" (optionsParamsM opts) , modOptions = opts }) where getMaybeDate :: String -> TimeZone -> Validation (Maybe Time) getMaybeDate name tz = case M.lookup name (optionsParams1 opts) of Just s -> parseTime' tz s >>= \time -> Right (Just time) _ -> Right Nothing getMaybeDuration :: String -> Validation (Maybe Int) getMaybeDuration name = case M.lookup name (optionsParams1 opts) of Just s -> Right (Just (read s :: Int)) _ -> Right Nothing actionToRecordArgs action = Nothing mode_mod = Mode { modeGroupModes = mempty , modeNames = ["mod"] , modeValue = options_empty "mod" , modeCheck = Right , modeReform = Just . reform , modeExpandAt = True , modeHelp = "Modify an existing item" , modeHelpSuffix = [] , modeArgs = ([], Just (flagArg updArgs "ID")) , modeGroupFlags = toGroup [ flagReq ["type"] (upd1 "type") "TYPE" "list|task. (default=task)" , flagReq ["status"] (upd1 "status") "STATUS" "open|closed|deleted" , flagReq ["parent", "p"] (upd1 "parent") "ID" "reference to parent of this item" , flagReq ["name", "n"] (upd1 "name") "NAME" "A filename for this item." , flagReq ["title"] (upd1 "title") "TITLE" "Title of the item." , flagReq ["content"] (upd1 "content") "CONTENT" "Content of the item." , flagReq ["stage", "s"] (upd1 "stage") "STAGE" "new|incubator|today. (default=new)" , flagReq ["closed"] (upd1 "closed") "TIME" "Time that this item was closed." , flagReq ["start"] (upd1 "start") "TIME" "Start time for this event." , flagReq ["end"] (upd1 "end") "TIME" "End time for this event." , flagReq ["due"] (upd1 "due") "TIME" "Due time." , flagReq ["estimate"] (upd1 "estimate") "DURATION" "Estimated time required to complete." , flagReq ["tag", "t"] (updM "tag") "TAG" "Associate this item with the given tag or context. Maybe be applied multiple times." , flagHelpSimple updHelp ] } mod :: Env -> ActionMod -> SqlPersistT (NoLoggingT (ResourceT IO)) (ActionResult) mod env action | trace ("mod "++(show action)) False = undefined mod env action = do let diffs = concat $ catMaybes [ get "type" modType , get "status" modStatus , get "parent" modParentUuid , get "name" modName , get "title" modTitle , get "content" modContent , get "stage" modStage , getTime "closed" modClosed , getTime "start" modStart , getTime "end" modEnd , getTime "due" modDue , getInt "estimate" modEstimate , (modTag action) >>= \l -> Just (map modToDiff l) ] let hunk = PatchHunk (modUuids action) diffs return (ActionResult [hunk] False [] []) where get :: String -> (ActionMod -> Maybe String) -> Maybe [Diff] get name fn = (fn action) >>= \x -> Just [DiffEqual name x] getInt :: String -> (ActionMod -> Maybe Int) -> Maybe [Diff] getInt name fn = (fn action) >>= \x -> Just [DiffEqual name (show x)] getTime :: String -> (ActionMod -> Maybe Time) -> Maybe [Diff] getTime name fn = (fn action) >>= \x -> Just [DiffEqual name (formatTime' x)] modToDiff :: Mod -> Diff modToDiff mod = case mod of ModNull name -> DiffNull name ModEqual n v -> DiffEqual n v ModAdd n v -> DiffAdd n v ModUnset n -> DiffUnset n ModRemove n v -> DiffRemove n v
ellis/OnTopOfThings
old-20150308/src/OnTopOfThings/Actions/Mod.hs
gpl-3.0
7,706
0
24
1,819
2,165
1,135
1,030
158
5
----------------------------------------------------------------------------- -- | -- Module : HEP.Parser.LHE.Sanitizer.FileIO -- Copyright : (c) 2013 Ian-Woo Kim -- -- License : GPL-3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- -- LHE file IO operation -- ----------------------------------------------------------------------------- module HEP.Parser.LHE.Sanitizer.FileIO where import Control.Monad.Trans import Control.Monad.State import Data.Conduit import qualified Data.Text.IO as TIO import System.IO import Text.XML.Conduit.Parse.Util -- import Data.Conduit.Internal as CU import Data.Conduit.Util.Count import HEP.Parser.LHE.Conduit import HEP.Parser.LHE.Type countEventInLHEFile :: FilePath -> IO () countEventInLHEFile fn = withFile fn ReadMode $ \ih -> do let iter = do header <- textLHEHeader liftIO $ mapM_ TIO.putStrLn header parseEvent =$ process process = CU.zipSinks countIter countMarkerIter r <- flip runStateT (0 :: Int) (parseXmlFile ih iter) putStrLn $ show r
wavewave/LHE-sanitizer
src/HEP/Parser/LHE/Sanitizer/FileIO.hs
gpl-3.0
1,121
0
16
200
214
127
87
21
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : Postmaster.FSM.Spooler Copyright : (c) 2004-2008 by Peter Simons License : GPL2 Maintainer : simons@cryp.to Stability : provisional Portability : Haskell 2-pre -} module Postmaster.FSM.Spooler where import Foreign import Control.Exception import Control.Concurrent.MVar import Control.Monad.State import System.Directory import System.IO import Postmaster.Base import Postmaster.IO import Postmaster.FSM.EventHandler import Postmaster.FSM.SessionState import Postmaster.FSM.DataHandler import Postmaster.FSM.MailID import Text.ParserCombinators.Parsec.Rfc2821 hiding ( path ) import OpenSSL.Digest import Data.Typeable data Spooler = S (Maybe FilePath) (Maybe WriteHandle) DigestState deriving (Typeable) spoolerState :: SmtpdVariable spoolerState = defineLocal "spoolerstate" getState :: Smtpd (MVar Spooler) getState = spoolerState getVar_ setState :: MVar Spooler -> Smtpd () setState st = spoolerState (`setVar` st) -- |The Standard Bad-Ass Payload Handler. Needs the path to -- the spool directory. handlePayload :: FilePath -> EventT handlePayload _ f Greeting = do liftIO (newMVar (S Nothing Nothing (DST nullPtr))) >>= setState setDataHandler feeder f Greeting handlePayload spool _ StartData = do st <- getState mid <- getMailID let path = spool ++ "/temp." ++ show mid liftIO . modifyMVar_ st $ \(S p' h' (DST c')) -> assert (p' == Nothing) $ assert (h' == Nothing) $ assert (c' == nullPtr) $ bracketOnError (openBinaryFile path WriteMode) (hClose) (\h -> bracketOnError ctxCreate ctxDestroy $ \ctx -> do hSetBuffering h NoBuffering when (ctx == nullPtr) (fail "can't initialize SHA1 digest context") md <- toMDEngine SHA1 when (md == nullPtr) (fail "can't initialize SHA1 digest engine") rc <- digestInit ctx md when (rc == 0) (fail "can't initialize SHA1 digest") return (S (Just path) (Just h) (DST ctx))) say 3 5 4 "terminate data with <CRLF>.<CRLF>" `fallback` say 4 5 1 "requested action aborted: error in processing" handlePayload spool _ Deliver = do st <- getState sha1 <- liftIO $ modifyMVar st $ \(S (Just p) (Just h) ctx@(DST c)) -> assert (c /= nullPtr) $ do hClose h sha1 <- fmap (>>= toHex) (evalStateT final ctx) let fname = spool ++ "/" ++ sha1 renameFile p fname return (S Nothing Nothing ctx, sha1) say 2 5 0 (sha1 ++ " message accepted for delivery") `fallback` say 4 5 1 "requested action aborted: error in processing" handlePayload _ f ResetState = clearState >> f ResetState handlePayload _ f Shutdown = clearState >> f Shutdown handlePayload _ f e = f e feeder :: DataHandler feeder buf@(Buf _ _ 0) = return (Nothing, buf) feeder buf@(Buf _ ptr n) = do xs <- liftIO (peekArray (fromIntegral n) ptr) let theEnd = map (toEnum . fromEnum) "\r\n.\r\n" (eod, i) = case strstr theEnd xs of Nothing -> (False, max 0 (n - 4)) Just j -> (True, fromIntegral (j-3)) i' = fromIntegral i st <- getState buf' <- liftIO . withMVar st $ \(S _ (Just h) ctx@(DST c)) -> assert (c /= nullPtr) $ do hPutBuf h ptr i' _ <- execStateT (update' (ptr, i')) ctx flush i buf if not eod then return (Nothing, buf') else do r <- trigger Deliver _ <- trigger ResetState -- TODO: this doesn't really setSessionState HaveHelo -- belong here return (Just r, buf') clearState :: Smtpd () clearState = do st <- getState liftIO . modifyMVar_ st $ \(S path h (DST ctx)) -> do let clean Nothing _ = return () clean (Just x) f = (try (f x) :: IO (Either SomeException ())) >> return () clean h hClose clean path removeFile when (ctx /= nullPtr) (ctxDestroy ctx) return (S Nothing Nothing (DST nullPtr))
richardfontana/postmaster
Postmaster/FSM/Spooler.hs
gpl-3.0
4,043
0
22
1,064
1,373
682
691
98
3
-- This file is formatted with Ormolu {-# LANGUAGE BlockArguments #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE RecordWildCards #-} -- | This module is the core of the GUI model and control. This module -- does not interact with GUI libraries. module GuiInternals ( Inputs (..), emptyInputs, AppState (..), emptyAppState, MouseButton (..), KeyInput (..), KeyEvent (..), renderCairo, updateBackground, backgroundPress, keyPress, keyRelease, scroll, step, ) where -- import Debug.Trace (trace) import Control.Monad (when) import Control.Monad.Trans.Reader (runReaderT) import Data.Coerce (Coercible) import Data.Foldable (traverse_) import Data.GI.Base (withManagedPtr) import Data.IORef (IORef, modifyIORef', readIORef, writeIORef) import qualified Data.IntMap.Strict as IntMap import Data.List (find) import Data.Maybe (fromMaybe, isNothing) import qualified Data.Set as Set import qualified Data.Text as Text import Data.Time.Clock.System (SystemTime (MkSystemTime)) import qualified Data.Tuple.Extra as Tuple import Foreign.Ptr (castPtr) import qualified GI.Cairo (Context (..)) import qualified Graphics.Rendering.Cairo as Cairo import Graphics.Rendering.Cairo.Internal (Render (runRender)) import Graphics.Rendering.Cairo.Types (Cairo (Cairo)) -- Constants minimumScale :: Double minimumScale = 0.1 panSpeed :: Double panSpeed = 2000 baseFontSize :: Double baseFontSize = 24 -- Types -- | An Enum of mouse buttons, so order is important! data MouseButton = LeftMouseButton | MiddleMouseButton | RightMouseButton | UnknownMouseButton deriving (Eq, Ord, Enum, Bounded, Show) data KeyInput = KeyInput { _kiKeyString :: Text.Text, _kiKeyEvent :: KeyEvent } deriving (Show, Eq) -- | What action should be taken when you press a key? data KeyEvent = UndoKey | AbortKey | MouseTranslateKey | MoveUp | MoveLeft | MoveDown | MoveRight | OtherKey Text.Text deriving (Eq, Ord, Show) -- | This is not an enmum so that new types of nodes can be created at -- runtime. Everything of type (Double, Double) is either (width, -- height) or (x, y). data NodeType = NodeType { _ntName :: !String, _ntNumInitialPorts :: !Int, -- | Returns which port was clicked on. If no port was clicked it -- returns Nothing. _ntPortClicked :: !( (Double, Double) -> -- (x, y) in the node's coordinates. Element -> -- Which element was clicked Maybe Int ), _ntDraw :: !( Transform -> (Int, Element) -> Maybe Port -> -- Currently selected port Render () ), -- | Given the port number, return the location of that port in -- the node's coordinates. _ntPortLocations :: !(Int -> (Double, Double)), -- | (x, y) position of the center of the handle. _ntHandleLocation :: !(Double, Double), -- ? Should the argument be Element instead? -- | Given the number of ports, return the size of the node. _ntSize :: !(Int -> (Double, Double)) } -- | A simple 2d transformation. See transform below for -- details. data Transform = Transform { -- | Controls scaling. This is a scale factor, so the size of -- visual elements are multiplied by this number. Thus a value of -- one is no scale, values greater than 1 scales in, and values -- between 0 and 1 scales out. Negative values result in undefined -- behavior, although it would be cool if negative values -- produced a flip across both the X and Y axes. _tScale :: !Double, -- | (x, y) _tTranslate :: !(Double, Double) } deriving (Show, Eq) -- TODO Add quick check tests that transform and unTransform are inverses transform :: Transform -> (Double, Double) -> (Double, Double) transform (Transform scale (deltaX, deltaY)) (x, y) = ( x * scale + deltaX, y * scale + deltaY ) unTransform :: Transform -> (Double, Double) -> (Double, Double) unTransform (Transform scale (deltaX, deltaY)) (transformedX, transformedY) = ( (transformedX - deltaX) / scale, (transformedY - deltaY) / scale ) windowToElementCoordinates :: AppState -> (Double, Double) -> (Double, Double) windowToElementCoordinates state = unTransform (_asTransform state) newtype ElemId = ElemId {_unElemId :: Int} deriving (Show, Eq, Ord, Num) -- | A graphical element that can be clicked data Element = Element { -- | (x, y) of top left corner. These values are in Element -- coordinates. Use the (transform _asTransform) function to -- convert these to window coordinates and (unTransform -- _asTransform) to convert window coordinates to _elPosition. _elPosition :: !(Double, Double), -- | Depth. Higher values are drawn on top -- _elZ is currently ignored _elZ :: !Int, _elType :: !NodeType, _elNumPorts :: !Int, _elPortText :: !(IntMap.IntMap Text.Text) } -- | When the translation key is first pressed, these values contain -- the mouse position and (_tTranslate . _asTransform) at that moment. data Panning = Panning { _panMouse :: !(Double, Double), _panTranslation :: !(Double, Double) } deriving (Eq, Ord, Show) -- | A specific port in a node. data Port = Port { -- | The node this port is in. _pNode :: ElemId, -- | The port number of the port in the node. _pPort :: Int } deriving (Eq, Ord, Show) data Inputs = Inputs { -- | Raw mouse x and y position in window coordinates. _inMouseXandY :: !(Double, Double), _inTime :: !SystemTime, _inPrevTime :: !SystemTime, _inEvents :: ![InputEvent], -- | If Something, then a translation is occuring. _inTranslation :: !(Maybe Panning), -- | All keys currently being pressed. _inPressedKeys :: !(Set.Set KeyEvent) } -- TODO Consider extracting History and UndoPosition into their own "object". data AppState = AppState { -- | This is a key for _asElements _asMovingNode :: !(Maybe ElemId), -- TODO _asEdges is a set, so consider using a set data structure here. -- | The connections between nodes. Each edge is a set of at least -- two ports that are connected. _asEdges :: !( Set.Set (Set.Set Port) -- Each Set of Ports is a single "edge". ), -- | Iff Just, an edge is currently being draw where the ElemId is -- one end of the edge. _asCurrentEdge :: !(Maybe Port), -- TODO current edge and current port have the same type. Can they -- be combined? Also, may want to edit the node type / -- handle. Should that be a "port" too? -- | Iff Just, then currently the text of this port is being edited. _asCurrentPort :: !(Maybe Port), _asElements :: !(IntMap.IntMap Element), -- | FPS rounded down to nearest hundred if over 200 fps. _asFPSr :: !Int, -- | A full history of the state of the app. Use addHistoryEvent -- to add new HistoryEvents, do not add events directly. _asHistory :: ![Undoable HistoryEvent], -- | A pointer into _asHistory. The undo command pops this -- stack, undos the HistoryEvent, and pushes the inverse of the -- popped HistoryEvent onto _asHistory. _asUndoPosition :: ![Undoable HistoryEvent], -- | The biggest ElemId used so far in the program. Not updated by undo. _asBiggestID :: !ElemId, -- | Controls scalaing (aka. zooming) and translation (aka. panning) _asTransform :: !Transform } data InputEvent = -- | Which node was clicked and the relative click position within a node. ClickOnNode !MouseButton !ElemId !(Double, Double) -- relative mouse position | AddNode !(Double, Double) -- where to add the node | -- | Undo the last action. UndoEvent | -- | Abort the current command (like C-g in Emacs). AbortEvent | -- | The scale factor is multiplied by this number. ScaleAdjustEvent !Double data Undoable a = Do !a | Undo !a ---------- NodeType instances ---------- ---- Apply Node ---- handleWidth :: Double handleWidth = 70 portWidth :: Double portWidth = 100 applyNodeHeight :: Double applyNodeHeight = 40 -- | Draw an apply node. This function's type will probably change -- since some of this could be done in drawNode. drawApply :: Transform -> (Int, Element) -> Maybe Port -> Render () drawApply transformation (elemId, Element {..}) selectedPort = do -- TODO See if there's a way to scale the entire Cairo drawing. let (x, y) = transform transformation _elPosition scale = _tScale transformation scaledPortWidth = scale * portWidth scaledHeight = scale * applyNodeHeight scaledHandleWidth = scale * handleWidth fontHeight = baseFontSize * scale drawPort portNum = do if | selectedPort == Just (Port {_pNode = ElemId elemId, _pPort = portNum}) -> Cairo.setSourceRGB 0 1 0 | portNum == 0 -> Cairo.setSourceRGB 1 1 1 | otherwise -> Cairo.setSourceRGB 1 0 0 let portText = fromMaybe "" $ IntMap.lookup portNum _elPortText Cairo.rectangle (x + scaledHandleWidth + scaledPortWidth * fromIntegral portNum) y scaledPortWidth scaledHeight Cairo.moveTo xPos (y - 0.4 * fontHeight) Cairo.showText portText Cairo.stroke where xPos = x + scaledHandleWidth + scaledPortWidth * fromIntegral portNum Cairo.setSourceRGB 0.5 0.5 0.5 Cairo.setLineWidth (3 * scale) -- Draw the handle Cairo.rectangle x y scaledHandleWidth scaledHeight Cairo.moveTo (x + 5 * scale) (y + scale * snd (_ntHandleLocation _elType)) -- Cairo.showText (show elemId <> " " <> _ntName _elType) Cairo.stroke Cairo.setSourceRGB 1 0 0 traverse_ drawPort [0 .. (_elNumPorts -1)] Cairo.stroke applyPortClicked :: (Double, Double) -> Element -> Maybe Int applyPortClicked (x, _) Element {_elNumPorts} = let rectClicked = floor ((x - handleWidth) / portWidth) in if x <= handleWidth then Nothing else Just rectClicked applyPortLocations :: Int -> (Double, Double) applyPortLocations port = ( handleWidth + (portWidth / 2) + (fromIntegral port * portWidth), applyNodeHeight / 2 ) applySize :: Int -> (Double, Double) applySize numPorts = ( handleWidth + portWidth * fromIntegral numPorts, applyNodeHeight ) apply :: NodeType apply = NodeType { _ntName = "apply", _ntNumInitialPorts = 3, _ntPortClicked = applyPortClicked, _ntDraw = drawApply, _ntPortLocations = applyPortLocations, _ntHandleLocation = (handleWidth / 2, applyNodeHeight / 2), _ntSize = applySize } ---- TextNode ---- -------- Types ---------- -- | Flip a Do to an Undo, and an Undo to a Do. invertUndoable :: Undoable a -> Undoable a invertUndoable undoable = case undoable of Do a -> Undo a Undo a -> Do a -- | Records actions so that they can be undone. data HistoryEvent = MovedNode -- TODO Record which node, and where the node was moved -- from (and to). | AddedNode ElemId (Double, Double) -- Id of node and position deriving (Show, Eq) emptyAppState :: AppState emptyAppState = AppState { _asMovingNode = Nothing, _asEdges = mempty, _asCurrentEdge = Nothing, _asCurrentPort = Nothing, _asElements = mempty, _asFPSr = 0, _asHistory = [], _asUndoPosition = [], _asBiggestID = 0, _asTransform = Transform 1 (0, 0) } emptyInputs :: Inputs emptyInputs = Inputs { _inMouseXandY = (0, 0), _inTime = MkSystemTime 0 0, _inPrevTime = MkSystemTime 0 0, _inEvents = mempty, _inTranslation = Nothing, _inPressedKeys = mempty } -- | Add a new HistoryEvent and reset _asUndoPosition. addHistoryEvent :: HistoryEvent -> AppState -> AppState addHistoryEvent event state@AppState {_asHistory, _asUndoPosition} = let updatedHistory = Do event : _asHistory in state { _asHistory = updatedHistory, _asUndoPosition = updatedHistory } -- | Add an event to the event queue in Inputs. addEvent :: InputEvent -> Inputs -> Inputs addEvent event inputs@Inputs {_inEvents} = inputs {_inEvents = event : _inEvents} -- | Uses the argument function to combine the tuples. elementwiseOp :: (a -> b -> c) -> (a, a) -> (b, b) -> (c, c) elementwiseOp f (x0, x1) (y0, y1) = (f x0 y0, f x1 y1) renderCairo :: Coercible a GI.Cairo.Context => a -> Render c -> IO c renderCairo c r = withManagedPtr c $ \pointer -> runReaderT (runRender r) (Cairo (castPtr pointer)) drawLine :: Transform -> (Double, Double) -> (Double, Double) -> Render () drawLine Transform {_tScale} (fromX, fromY) (toX, toY) = do Cairo.setSourceRGB 0 1 0 Cairo.setLineWidth (5 * _tScale) Cairo.moveTo fromX fromY Cairo.lineTo toX toY Cairo.stroke _drawCircle :: (Double, Double) -> Render () _drawCircle (x, y) = do -- setSourceRGB 1 0 0 Cairo.setLineWidth 1 -- moveTo x y let radius = 20 let tau = 2 * pi Cairo.arc x y radius 0 tau Cairo.stroke drawNode :: AppState -> (Int, Element) -> Render () drawNode AppState {_asCurrentPort, _asTransform} (elemId, element) = _ntDraw (_elType element) _asTransform (elemId, element) _asCurrentPort -- TODO This name should indicate that it's adding in the location of -- the element. portLocation :: Int -> Element -> (Double, Double) portLocation port element = elementwiseOp (+) (_elPosition element) (_ntPortLocations (_elType element) port) drawCurrentEdge :: (Double, Double) -> AppState -> Render () drawCurrentEdge mousePosition AppState {_asCurrentEdge, _asElements, _asTransform} = case _asCurrentEdge of Nothing -> pure () Just port -> case IntMap.lookup (_unElemId $ _pNode port) _asElements of Nothing -> pure () Just element -> drawLine _asTransform (transform _asTransform (portLocation (_pPort port) element)) mousePosition drawEdges :: AppState -> Render () drawEdges AppState {_asEdges, _asElements, _asTransform} = traverse_ drawEdge (Set.toList _asEdges >>= allPairs) where -- TODO Replace with a minimum spanning tree. -- For each edge, generate all pairs of ports allPairs :: Set.Set Port -> [(Port, Port)] allPairs portSet = do let ports = Set.toList portSet a <- ports let portsMinusA = Set.toList (Set.delete a portSet) b <- portsMinusA [(a, b)] drawEdge :: (Port, Port) -> Render () drawEdge (from, to) = case (lookupFrom, lookupTo) of (Just fromElem, Just toElem) -> drawLine _asTransform (transform _asTransform (portLocation (_pPort from) fromElem)) (transform _asTransform (portLocation (_pPort to) toElem)) _ -> pure () where lookupFrom = IntMap.lookup (_unElemId $ _pNode from) _asElements lookupTo = IntMap.lookup (_unElemId $ _pNode to) _asElements updateBackground :: p -> IORef Inputs -> IORef AppState -> Render () updateBackground _canvas inputsRef stateRef = do -- width <- (realToFrac <$> (liftIO $ Gtk.widgetGetAllocatedWidth canvas) -- :: Render Double) -- height <- (realToFrac <$> (liftIO $ Gtk.widgetGetAllocatedHeight canvas) -- :: Render Double) -- TODO This should be moved into the setup phase Cairo.setSourceRGB 0 0 0 Cairo.paint Cairo.setFontSize baseFontSize state <- Cairo.liftIO $ readIORef stateRef inputs <- Cairo.liftIO $ readIORef inputsRef let fps = _asFPSr state if fps >= 120 then Cairo.setSourceRGB 1 1 1 else Cairo.setSourceRGB 1 0 0 Cairo.moveTo 10 baseFontSize Cairo.showText ("fps=" <> show fps) Cairo.setFontSize (baseFontSize * _tScale (_asTransform state)) drawCurrentEdge (_inMouseXandY inputs) state drawEdges state traverse_ (drawNode state) (IntMap.toList (_asElements state)) findElementByPosition :: IntMap.IntMap Element -> (Double, Double) -> Maybe (Int, Element) findElementByPosition elements (mouseX, mouseY) = let mouseInElement (_elementId, Element {_elPosition, _elType, _elNumPorts}) = let (x, y) = _elPosition (width, height) = _ntSize _elType _elNumPorts in mouseX >= x && mouseX <= (x + width) && mouseY >= y && mouseY <= (y + height) in find mouseInElement (IntMap.toList elements) -- | Time between steps in seconds. calcFrameTime :: Inputs -> Double calcFrameTime Inputs {_inTime, _inPrevTime} = frameTime where nanoToSecond nanoSecond = fromIntegral nanoSecond / (10 ^ (9 :: Int)) frameTime = fromIntegral secondsDiff + nanosecondDiff (MkSystemTime seconds nanoseconds) = _inTime (MkSystemTime oldSeconds oldNanoseconds) = _inPrevTime secondsDiff = seconds - oldSeconds -- nanoseconds in MkSystemTime are unsigned, so they can not be -- directly subtracted. nanosecondDiff = nanoToSecond nanoseconds - nanoToSecond oldNanoseconds getFps :: Inputs -> Int getFps inputs = let fps :: Int fps = round $ 1 / calcFrameTime inputs in if fps >= 200 then div fps 100 * (100 :: Int) else fps clickOnNode :: MouseButton -> ElemId -> (Double, Double) -> -- Click position where (0,0) is top left of element AppState -> AppState clickOnNode mouseButton = case mouseButton of LeftMouseButton -> clickOnNodePrimaryAction RightMouseButton -> clickOnNodeSecondaryAction _ -> \_ _ -> id clickOnNodePrimaryAction :: ElemId -> (Double, Double) -> -- Click position where (0,0) is top left of element AppState -> AppState clickOnNodePrimaryAction elemId relativePosition oldState@AppState { _asMovingNode, _asHistory, _asElements, _asCurrentEdge, _asEdges } = let portClicked = case IntMap.lookup (_unElemId elemId) _asElements of Nothing -> Nothing Just element -> _ntPortClicked (_elType element) relativePosition element in case _asMovingNode of Nothing -> case portClicked of Nothing -> oldState {_asMovingNode = Just elemId} Just port -> case _asCurrentEdge of Nothing -> oldState { _asCurrentEdge = Just $ Port {_pNode = elemId, _pPort = port} } Just edgePort -> oldState { _asEdges = -- TODO May want to add one of the ports to the -- other's existing edge. Set.insert ( Set.fromList [ edgePort, Port {_pNode = elemId, _pPort = port} ] ) _asEdges, _asCurrentEdge = Nothing } Just _ -> addHistoryEvent MovedNode $ oldState {_asMovingNode = Nothing} clickOnNodeSecondaryAction :: ElemId -> (Double, Double) -> -- Click position where (0,0) is top left of element AppState -> AppState clickOnNodeSecondaryAction elemId relativePosition oldState@AppState { _asMovingNode, _asHistory, _asElements, _asCurrentPort, _asEdges } = let portClicked = case IntMap.lookup (_unElemId elemId) _asElements of Nothing -> Nothing Just element -> _ntPortClicked (_elType element) relativePosition element in case (portClicked, _asCurrentPort) of (Just port, _) -> oldState { _asCurrentPort = Just $ Port { _pNode = elemId, _pPort = port } } _ -> oldState {_asCurrentPort = Nothing} -- | Add a node to the canvas at the given position in Element -- coordinates with a known ID. addNodeWithId :: ElemId -> (Double, Double) -> AppState -> AppState addNodeWithId nodeId addPosition state@AppState {_asElements, _asHistory, _asBiggestID} = let applyNode = Element { _elPosition = addPosition, _elZ = 0, _elType = apply, _elNumPorts = _ntNumInitialPorts apply, _elPortText = mempty } newElements = IntMap.insert (_unElemId nodeId) applyNode _asElements in addHistoryEvent (AddedNode nodeId addPosition) $ state { _asElements = newElements, _asBiggestID = max _asBiggestID nodeId } -- | Add a node to the canvas at the given position. addNode :: (Double, Double) -> AppState -> AppState addNode addPosition state@AppState {_asBiggestID} = addNodeWithId (1 + _asBiggestID) addPosition state removeNode :: ElemId -> AppState -> AppState removeNode nodeId oldState@AppState {_asElements} = oldState {_asElements = IntMap.delete (_unElemId nodeId) _asElements} undo :: AppState -> AppState undo oldState@AppState {_asHistory, _asUndoPosition} = newState where newState = case _asUndoPosition of [] -> oldState historyEvent : restOfHistory -> undidState { _asHistory = invertUndoable historyEvent : _asHistory, _asUndoPosition = restOfHistory } where undidState = case historyEvent of Do MovedNode -> oldState -- TODO Implement undo move node. Do (AddedNode nodeId _) -> removeNode nodeId oldState Undo (AddedNode nodeId position) -> addNodeWithId nodeId position oldState Undo MovedNode -> oldState -- TODO Implement undo Undo move. -- | Abort the current action. This includes resetting the _asUndoPosition. abort :: AppState -> AppState abort state@AppState {_asHistory, _asUndoPosition} = state {_asUndoPosition = _asHistory} -- | Adjust the scale factor. adjustScale :: (Double, Double) -> Double -> AppState -> AppState adjustScale mousePosition scaleAdjustment state@AppState {_asTransform} = state { _asTransform = _asTransform { _tScale = newScale, _tTranslate = newTranslate } } where oldScale = _tScale _asTransform adjustedScale = oldScale * scaleAdjustment newScale = if adjustedScale > minimumScale then adjustedScale else oldScale -- When zooming, elements that are at the mouse position should -- stay at the mouse position under the new transform. Elements at -- the mouse position are at -- unTransform _asTransform mousePosition -- So -- mousePosition = -- transform newTransform (unTransform _asTransform mousePosision) -- Which when solved for the new translation produces the code below. unTransformedMousePosition = unTransform _asTransform mousePosition newTranslate = elementwiseOp (-) mousePosition ( Tuple.both (* newScale) unTransformedMousePosition ) processInput :: Inputs -> InputEvent -> AppState -> AppState processInput Inputs {_inMouseXandY} inputEvent oldState = case inputEvent of ClickOnNode mouseButton elemId relativePosition -> clickOnNode mouseButton elemId relativePosition oldState AddNode addPosition -> addNode addPosition oldState UndoEvent -> undo oldState AbortEvent -> abort oldState ScaleAdjustEvent scaleAdjustment -> adjustScale _inMouseXandY scaleAdjustment oldState processInputs :: Inputs -> AppState -> AppState processInputs inputs@Inputs {_inEvents} oldState@AppState {_asElements, _asMovingNode} = let compose = foldr (.) id in compose (fmap (processInput inputs) _inEvents) oldState -- The amount by which to adjust the translation when the panning keys -- are pressed. keyPanAdjustment :: Double -> Set.Set KeyEvent -> (Double, Double) keyPanAdjustment frameTime pressedKeys = (xAdjust, yAdjust) where moveAmount = frameTime * panSpeed moveLeft = if Set.member MoveLeft pressedKeys then moveAmount else 0 moveRight = if Set.member MoveRight pressedKeys then (- moveAmount) else 0 moveUp = if Set.member MoveUp pressedKeys then moveAmount else 0 moveDown = if Set.member MoveDown pressedKeys then (- moveAmount) else 0 xAdjust = moveLeft + moveRight yAdjust = moveUp + moveDown -- | Update the state based on the inputs and the old state. updateState :: Inputs -> AppState -> AppState updateState inputs@Inputs {_inMouseXandY, _inEvents, _inTranslation, _inPressedKeys} oldState@AppState {_asElements, _asMovingNode, _asTransform} = let -- Move the asMovingNode to MouseXandY newElements = case _asMovingNode of Nothing -> _asElements Just nodeId -> IntMap.adjust ( \oldNode@Element {_elPosition, _elType} -> let newPosition = elementwiseOp (-) (unTransform _asTransform _inMouseXandY) (_ntHandleLocation _elType) in oldNode {_elPosition = newPosition} ) (_unElemId nodeId) _asElements mousePanTranslate = case _inTranslation of Nothing -> _tTranslate _asTransform Just (Panning initialMousePosition initialTranslation) -> elementwiseOp (+) initialTranslation (elementwiseOp (-) _inMouseXandY initialMousePosition) newTranslate = elementwiseOp (+) mousePanTranslate ( keyPanAdjustment (calcFrameTime inputs) _inPressedKeys ) in oldState { _asElements = newElements, _asFPSr = getFps inputs, _asTransform = _asTransform {_tTranslate = newTranslate} } ---------- Input Callbacks --------------------------------- leftClickAction :: IORef Inputs -> IORef AppState -> (Double, Double) -> IO () leftClickAction inputsRef stateRef mousePosition = do state <- readIORef stateRef -- print (_asEdges state) let mElem = findElementByPosition (_asElements state) mousePosition addClickEvent inputs@Inputs {_inEvents} = case mElem of Nothing -> inputs Just (elemId, element) -> addEvent ( ClickOnNode LeftMouseButton (ElemId elemId) (elementwiseOp (-) mousePosition (_elPosition element)) ) inputs writeIORef stateRef (state {_asCurrentPort = Nothing}) modifyIORef' inputsRef addClickEvent -- TODO Refactor with leftClickAction. Passing the MouseButton to -- ClickOnNode feels wrong since actions should be separate from -- inputs. Perhaps PrimaryAction and SecondaryAction instead? rightClickAction :: IORef Inputs -> IORef AppState -> (Double, Double) -> IO () rightClickAction inputsRef stateRef mousePosition = do state <- readIORef stateRef let mElem = findElementByPosition (_asElements state) mousePosition addClickEvent inputs@Inputs {_inEvents} = case mElem of Nothing -> addEvent (AddNode mousePosition) inputs Just (elemId, element) -> addEvent ( ClickOnNode -- TODO Event should be move node or -- something like that. Selecting a port should be -- instant, not an event. RightMouseButton (ElemId elemId) (elementwiseOp (-) mousePosition (_elPosition element)) ) inputs when (isNothing mElem) (writeIORef stateRef (state {_asCurrentPort = Nothing})) modifyIORef' inputsRef addClickEvent pure () backgroundPress :: IORef Inputs -> IORef AppState -> MouseButton -> (Double, Double) -> IO () backgroundPress inputsRef stateRef mouseButton rawMousePosition = do putStrLn ("Background pressed by " <> show mouseButton) state <- readIORef stateRef let mousePosition = windowToElementCoordinates state rawMousePosition case mouseButton of RightMouseButton -> rightClickAction inputsRef stateRef mousePosition LeftMouseButton -> leftClickAction inputsRef stateRef mousePosition _ -> mempty addUndoInputAction :: IORef Inputs -> IO () addUndoInputAction inputsRef = do putStrLn "Undo" modifyIORef' inputsRef (addEvent UndoEvent) pure () addAbortAction :: IORef Inputs -> IO () addAbortAction inputsRef = do putStrLn "Abort" modifyIORef' inputsRef (addEvent AbortEvent) pure () editPortText :: Port -> Text.Text -> AppState -> AppState editPortText Port {_pNode, _pPort} newText oldState@AppState {_asElements} = oldState { _asElements = IntMap.adjust modifyElem (_unElemId _pNode) _asElements } where modifyElem :: Element -> Element modifyElem el@Element {_elPortText} = el {_elPortText = IntMap.alter changeText _pPort _elPortText} changeText :: (Maybe Text.Text -> Maybe Text.Text) changeText = case newText of -- "\b" is backspace "\b" -> \mText -> do -- Maybe monad text <- mText (inits, _) <- Text.unsnoc text pure inits _ -> Just . maybe newText (<> newText) keyPress :: IORef Inputs -> IORef AppState -> KeyInput -> IO () keyPress inputsRef stateRef keyInput = do -- print keyInput let keyEvent = _kiKeyEvent keyInput state <- readIORef stateRef preKeyPressedInputs <- readIORef inputsRef case _asCurrentPort state of Just port -> modifyIORef' stateRef (editPortText port (_kiKeyString keyInput)) Nothing -> do let inputs = preKeyPressedInputs { _inPressedKeys = Set.insert keyEvent (_inPressedKeys preKeyPressedInputs) } writeIORef inputsRef inputs -- print (_inPressedKeys inputs) case keyEvent of UndoKey -> addUndoInputAction inputsRef AbortKey -> addAbortAction inputsRef MouseTranslateKey -> if | isNothing (_inTranslation inputs) -> writeIORef inputsRef ( inputs { _inTranslation = Just ( Panning (_inMouseXandY inputs) (_tTranslate (_asTransform state)) ) } ) >> putStrLn "translate key pressed" | otherwise -> pure () OtherKey keyStr -> print keyStr _ -> pure () -- pure -- () keyRelease :: IORef Inputs -> KeyInput -> IO () keyRelease inputsRef keyInput = do let keyEvent = _kiKeyEvent keyInput modifyIORef' inputsRef ( \inputs -> inputs { _inPressedKeys = Set.delete keyEvent (_inPressedKeys inputs) } ) case keyEvent of MouseTranslateKey -> modifyIORef' inputsRef ( \inputs -> inputs { _inTranslation = Nothing } ) >> putStrLn "translate key released" _ -> pure () addScaleAdjustAction :: -- | Amount by which to change the scale factor Double -> IORef Inputs -> IO () addScaleAdjustAction scaleDelta inputsRef = do -- putStrLn ("Adjusting scale by " <> show scaleDelta) modifyIORef' inputsRef (addEvent (ScaleAdjustEvent scaleDelta)) pure () scroll :: IORef Inputs -> Double -> IO () scroll inputsRef deltaY = -- scale in (zooming in) is negative (usually -1), scale out -- (zooming out) is positive (usually 1) if deltaY /= 0.0 then addScaleAdjustAction (1 - (0.2 * deltaY)) inputsRef else pure () -- | Called by GtkGui.timeoutCallback step :: IORef Inputs -> IORef AppState -> SystemTime -> (Double, Double) -> IO a -> IO a step inputsRef stateRef newTime (mouseX, mouseY) drawCommand = do modifyIORef' inputsRef ( \inputs@Inputs {_inTime} -> inputs { _inMouseXandY = (mouseX, mouseY), _inTime = newTime, _inPrevTime = _inTime } ) inputs <- readIORef inputsRef modifyIORef' stateRef (updateState inputs . processInputs inputs) modifyIORef' inputsRef (\i -> i {_inEvents = []}) -- Clear the event queue. -- state <- readIORef stateRef -- print (_asCurrentPort state) drawCommand
rgleichman/glance
gui/GuiInternals.hs
gpl-3.0
32,861
0
28
8,929
7,348
3,945
3,403
805
7
module Handler.HomeSpec (spec) where import TestImport spec :: Spec spec = withApp $ do it "loads the index and checks it looks right" $ do get HomeR statusIs 200 htmlAllContain "h1" "Welcome to Yesod" request $ do setMethod "POST" setUrl HomeR addNonce fileByLabel "Choose a file" "test/Spec.hs" "text/plain" -- talk about self-reference byLabel "What's on the file?" "Some Content" statusIs 200 -- more debugging printBody htmlCount ".message" 1 htmlAllContain ".message" "Some Content" htmlAllContain ".message" "text/plain" -- This is a simple example of using a database access in a test. The -- test will succeed for a fresh scaffolded site with an empty database, -- but will fail on an existing database with a non-empty user table. it "leaves the user table empty" $ do get HomeR statusIs 200 users <- runDB $ selectList ([] :: [Filter User]) [] assertEqual "user table empty" 0 $ length users
prikhi/MyBookList
test/Handler/HomeSpec.hs
gpl-3.0
1,103
0
16
346
202
89
113
23
1
module HEP.Automation.MadGraph.Dataset.Set20110316set9 where import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.Cluster import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Dataset.Common my_ssetup :: ScriptSetup my_ssetup = SS { scriptbase = "/nobackup/iankim/nfs/workspace/ttbar/mc_script2/" , mg5base = "/nobackup/iankim/montecarlo/MG_ME_V4.4.44/MadGraph5_v0_6_1/" , workbase = "/nobackup/iankim/nfs/workspace/ttbar/mc/" } ucut :: UserCut ucut = UserCut { uc_metcut = 15.0 , uc_etacutlep = 1.2 , uc_etcutlep = 18.0 , uc_etacutjet = 2.5 , uc_etcutjet = 15.0 } processTTBar0or1jet :: [Char] processTTBar0or1jet = "\ngenerate P P > t t~ QED=99 @1 \nadd process P P > t t~ J QED=99 @2 \n" psetup_six_ttbar01j :: ProcessSetup psetup_six_ttbar01j = PS { mversion = MadGraph5 , model = Six , process = processTTBar0or1jet , processBrief = "ttbar01j" , workname = "316Six1JBig2" } my_csetup :: ClusterSetup my_csetup = CS { cluster = Parallel 10 } sixparamset :: [Param] sixparamset = [ SixParam mass g | mass <- [1400.0] , g <- [4.0] ] psetuplist :: [ProcessSetup] psetuplist = [ psetup_six_ttbar01j ] sets :: [Int] sets = [41..50] sixtasklist :: [WorkSetup] sixtasklist = [ WS my_ssetup (psetup_six_ttbar01j) (rsetupGen p MLM (UserCutDef ucut) RunPGS 100000 num) my_csetup | p <- sixparamset , num <- sets ] totaltasklist :: [WorkSetup] totaltasklist = sixtasklist
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110316set9.hs
gpl-3.0
1,696
0
10
409
356
219
137
46
1
module Hadolint.Formatter.Checkstyle ( printResults, formatResult, ) where import qualified Control.Foldl as Foldl import qualified Data.ByteString.Builder as Builder import qualified Data.ByteString.Lazy.Char8 as B import Data.Char (isAsciiLower, isAsciiUpper, isDigit, ord) import qualified Data.Text as Text import Data.Text.Encoding (encodeUtf8Builder) import Hadolint.Formatter.Format ( Result (..), errorBundlePretty, errorPosition, severityText, ) import Hadolint.Rule (CheckFailure (..), DLSeverity (..), RuleCode (..)) import System.IO (stdout) import Text.Megaparsec (TraversableStream) import Text.Megaparsec.Error ( ParseErrorBundle, ShowErrorComponent, ) import Text.Megaparsec.Pos (sourceColumn, sourceLine, unPos) import Text.Megaparsec.Stream (VisualStream) data CheckStyle = CheckStyle { line :: Int, column :: Int, impact :: Text.Text, msg :: Text.Text, source :: Text.Text } errorToCheckStyle :: (VisualStream s, TraversableStream s, ShowErrorComponent e) => ParseErrorBundle s e -> CheckStyle errorToCheckStyle err = CheckStyle { line = unPos (sourceLine pos), column = unPos (sourceColumn pos), impact = severityText DLErrorC, msg = Text.pack (errorBundlePretty err), source = "DL1000" } where pos = errorPosition err ruleToCheckStyle :: CheckFailure -> CheckStyle ruleToCheckStyle CheckFailure {..} = CheckStyle { line = line, column = 1, impact = severityText severity, msg = message, source = unRuleCode code } toXml :: CheckStyle -> Builder.Builder toXml CheckStyle {..} = "<error " <> attr "line" (Builder.intDec line) <> attr "column" (Builder.intDec column) <> attr "severity" (encode impact) <> attr "message" (encode msg) <> attr "source" (encode source) <> "/>" encode :: Text.Text -> Builder.Builder encode = encodeUtf8Builder . escape attr :: Text.Text -> Builder.Builder -> Builder.Builder attr name value = encodeUtf8Builder name <> "='" <> value <> "' " escape :: Text.Text -> Text.Text escape = Text.concatMap doEscape where doEscape c = if isOk c then Text.singleton c else "&#" <> Text.pack (show (ord c)) <> ";" isOk x = any (\check -> check x) [isAsciiUpper, isAsciiLower, isDigit, (`elem` [' ', '.', '/'])] formatResult :: (VisualStream s, TraversableStream s, ShowErrorComponent e) => Result s e -> Maybe FilePath -> Builder.Builder formatResult (Result filename errors checks) filePathInReport = header <> xmlBody <> footer where xmlBody = Foldl.fold (Foldl.premap toXml Foldl.mconcat) issues issues = checkstyleErrors <> checkstyleChecks checkstyleErrors = fmap errorToCheckStyle errors checkstyleChecks = fmap ruleToCheckStyle checks isEmpty = null checks && null errors name = if null filePathInReport then filename else getFilePath filePathInReport header = if isEmpty then "" else "<file " <> attr "name" (encode name) <> ">" footer = if isEmpty then "" else "</file>" printResults :: (Foldable f, VisualStream s, TraversableStream s, ShowErrorComponent e) => f (Result s e) -> Maybe FilePath -> IO () printResults results filePathInReport = do B.putStr header mapM_ put results B.putStr footer where header = "<?xml version='1.0' encoding='UTF-8'?><checkstyle version='4.3'>" footer = "</checkstyle>" put result = Builder.hPutBuilder stdout (formatResult result filePathInReport) getFilePath :: Maybe FilePath -> Text.Text getFilePath Nothing = "" getFilePath (Just filePath) = toText [filePath] toText :: [FilePath] -> Text.Text toText = foldMap Text.pack
lukasmartinelli/hadolint
src/Hadolint/Formatter/Checkstyle.hs
gpl-3.0
3,688
0
14
732
1,119
613
506
-1
-1
{-# LANGUAGE NoImplicitPrelude, RecordWildCards, OverloadedStrings #-} module Lamdu.GUI.ExpressionEdit.GetVarEdit ( make ) where import qualified Control.Lens as Lens import Control.Lens.Operators import qualified Data.ByteString.Char8 as SBS8 import Data.Monoid ((<>)) import Data.Store.Transaction (Transaction) import qualified Graphics.DrawingCombinators as Draw import qualified Graphics.UI.Bottle.EventMap as E import qualified Graphics.UI.Bottle.Widget as Widget import qualified Graphics.UI.Bottle.Widgets as BWidgets import Lamdu.Config (Config) import qualified Lamdu.Config as Config import qualified Lamdu.Data.Ops as DataOps import Lamdu.GUI.ExpressionGui (ExpressionGui) import qualified Lamdu.GUI.ExpressionGui as ExpressionGui import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM) import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT import qualified Lamdu.GUI.LightLambda as LightLambda import qualified Lamdu.GUI.WidgetIds as WidgetIds import Lamdu.Sugar.Names.Types (Name(..)) import qualified Lamdu.Sugar.Types as Sugar import Prelude.Compat makeSimpleView :: Monad m => Draw.Color -> Name m -> Widget.Id -> ExprGuiM m (ExpressionGui m) makeSimpleView color name myId = ExprGuiM.widgetEnv (BWidgets.makeFocusableView myId) <*> ExpressionGui.makeNameView name (Widget.toAnimId myId) <&> ExpressionGui.fromValueWidget & ExprGuiM.withFgColor color makeParamsRecord :: Monad m => Widget.Id -> Sugar.ParamsRecordVar (Name m) -> ExprGuiM m (ExpressionGui m) makeParamsRecord myId paramsRecordVar = do config <- ExprGuiM.readConfig let Config.Name{..} = Config.name config sequence [ ExpressionGui.makeLabel "Params {" (Widget.toAnimId myId <> ["prefix"]) , ExpressionGui.hboxSpaced <*> ( zip [0..] fieldNames & mapM (\(i, fieldName) -> makeSimpleView parameterColor fieldName $ Widget.joinId myId ["params", SBS8.pack (show (i::Int))]) ) , ExpressionGui.makeLabel "}" (Widget.toAnimId myId <> ["suffix"]) ] <&> ExpressionGui.hbox where Sugar.ParamsRecordVar fieldNames = paramsRecordVar makeNameRef :: Monad m => Widget.Id -> Sugar.NameRef name m -> (name -> Widget.Id -> ExprGuiM m (ExpressionGui m)) -> ExprGuiM m (ExpressionGui m) makeNameRef myId nameRef makeView = do cp <- ExprGuiM.readCodeAnchors config <- ExprGuiM.readConfig let jumpToDefinitionEventMap = Widget.keysEventMapMovesCursor (Config.jumpToDefinitionKeys config ++ Config.extractKeys config) (E.Doc ["Navigation", "Jump to definition"]) $ do DataOps.savePreJumpPosition cp myId WidgetIds.fromEntityId <$> nameRef ^. Sugar.nrGotoDefinition makeView (nameRef ^. Sugar.nrName) myId <&> ExpressionGui.egWidget %~ Widget.weakerEvents jumpToDefinitionEventMap makeInlineEventMap :: Monad m => Config -> Sugar.BinderVarInline m -> Widget.EventMap (Transaction m Widget.EventResult) makeInlineEventMap config (Sugar.InlineVar inline) = inline <&> WidgetIds.fromEntityId & Widget.keysEventMapMovesCursor (Config.inlineKeys config) (E.Doc ["Edit", "Inline"]) makeInlineEventMap config (Sugar.CannotInlineDueToUses (x:_)) = WidgetIds.fromEntityId x & return & Widget.keysEventMapMovesCursor (Config.inlineKeys config) (E.Doc ["Navigation", "Jump to next use"]) makeInlineEventMap _ _ = mempty make :: Monad m => Sugar.GetVar (Name m) m -> Sugar.Payload m ExprGuiT.Payload -> ExprGuiM m (ExpressionGui m) make getVar pl = do config <- ExprGuiM.readConfig let Config.Name{..} = Config.name config case getVar of Sugar.GetBinder binderVar -> case binderVar ^. Sugar.bvForm of Sugar.GetLet -> letColor Sugar.GetDefinition -> definitionColor & makeSimpleView & makeNameRef myId (binderVar ^. Sugar.bvNameRef) <&> ExpressionGui.egWidget %~ Widget.weakerEvents (makeInlineEventMap config (binderVar ^. Sugar.bvInline)) Sugar.GetParam param -> case param ^. Sugar.pBinderMode of Sugar.LightLambda -> makeSimpleView nameOriginFGColor <&> Lens.mapped %~ LightLambda.withUnderline (Config.lightLambda config) _ -> makeSimpleView parameterColor & makeNameRef myId (param ^. Sugar.pNameRef) Sugar.GetParamsRecord paramsRecordVar -> makeParamsRecord myId paramsRecordVar & ExpressionGui.stdWrap pl where myId = WidgetIds.fromExprPayload pl
da-x/lamdu
Lamdu/GUI/ExpressionEdit/GetVarEdit.hs
gpl-3.0
5,065
0
22
1,350
1,259
665
594
111
5
{-# 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.RemarketingListShares.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 one remarketing list share by remarketing list ID. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.remarketingListShares.get@. module Network.Google.Resource.DFAReporting.RemarketingListShares.Get ( -- * REST Resource RemarketingListSharesGetResource -- * Creating a Request , remarketingListSharesGet , RemarketingListSharesGet -- * Request Lenses , rlsgProFileId , rlsgRemarketingListId ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.remarketingListShares.get@ method which the -- 'RemarketingListSharesGet' request conforms to. type RemarketingListSharesGetResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "remarketingListShares" :> Capture "remarketingListId" (Textual Int64) :> QueryParam "alt" AltJSON :> Get '[JSON] RemarketingListShare -- | Gets one remarketing list share by remarketing list ID. -- -- /See:/ 'remarketingListSharesGet' smart constructor. data RemarketingListSharesGet = RemarketingListSharesGet' { _rlsgProFileId :: !(Textual Int64) , _rlsgRemarketingListId :: !(Textual Int64) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'RemarketingListSharesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rlsgProFileId' -- -- * 'rlsgRemarketingListId' remarketingListSharesGet :: Int64 -- ^ 'rlsgProFileId' -> Int64 -- ^ 'rlsgRemarketingListId' -> RemarketingListSharesGet remarketingListSharesGet pRlsgProFileId_ pRlsgRemarketingListId_ = RemarketingListSharesGet' { _rlsgProFileId = _Coerce # pRlsgProFileId_ , _rlsgRemarketingListId = _Coerce # pRlsgRemarketingListId_ } -- | User profile ID associated with this request. rlsgProFileId :: Lens' RemarketingListSharesGet Int64 rlsgProFileId = lens _rlsgProFileId (\ s a -> s{_rlsgProFileId = a}) . _Coerce -- | Remarketing list ID. rlsgRemarketingListId :: Lens' RemarketingListSharesGet Int64 rlsgRemarketingListId = lens _rlsgRemarketingListId (\ s a -> s{_rlsgRemarketingListId = a}) . _Coerce instance GoogleRequest RemarketingListSharesGet where type Rs RemarketingListSharesGet = RemarketingListShare type Scopes RemarketingListSharesGet = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient RemarketingListSharesGet'{..} = go _rlsgProFileId _rlsgRemarketingListId (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy RemarketingListSharesGetResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/RemarketingListShares/Get.hs
mpl-2.0
3,781
0
14
825
421
249
172
69
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.DLP.Types -- 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) -- module Network.Google.DLP.Types ( -- * Service Configuration dLPService -- * OAuth Scopes , cloudPlatformScope -- * GooglePrivacyDlpV2InfoTypeStats , GooglePrivacyDlpV2InfoTypeStats , googlePrivacyDlpV2InfoTypeStats , gpdvitsCount , gpdvitsInfoType -- * GooglePrivacyDlpV2RedactConfig , GooglePrivacyDlpV2RedactConfig , googlePrivacyDlpV2RedactConfig -- * GooglePrivacyDlpV2UpdateJobTriggerRequest , GooglePrivacyDlpV2UpdateJobTriggerRequest , googlePrivacyDlpV2UpdateJobTriggerRequest , gpdvujtrUpdateMask , gpdvujtrJobTrigger -- * GooglePrivacyDlpV2Range , GooglePrivacyDlpV2Range , googlePrivacyDlpV2Range , gpdvrStart , gpdvrEnd -- * GoogleRpcStatus , GoogleRpcStatus , googleRpcStatus , grsDetails , grsCode , grsMessage -- * GooglePrivacyDlpV2HybridInspectStatistics , GooglePrivacyDlpV2HybridInspectStatistics , googlePrivacyDlpV2HybridInspectStatistics , gpdvhisAbortedCount , gpdvhisPendingCount , gpdvhisProcessedCount -- * GooglePrivacyDlpV2FixedSizeBucketingConfig , GooglePrivacyDlpV2FixedSizeBucketingConfig , googlePrivacyDlpV2FixedSizeBucketingConfig , gpdvfsbcUpperBound , gpdvfsbcLowerBound , gpdvfsbcBucketSize -- * GooglePrivacyDlpV2InspectResult , GooglePrivacyDlpV2InspectResult , googlePrivacyDlpV2InspectResult , gpdvirFindingsTruncated , gpdvirFindings -- * GooglePrivacyDlpV2StoredInfoTypeConfig , GooglePrivacyDlpV2StoredInfoTypeConfig , googlePrivacyDlpV2StoredInfoTypeConfig , gpdvsitcRegex , gpdvsitcLargeCustomDictionary , gpdvsitcDisplayName , gpdvsitcDictionary , gpdvsitcDescription -- * GooglePrivacyDlpV2InfoTypeTransformation , GooglePrivacyDlpV2InfoTypeTransformation , googlePrivacyDlpV2InfoTypeTransformation , gpdvittInfoTypes , gpdvittPrimitiveTransformation -- * GooglePrivacyDlpV2FieldId , GooglePrivacyDlpV2FieldId , googlePrivacyDlpV2FieldId , gpdvfiName -- * GooglePrivacyDlpV2Container , GooglePrivacyDlpV2Container , googlePrivacyDlpV2Container , gpdvcFullPath , gpdvcUpdateTime , gpdvcVersion , gpdvcProjectId , gpdvcType , gpdvcRootPath , gpdvcRelativePath -- * GooglePrivacyDlpV2DlpJob , GooglePrivacyDlpV2DlpJob , googlePrivacyDlpV2DlpJob , gpdvdjInspectDetails , gpdvdjState , gpdvdjStartTime , gpdvdjJobTriggerName , gpdvdjRiskDetails , gpdvdjName , gpdvdjEndTime , gpdvdjType , gpdvdjErrors , gpdvdjCreateTime -- * GooglePrivacyDlpV2RecordTransformations , GooglePrivacyDlpV2RecordTransformations , googlePrivacyDlpV2RecordTransformations , gpdvrtRecordSuppressions , gpdvrtFieldTransformations -- * GooglePrivacyDlpV2CustomInfoTypeLikelihood , GooglePrivacyDlpV2CustomInfoTypeLikelihood (..) -- * GooglePrivacyDlpV2FindingLikelihood , GooglePrivacyDlpV2FindingLikelihood (..) -- * GooglePrivacyDlpV2Key , GooglePrivacyDlpV2Key , googlePrivacyDlpV2Key , gpdvkPartitionId , gpdvkPath -- * GooglePrivacyDlpV2BucketingConfig , GooglePrivacyDlpV2BucketingConfig , googlePrivacyDlpV2BucketingConfig , gpdvbcBuckets -- * GooglePrivacyDlpV2InspectConfig , GooglePrivacyDlpV2InspectConfig , googlePrivacyDlpV2InspectConfig , gpdvicInfoTypes , gpdvicMinLikelihood , gpdvicExcludeInfoTypes , gpdvicIncludeQuote , gpdvicCustomInfoTypes , gpdvicLimits , gpdvicContentOptions , gpdvicRuleSet -- * GooglePrivacyDlpV2RiskAnalysisJobConfig , GooglePrivacyDlpV2RiskAnalysisJobConfig , googlePrivacyDlpV2RiskAnalysisJobConfig , gpdvrajcPrivacyMetric , gpdvrajcActions , gpdvrajcSourceTable -- * GooglePrivacyDlpV2HybridInspectDlpJobRequest , GooglePrivacyDlpV2HybridInspectDlpJobRequest , googlePrivacyDlpV2HybridInspectDlpJobRequest , gpdvhidjrHybridItem -- * GooglePrivacyDlpV2QuoteInfo , GooglePrivacyDlpV2QuoteInfo , googlePrivacyDlpV2QuoteInfo , gpdvqiDateTime -- * GooglePrivacyDlpV2StoredInfoTypeStats , GooglePrivacyDlpV2StoredInfoTypeStats , googlePrivacyDlpV2StoredInfoTypeStats , gpdvsitsLargeCustomDictionary -- * GooglePrivacyDlpV2RecordSuppression , GooglePrivacyDlpV2RecordSuppression , googlePrivacyDlpV2RecordSuppression , gpdvrsCondition -- * GooglePrivacyDlpV2CryptoKey , GooglePrivacyDlpV2CryptoKey , googlePrivacyDlpV2CryptoKey , gpdvckTransient , gpdvckKmsWrApped , gpdvckUnwrApped -- * GooglePrivacyDlpV2LargeCustomDictionaryConfig , GooglePrivacyDlpV2LargeCustomDictionaryConfig , googlePrivacyDlpV2LargeCustomDictionaryConfig , gpdvlcdcBigQueryField , gpdvlcdcCloudStorageFileSet , gpdvlcdcOutputPath -- * GooglePrivacyDlpV2WordList , GooglePrivacyDlpV2WordList , googlePrivacyDlpV2WordList , gpdvwlWords -- * GooglePrivacyDlpV2ContentItem , GooglePrivacyDlpV2ContentItem , googlePrivacyDlpV2ContentItem , gpdvciValue , gpdvciByteItem , gpdvciTable -- * GooglePrivacyDlpV2CategoricalStatsHistogramBucket , GooglePrivacyDlpV2CategoricalStatsHistogramBucket , googlePrivacyDlpV2CategoricalStatsHistogramBucket , gpdvcshbValueFrequencyLowerBound , gpdvcshbBucketValues , gpdvcshbValueFrequencyUpperBound , gpdvcshbBucketSize , gpdvcshbBucketValueCount -- * GooglePrivacyDlpV2Result , GooglePrivacyDlpV2Result , googlePrivacyDlpV2Result , gpdvrProcessedBytes , gpdvrInfoTypeStats , gpdvrHybridStats , gpdvrTotalEstimatedBytes -- * GooglePrivacyDlpV2HybridOptionsLabels , GooglePrivacyDlpV2HybridOptionsLabels , googlePrivacyDlpV2HybridOptionsLabels , gpdvholAddtional -- * GooglePrivacyDlpV2InspectDataSourceDetails , GooglePrivacyDlpV2InspectDataSourceDetails , googlePrivacyDlpV2InspectDataSourceDetails , gpdvidsdResult , gpdvidsdRequestedOptions -- * GooglePrivacyDlpV2RedactImageResponse , GooglePrivacyDlpV2RedactImageResponse , googlePrivacyDlpV2RedactImageResponse , gpdvrirExtractedText , gpdvrirInspectResult , gpdvrirRedactedImage -- * GooglePrivacyDlpV2PublishToPubSub , GooglePrivacyDlpV2PublishToPubSub , googlePrivacyDlpV2PublishToPubSub , gpdvptpsTopic -- * GooglePrivacyDlpV2CustomInfoTypeExclusionType , GooglePrivacyDlpV2CustomInfoTypeExclusionType (..) -- * GooglePrivacyDlpV2BigQueryKey , GooglePrivacyDlpV2BigQueryKey , googlePrivacyDlpV2BigQueryKey , gpdvbqkTableReference , gpdvbqkRowNumber -- * GooglePrivacyDlpV2LikelihoodAdjustmentFixedLikelihood , GooglePrivacyDlpV2LikelihoodAdjustmentFixedLikelihood (..) -- * GooglePrivacyDlpV2DetectionRule , GooglePrivacyDlpV2DetectionRule , googlePrivacyDlpV2DetectionRule , gpdvdrHotwordRule -- * GooglePrivacyDlpV2TimePartConfigPartToExtract , GooglePrivacyDlpV2TimePartConfigPartToExtract (..) -- * GooglePrivacyDlpV2RecordCondition , GooglePrivacyDlpV2RecordCondition , googlePrivacyDlpV2RecordCondition , gpdvrcExpressions -- * GooglePrivacyDlpV2DateShiftConfig , GooglePrivacyDlpV2DateShiftConfig , googlePrivacyDlpV2DateShiftConfig , gpdvdscContext , gpdvdscUpperBoundDays , gpdvdscCryptoKey , gpdvdscLowerBoundDays -- * GooglePrivacyDlpV2InspectContentRequest , GooglePrivacyDlpV2InspectContentRequest , googlePrivacyDlpV2InspectContentRequest , gpdvicrInspectConfig , gpdvicrItem , gpdvicrLocationId , gpdvicrInspectTemplateName -- * GooglePrivacyDlpV2CategoricalStatsResult , GooglePrivacyDlpV2CategoricalStatsResult , googlePrivacyDlpV2CategoricalStatsResult , gpdvcsrValueFrequencyHistogramBuckets -- * GooglePrivacyDlpV2NumericalStatsResult , GooglePrivacyDlpV2NumericalStatsResult , googlePrivacyDlpV2NumericalStatsResult , gpdvnsrMaxValue , gpdvnsrQuantileValues , gpdvnsrMinValue -- * GooglePrivacyDlpV2TransformationErrorHandling , GooglePrivacyDlpV2TransformationErrorHandling , googlePrivacyDlpV2TransformationErrorHandling , gpdvtehThrowError , gpdvtehLeaveUntransformed -- * GooglePrivacyDlpV2PublishSummaryToCscc , GooglePrivacyDlpV2PublishSummaryToCscc , googlePrivacyDlpV2PublishSummaryToCscc -- * GooglePrivacyDlpV2UpdateInspectTemplateRequest , GooglePrivacyDlpV2UpdateInspectTemplateRequest , googlePrivacyDlpV2UpdateInspectTemplateRequest , gpdvuitrUpdateMask , gpdvuitrInspectTemplate -- * GooglePrivacyDlpV2EntityId , GooglePrivacyDlpV2EntityId , googlePrivacyDlpV2EntityId , gpdveiField -- * GooglePrivacyDlpV2HybridFindingDetailsLabels , GooglePrivacyDlpV2HybridFindingDetailsLabels , googlePrivacyDlpV2HybridFindingDetailsLabels , gpdvhfdlAddtional -- * GooglePrivacyDlpV2ByteContentItem , GooglePrivacyDlpV2ByteContentItem , googlePrivacyDlpV2ByteContentItem , gpdvbciData , gpdvbciType -- * GooglePrivacyDlpV2TaggedField , GooglePrivacyDlpV2TaggedField , googlePrivacyDlpV2TaggedField , gpdvtfField , gpdvtfInfoType , gpdvtfInferred , gpdvtfCustomTag -- * GooglePrivacyDlpV2BigQueryOptions , GooglePrivacyDlpV2BigQueryOptions , googlePrivacyDlpV2BigQueryOptions , gpdvbqoRowsLimit , gpdvbqoRowsLimitPercent , gpdvbqoTableReference , gpdvbqoIdentifyingFields , gpdvbqoExcludedFields , gpdvbqoSampleMethod -- * GooglePrivacyDlpV2PublishFindingsToCloudDataCatalog , GooglePrivacyDlpV2PublishFindingsToCloudDataCatalog , googlePrivacyDlpV2PublishFindingsToCloudDataCatalog -- * GooglePrivacyDlpV2KMapEstimationQuasiIdValues , GooglePrivacyDlpV2KMapEstimationQuasiIdValues , googlePrivacyDlpV2KMapEstimationQuasiIdValues , gpdvkmeqivEstimatedAnonymity , gpdvkmeqivQuasiIdsValues -- * GooglePrivacyDlpV2ExcludeInfoTypes , GooglePrivacyDlpV2ExcludeInfoTypes , googlePrivacyDlpV2ExcludeInfoTypes , gpdveitInfoTypes -- * GooglePrivacyDlpV2CreateInspectTemplateRequest , GooglePrivacyDlpV2CreateInspectTemplateRequest , googlePrivacyDlpV2CreateInspectTemplateRequest , gpdvcitrTemplateId , gpdvcitrLocationId , gpdvcitrInspectTemplate -- * GooglePrivacyDlpV2PathElement , GooglePrivacyDlpV2PathElement , googlePrivacyDlpV2PathElement , gpdvpeKind , gpdvpeName , gpdvpeId -- * GooglePrivacyDlpV2DeltaPresenceEstimationResult , GooglePrivacyDlpV2DeltaPresenceEstimationResult , googlePrivacyDlpV2DeltaPresenceEstimationResult , gpdvdperDeltaPresenceEstimationHistogram -- * GooglePrivacyDlpV2ConditionOperator , GooglePrivacyDlpV2ConditionOperator (..) -- * GooglePrivacyDlpV2InspectJobConfig , GooglePrivacyDlpV2InspectJobConfig , googlePrivacyDlpV2InspectJobConfig , gpdvijcActions , gpdvijcStorageConfig , gpdvijcInspectConfig , gpdvijcInspectTemplateName -- * GooglePrivacyDlpV2StoredType , GooglePrivacyDlpV2StoredType , googlePrivacyDlpV2StoredType , gpdvstName , gpdvstCreateTime -- * GooglePrivacyDlpV2FieldTransformation , GooglePrivacyDlpV2FieldTransformation , googlePrivacyDlpV2FieldTransformation , gpdvftInfoTypeTransformations , gpdvftPrimitiveTransformation , gpdvftCondition , gpdvftFields -- * OrganizationsLocationsDlpJobsListType , OrganizationsLocationsDlpJobsListType (..) -- * GooglePrivacyDlpV2HotwordRule , GooglePrivacyDlpV2HotwordRule , googlePrivacyDlpV2HotwordRule , gpdvhrProximity , gpdvhrLikelihoodAdjustment , gpdvhrHotwordRegex -- * GooglePrivacyDlpV2RedactImageRequest , GooglePrivacyDlpV2RedactImageRequest , googlePrivacyDlpV2RedactImageRequest , gpdvrirIncludeFindings , gpdvrirInspectConfig , gpdvrirByteItem , gpdvrirLocationId , gpdvrirImageRedactionConfigs -- * ProjectsJobTriggersListType , ProjectsJobTriggersListType (..) -- * GooglePrivacyDlpV2FindingLimits , GooglePrivacyDlpV2FindingLimits , googlePrivacyDlpV2FindingLimits , gpdvflMaxFindingsPerItem , gpdvflMaxFindingsPerInfoType , gpdvflMaxFindingsPerRequest -- * GooglePrivacyDlpV2Condition , GooglePrivacyDlpV2Condition , googlePrivacyDlpV2Condition , gpdvcField , gpdvcOperator , gpdvcValue -- * GooglePrivacyDlpV2TimespanConfig , GooglePrivacyDlpV2TimespanConfig , googlePrivacyDlpV2TimespanConfig , gpdvtcTimestampField , gpdvtcStartTime , gpdvtcEnableAutoPopulationOfTimespanConfig , gpdvtcEndTime -- * GooglePrivacyDlpV2MetadataLocationType , GooglePrivacyDlpV2MetadataLocationType (..) -- * GooglePrivacyDlpV2DateTimeDayOfWeek , GooglePrivacyDlpV2DateTimeDayOfWeek (..) -- * GooglePrivacyDlpV2CreateDeidentifyTemplateRequest , GooglePrivacyDlpV2CreateDeidentifyTemplateRequest , googlePrivacyDlpV2CreateDeidentifyTemplateRequest , gpdvcdtrTemplateId , gpdvcdtrDeidentifyTemplate , gpdvcdtrLocationId -- * GooglePrivacyDlpV2CloudStorageOptionsFileTypesItem , GooglePrivacyDlpV2CloudStorageOptionsFileTypesItem (..) -- * GooglePrivacyDlpV2TransientCryptoKey , GooglePrivacyDlpV2TransientCryptoKey , googlePrivacyDlpV2TransientCryptoKey , gpdvtckName -- * GooglePrivacyDlpV2DlpJobState , GooglePrivacyDlpV2DlpJobState (..) -- * GooglePrivacyDlpV2InfoTypeDescription , GooglePrivacyDlpV2InfoTypeDescription , googlePrivacyDlpV2InfoTypeDescription , gpdvitdName , gpdvitdDisplayName , gpdvitdSupportedBy , gpdvitdDescription -- * GoogleProtobufEmpty , GoogleProtobufEmpty , googleProtobufEmpty -- * GoogleRpcStatusDetailsItem , GoogleRpcStatusDetailsItem , googleRpcStatusDetailsItem , grsdiAddtional -- * GooglePrivacyDlpV2ImageRedactionConfig , GooglePrivacyDlpV2ImageRedactionConfig , googlePrivacyDlpV2ImageRedactionConfig , gpdvircRedactionColor , gpdvircInfoType , gpdvircRedactAllText -- * GooglePrivacyDlpV2Trigger , GooglePrivacyDlpV2Trigger , googlePrivacyDlpV2Trigger , gpdvtManual , gpdvtSchedule -- * GooglePrivacyDlpV2CloudStorageOptions , GooglePrivacyDlpV2CloudStorageOptions , googlePrivacyDlpV2CloudStorageOptions , gpdvcsoFileSet , gpdvcsoBytesLimitPerFile , gpdvcsoFileTypes , gpdvcsoBytesLimitPerFilePercent , gpdvcsoFilesLimitPercent , gpdvcsoSampleMethod -- * GooglePrivacyDlpV2SummaryResultCode , GooglePrivacyDlpV2SummaryResultCode (..) -- * GooglePrivacyDlpV2DeltaPresenceEstimationConfig , GooglePrivacyDlpV2DeltaPresenceEstimationConfig , googlePrivacyDlpV2DeltaPresenceEstimationConfig , gpdvdpecAuxiliaryTables , gpdvdpecRegionCode , gpdvdpecQuasiIds -- * GooglePrivacyDlpV2CreateStoredInfoTypeRequest , GooglePrivacyDlpV2CreateStoredInfoTypeRequest , googlePrivacyDlpV2CreateStoredInfoTypeRequest , gpdvcsitrConfig , gpdvcsitrLocationId , gpdvcsitrStoredInfoTypeId -- * GooglePrivacyDlpV2QuasiIdField , GooglePrivacyDlpV2QuasiIdField , googlePrivacyDlpV2QuasiIdField , gpdvqifField , gpdvqifCustomTag -- * GooglePrivacyDlpV2TimePartConfig , GooglePrivacyDlpV2TimePartConfig , googlePrivacyDlpV2TimePartConfig , gpdvtpcPartToExtract -- * GooglePrivacyDlpV2FindingLabels , GooglePrivacyDlpV2FindingLabels , googlePrivacyDlpV2FindingLabels , gpdvflAddtional -- * GooglePrivacyDlpV2InspectionRule , GooglePrivacyDlpV2InspectionRule , googlePrivacyDlpV2InspectionRule , gpdvirExclusionRule , gpdvirHotwordRule -- * GooglePrivacyDlpV2CustomInfoType , GooglePrivacyDlpV2CustomInfoType , googlePrivacyDlpV2CustomInfoType , gpdvcitRegex , gpdvcitStoredType , gpdvcitInfoType , gpdvcitExclusionType , gpdvcitLikelihood , gpdvcitDetectionRules , gpdvcitDictionary , gpdvcitSurrogateType -- * GooglePrivacyDlpV2KMapEstimationResult , GooglePrivacyDlpV2KMapEstimationResult , googlePrivacyDlpV2KMapEstimationResult , gpdvkmerKMapEstimationHistogram -- * GooglePrivacyDlpV2TransformationSummary , GooglePrivacyDlpV2TransformationSummary , googlePrivacyDlpV2TransformationSummary , gpdvtsResults , gpdvtsField , gpdvtsInfoType , gpdvtsRecordSuppress , gpdvtsTransformedBytes , gpdvtsFieldTransformations , gpdvtsTransformation -- * GooglePrivacyDlpV2LikelihoodAdjustment , GooglePrivacyDlpV2LikelihoodAdjustment , googlePrivacyDlpV2LikelihoodAdjustment , gpdvlaFixedLikelihood , gpdvlaRelativeLikelihood -- * GooglePrivacyDlpV2Regex , GooglePrivacyDlpV2Regex , googlePrivacyDlpV2Regex , gpdvrGroupIndexes , gpdvrPattern -- * GooglePrivacyDlpV2UpdateStoredInfoTypeRequest , GooglePrivacyDlpV2UpdateStoredInfoTypeRequest , googlePrivacyDlpV2UpdateStoredInfoTypeRequest , gpdvusitrConfig , gpdvusitrUpdateMask -- * GooglePrivacyDlpV2LeaveUntransformed , GooglePrivacyDlpV2LeaveUntransformed , googlePrivacyDlpV2LeaveUntransformed -- * GooglePrivacyDlpV2KAnonymityEquivalenceClass , GooglePrivacyDlpV2KAnonymityEquivalenceClass , googlePrivacyDlpV2KAnonymityEquivalenceClass , gpdvkaecEquivalenceClassSize , gpdvkaecQuasiIdsValues -- * GooglePrivacyDlpV2UpdateDeidentifyTemplateRequest , GooglePrivacyDlpV2UpdateDeidentifyTemplateRequest , googlePrivacyDlpV2UpdateDeidentifyTemplateRequest , gpdvudtrUpdateMask , gpdvudtrDeidentifyTemplate -- * GooglePrivacyDlpV2LDiversityConfig , GooglePrivacyDlpV2LDiversityConfig , googlePrivacyDlpV2LDiversityConfig , gpdvldcSensitiveAttribute , gpdvldcQuasiIds -- * GooglePrivacyDlpV2JobNotificationEmails , GooglePrivacyDlpV2JobNotificationEmails , googlePrivacyDlpV2JobNotificationEmails -- * ProjectsLocationsDlpJobsListType , ProjectsLocationsDlpJobsListType (..) -- * GooglePrivacyDlpV2DeidentifyContentRequest , GooglePrivacyDlpV2DeidentifyContentRequest , googlePrivacyDlpV2DeidentifyContentRequest , gpdvdcrInspectConfig , gpdvdcrDeidentifyConfig , gpdvdcrDeidentifyTemplateName , gpdvdcrItem , gpdvdcrLocationId , gpdvdcrInspectTemplateName -- * GooglePrivacyDlpV2Color , GooglePrivacyDlpV2Color , googlePrivacyDlpV2Color , gpdvcRed , gpdvcGreen , gpdvcBlue -- * GooglePrivacyDlpV2ListDlpJobsResponse , GooglePrivacyDlpV2ListDlpJobsResponse , googlePrivacyDlpV2ListDlpJobsResponse , gpdvldjrNextPageToken , gpdvldjrJobs -- * GooglePrivacyDlpV2Proximity , GooglePrivacyDlpV2Proximity , googlePrivacyDlpV2Proximity , gpdvpWindowAfter , gpdvpWindowBefore -- * GooglePrivacyDlpV2Finding , GooglePrivacyDlpV2Finding , googlePrivacyDlpV2Finding , gpdvfTriggerName , gpdvfResourceName , gpdvfLocation , gpdvfJobName , gpdvfInfoType , gpdvfQuoteInfo , gpdvfName , gpdvfLikelihood , gpdvfQuote , gpdvfLabels , gpdvfFindingId , gpdvfJobCreateTime , gpdvfCreateTime -- * GooglePrivacyDlpV2SummaryResult , GooglePrivacyDlpV2SummaryResult , googlePrivacyDlpV2SummaryResult , gpdvsrCount , gpdvsrDetails , gpdvsrCode -- * GooglePrivacyDlpV2Row , GooglePrivacyDlpV2Row , googlePrivacyDlpV2Row , gpdvrValues -- * GooglePrivacyDlpV2Manual , GooglePrivacyDlpV2Manual , googlePrivacyDlpV2Manual -- * GooglePrivacyDlpV2PublishToStackdriver , GooglePrivacyDlpV2PublishToStackdriver , googlePrivacyDlpV2PublishToStackdriver -- * GooglePrivacyDlpV2ReplaceWithInfoTypeConfig , GooglePrivacyDlpV2ReplaceWithInfoTypeConfig , googlePrivacyDlpV2ReplaceWithInfoTypeConfig -- * GoogleTypeTimeOfDay , GoogleTypeTimeOfDay , googleTypeTimeOfDay , gttodNanos , gttodHours , gttodMinutes , gttodSeconds -- * GooglePrivacyDlpV2OutputStorageConfigOutputSchema , GooglePrivacyDlpV2OutputStorageConfigOutputSchema (..) -- * GooglePrivacyDlpV2ExclusionRule , GooglePrivacyDlpV2ExclusionRule , googlePrivacyDlpV2ExclusionRule , gpdverRegex , gpdverExcludeInfoTypes , gpdverDictionary , gpdverMatchingType -- * GooglePrivacyDlpV2CreateDlpJobRequest , GooglePrivacyDlpV2CreateDlpJobRequest , googlePrivacyDlpV2CreateDlpJobRequest , gpdvcdjrRiskJob , gpdvcdjrJobId , gpdvcdjrInspectJob , gpdvcdjrLocationId -- * GooglePrivacyDlpV2RecordKey , GooglePrivacyDlpV2RecordKey , googlePrivacyDlpV2RecordKey , gpdvrkIdValues , gpdvrkDatastoreKey , gpdvrkBigQueryKey -- * GooglePrivacyDlpV2KMapEstimationHistogramBucket , GooglePrivacyDlpV2KMapEstimationHistogramBucket , googlePrivacyDlpV2KMapEstimationHistogramBucket , gpdvkmehbMaxAnonymity , gpdvkmehbBucketValues , gpdvkmehbMinAnonymity , gpdvkmehbBucketSize , gpdvkmehbBucketValueCount -- * GooglePrivacyDlpV2LargeCustomDictionaryStats , GooglePrivacyDlpV2LargeCustomDictionaryStats , googlePrivacyDlpV2LargeCustomDictionaryStats , gpdvlcdsApproxNumPhrases -- * GooglePrivacyDlpV2ListDeidentifyTemplatesResponse , GooglePrivacyDlpV2ListDeidentifyTemplatesResponse , googlePrivacyDlpV2ListDeidentifyTemplatesResponse , gpdvldtrNextPageToken , gpdvldtrDeidentifyTemplates -- * GooglePrivacyDlpV2BigQueryOptionsSampleMethod , GooglePrivacyDlpV2BigQueryOptionsSampleMethod (..) -- * GooglePrivacyDlpV2DlpJobType , GooglePrivacyDlpV2DlpJobType (..) -- * GooglePrivacyDlpV2KAnonymityConfig , GooglePrivacyDlpV2KAnonymityConfig , googlePrivacyDlpV2KAnonymityConfig , gpdvkacEntityId , gpdvkacQuasiIds -- * GooglePrivacyDlpV2DeidentifyContentResponse , GooglePrivacyDlpV2DeidentifyContentResponse , googlePrivacyDlpV2DeidentifyContentResponse , gOverview , gItem -- * GooglePrivacyDlpV2JobTrigger , GooglePrivacyDlpV2JobTrigger , googlePrivacyDlpV2JobTrigger , gpdvjtStatus , gpdvjtTriggers , gpdvjtLastRunTime , gpdvjtInspectJob , gpdvjtUpdateTime , gpdvjtName , gpdvjtDisplayName , gpdvjtErrors , gpdvjtDescription , gpdvjtCreateTime -- * GooglePrivacyDlpV2ListStoredInfoTypesResponse , GooglePrivacyDlpV2ListStoredInfoTypesResponse , googlePrivacyDlpV2ListStoredInfoTypesResponse , gpdvlsitrNextPageToken , gpdvlsitrStoredInfoTypes -- * GooglePrivacyDlpV2LDiversityEquivalenceClass , GooglePrivacyDlpV2LDiversityEquivalenceClass , googlePrivacyDlpV2LDiversityEquivalenceClass , gpdvldecTopSensitiveValues , gpdvldecEquivalenceClassSize , gpdvldecNumDistinctSensitiveValues , gpdvldecQuasiIdsValues -- * GooglePrivacyDlpV2ActivateJobTriggerRequest , GooglePrivacyDlpV2ActivateJobTriggerRequest , googlePrivacyDlpV2ActivateJobTriggerRequest -- * GooglePrivacyDlpV2DeidentifyConfig , GooglePrivacyDlpV2DeidentifyConfig , googlePrivacyDlpV2DeidentifyConfig , gpdvdcInfoTypeTransformations , gpdvdcTransformationErrorHandling , gpdvdcRecordTransformations -- * GooglePrivacyDlpV2CharacterMaskConfig , GooglePrivacyDlpV2CharacterMaskConfig , googlePrivacyDlpV2CharacterMaskConfig , gpdvcmcNumberToMask , gpdvcmcMaskingCharacter , gpdvcmcReverseOrder , gpdvcmcCharactersToIgnore -- * GooglePrivacyDlpV2DatastoreOptions , GooglePrivacyDlpV2DatastoreOptions , googlePrivacyDlpV2DatastoreOptions , gpdvdoPartitionId , gpdvdoKind -- * GooglePrivacyDlpV2ValueFrequency , GooglePrivacyDlpV2ValueFrequency , googlePrivacyDlpV2ValueFrequency , gpdvvfValue , gpdvvfCount -- * GooglePrivacyDlpV2BoundingBox , GooglePrivacyDlpV2BoundingBox , googlePrivacyDlpV2BoundingBox , gpdvbbHeight , gpdvbbLeft , gpdvbbWidth , gpdvbbTop -- * GooglePrivacyDlpV2PartitionId , GooglePrivacyDlpV2PartitionId , googlePrivacyDlpV2PartitionId , gpdvpiNamespaceId , gpdvpiProjectId -- * GooglePrivacyDlpV2SaveFindings , GooglePrivacyDlpV2SaveFindings , googlePrivacyDlpV2SaveFindings , gpdvsfOutputConfig -- * GooglePrivacyDlpV2StoredInfoTypeVersion , GooglePrivacyDlpV2StoredInfoTypeVersion , googlePrivacyDlpV2StoredInfoTypeVersion , gpdvsitvState , gpdvsitvConfig , gpdvsitvStats , gpdvsitvErrors , gpdvsitvCreateTime -- * GooglePrivacyDlpV2ListInfoTypesResponse , GooglePrivacyDlpV2ListInfoTypesResponse , googlePrivacyDlpV2ListInfoTypesResponse , gpdvlitrInfoTypes -- * GooglePrivacyDlpV2ContentLocation , GooglePrivacyDlpV2ContentLocation , googlePrivacyDlpV2ContentLocation , gpdvclImageLocation , gpdvclContainerName , gpdvclContainerTimestamp , gpdvclDocumentLocation , gpdvclContainerVersion , gpdvclRecordLocation , gpdvclMetadataLocation -- * GooglePrivacyDlpV2AuxiliaryTable , GooglePrivacyDlpV2AuxiliaryTable , googlePrivacyDlpV2AuxiliaryTable , gpdvatRelativeFrequency , gpdvatTable , gpdvatQuasiIds -- * GooglePrivacyDlpV2DeltaPresenceEstimationHistogramBucket , GooglePrivacyDlpV2DeltaPresenceEstimationHistogramBucket , googlePrivacyDlpV2DeltaPresenceEstimationHistogramBucket , gpdvdpehbBucketValues , gpdvdpehbMaxProbability , gpdvdpehbMinProbability , gpdvdpehbBucketSize , gpdvdpehbBucketValueCount -- * GooglePrivacyDlpV2InspectConfigMinLikelihood , GooglePrivacyDlpV2InspectConfigMinLikelihood (..) -- * GooglePrivacyDlpV2FileSet , GooglePrivacyDlpV2FileSet , googlePrivacyDlpV2FileSet , gpdvfsURL , gpdvfsRegexFileSet -- * GooglePrivacyDlpV2HybridOptions , GooglePrivacyDlpV2HybridOptions , googlePrivacyDlpV2HybridOptions , gpdvhoTableOptions , gpdvhoLabels , gpdvhoRequiredFindingLabelKeys , gpdvhoDescription -- * GooglePrivacyDlpV2ListInspectTemplatesResponse , GooglePrivacyDlpV2ListInspectTemplatesResponse , googlePrivacyDlpV2ListInspectTemplatesResponse , gpdvlitrNextPageToken , gpdvlitrInspectTemplates -- * GooglePrivacyDlpV2KAnonymityResult , GooglePrivacyDlpV2KAnonymityResult , googlePrivacyDlpV2KAnonymityResult , gpdvkarEquivalenceClassHistogramBuckets -- * GooglePrivacyDlpV2BigQueryField , GooglePrivacyDlpV2BigQueryField , googlePrivacyDlpV2BigQueryField , gpdvbqfField , gpdvbqfTable -- * GooglePrivacyDlpV2CharsToIgnoreCommonCharactersToIgnore , GooglePrivacyDlpV2CharsToIgnoreCommonCharactersToIgnore (..) -- * GooglePrivacyDlpV2HybridInspectJobTriggerRequest , GooglePrivacyDlpV2HybridInspectJobTriggerRequest , googlePrivacyDlpV2HybridInspectJobTriggerRequest , gpdvhijtrHybridItem -- * GooglePrivacyDlpV2OutputStorageConfig , GooglePrivacyDlpV2OutputStorageConfig , googlePrivacyDlpV2OutputStorageConfig , gpdvoscOutputSchema , gpdvoscTable -- * GooglePrivacyDlpV2CloudStorageFileSet , GooglePrivacyDlpV2CloudStorageFileSet , googlePrivacyDlpV2CloudStorageFileSet , gpdvcsfsURL -- * GooglePrivacyDlpV2InfoTypeTransformations , GooglePrivacyDlpV2InfoTypeTransformations , googlePrivacyDlpV2InfoTypeTransformations , gpdvittTransformations -- * GooglePrivacyDlpV2KmsWrAppedCryptoKey , GooglePrivacyDlpV2KmsWrAppedCryptoKey , googlePrivacyDlpV2KmsWrAppedCryptoKey , gpdvkwackWrAppedKey , gpdvkwackCryptoKeyName -- * GooglePrivacyDlpV2CryptoReplaceFfxFpeConfigCommonAlphabet , GooglePrivacyDlpV2CryptoReplaceFfxFpeConfigCommonAlphabet (..) -- * GooglePrivacyDlpV2InspectContentResponse , GooglePrivacyDlpV2InspectContentResponse , googlePrivacyDlpV2InspectContentResponse , gpdvicrResult -- * GooglePrivacyDlpV2LDiversityHistogramBucket , GooglePrivacyDlpV2LDiversityHistogramBucket , googlePrivacyDlpV2LDiversityHistogramBucket , gpdvldhbBucketValues , gpdvldhbSensitiveValueFrequencyLowerBound , gpdvldhbSensitiveValueFrequencyUpperBound , gpdvldhbBucketSize , gpdvldhbBucketValueCount -- * GooglePrivacyDlpV2ReidentifyContentResponse , GooglePrivacyDlpV2ReidentifyContentResponse , googlePrivacyDlpV2ReidentifyContentResponse , gpdvrcrOverview , gpdvrcrItem -- * GooglePrivacyDlpV2HybridInspectResponse , GooglePrivacyDlpV2HybridInspectResponse , googlePrivacyDlpV2HybridInspectResponse -- * GooglePrivacyDlpV2Expressions , GooglePrivacyDlpV2Expressions , googlePrivacyDlpV2Expressions , gpdveLogicalOperator , gpdveConditions -- * GooglePrivacyDlpV2CloudStorageOptionsSampleMethod , GooglePrivacyDlpV2CloudStorageOptionsSampleMethod (..) -- * Xgafv , Xgafv (..) -- * GooglePrivacyDlpV2DateTime , GooglePrivacyDlpV2DateTime , googlePrivacyDlpV2DateTime , gpdvdtTime , gpdvdtDate , gpdvdtTimeZone , gpdvdtDayOfWeek -- * GooglePrivacyDlpV2CloudStorageRegexFileSet , GooglePrivacyDlpV2CloudStorageRegexFileSet , googlePrivacyDlpV2CloudStorageRegexFileSet , gpdvcsrfsExcludeRegex , gpdvcsrfsBucketName , gpdvcsrfsIncludeRegex -- * GooglePrivacyDlpV2RequestedRiskAnalysisOptions , GooglePrivacyDlpV2RequestedRiskAnalysisOptions , googlePrivacyDlpV2RequestedRiskAnalysisOptions , gpdvrraoJobConfig -- * GooglePrivacyDlpV2ExclusionRuleMatchingType , GooglePrivacyDlpV2ExclusionRuleMatchingType (..) -- * GooglePrivacyDlpV2ValueDayOfWeekValue , GooglePrivacyDlpV2ValueDayOfWeekValue (..) -- * GooglePrivacyDlpV2ThrowError , GooglePrivacyDlpV2ThrowError , googlePrivacyDlpV2ThrowError -- * GooglePrivacyDlpV2Bucket , GooglePrivacyDlpV2Bucket , googlePrivacyDlpV2Bucket , gpdvbMax , gpdvbReplacementValue , gpdvbMin -- * GooglePrivacyDlpV2Action , GooglePrivacyDlpV2Action , googlePrivacyDlpV2Action , gpdvaPublishToStackdriver , gpdvaJobNotificationEmails , gpdvaPubSub , gpdvaPublishFindingsToCloudDataCatalog , gpdvaSaveFindings , gpdvaPublishSummaryToCscc -- * GoogleTypeDate , GoogleTypeDate , googleTypeDate , gtdDay , gtdYear , gtdMonth -- * GooglePrivacyDlpV2TableOptions , GooglePrivacyDlpV2TableOptions , googlePrivacyDlpV2TableOptions , gpdvtoIdentifyingFields -- * GooglePrivacyDlpV2SurrogateType , GooglePrivacyDlpV2SurrogateType , googlePrivacyDlpV2SurrogateType -- * GooglePrivacyDlpV2ByteContentItemType , GooglePrivacyDlpV2ByteContentItemType (..) -- * GooglePrivacyDlpV2Table , GooglePrivacyDlpV2Table , googlePrivacyDlpV2Table , gpdvtRows , gpdvtHeaders -- * GooglePrivacyDlpV2LDiversityResult , GooglePrivacyDlpV2LDiversityResult , googlePrivacyDlpV2LDiversityResult , gpdvldrSensitiveValueFrequencyHistogramBuckets -- * GooglePrivacyDlpV2KMapEstimationConfig , GooglePrivacyDlpV2KMapEstimationConfig , googlePrivacyDlpV2KMapEstimationConfig , gpdvkmecAuxiliaryTables , gpdvkmecRegionCode , gpdvkmecQuasiIds -- * GooglePrivacyDlpV2CryptoReplaceFfxFpeConfig , GooglePrivacyDlpV2CryptoReplaceFfxFpeConfig , googlePrivacyDlpV2CryptoReplaceFfxFpeConfig , gpdvcrffcContext , gpdvcrffcCommonAlphabet , gpdvcrffcSurrogateInfoType , gpdvcrffcCustomAlphabet , gpdvcrffcCryptoKey , gpdvcrffcRadix -- * GooglePrivacyDlpV2QuasiIdentifierField , GooglePrivacyDlpV2QuasiIdentifierField , googlePrivacyDlpV2QuasiIdentifierField , gField , gCustomTag -- * GooglePrivacyDlpV2InfoType , GooglePrivacyDlpV2InfoType , googlePrivacyDlpV2InfoType , gpdvitName -- * GooglePrivacyDlpV2InspectTemplate , GooglePrivacyDlpV2InspectTemplate , googlePrivacyDlpV2InspectTemplate , gInspectConfig , gUpdateTime , gName , gDisplayName , gDescription , gCreateTime -- * GooglePrivacyDlpV2KAnonymityHistogramBucket , GooglePrivacyDlpV2KAnonymityHistogramBucket , googlePrivacyDlpV2KAnonymityHistogramBucket , gpdvkahbEquivalenceClassSizeLowerBound , gpdvkahbEquivalenceClassSizeUpperBound , gpdvkahbBucketValues , gpdvkahbBucketSize , gpdvkahbBucketValueCount -- * GooglePrivacyDlpV2ReidentifyContentRequest , GooglePrivacyDlpV2ReidentifyContentRequest , googlePrivacyDlpV2ReidentifyContentRequest , gooInspectConfig , gooReidentifyTemplateName , gooItem , gooLocationId , gooInspectTemplateName , gooReidentifyConfig -- * GooglePrivacyDlpV2CryptoHashConfig , GooglePrivacyDlpV2CryptoHashConfig , googlePrivacyDlpV2CryptoHashConfig , gpdvchcCryptoKey -- * GooglePrivacyDlpV2InfoTypeLimit , GooglePrivacyDlpV2InfoTypeLimit , googlePrivacyDlpV2InfoTypeLimit , gpdvitlMaxFindings , gpdvitlInfoType -- * GooglePrivacyDlpV2TableLocation , GooglePrivacyDlpV2TableLocation , googlePrivacyDlpV2TableLocation , gpdvtlRowIndex -- * GooglePrivacyDlpV2TimeZone , GooglePrivacyDlpV2TimeZone , googlePrivacyDlpV2TimeZone , gpdvtzOffSetMinutes -- * GooglePrivacyDlpV2JobTriggerStatus , GooglePrivacyDlpV2JobTriggerStatus (..) -- * ProjectsDlpJobsListType , ProjectsDlpJobsListType (..) -- * GooglePrivacyDlpV2StorageConfig , GooglePrivacyDlpV2StorageConfig , googlePrivacyDlpV2StorageConfig , gpdvscHybridOptions , gpdvscTimespanConfig , gpdvscBigQueryOptions , gpdvscDatastoreOptions , gpdvscCloudStorageOptions -- * OrganizationsLocationsJobTriggersListType , OrganizationsLocationsJobTriggersListType (..) -- * GooglePrivacyDlpV2HybridFindingDetails , GooglePrivacyDlpV2HybridFindingDetails , googlePrivacyDlpV2HybridFindingDetails , gpdvhfdFileOffSet , gpdvhfdTableOptions , gpdvhfdRowOffSet , gpdvhfdContainerDetails , gpdvhfdLabels -- * GooglePrivacyDlpV2Value , GooglePrivacyDlpV2Value , googlePrivacyDlpV2Value , gpdvvDayOfWeekValue , gpdvvIntegerValue , gpdvvTimestampValue , gpdvvTimeValue , gpdvvStringValue , gpdvvDateValue , gpdvvBooleanValue , gpdvvFloatValue -- * GooglePrivacyDlpV2Dictionary , GooglePrivacyDlpV2Dictionary , googlePrivacyDlpV2Dictionary , gpdvdWordList , gpdvdCloudStoragePath -- * GooglePrivacyDlpV2InspectConfigContentOptionsItem , GooglePrivacyDlpV2InspectConfigContentOptionsItem (..) -- * GooglePrivacyDlpV2AnalyzeDataSourceRiskDetails , GooglePrivacyDlpV2AnalyzeDataSourceRiskDetails , googlePrivacyDlpV2AnalyzeDataSourceRiskDetails , gpdvadsrdRequestedPrivacyMetric , gpdvadsrdRequestedSourceTable , gpdvadsrdLDiversityResult , gpdvadsrdKAnonymityResult , gpdvadsrdKMapEstimationResult , gpdvadsrdRequestedOptions , gpdvadsrdDeltaPresenceEstimationResult , gpdvadsrdNumericalStatsResult , gpdvadsrdCategoricalStatsResult -- * GooglePrivacyDlpV2Conditions , GooglePrivacyDlpV2Conditions , googlePrivacyDlpV2Conditions , gpdvcConditions -- * GooglePrivacyDlpV2DatastoreKey , GooglePrivacyDlpV2DatastoreKey , googlePrivacyDlpV2DatastoreKey , gpdvdkEntityKey -- * GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues , GooglePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues , googlePrivacyDlpV2DeltaPresenceEstimationQuasiIdValues , gpdvdpeqivEstimatedProbability , gpdvdpeqivQuasiIdsValues -- * GooglePrivacyDlpV2CharsToIgnore , GooglePrivacyDlpV2CharsToIgnore , googlePrivacyDlpV2CharsToIgnore , gpdvctiCommonCharactersToIgnore , gpdvctiCharactersToSkip -- * GooglePrivacyDlpV2BigQueryTable , GooglePrivacyDlpV2BigQueryTable , googlePrivacyDlpV2BigQueryTable , gpdvbqtDataSetId , gpdvbqtProjectId , gpdvbqtTableId -- * GooglePrivacyDlpV2MetadataLocation , GooglePrivacyDlpV2MetadataLocation , googlePrivacyDlpV2MetadataLocation , gpdvmlStorageLabel , gpdvmlType -- * GooglePrivacyDlpV2RequestedOptions , GooglePrivacyDlpV2RequestedOptions , googlePrivacyDlpV2RequestedOptions , gpdvroSnapshotInspectTemplate , gpdvroJobConfig -- * GooglePrivacyDlpV2PrimitiveTransformation , GooglePrivacyDlpV2PrimitiveTransformation , googlePrivacyDlpV2PrimitiveTransformation , gpdvptFixedSizeBucketingConfig , gpdvptRedactConfig , gpdvptCharacterMaskConfig , gpdvptTimePartConfig , gpdvptDateShiftConfig , gpdvptBucketingConfig , gpdvptReplaceWithInfoTypeConfig , gpdvptCryptoDeterministicConfig , gpdvptCryptoHashConfig , gpdvptReplaceConfig , gpdvptCryptoReplaceFfxFpeConfig -- * GooglePrivacyDlpV2CancelDlpJobRequest , GooglePrivacyDlpV2CancelDlpJobRequest , googlePrivacyDlpV2CancelDlpJobRequest -- * GooglePrivacyDlpV2HybridContentItem , GooglePrivacyDlpV2HybridContentItem , googlePrivacyDlpV2HybridContentItem , gpdvhciFindingDetails , gpdvhciItem -- * GooglePrivacyDlpV2InfoTypeDescriptionSupportedByItem , GooglePrivacyDlpV2InfoTypeDescriptionSupportedByItem (..) -- * GooglePrivacyDlpV2RecordLocation , GooglePrivacyDlpV2RecordLocation , googlePrivacyDlpV2RecordLocation , gpdvrlTableLocation , gpdvrlFieldId , gpdvrlRecordKey -- * GooglePrivacyDlpV2StoredInfoTypeVersionState , GooglePrivacyDlpV2StoredInfoTypeVersionState (..) -- * GooglePrivacyDlpV2Error , GooglePrivacyDlpV2Error , googlePrivacyDlpV2Error , gpdveDetails , gpdveTimestamps -- * GooglePrivacyDlpV2StoredInfoType , GooglePrivacyDlpV2StoredInfoType , googlePrivacyDlpV2StoredInfoType , gpdvsitCurrentVersion , gpdvsitName , gpdvsitPendingVersions -- * GooglePrivacyDlpV2CryptoDeterministicConfig , GooglePrivacyDlpV2CryptoDeterministicConfig , googlePrivacyDlpV2CryptoDeterministicConfig , gpdvcdcContext , gpdvcdcSurrogateInfoType , gpdvcdcCryptoKey -- * GooglePrivacyDlpV2StatisticalTable , GooglePrivacyDlpV2StatisticalTable , googlePrivacyDlpV2StatisticalTable , gpdvstRelativeFrequency , gpdvstTable , gpdvstQuasiIds -- * ProjectsLocationsJobTriggersListType , ProjectsLocationsJobTriggersListType (..) -- * GooglePrivacyDlpV2DeidentifyTemplate , GooglePrivacyDlpV2DeidentifyTemplate , googlePrivacyDlpV2DeidentifyTemplate , gpdvdtUpdateTime , gpdvdtName , gpdvdtDeidentifyConfig , gpdvdtDisplayName , gpdvdtDescription , gpdvdtCreateTime -- * GooglePrivacyDlpV2ReplaceValueConfig , GooglePrivacyDlpV2ReplaceValueConfig , googlePrivacyDlpV2ReplaceValueConfig , gpdvrvcNewValue -- * GooglePrivacyDlpV2CategoricalStatsConfig , GooglePrivacyDlpV2CategoricalStatsConfig , googlePrivacyDlpV2CategoricalStatsConfig , gpdvcscField -- * GooglePrivacyDlpV2NumericalStatsConfig , GooglePrivacyDlpV2NumericalStatsConfig , googlePrivacyDlpV2NumericalStatsConfig , gpdvnscField -- * GooglePrivacyDlpV2ListJobTriggersResponse , GooglePrivacyDlpV2ListJobTriggersResponse , googlePrivacyDlpV2ListJobTriggersResponse , gpdvljtrNextPageToken , gpdvljtrJobTriggers -- * GooglePrivacyDlpV2CloudStoragePath , GooglePrivacyDlpV2CloudStoragePath , googlePrivacyDlpV2CloudStoragePath , gpdvcspPath -- * GooglePrivacyDlpV2FinishDlpJobRequest , GooglePrivacyDlpV2FinishDlpJobRequest , googlePrivacyDlpV2FinishDlpJobRequest -- * GooglePrivacyDlpV2Location , GooglePrivacyDlpV2Location , googlePrivacyDlpV2Location , gpdvlCodepointRange , gpdvlContainer , gpdvlContentLocations , gpdvlByteRange -- * GooglePrivacyDlpV2Schedule , GooglePrivacyDlpV2Schedule , googlePrivacyDlpV2Schedule , gpdvsRecurrencePeriodDuration -- * GooglePrivacyDlpV2ExpressionsLogicalOperator , GooglePrivacyDlpV2ExpressionsLogicalOperator (..) -- * GooglePrivacyDlpV2CreateJobTriggerRequest , GooglePrivacyDlpV2CreateJobTriggerRequest , googlePrivacyDlpV2CreateJobTriggerRequest , gpdvcjtrTriggerId , gpdvcjtrJobTrigger , gpdvcjtrLocationId -- * GooglePrivacyDlpV2TransformationOverview , GooglePrivacyDlpV2TransformationOverview , googlePrivacyDlpV2TransformationOverview , gpdvtoTransformedBytes , gpdvtoTransformationSummaries -- * GooglePrivacyDlpV2StorageMetadataLabel , GooglePrivacyDlpV2StorageMetadataLabel , googlePrivacyDlpV2StorageMetadataLabel , gpdvsmlKey -- * GooglePrivacyDlpV2ImageLocation , GooglePrivacyDlpV2ImageLocation , googlePrivacyDlpV2ImageLocation , gpdvilBoundingBoxes -- * GooglePrivacyDlpV2KindExpression , GooglePrivacyDlpV2KindExpression , googlePrivacyDlpV2KindExpression , gpdvkeName -- * GooglePrivacyDlpV2PrivacyMetric , GooglePrivacyDlpV2PrivacyMetric , googlePrivacyDlpV2PrivacyMetric , gpdvpmNumericalStatsConfig , gpdvpmCategoricalStatsConfig , gpdvpmKMapEstimationConfig , gpdvpmKAnonymityConfig , gpdvpmLDiversityConfig , gpdvpmDeltaPresenceEstimationConfig -- * GooglePrivacyDlpV2UnwrAppedCryptoKey , GooglePrivacyDlpV2UnwrAppedCryptoKey , googlePrivacyDlpV2UnwrAppedCryptoKey , gpdvuackKey -- * GooglePrivacyDlpV2InspectionRuleSet , GooglePrivacyDlpV2InspectionRuleSet , googlePrivacyDlpV2InspectionRuleSet , gpdvirsRules , gpdvirsInfoTypes -- * GooglePrivacyDlpV2QuasiId , GooglePrivacyDlpV2QuasiId , googlePrivacyDlpV2QuasiId , gpdvqiField , gpdvqiInfoType , gpdvqiInferred , gpdvqiCustomTag -- * GooglePrivacyDlpV2DocumentLocation , GooglePrivacyDlpV2DocumentLocation , googlePrivacyDlpV2DocumentLocation , gpdvdlFileOffSet ) where import Network.Google.DLP.Types.Product import Network.Google.DLP.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v2' of the Cloud Data Loss Prevention (DLP) API. This contains the host and root path used as a starting point for constructing service requests. dLPService :: ServiceConfig dLPService = defaultService (ServiceId "dlp:v2") "dlp.googleapis.com" -- | See, edit, configure, and delete your Google Cloud Platform data cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy
brendanhay/gogol
gogol-dlp/gen/Network/Google/DLP/Types.hs
mpl-2.0
43,290
0
7
7,805
3,316
2,301
1,015
972
1
filter' :: (a -> Bool) -> [a] -> [a] filter' _ [] = [] filter' p (x:xs) | p x = x : filter p xs | otherwise = filter p xs
tokyo-jesus/university
src/haskell/higherOrderFunctions/filter.hs
unlicense
136
0
8
46
90
44
46
5
1
module Problem073 where import Data.List import Data.Ratio main = print $ length $ takeWhile (< 1 % 2) $ dropWhile (<= 1 % 3) $ farey 12000 farey n = 0 : unfoldr step (0, 1, 1, n) where step (a, b, c, d) | c > n = Nothing | otherwise = let k = (n + b) `quot` d in Just (c % d, (c, d, k * c - a, k * d - b))
vasily-kartashov/playground
euler/problem-073.hs
apache-2.0
383
0
14
154
195
106
89
8
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QComboBox_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.QComboBox_h where import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt 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 (QComboBox ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QComboBox_unSetUserMethod" qtc_QComboBox_unSetUserMethod :: Ptr (TQComboBox a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QComboBoxSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QComboBox ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QComboBoxSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QComboBox ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QComboBoxSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QComboBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QComboBox ()) (QComboBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QComboBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QComboBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QComboBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQComboBox 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_QComboBox_setUserMethod" qtc_QComboBox_setUserMethod :: Ptr (TQComboBox a) -> CInt -> Ptr (Ptr (TQComboBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QComboBox :: (Ptr (TQComboBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQComboBox x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QComboBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QComboBoxSc a) (QComboBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QComboBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QComboBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QComboBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQComboBox 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 (QComboBox ()) (QComboBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QComboBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QComboBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QComboBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQComboBox 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_QComboBox_setUserMethodVariant" qtc_QComboBox_setUserMethodVariant :: Ptr (TQComboBox a) -> CInt -> Ptr (Ptr (TQComboBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QComboBox :: (Ptr (TQComboBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQComboBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QComboBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QComboBoxSc a) (QComboBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QComboBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QComboBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QComboBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQComboBox 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 (QComboBox ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QComboBox_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QComboBox_unSetHandler" qtc_QComboBox_unSetHandler :: Ptr (TQComboBox a) -> CWString -> IO (CBool) instance QunSetHandler (QComboBoxSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QComboBox_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QComboBox ()) (QComboBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj 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_QComboBox_setHandler1" qtc_QComboBox_setHandler1 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox1 :: (Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QComboBox1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj 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 QchangeEvent_h (QComboBox ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_changeEvent" qtc_QComboBox_changeEvent :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QComboBoxSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_changeEvent cobj_x0 cobj_x1 instance QcontextMenuEvent_h (QComboBox ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_contextMenuEvent" qtc_QComboBox_contextMenuEvent :: Ptr (TQComboBox a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QComboBoxSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QComboBox ()) (QComboBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool 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_QComboBox_setHandler2" qtc_QComboBox_setHandler2 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox2 :: (Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QComboBox2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool 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 Qevent_h (QComboBox ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_event cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_event" qtc_QComboBox_event :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QComboBoxSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_event cobj_x0 cobj_x1 instance QfocusInEvent_h (QComboBox ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_focusInEvent" qtc_QComboBox_focusInEvent :: Ptr (TQComboBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QComboBoxSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QComboBox ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_focusOutEvent" qtc_QComboBox_focusOutEvent :: Ptr (TQComboBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QComboBoxSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_focusOutEvent cobj_x0 cobj_x1 instance QhideEvent_h (QComboBox ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_hideEvent" qtc_QComboBox_hideEvent :: Ptr (TQComboBox a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QComboBoxSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QComboBox ()) (QComboBox x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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_QComboBox_setHandler3" qtc_QComboBox_setHandler3 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox3 :: (Ptr (TQComboBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQComboBox x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QComboBox3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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 QhidePopup_h (QComboBox ()) (()) where hidePopup_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_hidePopup cobj_x0 foreign import ccall "qtc_QComboBox_hidePopup" qtc_QComboBox_hidePopup :: Ptr (TQComboBox a) -> IO () instance QhidePopup_h (QComboBoxSc a) (()) where hidePopup_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_hidePopup cobj_x0 instance QkeyPressEvent_h (QComboBox ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_keyPressEvent" qtc_QComboBox_keyPressEvent :: Ptr (TQComboBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QComboBoxSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyPressEvent cobj_x0 cobj_x1 instance QkeyReleaseEvent_h (QComboBox ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_keyReleaseEvent" qtc_QComboBox_keyReleaseEvent :: Ptr (TQComboBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QComboBoxSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_keyReleaseEvent cobj_x0 cobj_x1 instance QsetHandler (QComboBox ()) (QComboBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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_QComboBox_setHandler4" qtc_QComboBox_setHandler4 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox4 :: (Ptr (TQComboBox x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQComboBox x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QComboBox4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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 QqminimumSizeHint_h (QComboBox ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint cobj_x0 foreign import ccall "qtc_QComboBox_minimumSizeHint" qtc_QComboBox_minimumSizeHint :: Ptr (TQComboBox a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QComboBoxSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QComboBox ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QComboBox_minimumSizeHint_qth" qtc_QComboBox_minimumSizeHint_qth :: Ptr (TQComboBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QComboBoxSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QmousePressEvent_h (QComboBox ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mousePressEvent" qtc_QComboBox_mousePressEvent :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QComboBoxSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QComboBox ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mouseReleaseEvent" qtc_QComboBox_mouseReleaseEvent :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QComboBoxSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseReleaseEvent cobj_x0 cobj_x1 instance QpaintEvent_h (QComboBox ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_paintEvent" qtc_QComboBox_paintEvent :: Ptr (TQComboBox a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QComboBoxSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_paintEvent cobj_x0 cobj_x1 instance QresizeEvent_h (QComboBox ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_resizeEvent" qtc_QComboBox_resizeEvent :: Ptr (TQComboBox a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QComboBoxSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_resizeEvent cobj_x0 cobj_x1 instance QshowEvent_h (QComboBox ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_showEvent" qtc_QComboBox_showEvent :: Ptr (TQComboBox a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QComboBoxSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_showEvent cobj_x0 cobj_x1 instance QshowPopup_h (QComboBox ()) (()) where showPopup_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_showPopup cobj_x0 foreign import ccall "qtc_QComboBox_showPopup" qtc_QComboBox_showPopup :: Ptr (TQComboBox a) -> IO () instance QshowPopup_h (QComboBoxSc a) (()) where showPopup_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_showPopup cobj_x0 instance QqsizeHint_h (QComboBox ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint cobj_x0 foreign import ccall "qtc_QComboBox_sizeHint" qtc_QComboBox_sizeHint :: Ptr (TQComboBox a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QComboBoxSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint cobj_x0 instance QsizeHint_h (QComboBox ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QComboBox_sizeHint_qth" qtc_QComboBox_sizeHint_qth :: Ptr (TQComboBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QComboBoxSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QwheelEvent_h (QComboBox ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_wheelEvent" qtc_QComboBox_wheelEvent :: Ptr (TQComboBox a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QComboBoxSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_wheelEvent cobj_x0 cobj_x1 instance QactionEvent_h (QComboBox ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_actionEvent" qtc_QComboBox_actionEvent :: Ptr (TQComboBox a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QComboBoxSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_actionEvent cobj_x0 cobj_x1 instance QcloseEvent_h (QComboBox ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_closeEvent" qtc_QComboBox_closeEvent :: Ptr (TQComboBox a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QComboBoxSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_closeEvent cobj_x0 cobj_x1 instance QsetHandler (QComboBox ()) (QComboBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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_QComboBox_setHandler5" qtc_QComboBox_setHandler5 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox5 :: (Ptr (TQComboBox x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQComboBox x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QComboBox5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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 QdevType_h (QComboBox ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_devType cobj_x0 foreign import ccall "qtc_QComboBox_devType" qtc_QComboBox_devType :: Ptr (TQComboBox a) -> IO CInt instance QdevType_h (QComboBoxSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_devType cobj_x0 instance QdragEnterEvent_h (QComboBox ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dragEnterEvent" qtc_QComboBox_dragEnterEvent :: Ptr (TQComboBox a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QComboBoxSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QComboBox ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dragLeaveEvent" qtc_QComboBox_dragLeaveEvent :: Ptr (TQComboBox a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QComboBoxSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QComboBox ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dragMoveEvent" qtc_QComboBox_dragMoveEvent :: Ptr (TQComboBox a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QComboBoxSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QComboBox ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_dropEvent" qtc_QComboBox_dropEvent :: Ptr (TQComboBox a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QComboBoxSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QComboBox ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_enterEvent" qtc_QComboBox_enterEvent :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QComboBoxSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_enterEvent cobj_x0 cobj_x1 instance QsetHandler (QComboBox ()) (QComboBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int 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_QComboBox_setHandler6" qtc_QComboBox_setHandler6 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox6 :: (Ptr (TQComboBox x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQComboBox x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QComboBox6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int 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 QheightForWidth_h (QComboBox ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QComboBox_heightForWidth" qtc_QComboBox_heightForWidth :: Ptr (TQComboBox a) -> CInt -> IO CInt instance QheightForWidth_h (QComboBoxSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_heightForWidth cobj_x0 (toCInt x1) instance QleaveEvent_h (QComboBox ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_leaveEvent" qtc_QComboBox_leaveEvent :: Ptr (TQComboBox a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QComboBoxSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_leaveEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QComboBox ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mouseDoubleClickEvent" qtc_QComboBox_mouseDoubleClickEvent :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QComboBoxSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QComboBox ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_mouseMoveEvent" qtc_QComboBox_mouseMoveEvent :: Ptr (TQComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QComboBoxSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_mouseMoveEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QComboBox ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_moveEvent" qtc_QComboBox_moveEvent :: Ptr (TQComboBox a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QComboBoxSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QComboBox ()) (QComboBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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_QComboBox_setHandler7" qtc_QComboBox_setHandler7 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox7 :: (Ptr (TQComboBox x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQComboBox x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QComboBox7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qComboBoxFromPtr 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 QpaintEngine_h (QComboBox ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_paintEngine cobj_x0 foreign import ccall "qtc_QComboBox_paintEngine" qtc_QComboBox_paintEngine :: Ptr (TQComboBox a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QComboBoxSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_paintEngine cobj_x0 instance QsetHandler (QComboBox ()) (QComboBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool 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_QComboBox_setHandler8" qtc_QComboBox_setHandler8 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox8 :: (Ptr (TQComboBox x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQComboBox x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QComboBox8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qComboBoxFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool 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 QsetVisible_h (QComboBox ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QComboBox_setVisible" qtc_QComboBox_setVisible :: Ptr (TQComboBox a) -> CBool -> IO () instance QsetVisible_h (QComboBoxSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QComboBox_setVisible cobj_x0 (toCBool x1) instance QtabletEvent_h (QComboBox ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QComboBox_tabletEvent" qtc_QComboBox_tabletEvent :: Ptr (TQComboBox a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QComboBoxSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QComboBox_tabletEvent cobj_x0 cobj_x1 instance QsetHandler (QComboBox ()) (QComboBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qComboBoxFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool 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_QComboBox_setHandler9" qtc_QComboBox_setHandler9 :: Ptr (TQComboBox a) -> CWString -> Ptr (Ptr (TQComboBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QComboBox9 :: (Ptr (TQComboBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQComboBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QComboBox9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QComboBoxSc a) (QComboBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QComboBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QComboBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QComboBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQComboBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qComboBoxFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool 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 QeventFilter_h (QComboBox ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QComboBox_eventFilter" qtc_QComboBox_eventFilter :: Ptr (TQComboBox a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QComboBoxSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QComboBox_eventFilter cobj_x0 cobj_x1 cobj_x2
uduki/hsQt
Qtc/Gui/QComboBox_h.hs
bsd-2-clause
56,032
0
18
12,116
18,697
9,019
9,678
-1
-1
{-# OPTIONS -fglasgow-exts #-} module Text.RegexC where newtype Regex a = Rx { runRegex :: (RxTarget -> [(RxTarget, a)]) } -- rxTargetBefore and rxTargetMatched hold scanned and matched chars in reverse order data RxTarget = RxTarget { rxTargetBefore :: String, rxTargetMatched :: String, rxTargetAfter :: String } afterToMatched :: RxTarget -> RxTarget afterToMatched (RxTarget bs ms (a : as)) = RxTarget bs (a : ms) as afterToMatched (RxTarget _ _ _) = error "Should not happen." matchedToBeforeAll :: RxTarget -> RxTarget matchedToBeforeAll (RxTarget bs ms as) = RxTarget (reverse ms ++ bs) [] as recoverTarget :: RxTarget -> RxTarget -> String -> RxTarget recoverTarget start returned matchedHere = RxTarget (rxTargetBefore start) (matchedHere ++ rxTargetMatched start) (rxTargetAfter returned) instance Monad Regex where m >>= next = Rx $ \target -> let thisCand = runRegex m target getNextCand (target', a) = runRegex (next a) target' in concatMap getNextCand thisCand return a = Rx $ \target -> [(target, a)] instance Functor Regex where fmap f rx = Rx $ \target -> map (\(t, v) -> (t, f v)) $ runRegex rx target rxOneChar :: Char -> Regex Char rxOneChar c = rxChar (== c) rxDot :: Regex Char rxDot = rxChar $ \_ -> True rxBracket :: String -> Regex Char rxBracket chars = rxChar (`elem` chars) rxChar :: (Char -> Bool) -> Regex Char rxChar isElement = Rx $ \target -> case target of RxTarget _ _ (x : _) -> if isElement x then [(afterToMatched target, x)] else [] _ -> [] rxStar :: Regex a -> Regex (String, Maybe a) rxStar = makeGroup reverse rxStarQ :: Regex a -> Regex (String, Maybe a) rxStarQ = makeGroup id rxParenthesis :: forall a . Regex a -> Regex (String, a) rxParenthesis rx = fmap nomaybe $ makeGroup (take 1 . drop 1) rx where nomaybe :: (String, Maybe a) -> (String, a) nomaybe (s, Just a) = (s, a) nomaybe (s, Nothing) = error "Should not happen." rxPipe :: Regex a -> Regex b -> Regex (String, Either a b) rxPipe rx1 rx2 = Rx $ \target -> case runRegex (rxParenthesis rx1) target of (t, (matched, ret)) : [] -> [(t, (matched, Left ret))] [] -> case runRegex (rxParenthesis rx2) target of (t, (matched, ret)) : [] -> [(t, (matched, Right ret))] [] -> [] _ -> error "Should not happen." _ -> error "Should not happen." rxPipe3 :: Regex a -> Regex a -> Regex a -> Regex (String, a) rxPipe3 rx1 rx2 rx3 = do (matched, ret) <- rxPipe rx1 $ rxPipe rx2 rx3 case ret of Left a -> return (matched, a) Right (_, Left a) -> return (matched, a) Right (_, Right a) -> return (matched, a) rxPipe3_ :: Regex a -> Regex b -> Regex c -> Regex String rxPipe3_ rx1 rx2 rx3 = do (matched, _) <- rxPipe rx1 $ rxPipe rx2 rx3 return matched -- http://www.haskell.org/ghc/docs/latest/html/users_guide/other-type-extensions.html#scoped-type-variables -- returns matched string and an arbitrary return value, which is Nothing if zero-matched. makeGroup :: forall a . (forall b . [b] -> [b]) -> Regex a -> Regex (String, Maybe a) makeGroup sortFunc sub = Rx $ \target -> let getCand' :: [(RxTarget, (String, Maybe a))] -> [(RxTarget, (String, Maybe a))] getCand' ((target', (matchedHere, _)) : _) = map (\(subTgt, a) -> (subTgt, (rxTargetMatched subTgt ++ matchedHere, Just a))) $ runRegex sub $ matchedToBeforeAll target' getCand' [] = [] getCand :: [(RxTarget, (String, Maybe a))] getCand = map (\(t, (str, ret)) -> (recoverTarget target t str, (reverse str, ret))) $ sortFunc $ map head $ takeWhile (not . null) $ iterate getCand' [(target, ([], Nothing))] in getCand rxCaret :: Regex () rxCaret = Rx $ \target -> case target of RxTarget [] _ _ -> [(target, ())] _ -> [] rxDollar :: Regex () rxDollar = Rx $ \target -> case target of RxTarget _ _ [] -> [(target, ())] _ -> [] regexMatch :: Regex a -> String -> Maybe String regexMatch rx str = case regexBase rx str of Nothing -> Nothing Just (_, matched, _, _) -> Just matched -- regexMatch :: Regex a -> String -> Maybe String -- regexMatch rx str = -- case runRegex regex (RxTarget [] [] str) of -- [] -> Nothing -- (_, matched) : _ -> Just matched -- where -- regex = do -- rxStarQ rxDot -- (matched, _) <- rxParenthesis rx -- return matched -- returns (before, matched, after, returnedValue) regexBase :: Regex a -> String -> Maybe (String, String, String, a) regexBase rx str = case runRegex regex (RxTarget [] [] str) of [] -> Nothing (RxTarget _ _ after, (before, matched, ret)) : _ -> Just (before, matched, after, ret) where regex = do (before, _) <- rxStarQ rxDot (matched, ret) <- rxParenthesis rx return (before, matched, ret)
harai/regexC
Text/RegexC.hs
bsd-2-clause
5,239
0
20
1,543
1,900
1,010
890
-1
-1
module Tisp.Value (Literal(..), Var(..), Neutral(..), Value(..), ValueVal(..), Name(..), nameBase) where import Data.Text (Text) import qualified Data.Text as T import Data.Word (Word64) import Data.String (IsString, fromString) import Data.Ratio import Text.PrettyPrint.ANSI.Leijen (Pretty, pretty, (<>), (<+>)) import qualified Text.PrettyPrint.ANSI.Leijen as PP hiding ((<$>)) import Tisp.Tokenize (SourceLoc(..), Symbol) data Name = NUser Symbol | NMachine Symbol Word64 deriving (Eq, Ord, Show) nameBase :: Name -> Symbol nameBase (NUser s) = s nameBase (NMachine s _) = s instance IsString Name where fromString = NUser . T.pack instance Pretty Name where pretty (NUser s) = PP.text (T.unpack s) pretty (NMachine s n) = PP.text (T.unpack s) <> PP.char '#' <> PP.integer (fromIntegral n) data Literal = LitNum Rational | LitText Text | LitForeign Text | LitUniverse Integer deriving (Eq, Show) instance Pretty Literal where pretty (LitNum r) = if denominator r == 1 then PP.integer (numerator r) else PP.parens $ PP.text "rational" <+> PP.integer (numerator r) <+> PP.integer (denominator r) pretty (LitText t) = PP.text (show t) pretty (LitForeign f) = PP.parens $ PP.text "foreign" <+> PP.text (T.unpack f) pretty (LitUniverse n) = PP.parens $ PP.text "Type" <+> PP.integer n data Var = Local Int | Global Symbol deriving (Show, Ord, Eq) data Neutral a = NVar Var | NApp (Neutral a) (Value a) data Value a = Value a (ValueVal a) data ValueVal a = VLiteral Literal | VNeutral (Neutral a) | VData Symbol [Value a] | VLambda Symbol (Value a) (Value a -> Value a) | VPi Symbol (Value a) (Value a -> Value a) | VError SourceLoc Text
Ralith/tisp
src/Tisp/Value.hs
bsd-3-clause
1,835
0
11
456
734
402
332
41
1
import Data.ByteString.Lazy.Char8 (unpack) import Data.Digest.SRI.Lazy main :: IO () main = do integrity <- sriHash256File "srihash.cabal" putStrLn (unpack integrity)
nejstastnejsistene/srihash
test/Spec.hs
bsd-3-clause
172
0
9
24
57
30
27
6
1
{-# LANGUAGE NoMonomorphismRestriction #-} module DetermineTheType where -- simple example example = 1 example1 = (* 9) 6 example2 = head [(0,"doge"),(1,"kitteh")] example3 = head [(0 :: Integer, "doge"),(1, "kitteh")] example4 = if False then True else False example5 = length [1, 2, 3, 4, 5] example6 = (length [1,2,3,4]) > (length "TACOCAT") -- 2-4. x = 5 y = x + 5 w = y * 10 z y = y * 10 f = 4 / y -- 5. t = "Julie" u = " <3 " v = "Haskell" m = t ++ u ++ v
pdmurray/haskell-book-ex
src/ch5/DetermineTheType.hs
bsd-3-clause
467
0
8
104
221
132
89
18
2
{-# LANGUAGE FlexibleContexts #-} module TTT.Minimax.Internal where import Control.Monad.State (MonadState(..), modify) import qualified Data.Map as M (Map(..), empty, insert, lookup) import TTT.GameState (GameState(..), Token(..), availableMoves, choose, isWinFor, makeMove) minimax gameState = do cache <- get case M.lookup gameState cache of Just score -> return score Nothing -> cacheMinimax gameState cacheMinimax:: MonadState (M.Map GameState Int) m => GameState -> m Int cacheMinimax gameState@(GameState board currentPlayer) |gameState `isWinFor` X = store 100 |gameState `isWinFor` O = store (-100) |moves == [] = store 0 |otherwise = do scores <- mapM (minimax . makeMove gameState) moves store ((choose currentPlayer (+) (-)) ((choose currentPlayer maximum minimum) scores) (length moves)) where store score = do modify (M.insert gameState score); return score moves = availableMoves gameState
jcg3challenges/haskell_ttt
src/TTT/Minimax/Internal.hs
bsd-3-clause
1,014
0
14
229
363
191
172
20
2
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : cryptol@galois.com -- Stability : provisional -- Portability : portable {-# LANGUAGE Safe #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts #-} {-# LANGUAGE DeriveGeneric #-} module Cryptol.TypeCheck.AST ( module Cryptol.TypeCheck.AST , TFun(..) , Name(..), QName(..), mkModName, mkName, mkUnqual, unqual , ModName(..) , Selector(..) , Import(..) , ImportSpec(..) , ExportType(..) , ExportSpec(..), isExportedBind, isExportedType , Pragma(..) , Fixity(..) ) where import Cryptol.ModuleSystem.Name (mkQual, mkName) import Cryptol.Prims.Syntax import Cryptol.Parser.AST ( Name(..), Selector(..),Pragma(..), ppSelector , Import(..), ImportSpec(..), ExportType(..) , ExportSpec(..), ModName(..), isExportedBind , isExportedType, QName(..), mkUnqual, unqual , mkModName , Fixity(..) ) import Cryptol.Utils.Panic(panic) import Cryptol.TypeCheck.PP import Cryptol.TypeCheck.Solver.InfNat import GHC.Generics (Generic) import Control.DeepSeq import Data.Map (Map) import qualified Data.Map as Map import qualified Data.IntMap as IntMap import Data.Set (Set) {- | A Cryptol module. -} data Module = Module { mName :: ModName , mExports :: ExportSpec , mImports :: [Import] , mTySyns :: Map QName TySyn , mNewtypes :: Map QName Newtype , mDecls :: [DeclGroup] } deriving (Show, Generic) instance NFData Module -- | Kinds, classify types. data Kind = KType | KNum | KProp | Kind :-> Kind deriving (Eq, Show, Generic) infixr 5 :-> instance NFData Kind -- | The types of polymorphic values. data Schema = Forall { sVars :: [TParam], sProps :: [Prop], sType :: Type } deriving (Eq, Show, Generic) instance NFData Schema -- | Type synonym. data TySyn = TySyn { tsName :: QName -- ^ Name , tsParams :: [TParam] -- ^ Parameters , tsConstraints :: [Prop] -- ^ Ensure body is OK , tsDef :: Type -- ^ Definition } deriving (Eq, Show, Generic) instance NFData TySyn -- | Named records data Newtype = Newtype { ntName :: QName , ntParams :: [TParam] , ntConstraints :: [Prop] , ntFields :: [(Name,Type)] } deriving (Show, Generic) instance NFData Newtype -- | Type parameters. data TParam = TParam { tpUnique :: !Int -- ^ Parameter identifier , tpKind :: Kind -- ^ Kind of parameter , tpName :: Maybe QName-- ^ Name from source, if any. } deriving (Show, Generic) instance NFData TParam instance Eq TParam where x == y = tpUnique x == tpUnique y instance Ord TParam where compare x y = compare (tpUnique x) (tpUnique y) tpVar :: TParam -> TVar tpVar p = TVBound (tpUnique p) (tpKind p) -- | The internal representation of types. -- These are assumed to be kind correct. data Type = TCon TCon [Type] -- ^ Type constant with args | TVar TVar -- ^ Type variable (free or bound) | TUser QName [Type] Type {- ^ This is just a type annotation, for a type that was written as a type synonym. It is useful so that we can use it to report nicer errors. Example: `TUser T ts t` is really just the type `t` that was written as `T ts` by the user. -} | TRec [(Name,Type)] -- ^ Record type deriving (Show,Eq,Ord,Generic) instance NFData Type -- | The type is supposed to be of kind `KProp` type Prop = Type -- | The type is "simple" (i.e., it contains no type functions). type SType = Type -- | Type variables. data TVar = TVFree !Int Kind (Set TVar) Doc -- ^ Unique, kind, ids of bound type variables that are in scope -- The `Doc` is a description of how this type came to be. | TVBound !Int Kind deriving (Show,Generic) instance NFData TVar -- | Type constants. data TCon = TC TC | PC PC | TF TFun deriving (Show,Eq,Ord,Generic) instance NFData TCon -- | Built-in type constants. -- | Predicate symbols. data PC = PEqual -- ^ @_ == _@ | PNeq -- ^ @_ /= _@ | PGeq -- ^ @_ >= _@ | PFin -- ^ @fin _@ -- classes | PHas Selector -- ^ @Has sel type field@ does not appear in schemas | PArith -- ^ @Arith _@ | PCmp -- ^ @Cmp _@ deriving (Show,Eq,Ord,Generic) instance NFData PC -- | 1-1 constants. data TC = TCNum Integer -- ^ Numbers | TCInf -- ^ Inf | TCBit -- ^ Bit | TCSeq -- ^ @[_] _@ | TCFun -- ^ @_ -> _@ | TCTuple Int -- ^ @(_, _, _)@ | TCNewtype UserTC -- ^ user-defined, @T@ deriving (Show,Eq,Ord,Generic) instance NFData TC data UserTC = UserTC QName Kind deriving (Show,Generic) instance NFData UserTC instance Eq UserTC where UserTC x _ == UserTC y _ = x == y instance Ord UserTC where compare (UserTC x _) (UserTC y _) = compare x y instance Eq TVar where TVBound x _ == TVBound y _ = x == y TVFree x _ _ _ == TVFree y _ _ _ = x == y _ == _ = False instance Ord TVar where compare (TVFree x _ _ _) (TVFree y _ _ _) = compare x y compare (TVFree _ _ _ _) _ = LT compare _ (TVFree _ _ _ _) = GT compare (TVBound x _) (TVBound y _) = compare x y data Expr = EList [Expr] Type -- ^ List value (with type of elements) | ETuple [Expr] -- ^ Tuple value | ERec [(Name,Expr)] -- ^ Record value | ESel Expr Selector -- ^ Elimination for tuple/record/list | EIf Expr Expr Expr -- ^ If-then-else | EComp Type Expr [[Match]] -- ^ List comprehensions -- The type caches the type of the -- expr. | EVar QName -- ^ Use of a bound variable | ETAbs TParam Expr -- ^ Function Value | ETApp Expr Type -- ^ Type application | EApp Expr Expr -- ^ Function application | EAbs QName Type Expr -- ^ Function value {- | Proof abstraction. Because we don't keep proofs around we don't need to name the assumption, but we still need to record the assumption. The assumption is the `Type` term, which should be of kind `KProp`. -} | EProofAbs {- x -} Prop Expr {- | If `e : p => t`, then `EProofApp e : t`, as long as we can prove `p`. We don't record the actual proofs, as they are not used for anything. It may be nice to keep them around for sanity checking. -} | EProofApp Expr {- proof -} {- | if e : t1, then cast e : t2 as long as we can prove that 't1 = t2'. We could express this in terms of a built-in constant. `cast :: {a,b} (a =*= b) => a -> b` Using the constant is a bit verbose though, because we end up with both the source and target type. So, instead we use this language construct, which only stores the target type, and the source type can be reconstructed from the expression. Another way to think of this is simply as an expression with an explicit type annotation. -} | ECast Expr Type | EWhere Expr [DeclGroup] deriving (Show, Generic) instance NFData Expr data Match = From QName Type Expr-- ^ do we need this type? it seems like it -- can be computed from the expr | Let Decl deriving (Show, Generic) instance NFData Match data DeclGroup = Recursive [Decl] -- ^ Mutually recursive declarations | NonRecursive Decl -- ^ Non-recursive declaration deriving (Show,Generic) instance NFData DeclGroup groupDecls :: DeclGroup -> [Decl] groupDecls dg = case dg of Recursive ds -> ds NonRecursive d -> [d] data Decl = Decl { dName :: QName , dSignature :: Schema , dDefinition :: DeclDef , dPragmas :: [Pragma] , dInfix :: !Bool , dFixity :: Maybe Fixity , dDoc :: Maybe String } deriving (Show,Generic) instance NFData Decl data DeclDef = DPrim | DExpr Expr deriving (Show,Generic) instance NFData DeclDef -------------------------------------------------------------------------------- isFreeTV :: TVar -> Bool isFreeTV (TVFree {}) = True isFreeTV _ = False isBoundTV :: TVar -> Bool isBoundTV (TVBound {}) = True isBoundTV _ = False -------------------------------------------------------------------------------- tIsNat' :: Type -> Maybe Nat' tIsNat' ty = case tNoUser ty of TCon (TC (TCNum x)) [] -> Just (Nat x) TCon (TC TCInf) [] -> Just Inf _ -> Nothing tIsNum :: Type -> Maybe Integer tIsNum ty = do Nat x <- tIsNat' ty return x tIsInf :: Type -> Bool tIsInf ty = tIsNat' ty == Just Inf tIsVar :: Type -> Maybe TVar tIsVar ty = case tNoUser ty of TVar x -> Just x _ -> Nothing tIsFun :: Type -> Maybe (Type, Type) tIsFun ty = case tNoUser ty of TCon (TC TCFun) [a, b] -> Just (a, b) _ -> Nothing tIsSeq :: Type -> Maybe (Type, Type) tIsSeq ty = case tNoUser ty of TCon (TC TCSeq) [n, a] -> Just (n, a) _ -> Nothing tIsBit :: Type -> Bool tIsBit ty = case tNoUser ty of TCon (TC TCBit) [] -> True _ -> False tIsTuple :: Type -> Maybe [Type] tIsTuple ty = case tNoUser ty of TCon (TC (TCTuple _)) ts -> Just ts _ -> Nothing tIsBinFun :: TFun -> Type -> Maybe (Type,Type) tIsBinFun f ty = case tNoUser ty of TCon (TF g) [a,b] | f == g -> Just (a,b) _ -> Nothing -- | Split up repeated occurances of the given binary type-level function. tSplitFun :: TFun -> Type -> [Type] tSplitFun f t0 = go t0 [] where go ty xs = case tIsBinFun f ty of Just (a,b) -> go a (go b xs) Nothing -> ty : xs pIsFin :: Prop -> Maybe Type pIsFin ty = case tNoUser ty of TCon (PC PFin) [t1] -> Just t1 _ -> Nothing pIsGeq :: Prop -> Maybe (Type,Type) pIsGeq ty = case tNoUser ty of TCon (PC PGeq) [t1,t2] -> Just (t1,t2) _ -> Nothing pIsEq :: Prop -> Maybe (Type,Type) pIsEq ty = case tNoUser ty of TCon (PC PEqual) [t1,t2] -> Just (t1,t2) _ -> Nothing pIsArith :: Prop -> Maybe Type pIsArith ty = case tNoUser ty of TCon (PC PArith) [t1] -> Just t1 _ -> Nothing pIsCmp :: Prop -> Maybe Type pIsCmp ty = case tNoUser ty of TCon (PC PCmp) [t1] -> Just t1 _ -> Nothing pIsNumeric :: Prop -> Bool pIsNumeric (TCon (PC PEqual) _) = True pIsNumeric (TCon (PC PNeq) _) = True pIsNumeric (TCon (PC PGeq) _) = True pIsNumeric (TCon (PC PFin) _) = True pIsNumeric (TUser _ _ t) = pIsNumeric t pIsNumeric _ = False -------------------------------------------------------------------------------- tNum :: Integral a => a -> Type tNum n = TCon (TC (TCNum (fromIntegral n))) [] tZero :: Type tZero = tNum (0 :: Int) tOne :: Type tOne = tNum (1 :: Int) tTwo :: Type tTwo = tNum (2 :: Int) tInf :: Type tInf = TCon (TC TCInf) [] tNat' :: Nat' -> Type tNat' n' = case n' of Inf -> tInf Nat n -> tNum n tBit :: Type tBit = TCon (TC TCBit) [] ePrim :: String -> Expr ePrim n = EVar (mkQual (mkModName ["Cryptol"]) (mkName n)) eTrue :: Expr eTrue = ePrim "True" eFalse :: Expr eFalse = ePrim "False" tWord :: Type -> Type tWord a = tSeq a tBit tSeq :: Type -> Type -> Type tSeq a b = TCon (TC TCSeq) [a,b] tChar :: Type tChar = tWord (tNum (8 :: Int)) eChar :: Char -> Expr eChar c = ETApp (ETApp (ePrim "demote") (tNum v)) (tNum w) where v = fromEnum c w = 8 :: Int tString :: Int -> Type tString len = tSeq (tNum len) tChar eString :: String -> Expr eString str = EList (map eChar str) tChar -- | Make an expression that is `error` pre-applied to a type and a -- message. eError :: Type -> String -> Expr eError t str = EApp (ETApp (ETApp (ePrim "error") t) (tNum (length str))) (eString str) tRec :: [(Name,Type)] -> Type tRec = TRec tTuple :: [Type] -> Type tTuple ts = TCon (TC (TCTuple (length ts))) ts infixr 5 `tFun` -- | Make a function type. tFun :: Type -> Type -> Type tFun a b = TCon (TC TCFun) [a,b] -- | Eliminate outermost type synonyms. tNoUser :: Type -> Type tNoUser t = case t of TUser _ _ a -> tNoUser a _ -> t tWidth :: Type -> Type tWidth t = TCon (TF TCWidth) [t] tLenFromThen :: Type -> Type -> Type -> Type tLenFromThen t1 t2 t3 = TCon (TF TCLenFromThen) [t1,t2,t3] tLenFromThenTo :: Type -> Type -> Type -> Type tLenFromThenTo t1 t2 t3 = TCon (TF TCLenFromThenTo) [t1,t2,t3] tMax :: Type -> Type -> Type tMax t1 t2 = TCon (TF TCMax) [t1,t2] infix 4 =#=, >== infixl 6 .+. infixl 7 .*. -- | Equality for numeric types. (=#=) :: Type -> Type -> Prop x =#= y = TCon (PC PEqual) [x,y] (=/=) :: Type -> Type -> Prop x =/= y = TCon (PC PNeq) [x,y] pArith :: Type -> Prop pArith t = TCon (PC PArith) [t] pCmp :: Type -> Prop pCmp t = TCon (PC PCmp) [t] -- | Make a greater-than-or-equal-to constraint. (>==) :: Type -> Type -> Prop x >== y = TCon (PC PGeq) [x,y] -- | A `Has` constraint, used for tuple and record selection. pHas :: Selector -> Type -> Type -> Prop pHas l ty fi = TCon (PC (PHas l)) [ty,fi] pFin :: Type -> Prop pFin ty = TCon (PC PFin) [ty] -- | Make multiplication type. (.*.) :: Type -> Type -> Type x .*. y = TCon (TF TCMul) [x,y] -- | Make addition type. (.+.) :: Type -> Type -> Type x .+. y = TCon (TF TCAdd) [x,y] (.-.) :: Type -> Type -> Type x .-. y = TCon (TF TCSub) [x,y] (.^.) :: Type -> Type -> Type x .^. y = TCon (TF TCExp) [x,y] tDiv :: Type -> Type -> Type tDiv x y = TCon (TF TCDiv) [x,y] tMod :: Type -> Type -> Type tMod x y = TCon (TF TCMod) [x,y] -- | Make a @min@ type. tMin :: Type -> Type -> Type tMin x y = TCon (TF TCMin) [x,y] newtypeTyCon :: Newtype -> TCon newtypeTyCon nt = TC $ TCNewtype $ UserTC (ntName nt) (kindOf nt) newtypeConType :: Newtype -> Schema newtypeConType nt = Forall as (ntConstraints nt) $ TRec (ntFields nt) `tFun` TCon (newtypeTyCon nt) (map (TVar . tpVar) as) where as = ntParams nt -------------------------------------------------------------------------------- class HasKind t where kindOf :: t -> Kind instance HasKind TVar where kindOf (TVFree _ k _ _) = k kindOf (TVBound _ k) = k instance HasKind TCon where kindOf (TC tc) = kindOf tc kindOf (PC pc) = kindOf pc kindOf (TF tf) = kindOf tf instance HasKind UserTC where kindOf (UserTC _ k) = k instance HasKind TC where kindOf tcon = case tcon of TCNum _ -> KNum TCInf -> KNum TCBit -> KType TCSeq -> KNum :-> KType :-> KType TCFun -> KType :-> KType :-> KType TCTuple n -> foldr (:->) KType (replicate n KType) TCNewtype x -> kindOf x instance HasKind PC where kindOf pc = case pc of PEqual -> KNum :-> KNum :-> KProp PNeq -> KNum :-> KNum :-> KProp PGeq -> KNum :-> KNum :-> KProp PFin -> KNum :-> KProp PHas _ -> KType :-> KType :-> KProp PArith -> KType :-> KProp PCmp -> KType :-> KProp instance HasKind TFun where kindOf tfun = case tfun of TCWidth -> KNum :-> KNum TCAdd -> KNum :-> KNum :-> KNum TCSub -> KNum :-> KNum :-> KNum TCMul -> KNum :-> KNum :-> KNum TCDiv -> KNum :-> KNum :-> KNum TCMod -> KNum :-> KNum :-> KNum TCExp -> KNum :-> KNum :-> KNum TCMin -> KNum :-> KNum :-> KNum TCMax -> KNum :-> KNum :-> KNum TCLenFromThen -> KNum :-> KNum :-> KNum :-> KNum TCLenFromThenTo -> KNum :-> KNum :-> KNum :-> KNum instance HasKind Type where kindOf ty = case ty of TVar a -> kindOf a TCon c ts -> quickApply (kindOf c) ts TUser _ _ t -> kindOf t TRec {} -> KType instance HasKind TySyn where kindOf (TySyn _ as _ t) = foldr (:->) (kindOf t) (map kindOf as) instance HasKind Newtype where kindOf nt = foldr (:->) KType (map kindOf (ntParams nt)) instance HasKind TParam where kindOf p = tpKind p quickApply :: Kind -> [a] -> Kind quickApply k [] = k quickApply (_ :-> k) (_ : ts) = quickApply k ts quickApply k _ = panic "Cryptol.TypeCheck.AST.quickApply" [ "Applying a non-function kind:", show k ] -- Pretty Printing ------------------------------------------------------------- instance PP Kind where ppPrec p k = case k of KType -> char '*' KNum -> char '#' KProp -> text "Prop" l :-> r -> optParens (p >= 1) (sep [ppPrec 1 l, text "->", ppPrec 0 r]) instance PP (WithNames TVar) where ppPrec _ (WithNames (TVBound x _) mp) = case IntMap.lookup x mp of Just a -> text a Nothing -> text ("a`" ++ show x) ppPrec _ (WithNames (TVFree x _ _ _) _) = char '?' <> text (intToName x) instance PP TVar where ppPrec = ppWithNamesPrec IntMap.empty instance PP TParam where ppPrec = ppWithNamesPrec IntMap.empty instance PP (WithNames TParam) where ppPrec _ (WithNames p mp) = ppWithNames mp (tpVar p) instance PP (WithNames Type) where ppPrec prec ty0@(WithNames ty nmMap) = case ty of TVar a -> ppWithNames nmMap a TRec fs -> braces $ fsep $ punctuate comma [ pp l <+> text ":" <+> go 0 t | (l,t) <- fs ] TUser c ts _ -> optParens (prec > 3) $ pp c <+> fsep (map (go 4) ts) TCon (TC tc) ts -> case (tc,ts) of (TCNum n, []) -> integer n (TCInf, []) -> text "inf" (TCBit, []) -> text "Bit" (TCSeq, [t1,TCon (TC TCBit) []]) -> brackets (go 0 t1) (TCSeq, [t1,t2]) -> optParens (prec > 3) $ brackets (go 0 t1) <> go 3 t2 (TCFun, [t1,t2]) -> optParens (prec > 1) $ go 2 t1 <+> text "->" <+> go 1 t2 (TCTuple _, fs) -> parens $ fsep $ punctuate comma $ map (go 0) fs (_, _) -> pp tc <+> fsep (map (go 4) ts) TCon (PC pc) ts -> case (pc,ts) of (PEqual, [t1,t2]) -> go 0 t1 <+> text "==" <+> go 0 t2 (PNeq , [t1,t2]) -> go 0 t1 <+> text "/=" <+> go 0 t2 (PGeq, [t1,t2]) -> go 0 t1 <+> text ">=" <+> go 0 t2 (PFin, [t1]) -> text "fin" <+> (go 4 t1) (PHas x, [t1,t2]) -> ppSelector x <+> text "of" <+> go 0 t1 <+> text "is" <+> go 0 t2 (PArith, [t1]) -> pp pc <+> go 4 t1 (PCmp, [t1]) -> pp pc <+> go 4 t1 (_, _) -> pp pc <+> fsep (map (go 4) ts) _ | Just tinf <- isTInfix ty0 -> optParens (prec > 2) $ ppInfix 2 isTInfix tinf TCon f ts -> optParens (prec > 3) $ pp f <+> fsep (map (go 4) ts) where go p t = ppWithNamesPrec nmMap p t isTInfix (WithNames (TCon (TF ieOp) [ieLeft',ieRight']) _) = do let ieLeft = WithNames ieLeft' nmMap ieRight = WithNames ieRight' nmMap (ieAssoc,iePrec) <- Map.lookup ieOp tBinOpPrec return Infix { .. } isTInfix _ = Nothing addTNames :: [TParam] -> NameMap -> NameMap addTNames as ns = foldr (uncurry IntMap.insert) ns $ named ++ zip unnamed avail where avail = filter (`notElem` used) (nameList []) named = [ (u,show (pp n)) | TParam { tpUnique = u, tpName = Just n } <- as ] unnamed = [ u | TParam { tpUnique = u, tpName = Nothing } <- as ] used = map snd named ++ IntMap.elems ns ppNewtypeShort :: Newtype -> Doc ppNewtypeShort nt = text "newtype" <+> pp (ntName nt) <+> hsep (map (ppWithNamesPrec nm 9) ps) where ps = ntParams nt nm = addTNames ps emptyNameMap instance PP Schema where ppPrec = ppWithNamesPrec IntMap.empty instance PP (WithNames Schema) where ppPrec _ (WithNames s ns) = vars <+> props <+> ppWithNames ns1 (sType s) where vars = case sVars s of [] -> empty vs -> braces $ commaSep $ map (ppWithNames ns1) vs props = case sProps s of [] -> empty ps -> parens (commaSep (map (ppWithNames ns1) ps)) <+> text "=>" ns1 = addTNames (sVars s) ns instance PP TySyn where ppPrec = ppWithNamesPrec IntMap.empty instance PP (WithNames TySyn) where ppPrec _ (WithNames (TySyn n ps _ ty) ns) = text "type" <+> pp n <+> sep (map (ppWithNames ns1) ps) <+> char '=' <+> ppWithNames ns1 ty where ns1 = addTNames ps ns instance PP Type where ppPrec n t = ppWithNamesPrec IntMap.empty n t instance PP TCon where ppPrec _ (TC tc) = pp tc ppPrec _ (PC tc) = pp tc ppPrec _ (TF tc) = pp tc instance PP PC where ppPrec _ x = case x of PEqual -> text "(==)" PNeq -> text "(/=)" PGeq -> text "(>=)" PFin -> text "fin" PHas sel -> parens (ppSelector sel) PArith -> text "Arith" PCmp -> text "Cmp" instance PP TC where ppPrec _ x = case x of TCNum n -> integer n TCInf -> text "inf" TCBit -> text "Bit" TCSeq -> text "[]" TCFun -> text "(->)" TCTuple 0 -> text "()" TCTuple 1 -> text "(one tuple?)" TCTuple n -> parens $ hcat $ replicate (n-1) comma TCNewtype u -> pp u instance PP UserTC where ppPrec p (UserTC x _) = ppPrec p x instance PP (WithNames Expr) where ppPrec prec (WithNames expr nm) = case expr of EList [] t -> optParens (prec > 0) $ text "[]" <+> colon <+> ppWP prec t EList es _ -> brackets $ sep $ punctuate comma $ map ppW es ETuple es -> parens $ sep $ punctuate comma $ map ppW es ERec fs -> braces $ sep $ punctuate comma [ pp f <+> text "=" <+> ppW e | (f,e) <- fs ] ESel e sel -> ppWP 4 e <+> text "." <> pp sel EIf e1 e2 e3 -> optParens (prec > 0) $ sep [ text "if" <+> ppW e1 , text "then" <+> ppW e2 , text "else" <+> ppW e3 ] EComp _ e mss -> let arm ms = text "|" <+> commaSep (map ppW ms) in brackets $ ppW e <+> vcat (map arm mss) EVar x -> withNameEnv $ \ env -> let NameInfo qn isInfix = getNameInfo x env in optParens isInfix (ppQName qn) EAbs {} -> let (xs,e) = splitWhile splitAbs expr in ppLam nm prec [] [] xs e EProofAbs {} -> let (ps,e1) = splitWhile splitProofAbs expr (xs,e2) = splitWhile splitAbs e1 in ppLam nm prec [] ps xs e2 ETAbs {} -> let (ts,e1) = splitWhile splitTAbs expr (ps,e2) = splitWhile splitProofAbs e1 (xs,e3) = splitWhile splitAbs e2 in ppLam nm prec ts ps xs e3 -- infix applications EApp (EApp (EVar o) a) b -> withNameEnv $ \ env -> let NameInfo qn isInfix = getNameInfo o env in optParens (prec > 3) $ if isInfix then ppPrec 3 a <+> ppQName qn <+> ppPrec 3 b else ppQName qn <+> ppPrec 3 a <+> ppPrec 3 b EApp e1 e2 -> optParens (prec > 3) $ ppWP 3 e1 <+> ppWP 4 e2 EProofApp e -> optParens (prec > 3) $ ppWP 3 e <+> text "<>" ETApp e t -> optParens (prec > 3) $ ppWP 3 e <+> ppWP 4 t ECast e t -> optParens (prec > 0) ( ppWP 2 e <+> text ":" <+> ppW t ) EWhere e ds -> optParens (prec > 0) ( ppW e $$ text "where" $$ nest 2 (vcat (map ppW ds)) $$ text "" ) where ppW x = ppWithNames nm x ppWP x = ppWithNamesPrec nm x ppLam :: NameMap -> Int -> [TParam] -> [Prop] -> [(QName,Type)] -> Expr -> Doc ppLam nm prec [] [] [] e = ppWithNamesPrec nm prec e ppLam nm prec ts ps xs e = optParens (prec > 0) $ sep [ text "\\" <> tsD <+> psD <+> xsD <+> text "->" , ppWithNames ns1 e ] where ns1 = addTNames ts nm tsD = if null ts then empty else braces $ sep $ punctuate comma $ map ppT ts psD = if null ps then empty else parens $ sep $ punctuate comma $ map ppP ps xsD = if null xs then empty else sep $ map ppArg xs ppT = ppWithNames ns1 ppP = ppWithNames ns1 ppArg (x,t) = parens (pp x <+> text ":" <+> ppWithNames ns1 t) splitWhile :: (a -> Maybe (b,a)) -> a -> ([b],a) splitWhile f e = case f e of Nothing -> ([], e) Just (x,e1) -> let (xs,e2) = splitWhile f e1 in (x:xs,e2) splitAbs :: Expr -> Maybe ((QName,Type), Expr) splitAbs (EAbs x t e) = Just ((x,t), e) splitAbs _ = Nothing splitTAbs :: Expr -> Maybe (TParam, Expr) splitTAbs (ETAbs t e) = Just (t, e) splitTAbs _ = Nothing splitProofAbs :: Expr -> Maybe (Prop, Expr) splitProofAbs (EProofAbs p e) = Just (p,e) splitProofAbs _ = Nothing instance PP Expr where ppPrec n t = ppWithNamesPrec IntMap.empty n t instance PP (WithNames Match) where ppPrec _ (WithNames mat nm) = case mat of From x _ e -> pp x <+> text "<-" <+> ppWithNames nm e Let d -> text "let" <+> ppWithNames nm d instance PP Match where ppPrec = ppWithNamesPrec IntMap.empty instance PP (WithNames DeclGroup) where ppPrec _ (WithNames dg nm) = case dg of Recursive ds -> text "/* Recursive */" $$ vcat (map (ppWithNames nm) ds) $$ text "" NonRecursive d -> text "/* Not recursive */" $$ ppWithNames nm d $$ text "" instance PP DeclGroup where ppPrec = ppWithNamesPrec IntMap.empty instance PP (WithNames Decl) where ppPrec _ (WithNames Decl { .. } nm) = pp dName <+> text ":" <+> ppWithNames nm dSignature $$ (if null dPragmas then empty else text "pragmas" <+> pp dName <+> sep (map pp dPragmas) ) $$ pp dName <+> text "=" <+> ppWithNames nm dDefinition instance PP (WithNames DeclDef) where ppPrec _ (WithNames DPrim _) = text "<primitive>" ppPrec _ (WithNames (DExpr e) nm) = ppWithNames nm e instance PP Decl where ppPrec = ppWithNamesPrec IntMap.empty instance PP Module where ppPrec = ppWithNamesPrec IntMap.empty instance PP (WithNames Module) where ppPrec _ (WithNames Module { .. } nm) = text "module" <+> pp mName $$ -- XXX: Print exports? vcat (map pp mImports) $$ -- XXX: Print tysyns vcat (map (ppWithNames nm) mDecls)
iblumenfeld/cryptol
src/Cryptol/TypeCheck/AST.hs
bsd-3-clause
29,048
0
18
10,635
9,676
4,979
4,697
642
4
{-| Module : Riff.Files Description : Functions for working with file pairs and obtaining directory listings Copyright : (c) 2019 Steven Meunier License : BSD-style (see the file LICENSE) -} module Riff.Files ( -- * Types FilePair(..) , FilePairs -- * FilePairs , new , old , newExist , rename , filePairs , renameableFilePairs -- * Directory Listing , dirContents , dirs , files ) where import Riff.Prelude import Riff.Sanitize import Control.Monad ( filterM ) import System.Directory ( getDirectoryContents , makeAbsolute ) import System.FilePath ( takeFileName , (</>) ) import System.Posix.Files ( FileStatus , fileExist , getFileStatus , isDirectory , isRegularFile ) import qualified System.Posix.Files as F ( rename ) import Text.Show type OldFilePath = FilePath type NewFilePath = FilePath -- | 'FilePath's grouped as the old 'FilePath' and the new 'FilePath' -- that the file can be renamed to. data FilePair = FilePair OldFilePath NewFilePath -- | List of FilePairs type FilePairs = [FilePair] instance Show FilePair where show (FilePair x y) = x <> " -> " <> takeFileName y -- | Return the new name in a 'FilePair'. new :: FilePair -> FilePath new (FilePair _ x) = x -- | Return the old name in 'FilePair'. old :: FilePair -> FilePath old (FilePair x _) = x -- | Check if a file or directory corresponding to the new name already exists. newExist :: FilePair -> IO Bool newExist (FilePair _ x) = fileExist x -- | Rename the old file in a 'FilePair' to the new name. rename :: FilePair -> IO () rename (FilePair x y) = F.rename x y -- | Build a list of 'FilePair's by processing a list of 'FilePath's -- with a given 'Transformer'. Any 'FilePath's that are the same -- after being transformed are filtered from the resulting -- 'FilePairs'. filePairs :: Transformer -> [FilePath] -> FilePairs filePairs f xs = filter (not . namesSame) $ map mkFilePair xs where namesSame (FilePair x y) = x == y mkFilePair x = FilePair x (transform f x) -- | Filter 'FilePairs' to remove the 'FilePair's that possess a new -- file name where that file already exists and renaming the file -- would clobber the existing file. renameableFilePairs :: FilePairs -> IO FilePairs renameableFilePairs = filterM (fmap not . newExist) -- | List the directory names one level deep under a given parent directory. dirs :: FilePath -> IO [FilePath] dirs = flip filteredLs isDirectory -- | List the regular files in a given a directory. files :: FilePath -> IO [FilePath] files = flip filteredLs isRegularFile -- | List all the files in a given directory with the regular files -- preceding directories. dirContents :: FilePath -> IO [FilePath] dirContents x = (++) <$> files x <*> dirs x -- | Filter out '.' and '..' from a directory listing. filterSpecial :: [FilePath] -> IO [FilePath] filterSpecial = filterM (\x -> return $ x /= "." && x /= "..") -- | List a filtered directory listing for a given path. filteredLs :: FilePath -> (FileStatus -> Bool) -> IO [FilePath] filteredLs x p = ls x >>= filterM (fmap p . getFileStatus) -- | List the absolute path for all files in a given directory. ls :: FilePath -> IO [FilePath] ls x = getDirectoryContents x >>= filterSpecial >>= absPaths where absPaths = mapM (makeAbsolute . (x </>))
solaryeti/riff
src/Riff/Files.hs
bsd-3-clause
3,914
0
11
1,258
713
398
315
61
1
{-# LANGUAGE FlexibleContexts #-} module Network.Salvia.Handler.SendFile (hSendFileResource) where import Control.Monad.Trans import Data.Record.Label import Network.Protocol.Http import Network.Salvia import Network.Socket.SendFile import System.IO -- TODO: closing of file after getting filesize? hSendFileResource :: (MonadIO m, HttpM Response m, SendM m, SocketQueueM m) => FilePath -> m () hSendFileResource f = hSafeIO (openBinaryFile f ReadMode) $ \fd -> hSafeIO (hFileSize fd) $ \fs -> do response $ do status =: OK contentType =: Just (fileMime f, Just "utf-8") contentLength =: Just fs enqueueSock (\s -> sendFile' s f 0 fs)
sebastiaanvisser/salvia-extras
src/Network/Salvia/Handler/SendFile.hs
bsd-3-clause
709
0
17
160
207
109
98
17
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : HaskDeep.Computation.Writer -- Copyright : Mauro Taraborelli 2012 -- License : BSD3 -- -- Maintainer : maurotaraborelli@gmail.com -- Stability : experimental -- Portability : unknown -- -- Computes hashes traversing recursively through a directory structure. -- Uses a list of known hashes to audit a set of files. -- -- Internal module. module HaskDeep.KnownHash.Writer ( -- * Write the known hashes file writeHashes -- HaskDeepConfiguration -> HashSet -> IO () ) where import Control.Monad.Trans.Resource (runResourceT) import Prelude hiding (FilePath) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as B8 import Data.Conduit (($$)) import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import qualified Data.Time as DT import qualified Data.Text as T import qualified Data.Text.Encoding as TE import System.FilePath () import HaskDeep.Configuration import HaskDeep.HashSet (HashSet) import qualified HaskDeep.HashSet as HS -- | Write an @HashSet@ to a known hashes file. writeHashes :: HaskDeepConfiguration -- ^ Configuration -> HashSet -- ^ @HashSet@ to write -> IO () writeHashes conf hs = runResourceT $ CL.sourceList bs_known $$ CB.sinkFile (knownHashes conf) where newline = "\n" :: ByteString root = TE.encodeUtf8 $ T.pack $ rootDirectory conf exclude_regex = case excludeRegex conf of (Just regex) -> TE.encodeUtf8 regex Nothing -> BS.empty include_mod_from = case includeModFrom conf of (Just modFrom) -> B8.pack $ DT.formatTime DT.defaultTimeLocale "%FT%TZ" modFrom Nothing -> BS.empty include_mod_upto = case includeModUpTo conf of (Just modUpTo) -> B8.pack $ DT.formatTime DT.defaultTimeLocale "%FT%TZ" modUpTo Nothing -> BS.empty files_count = B8.pack $ show $ HS.filesCount hs size_sum = B8.pack $ show $ HS.sizeSum hs known_header1 = "%%%% HASHDEEP-1.0" `BS.append` newline known_header2 = "%%%% size," `BS.append` TE.encodeUtf8 (HS.compSymbol hs) `BS.append` ",filename" `BS.append` newline bs_comments = map (flip BS.append newline . BS.append "## ") [ "Root directory : " `BS.append` root , "Exclude regex : " `BS.append` exclude_regex , "Include mod. from : " `BS.append` include_mod_from , "Include mod. upto : " `BS.append` include_mod_upto , "Files count : " `BS.append` files_count , "Files size : " `BS.append` size_sum , "" ] bs_hash_set = map (flip BS.append newline . HS.toByteString) $ HS.toAscList hs bs_known = [known_header1, known_header2] ++ bs_comments ++ bs_hash_set
maurotrb/haskdeep
src/HaskDeep/KnownHash/Writer.hs
bsd-3-clause
3,320
0
13
1,119
627
365
262
52
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module KnownNat where import Data.Proxy import GHC.TypeLits {- $setup >>> :set -XDataKinds -} {-| >>> f (Proxy :: Proxy 1) 3 -} f :: forall n m. (KnownNat n, KnownNat m, m ~ (n + 2)) => Proxy n -> Integer f _ = natVal (Proxy :: Proxy m)
notae/haskell-exercise
type/KnownNat.hs
bsd-3-clause
389
0
10
92
88
51
37
9
1
module ProgramExecutionSpec where import ProgramExecution (RunType (..)) import Test.Hspec import Test.Hspec.Checkers import Test.QuickCheck.Classes rtSpec :: SpecWith () rtSpec = describe "RunType ?Monoid?" $ testBatch $ monoid (undefined :: RunType)
qfjp/csce_dfa_project_test
test/ProgramExecutionSpec.hs
bsd-3-clause
310
0
7
87
68
40
28
9
1
module CUDA (hasCUDA, loadCUDAArray, synchronizeCUDA, getCudaArchitecture) where import Data.Int import Foreign.Ptr #ifdef DEX_CUDA import Foreign.C #else #endif hasCUDA :: Bool #ifdef DEX_CUDA hasCUDA = True foreign import ccall "dex_cuMemcpyDtoH" cuMemcpyDToH :: Int64 -> Ptr () -> Ptr () -> IO () foreign import ccall "dex_synchronizeCUDA" synchronizeCUDA :: IO () foreign import ccall "dex_ensure_has_cuda_context" ensureHasCUDAContext :: IO () foreign import ccall "dex_get_cuda_architecture" dex_getCudaArchitecture :: Int -> CString -> IO () getCudaArchitecture :: Int -> IO String getCudaArchitecture dev = withCString "sm_00" $ \cs -> dex_getCudaArchitecture dev cs >> peekCString cs #else hasCUDA = False cuMemcpyDToH :: Int64 -> Ptr () -> Ptr () -> IO () cuMemcpyDToH = error "Dex built without CUDA support" synchronizeCUDA :: IO () synchronizeCUDA = return () ensureHasCUDAContext :: IO () ensureHasCUDAContext = return () getCudaArchitecture :: Int -> IO String getCudaArchitecture _ = error "Dex built without CUDA support" #endif loadCUDAArray :: Ptr () -> Ptr () -> Int -> IO () loadCUDAArray hostPtr devicePtr bytes = do ensureHasCUDAContext cuMemcpyDToH (fromIntegral bytes) devicePtr hostPtr
google-research/dex-lang
src/lib/CUDA.hs
bsd-3-clause
1,241
0
10
198
254
133
121
17
1
import Disorder.Core.Main import qualified Test.Mismi.EC2.Data main :: IO () main = disorderMain [ Test.Mismi.EC2.Data.tests ]
ambiata/mismi
mismi-ec2/test/test.hs
bsd-3-clause
151
0
7
39
41
25
16
6
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} module Graphics.CadSim.Boolean where class BooleanOps a where union :: a -> a -> a intersection :: a -> a -> a xor :: a -> a -> a
chetant/cadsim
Graphics/CadSim/Boolean.hs
bsd-3-clause
207
0
8
47
56
31
25
6
0
{-# LANGUAGE DeriveDataTypeable #-} import Prelude hiding (readFile, catch) import Control.Exception import Control.Applicative import Control.Monad.Writer import Data.Map (Map) import Data.Set (Set) import Data.Maybe import Data.Foldable (foldMap) import Data.Traversable (for) import Data.List import Data.Version import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.List.Key as Key import System.Console.CmdArgs import System.FilePath import System.Directory import System.IO.Strict import System.IO hiding (readFile, hGetContents) import Language.Haskell.Exts.Syntax hiding (ModuleName) import qualified Language.Haskell.Exts.Syntax as Syntax import Language.Haskell.Exts (parseFileContents) import qualified Language.Haskell.Exts.Parser as Haskell import Distribution.Package import Distribution.PackageDescription import qualified Distribution.ModuleName as DistModule import qualified Distribution.PackageDescription.Parse as DistParse import Distribution.Verbosity import Distribution.Simple.Utils import Distribution.Version -------------- -- Driver code data HackageQuery = Collisions { argDir :: FilePath } | Tools { argDir :: FilePath } | Dependencies { argDir :: FilePath } deriving (Data, Typeable, Show, Eq) dirFlags = args &= typ "HACKAGE-DIR" &= argPos 0 mymodes :: HackageQuery mymodes = modes [collisions, tools, dependencies] main :: IO () main = do args <- cmdArgs mymodes case args of Collisions {} -> runCollisions args >> return () Tools {} -> runTools args >> return () Dependencies {} -> runDependencies args >> return () -------------------- -- Data declarations newtype SetMap k v = SetMap { unSetMap :: Map k (Set v) } deriving (Show) instance (Ord k, Ord v) => Monoid (SetMap k v) where mempty = SetMap Map.empty mappend (SetMap a) (SetMap b) = SetMap $ Map.unionWith Set.union a b mconcat = SetMap . Map.unionsWith Set.union . map unSetMap setMapSingleton :: (Ord k, Ord v) => k -> v -> SetMap k v setMapSingleton k v = SetMap $ Map.singleton k (Set.singleton v) --------------------- -- Utility functions -- | Strictly parses a Haskell file with extensions. parseFile :: FilePath -> IO (Haskell.ParseResult Module) parseFile filename = tryParse utf8 `catch` ioConst (tryParse latin1) where ioConst :: a -> IOException -> a ioConst a _ = a tryParse enc = withFile filename ReadMode $ \h -> do -- this does the wrong thing for latin1; better idea is to -- parametrize over encodings and try both hSetEncoding h enc contents <- hGetContents h -- haskell-src-exts emits a user exception we need to catch (return $! parseFileContents contents) `catch` errorHandler errorHandler :: ErrorCall -> IO (Haskell.ParseResult Module) errorHandler e = return (Haskell.ParseFailed (SrcLoc filename 0 0) (show e)) parseResultToMaybe :: Haskell.ParseResult a -> Maybe a parseResultToMaybe (Haskell.ParseOk a) = Just a parseResultToMaybe _ = Nothing -- | Returns a list of visible file names in a directory. getVisibleDirectoryContents :: FilePath -> IO [String] getVisibleDirectoryContents d = filter (`notElem` [".",".."]) <$> getDirectoryContents d ------------------------------------- -- Drilling into the Hackage database withPackages' :: (FilePath -> String -> (FilePath -> GenericPackageDescription -> IO a) -> IO r) -> FilePath -> (FilePath -> GenericPackageDescription -> IO a) -> IO [r] withPackages' h hackageDir f = do packageNames <- getVisibleDirectoryContents hackageDir mapM (\name -> h hackageDir name f) packageNames withPackages1 = withPackages' withPackage1 withPackages = withPackages' withPackage -- Runs an action with a description of the package withPackage1 :: FilePath -> String -> (FilePath -> GenericPackageDescription -> IO a) -> IO a withPackage1 hackageDir packageName f = do packageDir <- findLatestPackageDir hackageDir packageName pkgd <- readPackageDir packageDir packageName f packageDir pkgd -- Handles the case where there are multiple versions withPackage :: FilePath -> String -> (FilePath -> GenericPackageDescription -> IO a) -> IO (String, [a]) withPackage hackageDir packageName f = do packageDirs <- findAllPackageDirs hackageDir packageName r <- mapM (\d -> readPackageDir d packageName >>= f d) packageDirs return (packageName, r) -- Runs an action for each visible module in a package. forModules :: FilePath -> GenericPackageDescription -> (Module -> IO a) -> IO [a] forModules packageDir pkgd f = do let moduleNames = packageModuleNames pkgd sourceDirs = packageSourceDirs packageDir pkgd errHandler :: SomeException -> IO [a] errHandler _ = return [] filePairs <- findModuleFiles (packageDir:sourceDirs) [".hs"] moduleNames `catch` errHandler let files = map (uncurry (</>)) filePairs modules <- parseModuleFiles files forM modules f -- | Parses a list of module files, dropping module files that fail to -- parse parseModuleFiles :: [FilePath] -> IO [Module] parseModuleFiles paths = do parses <- mapM ((`catch` errHandler) . fmap Just . parseFile) paths return . mapMaybe parseResultToMaybe . catMaybes $ parses where errHandler :: IOException -> IO (Maybe a) errHandler e = do hPutStrLn stderr (show e) -- (directory ++ ":" ++ name ++ ". " ++ show e) return Nothing -- | Determines the directory corresponding to the package directory of -- the latest version of 'packageName' in an extracted Hackage archive -- located in 'hackageDir'. -- XXX method is kind of skeevy findLatestPackageDir :: FilePath -> String -> IO FilePath findLatestPackageDir hackageDir packageName = (head . reverse . sort) `fmap` findAllPackageDirs hackageDir packageName -- | Determines the directory corresponding to the package directory of -- the latest version of 'packageName' in an extracted Hackage archive -- located in 'hackageDir'. findAllPackageDirs :: FilePath -> String -> IO [FilePath] findAllPackageDirs hackageDir packageName = do let versionsDir = hackageDir </> packageName versions <- getVisibleDirectoryContents versionsDir -- XXX assumes that no new directory is created return $ map (\v -> versionsDir </> v) versions -- | Reads the Cabal package file out of a package directory. readPackageDir :: FilePath -> String -> IO GenericPackageDescription readPackageDir packageDir packageName = do let cabalFile = packageDir </> packageName ++ ".cabal" DistParse.readPackageDescription silent cabalFile -- | Retrieves all of the source directories (where module hirearchies -- live) in a package. Paths are prefixed by 'packageDir'. packageSourceDirs :: FilePath -> GenericPackageDescription -> [FilePath] packageSourceDirs packageDir = map (packageDir </>) . concatMap hsSourceDirs . allBuildInfo . packageDescription -- | Retrieves all of the exposed libraries from a package. packageLibraries :: GenericPackageDescription -> [Library] packageLibraries pkgd = condLibraries ++ uncondLibraries where condLibraries = maybe [] (execWriter . handleCondNode) (condLibrary pkgd) where handleCondNode (CondNode a _ ps) = tell [a] >> mapM_ handleTuple ps handleTuple (_, n, Just m) = handleCondNode n >> handleCondNode m handleTuple (_, n, Nothing) = handleCondNode n uncondLibraries = maybe [] return . library $ packageDescription pkgd -- | Retrieves all of the exposed module names from a package. packageModuleNames :: GenericPackageDescription -> [DistModule.ModuleName] packageModuleNames = concatMap exposedModules . packageLibraries ------------- -- Collisions collisions = Collisions { argDir = def &= dirFlags } &= help "Search Hackage for identifier collisions" runCollisions args = do let hackageDir = argDir args packageNames <- getVisibleDirectoryContents hackageDir bag <- mconcat . concat <$> mapM (findIdentifiers hackageDir) packageNames render . Key.sort (negate . Set.size . snd) . Map.toList . unSetMap $ bag where render :: [(Name, Set Syntax.ModuleName)] -> IO () render results = do let xs = filter isSymbol results mapM_ renderResult xs mapM_ renderModules xs where renderResult (v, ms) = putStrLn (show (Set.size ms) ++ " " ++ unwrapName v) renderModules (v, ms) = putStrLn (show v ++ " " ++ show ms) unwrapName (Syntax.Ident n) = n unwrapName (Syntax.Symbol n) = n isSymbol (Syntax.Symbol _, _) = True isSymbol _ = False -- | Grabs the public identifiers given a Hackage directory and a module name. findIdentifiers :: FilePath -> String -> IO [SetMap Name Syntax.ModuleName] findIdentifiers hackageDir packageName = withPackage1 hackageDir packageName $ \packageDir pkgd -> forModules packageDir pkgd $ \m -> evaluate (modulePublicIdentifiers m) -- | Extracts public identifiers from a module's abstract syntax tree. modulePublicIdentifiers :: Module -> SetMap Name Syntax.ModuleName modulePublicIdentifiers (Module _ m _ _ (Just exports) _ _) = foldMap handleExport $ exports where handleExport x = case x of EVar (UnQual n) -> add n EAbs (UnQual n) -> add n EThingAll (UnQual n) -> add n -- XXX also lookup the rest -- XXX: Can a qualified export have unqualified insides? I -- don't think so... EThingWith (UnQual n) cs -> add n `mappend` (foldMap handleCName) cs _ -> mempty handleCName x = case x of VarName n -> add n ConName n -> add n add n = setMapSingleton n m -- should also case for an empty exports list, in which case all -- identifiers are exported modulePublicIdentifiers _ = mempty unPackageName (PackageName s) = s getPackageName pkgd = unPackageName (pkgName (package (packageDescription pkgd))) -------- -- Tools tools = Tools { argDir = def &= dirFlags } &= help "Search Hackage for build tool usage" runTools args = do let hackageDir = argDir args results <- withPackages1 hackageDir $ \pkgDir pkgd -> do let packageName = getPackageName pkgd let tools = packageBuildToolNames pkgd return $ foldMap (\(PackageName tool) -> setMapSingleton tool packageName) tools let bag = mconcat results sortedResults = Key.sort (negate . Set.size . snd) . Map.toList . unSetMap $ bag forM_ sortedResults $ \(tool, packages) -> do putStrLn $ tool ++ " (" ++ show (Set.size packages) ++ ")" forM_ (Set.toList packages) $ \package -> putStrLn $ " " ++ package putStrLn "" packageBuildToolNames :: GenericPackageDescription -> [PackageName] packageBuildToolNames pkgd = uncondTools ++ condLibraryTools where uncondTools = flattenTools . allBuildInfo . packageDescription $ pkgd condLibraryTools = flattenTools . maybe [] (execWriter . handleCondNode) $ (condLibrary pkgd) handleCondNode (CondNode a _ ps) = tell [libBuildInfo a] >> mapM_ handleCondTuple ps handleCondTuple (_, n, Just m) = handleCondNode n >> handleCondNode m handleCondTuple (_, n, Nothing) = handleCondNode n flattenTools = map (\(Dependency name _) -> name) . concatMap buildTools ---------------- -- Compatibility -- XXX watch out: you want easy to handle data first -- so that rapid iteration on visualization is possible -- package name, package dep, date, *versions (blob)* dependencies = Dependencies { argDir = def &= dirFlags } &= help "Analyze per-version dependencies" runDependencies args = do let hackageDir = argDir args withPackages hackageDir $ \pkgDir pkgd -> do let packageName = getPackageName pkgd let packageVer = packageVersion pkgd let deps = buildDepends (packageDescription pkgd) -- XXX We're going to falsely assume that there is only one version -- interval forM_ deps $ \(Dependency dep ver) -> case versionIntervals (toVersionIntervals ver) of ((LowerBound lb _,rub):xs) -> do when (not (null xs)) $ hPutStrLn stderr ("oops, too much data " ++ packageName ++ "-" ++ showVersion packageVer) let ub = case rub of NoUpperBound -> Nothing UpperBound x _ -> Just x putStrLn $ packageName ++ "," ++ showVersion packageVer ++ "," ++ unPackageName dep ++ "," ++ showVersion lb ++ "," ++ maybe "" showVersion ub [] -> hPutStrLn stderr ("oops, no data " ++ packageName ++ "-" ++ showVersion packageVer)
ezyang/hackage-query
hackage-query.hs
bsd-3-clause
13,234
0
26
3,233
3,408
1,744
1,664
220
6
module Bindings (idle,display,reshape,keyboardMouse) where import Graphics.Rendering.OpenGL import Graphics.UI.GLUT import Data.IORef import Display reshape s@(Size w h) = do viewport $= (Position 0 0, s) keyboardAct delta (Char '+') Down = do delta' <- get delta delta $= 2*delta' keyboardAct delta (Char '-') Down = do delta' <- get delta delta $= delta'/2 keyboardAct _ _ _ = return () keyboardMouse delta key state modifiers position = do keyboardAct delta key state
kjellwinblad/HaskellGravityWorld
Bindings.hs
bsd-3-clause
493
0
9
93
196
100
96
16
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} module Templates.Styles where import Text.Lucius import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Language.Haskell.TH mainStyle :: LT.Text mainStyle = renderCss $ mainStyle' undefined where mainStyle' = [lucius| @darkMain: #95502d; @otherDarkMain: #c49986; @otherMain: #d1ad9e; @font-face { font-family: "deftone"; src: url("/fonts/deftone_stylus.ttf"); } @font-face { font-family: "norton"; src: url("/fonts/NORTON.TTF"); } @font-face { font-family: "fontleroy"; src: url("/fonts/LittleLordFontleroyNF.otf"); } body { background: #ac6546; } #nav { padding-top: 1rem; background: #d9a084; } #nav ul { list-style: none; margin-left: 0; } #nav ul ul { list-style: none; margin-left: 0; padding-left: 0.5rem; } #nav ul li { line-height: 1.2em; color: #95502D; } #nav ul ul li:before { font-size: 1.2em; content: "├ "; } #nav ul ul li:last-child:before { font-size: 1.2em; content: "└ "; } #content { background: #e6c0ad; padding: 1.5rem; } footer { padding: 1rem; text-align: right; } header { vertical-align: bottom; height: 9rem; position: relative; } #logo { color: #fff; text-shadow: 0.2rem 0.2rem #{darkMain}; } #subtitle { -webkit-font-smoothing: antialiased; font-smoothing: antialiased; font-family: "fontleroy", "Liberation Sans", sans; color: #ddd; font-size: 2.5rem; text-shadow: 0.1rem 0.1rem #{darkMain}; margin-left: 6rem; margin-bottom: 0; position: absolute; bottom: 0; } #linkedin { width: 15px; height: 15px; vertical-align: -1px; border: 0; } .octicons { vertical-align: 1px; } blockquote { border-left: 1rem solid #{otherDarkMain}; background: #{otherMain}; padding-bottom: 0.5rem; } blockquote code { background: #dcbeb6; border: 1px solid #e4cdc6; } blockquote p:last-child { margin-bottom: 0; } blockquote p { padding-left: 0; color: #555; } hr { border: 0.5rem solid #{otherMain}; } h1 { margin-left: 2rem; -webkit-font-smoothing: antialiased; font-smoothing: antialiased; font-family: "deftone", sans; } h2 { -webkit-font-smoothing: antialiased; font-smoothing: antialiased; font-family: "norton", sans; box-shadow: inset 0 -0.3rem #222; width: auto; display: inline-block; } h3 { text-align: right; padding-right: 2rem; margin-right: 1rem; margin-left: 3rem; font-style: italic; box-shadow: inset 0 -1.25rem 0 #D1AD9E; } h4 { font-weight: bold; } h5 { font-weight: bold; } a, a:link, a:active, a:visited { color: #95502d; text-decoration: none; transition-property: color; transition-duration: 0.3s; } a:hover { color: #cd6942; text-decoration: none; } pre { margin-bottom: 1rem; } p:last-child { margin-bottom: 0; } code { white-space: pre; width: 100%; background: #e3cbbe; border-radius: 0.25rem; border: 1px solid #eed4ca; } pre code { display: inline-block; border-radius: 0.5rem; border: 1px solid #d9a995; } table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode { margin: 0; padding: 0; vertical-align: baseline; border: none; } table.sourceCode { width: 100%; line-height: 100%; } td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; } td.sourceCode { padding-left: 5px; } code > span.kw { color: #007020; font-weight: bold; } code > span.dt { color: #902000; } code > span.dv { color: #40a070; } code > span.bn { color: #40a070; } code > span.fl { color: #40a070; } code > span.ch { color: #4070a0; } code > span.st { color: #4070a0; } code > span.co { color: #60a0b0; font-style: italic; } code > span.ot { color: #007020; } code > span.al { color: #ff0000; font-weight: bold; } code > span.fu { color: #06287e; } code > span.er { color: #ff0000; font-weight: bold; } .date { color: #434343; } table { background: #e1ae9a; border: 1px solid #e1ae9a; } table.wide { width: 100%; } table thead { background: #cd8a6f; } table tr.even, table tr.alt, table tr:nth-of-type(2n) { background: #D9A084; } .adsbygoogle { margin-top: 0.9375rem; margin-right: 0.9375rem; height: 125px; width: 152px; display: inline-block; text-align: center; border-radius: 0.5rem; } .selfieAd { display: none; margin-top: 0.9375rem; margin-right: 0.9375rem; border-radius: 0.5rem; text-align: center; background: #dbc56f; padding-top: 0.9375rem; } .selfieAd .button { background: #bda154; transition-property: background; transition-duration: 0.3s; } .selfieAd .button:hover { background: #835626; } |] mediaQueries = LT.concat [ "@media print {" , " html {" , " margin: 25mm;" , " }" , "}" , "@media only screen and (min-width: 64.063em) {" , " #nav {" , " border-radius: 0.5rem 0 0 0.5rem;" , " }" , " #content {" , " border-radius: 0 0.5rem 0.5rem 0.5rem;" , " }" , " .selfieAd {" , " display: inline-block;" , " }" , "}" ]
athanclark/deconfigured
src/Templates/Styles.hs
bsd-3-clause
5,098
0
6
1,012
125
82
43
28
1
{-# LANGUAGE LambdaCase, RecordWildCards #-} module AbstractInterpretation.HeapPointsTo.Pretty where import Data.Functor.Foldable as Foldable import Text.PrettyPrint.ANSI.Leijen import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.Vector (Vector) import qualified Data.Vector as V import Grin.Grin (Tag, Name) import Grin.Pretty import qualified AbstractInterpretation.HeapPointsTo.Result as R -- HPT Result NEW instance Pretty R.SimpleType where pretty = \case R.T_UnspecifiedLocation -> red $ text "#ptr" R.T_Location l -> cyan . int $ fromIntegral l ty -> red $ text $ show ty prettyHPTNode :: (Tag, Vector (Set R.SimpleType)) -> Doc prettyHPTNode (tag, args) = pretty tag <> list (map pretty $ V.toList args) prettyHPTFunction :: (Name, (R.TypeSet, Vector R.TypeSet)) -> Doc prettyHPTFunction = prettyFunction instance Pretty R.NodeSet where pretty (R.NodeSet m) = prettyBracedList (map prettyHPTNode $ Map.toList m) instance Pretty R.TypeSet where pretty (R.TypeSet ty (R.NodeSet ns)) = prettyBracedList (map prettyHPTNode (Map.toList ns) ++ map pretty (Set.toList ty)) instance Pretty R.HPTResult where pretty R.HPTResult{..} = vsep [ yellow (text "Heap") <$$> indent 4 (prettyKeyValue $ zip [(0 :: Int)..] $ V.toList _memory) , yellow (text "Env") <$$> indent 4 (prettyKeyValue $ Map.toList _register) , yellow (text "Function") <$$> indent 4 (vsep $ map prettyHPTFunction $ Map.toList _function) ]
andorp/grin
grin/src/AbstractInterpretation/HeapPointsTo/Pretty.hs
bsd-3-clause
1,622
0
15
287
559
300
259
33
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, GeneralizedNewtypeDeriving #-} {- | Module : System.Console.Haskeline.Class Copyright : (c) Antoine Latter, 2009 License : BSD3 Maintainer : Antoine Latter <aslatter@gmail.com> Stability : experimental Portability : FlexibleInstances, MultiPatamTypeClasses, UndecidableInstances, GeneralizedNewtypeDeriving Haskeline provides all of its functionality within the scope of a monad transformer. This module adds two pieces to this: - Introduced here is a type-class which defines the operations supported by the Haskeline monad transformer - MonadHaskeline - A newtype wrapper around Haskeline's InputT, called HaskelineT. Sadly, InputT defines ints own instance of the mtl MonadState, which is no good for folks wanting to use InputT in an existing monad transformer stack. HaskelineT also has an instance of MonadState, but it merely lifts the functions further in the transformer stack. Large portions of the Haskeline functionality are re-exported here for convinience. -} module System.Console.Haskeline.Class (HaskelineT ,runHaskelineT ,runHaskelineTWithPrefs ,MonadHaskeline(..) ,H.Settings(..) ,H.defaultSettings ,H.setComplete ,H.Prefs() ,H.readPrefs ,H.defaultPrefs ,H.Interrupt(..) ,H.handleInterrupt ,module System.Console.Haskeline.Completion ,module System.Console.Haskeline.MonadException ) where import qualified System.Console.Haskeline as H import System.Console.Haskeline.Completion import System.Console.Haskeline.MonadException import Control.Applicative import Control.Monad.State newtype HaskelineT m a = HaskelineT {unHaskeline :: H.InputT m a} deriving (Monad, Functor, Applicative, MonadIO, MonadException, MonadTrans, MonadHaskeline) -- | Run a line-reading application, reading user 'Prefs' from -- @~/.haskeline@ runHaskelineT :: MonadException m => H.Settings m -> HaskelineT m a -> m a runHaskelineT s m = H.runInputT s (unHaskeline m) runHaskelineTWithPrefs :: MonadException m => H.Prefs -> H.Settings m -> HaskelineT m a -> m a runHaskelineTWithPrefs p s m = H.runInputTWithPrefs p s (unHaskeline m) class MonadException m => MonadHaskeline m where getInputLine :: String -> m (Maybe String) getInputChar :: String -> m (Maybe Char) outputStr :: String -> m () outputStrLn :: String -> m () instance MonadException m => MonadHaskeline (H.InputT m) where getInputLine = H.getInputLine getInputChar = H.getInputChar outputStr = H.outputStr outputStrLn = H.outputStrLn instance MonadState s m => MonadState s (HaskelineT m) where get = lift get put = lift . put instance MonadHaskeline m => MonadHaskeline (StateT s m) where getInputLine = lift . getInputLine getInputChar = lift . getInputChar outputStr = lift . outputStr outputStrLn = lift . outputStrLn
aslatter/haskeline-class
System/Console/Haskeline/Class.hs
bsd-3-clause
2,942
0
10
531
538
295
243
48
1
{-# LANGUAGE DataKinds, GADTs, StandaloneDeriving #-} module Page2 (Red(Red), Black(Leaf, Black2, Black3, Black4), Root(Root)) where import Data.Type.Natural data Red a n where Red :: a -> (Black a n) -> (Black a n) -> Red a n data Black a n where Leaf :: Black a Z Black2 :: a -> (Black a n) -> (Black a n) -> Black a (S n) Black3 :: a -> (Red a n) -> (Black a n) -> Black a (S n) Black4 :: a -> (Red a n) -> (Red a n) -> Black a (S n) deriving instance Show a => Show (Black a n) deriving instance Show a => Show (Red a n) data Root a where Root :: Black a n -> Root a deriving instance Show a => Show (Root a)
farrellm/dependent-rbtree
src/Page2.hs
bsd-3-clause
632
0
11
152
321
174
147
22
0
module Unison.Note where import Data.List import Control.Monad import Control.Applicative -- | Hierarchical error message type used throughout Unison newtype Note = Note [String] -- | Monad transformer for adding notes newtype Noted m a = Noted { unnote :: m (Either Note a) } run :: Monad m => Noted m a -> m a run (Noted m) = m >>= \e -> case e of Left (Note stack) -> fail ("\n" ++ intercalate "\n" stack) Right a -> return a noted :: m (Either Note a) -> Noted m a noted = Noted liftMaybe :: Applicative m => String -> Maybe a -> Noted m a liftMaybe msg Nothing = failure msg liftMaybe _ (Just a) = pure a noted' :: Functor m => String -> m (Maybe a) -> Noted m a noted' ifNothing moa = noted (fmap (maybe (Left (note ifNothing)) Right) moa) lift :: Functor m => m a -> Noted m a lift = Noted . fmap Right failure :: Applicative m => String -> Noted m a failure = Noted . pure . Left . note scoped :: Functor m => String -> Noted m a -> Noted m a scoped msg inner = Noted $ fmap (scope msg) (unnote inner) orElse :: Monad m => Noted m a -> Noted m a -> Noted m a orElse a b = Noted $ unnote a >>= go where go (Left _) = unnote b go (Right a) = return (Right a) instance Monad m => Monad (Noted m) where return = Noted . return . return fail s = Noted . return . Left . note $ s Noted a >>= f = Noted $ a >>= \e -> case e of Left e -> return $ Left e Right a -> unnote (f a) instance Functor m => Functor (Noted m) where fmap f (Noted a) = Noted $ fmap go a where go (Left e) = Left e go (Right a) = Right (f a) instance Applicative m => Applicative (Noted m) where pure = Noted . pure . pure (Noted f) <*> (Noted a) = Noted $ liftA2 (<*>) f a note :: String -> Note note s = Note [s] note' :: String -> Maybe a -> Either Note a note' s Nothing = Left (note s) note' _ (Just a) = Right a scope :: String -> Either Note a -> Either Note a scope s (Left (Note stack)) = Left (Note (s : stack)) scope _ e = e scopeM :: Monad m => String -> m (Either Note a) -> m (Either Note a) scopeM s = liftM (scope s) scopeF :: Functor f => String -> f (Either Note a) -> f (Either Note a) scopeF s = fmap (scope s) instance Show Note where show (Note stack) = intercalate "\n" stack
CGenie/platform
shared/src/Unison/Note.hs
mit
2,236
0
13
540
1,130
552
578
54
2
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Tests.Writers.HTML (tests) where import Test.Framework import Text.Pandoc.Builder import Text.Pandoc import Tests.Helpers import Tests.Arbitrary() import Text.Pandoc.Highlighting (languages) -- null if no hl support html :: (ToString a, ToPandoc a) => a -> String html = writeHtmlString defaultWriterOptions{ writerWrapText = False } . toPandoc {- "my test" =: X =?> Y is shorthand for test html "my test" $ X =?> Y which is in turn shorthand for test html "my test" (X,Y) -} infix 5 =: (=:) :: (ToString a, ToPandoc a) => String -> (a, String) -> Test (=:) = test html tests :: [Test] tests = [ testGroup "inline code" [ "basic" =: code "@&" =?> "<code>@&amp;</code>" , "haskell" =: codeWith ("",["haskell"],[]) ">>=" =?> if null languages then "<code class=\"haskell\">&gt;&gt;=</code>" else "<code class=\"sourceCode haskell\"><span class=\"fu\">&gt;&gt;=</span></code>" , "nolanguage" =: codeWith ("",["nolanguage"],[]) ">>=" =?> "<code class=\"nolanguage\">&gt;&gt;=</code>" ] , testGroup "images" [ "alt with formatting" =: image "/url" "title" ("my " <> emph "image") =?> "<img src=\"/url\" title=\"title\" alt=\"my image\" />" ] ]
sol/pandoc
src/Tests/Writers/HTML.hs
gpl-2.0
1,376
0
13
349
292
167
125
27
2
--{-# OPTIONS_GHC -Wextra -fplugin ThinErr #-} module Generics.SOP.Monadic ( SumChoiceT, PerformChoiceT, ReadFieldT , Result , recover -- reexports , DatatypeInfo(..), ConstructorInfo(..), FieldInfo(..) ) where import qualified Data.List as L import qualified Generics.SOP as SOP import qualified Generics.SOP.NP as SOP import qualified Generics.SOP.Traversal as SOP import ExternalImports -- * Somewhat generic enumerate ∷ SListI xs ⇒ NP ConstructorInfo xs → NP (((,) Int) :.: ConstructorInfo) xs enumerate cs = SOP.hliftA2 (\c (K n)→ Comp (n, c)) cs (fromJust $ SOP.fromList $ L.take (SOP.lengthSList cs) [0..]) data family Result t s ∷ Type type SumChoiceT = Int type ADTChoice m xss = m SumChoiceT type PerformChoiceT t m a xss = () ⇒ Proxy (t, a) → DatatypeInfo xss → m SumChoiceT type ReadFieldT c t m u a xss xs = (All c xs, c a) ⇒ Proxy c → Proxy (t, u, a) → DatatypeInfo xss → SumChoiceT → ConstructorInfo xs → FieldInfo a → (u → a) → m (Result t a) recover ∷ ∀ a (c ∷ Type → Constraint) (t ∷ Type) m xss. ( Code a ~ xss, HasDatatypeInfo a , All2 c xss , HasCallStack, Monad m, Applicative (Result t)) ⇒ Proxy c → Proxy (t, a) → PerformChoiceT t m a xss → (forall f xs. (c f, All2 c xss) ⇒ ReadFieldT c t m a f xss xs) → m (Result t a) recover pC pTA choicef fieldf = let dti = datatypeInfo (Proxy @a) ∷ DatatypeInfo xss in case dti of ADT _moduleName typeName cInfos → do choice ← choicef pTA dti let pop ∷ POP (m :.: Result t) xss = recover' pC pTA fieldf $ (datatypeInfo (Proxy @a) ∷ DatatypeInfo xss) ct ∷ SOP (m :.: Result t) xss = (!! choice) $ SOP.apInjs_POP pop Comp mrsop ∷ (m :.: Result t) (SOP I xss) = hsequence ct case SOP.sList ∷ SOP.SList xss of SOP.SCons → (SOP.to <$>) <$> mrsop Newtype _moduleName typeName cInfo → do let nCInfos -- ~∷ NP ((,) Int :.: ConstructorInfo) '[ '[x]] = enumerate $ cInfo :* Nil sop ∷ SOP (m :.: Result t) xss = SOP.SOP $ SOP.Z $ recoverCtor pC pTA fieldf dti (SOP.hd nCInfos) (SOP.hd ((gtraversals -- ~∷ NP (NP (GTraversal (→) (→) s)) '[ '[x]] ))) Comp mdsop ∷ (m :.: Result t) (SOP I xss) = hsequence sop (SOP.to <$>) <$> mdsop recover' ∷ ∀ a (c ∷ Type → Constraint) (t ∷ Type) m xss. ( SOP.Generic a, Code a ~ xss , All2 c xss , HasCallStack, Monad m) ⇒ Proxy c → Proxy (t, a) → (forall f xs. c f ⇒ ReadFieldT c t m a f xss xs) → DatatypeInfo xss → POP (m :.: Result t) xss recover' pC pTA fieldf dti@(ADT _ name cs) = POP $ SOP.hcliftA2 (Proxy @(All c)) --(Proxy @(All (HasReadField t m a))) (recoverCtor pC pTA fieldf dti) (enumerate cs) (gtraversals ∷ NP (NP (GTraversal (→) (→) a)) xss) recover' _ _ _ _ = error "Non-ADTs not supported." -- * 1. Extract the constructor's product of field names -- 2. Feed that to the field-name→action interpreter recoverCtor ∷ ∀ a (c ∷ Type → Constraint) (t ∷ Type) m xss xs. ( Code a ~ xss , All c xs , HasCallStack, Monad m) ⇒ Proxy c → Proxy (t, a) → (forall f. c f ⇒ ReadFieldT c t m a f xss xs) → DatatypeInfo xss → (((,) SumChoiceT) :.: ConstructorInfo) xs → NP (GTraversal (→) (→) a) xs → NP (m :.: Result t) xs recoverCtor pC pTA fieldf dti (Comp (consNr, consi@(Record _ finfos))) travs = recoverFields pC pTA fieldf dti consNr consi travs finfos recoverCtor pC pTA fieldf dti (Comp (consNr, consi@Constructor{})) travs = recoverFields pC pTA fieldf dti consNr consi travs (SOP.hpure (FieldInfo "")) recoverCtor _ _ _ (ADT _ name _) _ _ = error $ printf "Infix ADTs not supported: type %s." name -- * Key part: NP (K Text) xs → NP m xs -- convert a product of field names to a product of monadic actions yielding 'a' recoverFields ∷ ∀ (c ∷ Type → Constraint) (t ∷ Type) m u xss xs. ( Code u ~ xss , All c xs , SListI xs , HasCallStack, Monad m) ⇒ Proxy c → Proxy (t, u) → (forall a. ReadFieldT c t m u a xss xs) → DatatypeInfo xss → SumChoiceT → ConstructorInfo xs → NP (GTraversal (→) (→) u) xs → NP (FieldInfo) xs → NP (m :.: Result t) xs recoverFields pC _pTU fieldf dtinfo consNr cinfo traversals finfos = hcliftA2 pC (recoverField dtinfo consNr cinfo) finfos traversals where recoverField ∷ ∀ a. (c a) ⇒ DatatypeInfo xss → SumChoiceT → ConstructorInfo xs → FieldInfo a → GTraversal (→) (→) u a → (m :.: Result t) a recoverField dtinfo consNr cinfo finfo trav = Comp $ fieldf (Proxy @c) (Proxy @(t, u, a)) dtinfo consNr cinfo finfo (gtravget trav ∷ u → a)
deepfire/mood
src/Generics/SOP/Monadic.hs
agpl-3.0
5,124
2
20
1,485
1,933
1,020
913
-1
-1
module CobolLib ( parseCobol, parseCobolFile, module CobolSyntax, module CobolSyntaxTermInstances, module CobolSyntaxATermConvertibleInstances, module ATermLib ) where import CobolSyntax import CobolSyntaxTermInstances import CobolSyntaxATermConvertibleInstances import ATermLib import SGLR import Configuration -- We just read in an ATerm; parsing is done externally ---------------------- parseCobol :: IO Cobol_source_program = do inp <- getContents return (fromATerm . afunCap . readATerm $ (dehyphen inp)) -- We parse from within Haskell parseCobolFile :: FilePath -> IO Cobol_source_program parseCobolFile fileName = do let tableName = compilationDir++"/CobolSyntax.tbl" let sortName = "Cobol-source-program" --putStrLn $ "sglr -p "++" -i "++fileName++" -s "++sortName sglr tableName fileName sortName --------------------
jkoppel/Strafunski-Sdf2Haskell
examples/vs-cobol-ii/CobolLib.hs
bsd-3-clause
876
0
11
142
149
82
67
-1
-1
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses, PatternGuards, RankNTypes, TypeSynonymInstances #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Navigation2D -- Copyright : (c) 2011 Norbert Zeh <nzeh@cs.dal.ca> -- License : BSD3-style (see LICENSE) -- -- Maintainer : Norbert Zeh <nzeh@cs.dal.ca> -- Stability : unstable -- Portability : unportable -- -- Navigation2D is an xmonad extension that allows easy directional -- navigation of windows and screens (in a multi-monitor setup). ----------------------------------------------------------------------------- module XMonad.Actions.Navigation2D ( -- * Usage -- $usage -- * Finer points -- $finer_points -- * Alternative directional navigation modules -- $alternatives -- * Incompatibilities -- $incompatibilities -- * Detailed technical discussion -- $technical -- * Exported functions and types -- #Exports# withNavigation2DConfig , Navigation2DConfig(..) , defaultNavigation2DConfig , Navigation2D , lineNavigation , centerNavigation , fullScreenRect , singleWindowRect , switchLayer , windowGo , windowSwap , windowToScreen , screenGo , screenSwap , Direction2D(..) ) where import Control.Applicative import qualified Data.List as L import qualified Data.Map as M import Data.Maybe import XMonad hiding (Screen) import qualified XMonad.StackSet as W import qualified XMonad.Util.ExtensibleState as XS import XMonad.Util.Types -- $usage -- #Usage# -- Navigation2D provides directional navigation (go left, right, up, down) for -- windows and screens. It treats floating and tiled windows as two separate -- layers and provides mechanisms to navigate within each layer and to switch -- between layers. Navigation2D provides two different navigation strategies -- (see <#Technical_Discussion> for details): /Line navigation/ feels rather -- natural but may make it impossible to navigate to a given window from the -- current window, particularly in the floating layer. /Center navigation/ -- feels less natural in certain situations but ensures that all windows can be -- reached without the need to involve the mouse. Navigation2D allows different -- navigation strategies to be used in the two layers and allows customization -- of the navigation strategy for the tiled layer based on the layout currently -- in effect. -- -- You can use this module with (a subset of) the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Actions.Navigation2D -- -- Then edit your keybindings: -- -- > -- Switch between layers -- > , ((modm, xK_space), switchLayers) -- > -- > -- Directional navigation of windows -- > , ((modm, xK_Right), windowGo R False) -- > , ((modm, xK_Left ), windowGo L False) -- > , ((modm, xK_Up ), windowGo U False) -- > , ((modm, xK_Down ), windowGo D False) -- > -- > -- Swap adjacent windows -- > , ((modm .|. controlMask, xK_Right), windowSwap R False) -- > , ((modm .|. controlMask, xK_Left ), windowSwap L False) -- > , ((modm .|. controlMask, xK_Up ), windowSwap U False) -- > , ((modm .|. controlMask, xK_Down ), windowSwap D False) -- > -- > -- Directional navigation of screens -- > , ((modm, xK_r ), screenGo R False) -- > , ((modm, xK_l ), screenGo L False) -- > , ((modm, xK_u ), screenGo U False) -- > , ((modm, xK_d ), screenGo D False) -- > -- > -- Swap workspaces on adjacent screens -- > , ((modm .|. controlMask, xK_r ), screenSwap R False) -- > , ((modm .|. controlMask, xK_l ), screenSwap L False) -- > , ((modm .|. controlMask, xK_u ), screenSwap U False) -- > , ((modm .|. controlMask, xK_d ), screenSwap D False) -- > -- > -- Send window to adjacent screen -- > , ((modm .|. mod1Mask, xK_r ), windowToScreen R False) -- > , ((modm .|. mod1Mask, xK_l ), windowToScreen L False) -- > , ((modm .|. mod1Mask, xK_u ), windowToScreen U False) -- > , ((modm .|. mod1Mask, xK_d ), windowToScreen D False) -- -- and add the configuration of the module to your main function: -- -- > main = xmonad $ withNavigation2DConfig defaultNavigation2DConfig -- > $ defaultConfig -- -- For detailed instruction on editing the key binding see: -- -- "XMonad.Doc.Extending#Editing_key_bindings". -- $finer_points -- #Finer_Points# -- The above should get you started. Here are some finer points: -- -- Navigation2D has the ability to wrap around at screen edges. For example, if -- you navigated to the rightmost window on the rightmost screen and you -- continued to go right, this would get you to the leftmost window on the -- leftmost screen. This feature may be useful for switching between screens -- that are far apart but may be confusing at least to novice users. Therefore, -- it is disabled in the above example (e.g., navigation beyond the rightmost -- window on the rightmost screen is not possible and trying to do so will -- simply not do anything.) If you want this feature, change all the 'False' -- values in the above example to 'True'. You could also decide you want -- wrapping only for a subset of the operations and no wrapping for others. -- -- By default, all layouts use the 'defaultTiledNavigation' strategy specified -- in the 'Navigation2DConfig' (by default, line navigation is used). To -- override this behaviour for some layouts, add a pair (\"layout name\", -- navigation strategy) to the 'layoutNavigation' list in the -- 'Navigation2DConfig', where \"layout name\" is the string reported by the -- layout's description method (normally what is shown as the layout name in -- your status bar). For example, all navigation strategies normally allow only -- navigation between mapped windows. The first step to overcome this, for -- example, for the Full layout, is to switch to center navigation for the Full -- layout: -- -- > myNavigation2DConfig = defaultNavigation2DConfig { layoutNavigation = [("Full", centerNavigation)] } -- > -- > main = xmonad $ withNavigation2DConfig myNavigation2DConfig -- > $ defaultConfig -- -- The navigation between windows is based on their screen rectangles, which are -- available /and meaningful/ only for mapped windows. Thus, as already said, -- the default is to allow navigation only between mapped windows. However, -- there are layouts that do not keep all windows mapped. One example is the -- Full layout, which unmaps all windows except the one that has the focus, -- thereby preventing navigation to any other window in the layout. To make -- navigation to unmapped windows possible, unmapped windows need to be assigned -- rectangles to pretend they are mapped, and a natural way to do this for the -- Full layout is to pretend all windows occupy the full screen and are stacked -- on top of each other so that only the frontmost one is visible. This can be -- done as follows: -- -- > myNavigation2DConfig = defaultNavigation2DConfig { layoutNavigation = [("Full", centerNavigation)] -- > , unmappedWindowRect = [("Full", singleWindowRect)] -- > } -- > -- > main = xmonad $ withNavigation2DConfig myNavigation2DConfig -- > $ defaultConfig -- -- With this setup, Left/Up navigation behaves like standard -- 'XMonad.StackSet.focusUp' and Right/Down navigation behaves like -- 'XMonad.StackSet.focusDown', thus allowing navigation between windows in the -- layout. -- -- In general, each entry in the 'unmappedWindowRect' association list is a pair -- (\"layout description\", function), where the function computes a rectangle -- for each unmapped window from the screen it is on and the window ID. -- Currently, Navigation2D provides only two functions of this type: -- 'singleWindowRect' and 'fullScreenRect'. -- -- With per-layout navigation strategies, if different layouts are in effect on -- different screens in a multi-monitor setup, and different navigation -- strategies are defined for these active layouts, the most general of these -- navigation strategies is used across all screens (because Navigation2D does -- not distinguish between windows on different workspaces), where center -- navigation is more general than line navigation, as discussed formally under -- <#Technical_Discussion>. -- $alternatives -- #Alternatives# -- -- There exist two alternatives to Navigation2D: -- "XMonad.Actions.WindowNavigation" and "XMonad.Layout.WindowNavigation". -- X.L.WindowNavigation has the advantage of colouring windows to indicate the -- window that would receive the focus in each navigation direction, but it does -- not support navigation across multiple monitors, does not support directional -- navigation of floating windows, and has a very unintuitive definition of -- which window receives the focus next in each direction. X.A.WindowNavigation -- does support navigation across multiple monitors but does not provide window -- colouring while retaining the unintuitive navigational semantics of -- X.L.WindowNavigation. This makes it very difficult to predict which window -- receives the focus next. Neither X.A.WindowNavigation nor -- X.L.WindowNavigation supports directional navigation of screens. -- $technical -- #Technical_Discussion# -- An in-depth discussion of the navigational strategies implemented in -- Navigation2D, including formal proofs of their properties, can be found -- at <http://www.cs.dal.ca/~nzeh/xmonad/Navigation2D.pdf>. -- $incompatibilities -- #Incompatibilities# -- Currently Navigation2D is known not to play nicely with tabbed layouts, but -- it should work well with any other tiled layout. My hope is to address the -- incompatibility with tabbed layouts in a future version. The navigation to -- unmapped windows, for example in a Full layout, by assigning rectangles to -- unmapped windows is more a workaround than a clean solution. Figuring out -- how to deal with tabbed layouts may also lead to a more general and cleaner -- solution to query the layout for a window's rectangle that may make this -- workaround unnecessary. At that point, the 'unmappedWindowRect' field of the -- 'Navigation2DConfig' will disappear. -- | A rectangle paired with an object type Rect a = (a, Rectangle) -- | A shorthand for window-rectangle pairs. Reduces typing. type WinRect = Rect Window -- | A shorthand for workspace-rectangle pairs. Reduces typing. type WSRect = Rect WorkspaceId ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- -- -- -- PUBLIC INTERFACE -- -- -- ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- -- | Encapsulates the navigation strategy data Navigation2D = N Generality (forall a . Eq a => Direction2D -> Rect a -> [Rect a] -> Maybe a) runNav :: forall a . Eq a => Navigation2D -> (Direction2D -> Rect a -> [Rect a] -> Maybe a) runNav (N _ nav) = nav -- | Score that indicates how general a navigation strategy is type Generality = Int instance Eq Navigation2D where (N x _) == (N y _) = x == y instance Ord Navigation2D where (N x _) <= (N y _) = x <= y -- | Line navigation. To illustrate this navigation strategy, consider -- navigating to the left from the current window. In this case, we draw a -- horizontal line through the center of the current window and consider all -- windows that intersect this horizontal line and whose right boundaries are to -- the left of the left boundary of the current window. From among these -- windows, we choose the one with the rightmost right boundary. lineNavigation :: Navigation2D lineNavigation = N 1 doLineNavigation -- | Center navigation. Again, consider navigating to the left. Then we -- consider the cone bounded by the two rays shot at 45-degree angles in -- north-west and south-west direction from the center of the current window. A -- window is a candidate to receive the focus if its center lies in this cone. -- We choose the window whose center has minimum L1-distance from the current -- window center. The tie breaking strategy for windows with the same distance -- is a bit complicated (see <#Technical_Discussion>) but ensures that all -- windows can be reached and that windows with the same center are traversed in -- their order in the window stack, that is, in the order -- 'XMonad.StackSet.focusUp' and 'XMonad.StackSet.focusDown' would traverse -- them. centerNavigation :: Navigation2D centerNavigation = N 2 doCenterNavigation -- | Stores the configuration of directional navigation data Navigation2DConfig = Navigation2DConfig { defaultTiledNavigation :: Navigation2D -- ^ default navigation strategy for the tiled layer , floatNavigation :: Navigation2D -- ^ navigation strategy for the float layer , screenNavigation :: Navigation2D -- ^ strategy for navigation between screens , layoutNavigation :: [(String, Navigation2D)] -- ^ association list of customized navigation strategies -- for different layouts in the tiled layer. Each pair -- is of the form (\"layout description\", navigation -- strategy). If there is no pair in this list whose first -- component is the name of the current layout, the -- 'defaultTiledNavigation' strategy is used. , unmappedWindowRect :: [(String, Screen -> Window -> X (Maybe Rectangle))] -- ^ list associating functions to calculate rectangles -- for unmapped windows with layouts to which they are -- to be applied. Each pair in this list is of -- the form (\"layout description\", function), where the -- function calculates a rectangle for a given unmapped -- window from the screen it is on and its window ID. -- See <#Finer_Points> for how to use this. } deriving Typeable -- | Shorthand for the tedious screen type type Screen = W.Screen WorkspaceId (Layout Window) Window ScreenId ScreenDetail -- So we can store the configuration in extensible state instance ExtensionClass Navigation2DConfig where initialValue = defaultNavigation2DConfig -- | Modifies the xmonad configuration to store the Navigation2D configuration withNavigation2DConfig :: Navigation2DConfig -> XConfig a -> XConfig a withNavigation2DConfig conf2d xconf = xconf { startupHook = startupHook xconf >> XS.put conf2d } -- | Default navigation configuration. It uses line navigation for the tiled -- layer and for navigation between screens, and center navigation for the float -- layer. No custom navigation strategies or rectangles for unmapped windows are -- defined for individual layouts. defaultNavigation2DConfig :: Navigation2DConfig defaultNavigation2DConfig = Navigation2DConfig { defaultTiledNavigation = lineNavigation , floatNavigation = centerNavigation , screenNavigation = lineNavigation , layoutNavigation = [] , unmappedWindowRect = [] } -- | Switches focus to the closest window in the other layer (floating if the -- current window is tiled, tiled if the current window is floating). Closest -- means that the L1-distance between the centers of the windows is minimized. switchLayer :: X () switchLayer = actOnLayer otherLayer ( \ _ cur wins -> windows $ doFocusClosestWindow cur wins ) ( \ _ cur wins -> windows $ doFocusClosestWindow cur wins ) ( \ _ _ _ -> return () ) False -- | Moves the focus to the next window in the given direction and in the same -- layer as the current window. The second argument indicates whether -- navigation should wrap around (e.g., from the left edge of the leftmost -- screen to the right edge of the rightmost screen). windowGo :: Direction2D -> Bool -> X () windowGo dir wrap = actOnLayer thisLayer ( \ conf cur wins -> windows $ doTiledNavigation conf dir W.focusWindow cur wins ) ( \ conf cur wins -> windows $ doFloatNavigation conf dir W.focusWindow cur wins ) ( \ conf cur wspcs -> windows $ doScreenNavigation conf dir W.view cur wspcs ) wrap -- | Swaps the current window with the next window in the given direction and in -- the same layer as the current window. (In the floating layer, all that -- changes for the two windows is their stacking order if they're on the same -- screen. If they're on different screens, each window is moved to the other -- window's screen but retains its position and size relative to the screen.) -- The second argument indicates wrapping (see 'windowGo'). windowSwap :: Direction2D -> Bool -> X () windowSwap dir wrap = actOnLayer thisLayer ( \ conf cur wins -> windows $ doTiledNavigation conf dir swap cur wins ) ( \ conf cur wins -> windows $ doFloatNavigation conf dir swap cur wins ) ( \ _ _ _ -> return () ) wrap -- | Moves the current window to the next screen in the given direction. The -- second argument indicates wrapping (see 'windowGo'). windowToScreen :: Direction2D -> Bool -> X () windowToScreen dir wrap = actOnScreens ( \ conf cur wspcs -> windows $ doScreenNavigation conf dir W.shift cur wspcs ) wrap -- | Moves the focus to the next screen in the given direction. The second -- argument indicates wrapping (see 'windowGo'). screenGo :: Direction2D -> Bool -> X () screenGo dir wrap = actOnScreens ( \ conf cur wspcs -> windows $ doScreenNavigation conf dir W.view cur wspcs ) wrap -- | Swaps the workspace on the current screen with the workspace on the screen -- in the given direction. The second argument indicates wrapping (see -- 'windowGo'). screenSwap :: Direction2D -> Bool -> X () screenSwap dir wrap = actOnScreens ( \ conf cur wspcs -> windows $ doScreenNavigation conf dir W.greedyView cur wspcs ) wrap -- | Maps each window to a fullscreen rect. This may not be the same rectangle the -- window maps to under the Full layout or a similar layout if the layout -- respects statusbar struts. In such cases, it may be better to use -- 'singleWindowRect'. fullScreenRect :: Screen -> Window -> X (Maybe Rectangle) fullScreenRect scr _ = return (Just . screenRect . W.screenDetail $ scr) -- | Maps each window to the rectangle it would receive if it was the only -- window in the layout. Useful, for example, for determining the default -- rectangle for unmapped windows in a Full layout that respects statusbar -- struts. singleWindowRect :: Screen -> Window -> X (Maybe Rectangle) singleWindowRect scr win = listToMaybe . map snd . fst <$> runLayout ((W.workspace scr) { W.stack = W.differentiate [win] }) (screenRect . W.screenDetail $ scr) ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- -- -- -- PRIVATE X ACTIONS -- -- -- ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- -- | Acts on the appropriate layer using the given action functions actOnLayer :: ([WinRect] -> [WinRect] -> [WinRect]) -- ^ Chooses which layer to operate on, relative -- to the current window (same or other layer) -> (Navigation2DConfig -> WinRect -> [WinRect] -> X ()) -- ^ The action for the tiled layer -> (Navigation2DConfig -> WinRect -> [WinRect] -> X ()) -- ^ The action for the float layer -> (Navigation2DConfig -> WSRect -> [WSRect] -> X ()) -- ^ The action if the current workspace is empty -> Bool -- ^ Should navigation wrap around screen edges? -> X () actOnLayer choice tiledact floatact wsact wrap = withWindowSet $ \winset -> do conf <- XS.get (floating, tiled) <- navigableWindows conf wrap winset let cur = W.peek winset case cur of Nothing -> actOnScreens wsact wrap Just w | Just rect <- L.lookup w tiled -> tiledact conf (w, rect) (choice tiled floating) | Just rect <- L.lookup w floating -> floatact conf (w, rect) (choice floating tiled) | otherwise -> return () -- | Returns the list of windows on the currently visible workspaces navigableWindows :: Navigation2DConfig -> Bool -> WindowSet -> X ([WinRect], [WinRect]) navigableWindows conf wrap winset = L.partition (\(win, _) -> M.member win (W.floating winset)) . addWrapping winset wrap . catMaybes . concat <$> ( mapM ( \scr -> mapM (maybeWinRect scr) $ W.integrate' $ W.stack $ W.workspace scr ) . sortedScreens ) winset where maybeWinRect scr win = do winrect <- windowRect win rect <- case winrect of Just _ -> return winrect Nothing -> maybe (return Nothing) (\f -> f scr win) (L.lookup (description . W.layout . W.workspace $ scr) (unmappedWindowRect conf)) return ((,) win <$> rect) -- | Returns the current rectangle of the given window, Nothing if the window isn't mapped windowRect :: Window -> X (Maybe Rectangle) windowRect win = withDisplay $ \dpy -> do mp <- isMapped win if mp then do (_, x, y, w, h, bw, _) <- io $ getGeometry dpy win return $ Just $ Rectangle x y (w + 2 * bw) (h + 2 * bw) `catchX` return Nothing else return Nothing -- | Acts on the screens using the given action function actOnScreens :: (Navigation2DConfig -> WSRect -> [WSRect] -> X ()) -> Bool -- ^ Should wrapping be used? -> X () actOnScreens act wrap = withWindowSet $ \winset -> do conf <- XS.get let wsrects = visibleWorkspaces winset wrap cur = W.tag . W.workspace . W.current $ winset rect = fromJust $ L.lookup cur wsrects act conf (cur, rect) wsrects -- | Determines whether a given window is mapped isMapped :: Window -> X Bool isMapped win = withDisplay $ \dpy -> io $ (waIsUnmapped /=) . wa_map_state <$> getWindowAttributes dpy win ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- -- -- -- PRIVATE PURE FUNCTIONS -- -- -- ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- -- | Finds the window closest to the given window and focuses it. Ties are -- broken by choosing the first window in the window stack among the tied -- windows. (The stack order is the one produced by integrate'ing each visible -- workspace's window stack and concatenating these lists for all visible -- workspaces.) doFocusClosestWindow :: WinRect -> [WinRect] -> (WindowSet -> WindowSet) doFocusClosestWindow (cur, rect) winrects | null winctrs = id | otherwise = W.focusWindow . fst $ L.foldl1' closer winctrs where ctr = centerOf rect winctrs = filter ((cur /=) . fst) $ map (\(w, r) -> (w, centerOf r)) winrects closer wc1@(_, c1) wc2@(_, c2) | lDist ctr c1 > lDist ctr c2 = wc2 | otherwise = wc1 -- | Implements navigation for the tiled layer doTiledNavigation :: Navigation2DConfig -> Direction2D -> (Window -> WindowSet -> WindowSet) -> WinRect -> [WinRect] -> (WindowSet -> WindowSet) doTiledNavigation conf dir act cur winrects winset | Just win <- runNav nav dir cur winrects = act win winset | otherwise = winset where layouts = map (description . W.layout . W.workspace) $ W.screens winset nav = maximum $ map ( fromMaybe (defaultTiledNavigation conf) . flip L.lookup (layoutNavigation conf) ) $ layouts -- | Implements navigation for the float layer doFloatNavigation :: Navigation2DConfig -> Direction2D -> (Window -> WindowSet -> WindowSet) -> WinRect -> [WinRect] -> (WindowSet -> WindowSet) doFloatNavigation conf dir act cur winrects | Just win <- runNav nav dir cur winrects = act win | otherwise = id where nav = floatNavigation conf -- | Implements navigation between screens doScreenNavigation :: Navigation2DConfig -> Direction2D -> (WorkspaceId -> WindowSet -> WindowSet) -> WSRect -> [WSRect] -> (WindowSet -> WindowSet) doScreenNavigation conf dir act cur wsrects | Just ws <- runNav nav dir cur wsrects = act ws | otherwise = id where nav = screenNavigation conf -- | Implements line navigation. For layouts without overlapping windows, there -- is no need to break ties between equidistant windows. When windows do -- overlap, even the best tie breaking rule cannot make line navigation feel -- natural. Thus, we fairly arbtitrarily break ties by preferring the window -- that comes first in the window stack. (The stack order is the one produced -- by integrate'ing each visible workspace's window stack and concatenating -- these lists for all visible workspaces.) doLineNavigation :: Eq a => Direction2D -> Rect a -> [Rect a] -> Maybe a doLineNavigation dir (cur, rect) winrects | null winrects' = Nothing | otherwise = Just . fst $ L.foldl1' closer winrects' where -- The current window's center ctr@(xc, yc) = centerOf rect -- The list of windows that are candidates to receive focus. winrects' = filter dirFilter $ filter ((cur /=) . fst) $ winrects -- Decides whether a given window matches the criteria to be a candidate to -- receive the focus. dirFilter (_, r) = (dir == L && leftOf r rect && intersectsY yc r) || (dir == R && leftOf rect r && intersectsY yc r) || (dir == U && above r rect && intersectsX xc r) || (dir == D && above rect r && intersectsX xc r) -- Decide whether r1 is left of/above r2. leftOf r1 r2 = rect_x r1 + fi (rect_width r1) <= rect_x r2 above r1 r2 = rect_y r1 + fi (rect_height r1) <= rect_y r2 -- Check whether r's x-/y-range contains the given x-/y-coordinate. intersectsX x r = rect_x r <= x && rect_x r + fi (rect_width r) >= x intersectsY y r = rect_y r <= y && rect_y r + fi (rect_height r) >= y -- Decides whether r1 is closer to the current window's center than r2 closer wr1@(_, r1) wr2@(_, r2) | dist ctr r1 > dist ctr r2 = wr2 | otherwise = wr1 -- Returns the distance of r from the point (x, y) dist (x, y) r | dir == L = x - rect_x r - fi (rect_width r) | dir == R = rect_x r - x | dir == U = y - rect_y r - fi (rect_height r) | otherwise = rect_y r - y -- | Implements center navigation doCenterNavigation :: Eq a => Direction2D -> Rect a -> [Rect a] -> Maybe a doCenterNavigation dir (cur, rect) winrects | ((w, _):_) <- onCtr' = Just w | otherwise = closestOffCtr where -- The center of the current window (xc, yc) = centerOf rect -- All the windows with their center points relative to the current -- center rotated so the right cone becomes the relevant cone. -- The windows are ordered in the order they should be preferred -- when they are otherwise tied. winctrs = map (\(w, r) -> (w, dirTransform . centerOf $ r)) $ stackTransform $ winrects -- Give preference to windows later in the stack for going left or up and to -- windows earlier in the stack for going right or down. (The stack order -- is the one produced by integrate'ing each visible workspace's window -- stack and concatenating these lists for all visible workspaces.) stackTransform | dir == L || dir == U = reverse | otherwise = id -- Transform a point into a difference to the current window center and -- rotate it so that the relevant cone becomes the right cone. dirTransform (x, y) | dir == R = ( x - xc , y - yc ) | dir == L = (-(x - xc), -(y - yc)) | dir == D = ( y - yc , x - xc ) | otherwise = (-(y - yc), -(x - xc)) -- Partition the points into points that coincide with the center -- and points that do not. (onCtr, offCtr) = L.partition (\(_, (x, y)) -> x == 0 && y == 0) winctrs -- All the points that coincide with the current center and succeed it -- in the (appropriately ordered) window stack. onCtr' = L.tail $ L.dropWhile ((cur /=) . fst) onCtr -- tail should be safe here because cur should be in onCtr -- All the points that do not coincide with the current center and which -- lie in the (rotated) right cone. offCtr' = L.filter (\(_, (x, y)) -> x > 0 && y < x && y >= -x) offCtr -- The off-center point closest to the center and -- closest to the bottom ray of the cone. Nothing if no off-center -- point is in the cone closestOffCtr = if null offCtr' then Nothing else Just $ fst $ L.foldl1' closest offCtr' closest wp@(_, p@(_, yp)) wq@(_, q@(_, yq)) | lDist (0, 0) q < lDist (0, 0) p = wq -- q is closer than p | lDist (0, 0) p < lDist (0, 0) q = wp -- q is farther away than p | yq < yp = wq -- q is closer to the bottom ray than p | otherwise = wp -- q is farther away from the bottom ray than p -- or it has the same distance but comes later -- in the window stack -- | Swaps the current window with the window given as argument swap :: Window -> WindowSet -> WindowSet swap win winset = W.focusWindow cur $ L.foldl' (flip W.focusWindow) newwinset newfocused where -- The current window cur = fromJust $ W.peek winset -- All screens scrs = W.screens winset -- All visible workspaces visws = map W.workspace scrs -- The focused windows of the visible workspaces focused = mapMaybe (\ws -> W.focus <$> W.stack ws) visws -- The window lists of the visible workspaces wins = map (W.integrate' . W.stack) visws -- Update focused windows and window lists to reflect swap of windows. newfocused = map swapWins focused newwins = map (map swapWins) wins -- Replaces the current window with the argument window and vice versa. swapWins x | x == cur = win | x == win = cur | otherwise = x -- Reconstruct the workspaces' window stacks to reflect the swap. newvisws = zipWith (\ws wns -> ws { W.stack = W.differentiate wns }) visws newwins newscrs = zipWith (\scr ws -> scr { W.workspace = ws }) scrs newvisws newwinset = winset { W.current = head newscrs , W.visible = tail newscrs } -- | Calculates the center of a rectangle centerOf :: Rectangle -> (Position, Position) centerOf r = (rect_x r + fi (rect_width r) `div` 2, rect_y r + fi (rect_height r) `div` 2) -- | Shorthand for integer conversions fi :: (Integral a, Num b) => a -> b fi = fromIntegral -- | Functions to choose the subset of windows to operate on thisLayer, otherLayer :: a -> a -> a thisLayer = curry fst otherLayer = curry snd -- | Returns the list of visible workspaces and their screen rects visibleWorkspaces :: WindowSet -> Bool -> [WSRect] visibleWorkspaces winset wrap = addWrapping winset wrap $ map ( \scr -> ( W.tag . W.workspace $ scr , screenRect . W.screenDetail $ scr ) ) $ sortedScreens winset -- | Creates five copies of each (window/workspace, rect) pair in the input: the -- original and four offset one desktop size (desktop = collection of all -- screens) to the left, to the right, up, and down. Wrap-around at desktop -- edges is implemented by navigating into these displaced copies. addWrapping :: WindowSet -- ^ The window set, used to get the desktop size -> Bool -- ^ Should wrapping be used? Do nothing if not. -> [Rect a] -- ^ Input set of (window/workspace, rect) pairs -> [Rect a] addWrapping _ False wrects = wrects addWrapping winset True wrects = [ (w, r { rect_x = rect_x r + fi x , rect_y = rect_y r + fi y } ) | (w, r) <- wrects , (x, y) <- [(0, 0), (-xoff, 0), (xoff, 0), (0, -yoff), (0, yoff)] ] where (xoff, yoff) = wrapOffsets winset -- | Calculates the offsets for window/screen coordinates for the duplication -- of windows/workspaces that implements wrap-around. wrapOffsets :: WindowSet -> (Integer, Integer) wrapOffsets winset = (max_x - min_x, max_y - min_y) where min_x = fi $ minimum $ map rect_x rects min_y = fi $ minimum $ map rect_y rects max_x = fi $ maximum $ map (\r -> rect_x r + (fi $ rect_width r)) rects max_y = fi $ maximum $ map (\r -> rect_y r + (fi $ rect_height r)) rects rects = map snd $ visibleWorkspaces winset False -- | Returns the list of screens sorted primarily by their centers' -- x-coordinates and secondarily by their y-coordinates. sortedScreens :: WindowSet -> [Screen] sortedScreens winset = L.sortBy cmp $ W.screens winset where cmp s1 s2 | x1 < x2 = LT | x1 > x2 = GT | y1 < x2 = LT | y1 > y2 = GT | otherwise = EQ where (x1, y1) = centerOf (screenRect . W.screenDetail $ s1) (x2, y2) = centerOf (screenRect . W.screenDetail $ s2) -- | Calculates the L1-distance between two points. lDist :: (Position, Position) -> (Position, Position) -> Int lDist (x1, y1) (x2, y2) = abs (fi $ x1 - x2) + abs (fi $ y1 - y2)
kmels/xmonad-launcher
XMonad/Actions/Navigation2D.hs
bsd-3-clause
39,746
0
20
13,349
5,448
2,995
2,453
311
2
{-# LANGUAGE PatternGuards #-} module Config ( Config(..) , defaultMailer , slurpConfig) where import BuildBox import Args import System.Console.ParseArgs hiding (args) import System.Directory import Control.Monad import Data.Maybe import qualified Data.Traversable as T -- Config ----------------------------------------------------------------------------------------- -- | Buildbot command line configuration. data Config = Config { configVerbose :: Bool -- Building GHC and its libs , configScratchDir :: Maybe String , configGhcUnpack :: Maybe FilePath , configGhcBuild :: Maybe FilePath -- Depending on the above options, these will get filled in with -- paths to the actual ghc and ghc-pkg binaries we should be using. , configWithGhc :: FilePath , configWithGhcPkg :: FilePath -- What libraries we should install into the GHC tree. -- TODO: If we had a better options parser we wouldn't have to hack everything into the same arg. , configLibs :: Maybe String -- Test stages ------------------------------------ -- What libraries to test. , configDoTestDPH :: Maybe FilePath , configDoTestRepa :: Maybe FilePath , configDoTestNoSlow :: Maybe FilePath -- Testing config --------------------------------- , configIterations :: Int , configAgainstResults :: Maybe FilePath , configSwingFraction :: Maybe Double -- What do with the results ----------------------- , configWriteResults :: Maybe (FilePath, Bool) , configMailFromTo :: Maybe (String, String) , configMailFailTo :: Maybe String , configMailBanner :: Maybe String , configMailBranchName :: Maybe String , configUploadResults :: Maybe String } deriving Show -- Hard Coded ------------------------------------------------------------------------------------- -- Hard coded config. -- Can't be bothered turning these into cmd line args. defaultMailer :: Mailer defaultMailer = MailerMSMTP { mailerPath = "msmtp" , mailerPort = Just 587 } -- Slurp ------------------------------------------------------------------------------------------ -- | Slurp configuration information from the command line arguments. slurpConfig :: Args BuildArg -> IO Config slurpConfig args = do let Just iterations = getArg args ArgTestIterations mScratchDir <- maybe (return Nothing) (liftM Just . canonicalizePath) (getArg args ArgScratchDir) -- If we've been given the --ghc-use flag then use that compiler first off. -- Otherwise use whatever is in the PATH. withGhc <- maybe (return "ghc") (\dir -> canonicalizePath $ dir ++ "/inplace/bin/ghc-stage2") (getArg args ArgGhcUse) withGhcPkg <- maybe (return "ghc-pkg") (\dir -> canonicalizePath $ dir ++ "/inplace/bin/ghc-pkg") (getArg args ArgGhcUse) -- If we're supposed to unpack a GHC snapshot tarball, -- then canonicalize its path. let ghcUnpack' | Just path <- getArg args ArgGhcUnpack = liftM Just $ canonicalizePath path | Just path <- getArg args ArgGhcUnpackBuild = liftM Just $ canonicalizePath path | otherwise = return Nothing ghcUnpack <- ghcUnpack' -- If we're supposed to build a GHC, then determine where the build tree will be. let ghcBuild' | Just path <- getArg args ArgGhcBuild = liftM Just $ canonicalizePath path | Just _ <- (getArg args ArgGhcUnpackBuild) :: Maybe String , scratchDir <- fromMaybe (error "must specifiy --scratch with --ghc-unpack-build") mScratchDir = return $ Just $ scratchDir ++ "/ghc-head" | otherwise = return Nothing ghcBuild <- ghcBuild' -- Testing -------------------------------------------------- doTestDPH <- T.mapM canonicalizePath $ if gotArg args ArgDoTestDPH then msum [ getArg args ArgUseDPH , liftM (++ "/ghc-head/libraries/dph") mScratchDir , Just $ error "must specify --scratch or --use-dph with --test-dph" ] else Nothing doTestRepa <- T.mapM canonicalizePath $ if gotArg args ArgDoTestRepa then msum [ getArg args ArgUseDPH , liftM (++ "/repa-head") mScratchDir , Just $ error "must specify --scratch or --use-repa with --test-repa" ] else Nothing doTestNoSlow <- T.mapM canonicalizePath $ if gotArg args ArgDoTestNoSlow then msum [ getArg args ArgUseDPH , liftM (++ "/NoSlow-head") mScratchDir , Just $ error "must specify --scratch or --use-noslow with --test-noslow" ] else Nothing -- Build the final config ----------------------------------- return $ Config { configVerbose = gotArg args ArgVerbose , configScratchDir = mScratchDir , configGhcUnpack = ghcUnpack , configGhcBuild = ghcBuild , configWithGhc = withGhc , configWithGhcPkg = withGhcPkg , configLibs = getArg args ArgLibs -- Testing stages , configDoTestDPH = doTestDPH , configDoTestRepa = doTestRepa , configDoTestNoSlow = doTestNoSlow -- Testing config. , configIterations = iterations , configWriteResults = let result | Just name <- getArg args ArgWriteResultsStamped = Just (name, True) | Just name <- getArg args ArgWriteResults = Just (name, False) | otherwise = Nothing in result , configUploadResults = getArg args ArgUploadResults , configAgainstResults = getArg args ArgAgainstResults , configSwingFraction = getArg args ArgSwingFraction -- TODO: check we have both args , configMailFromTo = let result | Just from <- getArg args ArgMailFrom , Just to <- getArg args ArgMailTo = Just (from, to) | otherwise = Nothing in result , configMailFailTo = getArg args ArgMailFailTo , configMailBanner = getArg args ArgMailBanner , configMailBranchName = getArg args ArgMailBranchName }
mainland/dph
dph-buildbot/src/Config.hs
bsd-3-clause
5,995
285
10
1,427
1,281
717
564
125
4
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="tr-TR"> <title>AdvFuzzer Eklentisi</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>İçindekiler</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Dizin</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Arama</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoriler</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/fuzz/src/main/javahelp/org/zaproxy/zap/extension/fuzz/resources/help_tr_TR/helpset_tr_TR.hs
apache-2.0
968
82
52
156
393
207
186
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="es-ES"> <title>SAML Support</title> <maps> <homeID>saml</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
denniskniep/zap-extensions
addOns/saml/src/main/javahelp/help_es_ES/helpset_es_ES.hs
apache-2.0
958
82
52
156
390
206
184
-1
-1
{-# LANGUAGE DeriveGeneric #-} module Distribution.Solver.Types.SolverId ( SolverId(..) ) where import Distribution.Compat.Binary (Binary(..)) import Distribution.Package (PackageId, Package(..), UnitId) import GHC.Generics (Generic) -- | The solver can produce references to existing packages or -- packages we plan to install. Unlike 'ConfiguredId' we don't -- yet know the 'UnitId' for planned packages, because it's -- not the solver's job to compute them. -- data SolverId = PreExistingId { solverSrcId :: PackageId, solverInstId :: UnitId } | PlannedId { solverSrcId :: PackageId } deriving (Eq, Ord, Generic) instance Binary SolverId instance Show SolverId where show = show . solverSrcId instance Package SolverId where packageId = solverSrcId
mydaum/cabal
cabal-install/Distribution/Solver/Types/SolverId.hs
bsd-3-clause
793
0
8
144
152
94
58
14
0