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
{------------------------------------------------------------------------------- A printing shop runs 16 batches (jobs) every week and each batch requires a sheet of special colour-proofing paper of size A5. Every Monday morning, the foreman opens a new envelope, containing a large sheet of the special paper with size A1. He proceeds to cut it in half, thus getting two sheets of size A2. Then he cuts one of them in half to get two sheets of size A3 and so on until he obtains the A5-size sheet needed for the first batch of the week. All the unused sheets are placed back in the envelope. -------------- | | | | | A | | | 3 | | A2 |-----| | | |A5| | |A4|--| | | |A5| -------------- At the beginning of each subsequent batch, he takes from the envelope one sheet of paper at random. If it is of size A5, he uses it. If it is larger, he repeats the 'cut-in-half' procedure until he has what he needs and any remaining sheets are always placed back in the envelope. Excluding the first and last batch of the week, find the expected number of times (during each week) that the foreman finds a single sheet of paper in the envelope. Give your answer rounded to six decimal places using the format x.xxxxxx . -------------------------------------------------------------------------------- The approach is to compute the probability density of the envelop content for the 14 batches 2 to 15. -------------------------------------------------------------------------------} import qualified Data.Map as M import qualified Data.List as L -- A State corresponds to the number of sheets of each size in the envelop. -- Constraint: a State instance must have 4 values. The first one corresponds to -- the number of A5 sheets, the second one of A4 sheets, ... type State = [Int] -- A StateSpace associates each state to its probability of realisation. type StateSpace = M.Map State Float -- Given a state, 'stepState' returns all possible outcomes after the batch -- processing, with the associated probability stepState :: State -> [(State, Float)] stepState sheets = let nSheets = fromIntegral $ sum sheets in [ ((zipWith (+) hs (repeat 1)) ++ (l-1:ls), fromIntegral l / nSheets) | (hs, (l:ls)) <- [splitAt i sheets | i <- [0..4]], l > 0] -- Given a state space, 'stepStateSpace' returns it updated by the batch -- processing stepStateSpace :: StateSpace -> StateSpace stepStateSpace stateSpace = L.foldl' iter M.empty $ M.assocs stateSpace where iter :: StateSpace -> (State, Float) -> StateSpace iter stateSpace (state, p) = L.foldl' update stateSpace $ stepState state where update :: StateSpace -> (State, Float) -> StateSpace update stateSpace (state, p') = M.insertWith (+) state (p*p') stateSpace euler = sum $ singleSheetPropaPerDay where initialState = ([1, 1, 1, 1], 1) -- The state space for the 14 batches in the middle allStates = take 14 $ iterate stepStateSpace $ M.fromList [initialState] singleSheetPropaPerDay = map ( L.foldl' (\a (_, b) -> a+b) 0 . discardMultiSheets . M.assocs) allStates discardMultiSheets = filter (\ (s, _) -> sum s == 1) round6 x = fromIntegral (round $ x * 1000000) / 1000000 main = putStrLn $ concat ["Euler 151: ", show $ round6 euler, "\n" ]
dpieroux/euler
0151.hs
mit
3,677
3
13
1,023
548
295
253
25
1
module Network.API.Twitter.Shim ( shimToken ) where import Network.OAuth.Consumer (Token) import Data.Binary (decode) import Data.ByteString.Lazy.Char8 (pack) shimToken :: Token shimToken = decode $ pack shimStr shimStr = "\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SYNy7mcOjAr18BvMV5KVKNW0g\NUL\NUL\NUL\NUL\NUL\NUL\NUL*uOP2Ij1IYBwVJYotgkWj11XvtUP5aStutQieczCnuo\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ACK\NUL\NUL\NUL\NUL\NUL\NUL\NUL\auser_id\NUL\NUL\NUL\NUL\NUL\NUL\NUL\b22679264\NUL\NUL\NUL\NUL\NUL\NUL\NUL\vscreen_name\NUL\NUL\NUL\NUL\NUL\NUL\NUL\asighawk\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SOoauth_verifier\NUL\NUL\NUL\NUL\NUL\NUL\NUL\a8810269\NUL\NUL\NUL\NUL\NUL\NUL\NUL\voauth_token\NUL\NUL\NUL\NUL\NUL\NUL\NUL222679264-TAVU4694pTsSTEttvuDQI52ryUyFAHt4yxc6udN07\NUL\NUL\NUL\NUL\NUL\NUL\NUL\DC2oauth_token_secret\NUL\NUL\NUL\NUL\NUL\NUL\NUL*C714hivzCDbXVq2oSG45d5UiUOPfNI3MqZJhOGZWtQ\NUL\NUL\NUL\NUL\NUL\NUL\NUL\CANoauth_callback_confirmed\NUL\NUL\NUL\NUL\NUL\NUL\NUL\EOTtrue"
whittle/twitter-api
Network/API/Twitter/Shim.hs
mit
975
0
6
44
68
42
26
8
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module IHaskell.Display.Widgets.Float.BoundedFloat.FloatProgress ( -- * The FloatProgress Widget FloatProgress -- * Constructor , mkFloatProgress ) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Data.Aeson import Data.IORef (newIORef) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common import IHaskell.Display.Widgets.Layout.LayoutWidget import IHaskell.Display.Widgets.Style.ProgressStyle -- | 'FloatProgress' represents an FloatProgress widget from IPython.html.widgets. type FloatProgress = IPythonWidget 'FloatProgressType -- | Create a new widget mkFloatProgress :: IO FloatProgress mkFloatProgress = do -- Default properties, with a random uuid wid <- U.random layout <- mkLayout pstyle <- mkProgressStyle let boundedFloatAttrs = defaultBoundedFloatWidget "ProgressView" "FloatProgressModel" layout $ StyleWidget pstyle progressAttrs = (Orientation =:: HorizontalOrientation) :& (BarStyle =:: DefaultBar) :& RNil widgetState = WidgetState $ boundedFloatAttrs <+> progressAttrs stateIO <- newIORef widgetState let widget = IPythonWidget wid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the widget return widget instance IHaskellWidget FloatProgress where getCommUUID = uuid
gibiansky/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Float/BoundedFloat/FloatProgress.hs
mit
1,855
0
13
407
284
165
119
37
1
module Week4 where fun1 :: [Integer] -> Integer fun1 [] = 1 fun1 (x:xs) | even x = (x - 2) * fun1 xs | otherwise = fun1 xs fun1' :: [Integer] -> Integer fun1' = foldr (\x acc-> acc * (x - 2)) 1 . filter even fun2 :: Integer -> Integer fun2 1 = 0 fun2 n | even n = n + fun2 (n `div` 2) | otherwise = fun2 (3 * n + 1) collatz :: Integer -> Integer collatz x | x == 1 = 0 | even x = x `div` 2 | otherwise = 3 * x + 1 fun2' :: Integer -> Integer fun2' = sum . filter even . takeWhile (0 /= ) . iterate collatz -- This is fun. Since we need a strictly balanced binary tree, we cannot use -- red-black tree, or a scapegoat tree. An AA tree would work, but stores a -- "level" which has a "loose" connection with the height. Pretty sure the -- orginal author wanted an AVL tree. -- -- The exercise starts numbering at 0, this starts at 1. data Tree a = Leaf | Node Integer (Tree a) a (Tree a) deriving (Show, Eq) foldTree :: Ord a => [a] -> Tree a foldTree = foldr (insert) Leaf insert :: Ord a => a -> Tree a -> Tree a insert k Leaf = Node 1 Leaf k Leaf insert k t@(Node _ left l right) = balance $ Node h' left' l right' where h' = nextHeight left' right' insert' = insert k (left', right') = if k < l then (insert' left, right) else (left, insert' right) height :: Tree a -> Integer height Leaf = 0 height (Node h _ _ _) = h nextHeight :: Tree a -> Tree a -> Integer nextHeight x y = 1 + max (height x) (height y) balance :: Tree a -> Tree a balance t | factor < -1 = fullRotateLeft t | factor > 1 = fullRotateRight t | otherwise = t where factor = balanceFactor t balanceFactor :: Tree a -> Integer balanceFactor (Node _ left _ right) = height left - height right fullRotateLeft :: Tree a -> Tree a fullRotateLeft t@(Node _ l v r) = rotateLeft $ Node h' l v r' where r' = if balanceFactor r > 0 then rotateRight r else r h' = nextHeight l r' fullRotateRight :: Tree a -> Tree a fullRotateRight t@(Node _ l v r) = rotateRight $ Node h' l' v r where l' = if balanceFactor l < 0 then rotateLeft l else l h' = nextHeight l' r rotateLeft :: Tree a -> Tree a rotateLeft root@(Node rh rl rv rr@(Node ch cl cv cr)) = Node (nextHeight l' cr) l' cv cr where l' = Node (nextHeight rl cl) rl rv cl rotateRight :: Tree a -> Tree a rotateRight root@(Node rh rl@(Node ch cl cv cr) rv rr) = Node (nextHeight cl r') cl cv r' where r' = Node (nextHeight cr rr) cr rv rr xor :: [Bool] -> Bool xor = foldr (/=) False map' :: (a -> b) -> [a] -> [b] map' f = foldr (\x a -> f x : a ) [] myFoldl :: (b -> a -> b) -> b -> [a] -> b myFoldl f = foldr (flip f) sieveSundaram n = (map succ . map (2 *) . filter goodNum) $ [1..n] where goodNum = not . flip elem (bad n) bad :: Integer -> [Integer] bad n = [ i + j + 2 * i * j | j <- [1..n], i <- [1..j] ]
taylor1791/cis-194-spring
src/Week4.hs
mit
2,872
0
11
763
1,351
686
665
72
2
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} module Betfair.APING.Types.MarketDescription ( MarketDescription(..) ) where import Data.Aeson.TH (Options (omitNothingFields), defaultOptions, deriveJSON) import Protolude import Text.PrettyPrint.GenericPretty import Betfair.APING.Types.MarketBettingType (MarketBettingType) import Betfair.APING.Types.MarketLineRangeInfo (MarketLineRangeInfo) import Betfair.APING.Types.PriceLadderDescription (PriceLadderDescription) type DateString = Text data MarketDescription = MarketDescription { persistenceEnabled :: Bool , bspMarket :: Bool , marketTime :: DateString , suspendTime :: DateString , settleTime :: Maybe DateString , bettingType :: MarketBettingType , turnInPlayEnabled :: Bool , marketType :: Text , regulator :: Text , marketBaseRate :: Double , discountAllowed :: Bool , wallet :: Maybe Text , rules :: Maybe Text , rulesHasDate :: Maybe Bool , eachWayDivisor :: Maybe Double , clarifications :: Maybe Text , lineRangeInfo :: Maybe MarketLineRangeInfo , priceLadderDescription :: Maybe PriceLadderDescription } deriving (Eq, Show, Generic, Pretty) $(deriveJSON defaultOptions {omitNothingFields = True} ''MarketDescription)
joe9/betfair-api
src/Betfair/APING/Types/MarketDescription.hs
mit
1,656
0
9
436
278
173
105
38
0
module Utils.IOFold where ioFoldl :: (a -> IO b) -> [b] -> [a] -> IO [b] ioFoldl _ l [] = return l ioFoldl f l (x:xs) = do i <- f x if not $ null xs then ioFoldl f (i:l) xs else return (i:l) -- Esta implementação tem de ser revista ioFoldr :: (a -> IO b) -> [b] -> [a] -> IO [b] ioFoldr f l xs = do result <- ioFoldl f l xs return $ reverse result ioFoldl' :: (a -> IO [b]) -> [b] -> [a] -> IO [b] ioFoldl' _ l [] = return l ioFoldl' f l (x:xs) = do i <- f x if not $ null xs then ioFoldl' f (i++l) xs else return (i++l) -- Esta implementação tem de ser revista ioFoldr' :: (a -> IO [b]) -> [b] -> [a] -> IO [b] ioFoldr' f l xs = do result <- ioFoldl' f l xs return $ reverse result
Miguel-Fontes/hs-file-watcher
src/Utils/IOFold.hs
mit
754
0
10
228
418
212
206
23
2
module Counting ( Color(..), territories, territoryFor ) where import Data.Array.IArray ((!), Array) import qualified Data.Array.IArray as Array import Data.Maybe (catMaybes, isNothing, mapMaybe) import Data.Set (Set) import qualified Data.Set as Set -- | A board is an efficient dense mapping of coordinates to stones (where -- each point may either have a stone or not. type Board = Array Coord (Maybe Color) type Coord = (Int, Int) -- Coords are 1 based data Color = Black | White deriving (Eq, Ord, Show, Enum, Bounded) -- | Return the territories along with the side that has claimed them (if -- any). -- -- The input should consist of lines of equal length. -- -- The character 'B' will mean black, the character 'W' will mean white and -- every other character will mean an empty square. territories :: [String] -> [(Set Coord, Maybe Color)] territories ls = let b = buildBoard ls fps = freePoints b in worker [] b fps where worker ts _ [] = ts worker ts b fps@(fp:_) = let s = groupContaining b fp o = groupOwner b s in worker ((s, o):ts) b (filter (`Set.notMember` s) fps) -- | Return the territory and the side that has claimed it given -- a coordinate that is in the territory. If the coordinate is not in any -- territory returns Nothing. -- -- See 'territories' for notes about the expected board format. territoryFor :: [String] -> Coord -> Maybe (Set Coord, Maybe Color) territoryFor ls c = let b = buildBoard ls s = groupContaining b c o = groupOwner b s in if Set.null s then Nothing else Just (s, o) -- | Transform the list of lines into a Board. -- -- The character 'B' will mean black, the character 'W' will mean white and -- every other character will mean an empty square. -- -- The input must contain at least one line. buildBoard :: [String] -> Board buildBoard ls = let xmax = length (head ls) ymax = length ls bounds = ((1,1), (xmax, ymax)) assocs = [ ((x, y), toMColor c) | (y, l) <- zip [1..] ls , (x, c) <- zip [1..] l] in Array.array bounds assocs where toMColor 'B' = Just Black toMColor 'W' = Just White toMColor _ = Nothing -- | Get the coordinates of all free points on the board. freePoints :: Board -> [Coord] freePoints = mapMaybe worker . Array.assocs where worker (_, Just _) = Nothing worker (c, Nothing) = Just c -- | True iff the coordinate is within the bounds of the board. inBounds :: Board -> Coord -> Bool inBounds b (cx, cy) = let ((xmin, ymin), (xmax, ymax)) = Array.bounds b in cx >= xmin && cx <= xmax && cy >= ymin && cy <= ymax -- | True iff the point not occupied by a stone. -- -- Does not check if the point is valid. isFreePoint :: Board -> Coord -> Bool isFreePoint b c = isNothing (b ! c) -- | Get the adjacent valid coordinates for a coordinate. adjacentCoords :: Board -> Coord -> [Coord] adjacentCoords b (cx, cy) = filter (inBounds b) [(cx+1, cy), (cx, cy+1), (cx-1, cy), (cx, cy-1)] -- | Get a group of free points, starting with the given coordinate. groupContaining :: Board -> Coord -> Set Coord groupContaining b c | not (inBounds b c && isFreePoint b c) = Set.empty | otherwise = -- The algorithm here is quite simple. In every iteration we add to -- a list all free points adjacent to points in the "last added" list. -- Then we add those points into the set and use the "last added" list -- in the next iteration. -- -- Once no more free points are found in an iteration we are done. worker [c] (Set.singleton c) where worker [] s = s worker la s = let coords = (`Set.difference` s) . Set.fromList . catMaybes $ do -- List monad lc <- la ac <- adjacentCoords b lc return $ if isFreePoint b ac then Just ac else Nothing in worker (Set.toList coords) (Set.union s coords) -- | Given a group of free points return who owns this territory (if -- anyone). -- -- The owner of a territory is the player whose stones are the only stones -- adjacent to the territory (dead stones are assumed to have already been -- removed). groupOwner :: Board -> Set Coord -> Maybe Color groupOwner b s = let stones = catMaybes [b ! ac | c <- Set.toList s, ac <- adjacentCoords b c] in case stones of [] -> Nothing (h:t) -> if all (==h) t then Just h else Nothing
exercism/xhaskell
exercises/practice/go-counting/.meta/examples/success-standard/src/Counting.hs
mit
4,592
0
16
1,263
1,225
670
555
73
3
-- | This module implements the ancient Scytale transposition cipher (for more -- info, see <https://en.wikipedia.org/wiki/Scytale Wikipedia>. module Text.Cipher.Scytale where import Text.Cipher.Types -- | Given a perimeter for the scytale, transpose a text from -- any character set. -- -- >>> scytale 5 "i like trains" -- "iei nltsir ka " scytale :: Int -> Message Plain -> Message Cipher scytale perimeter text = do let text' = ensure perimeter text x <- [0..(perimeter - 1)] y <- [x, (x + perimeter) .. (length text' - 1)] return (text' !! y) where ensure perimeter text | 0 <- length text `mod` perimeter = text | otherwise = ensure perimeter (text ++ " ") -- | This is the inverse operation to the 'scytale' function. unscytale :: Int -> Message Cipher -> Message Plain unscytale perimeter text = scytale perimeter' text where perimeter' = length text `div` perimeter
kmein/ciphers
src/Text/Cipher/Scytale.hs
mit
938
0
12
211
231
121
110
14
1
-- Test the fast buffer implementation module Tests.Buffer where import Yi.Buffer import Yi.FastBuffer import Data.Unique import Data.Char import Data.List import Data.Maybe import System.Directory import System.IO.Unsafe import Control.Monad import qualified Control.Exception import Control.Concurrent import TestFramework instance Show Unique where showsPrec _ u = showString "<unique>" -- really test it! contents = unsafePerformIO $ do s <- readFile "data" forkIO (Control.Exception.evaluate (length s) >> return ()) return s lendata = length contents str ="\n\nabc\n\ndef\n" lenstr = length str $(tests "fastBuffer" [d| testElems = do b <- newB "testbuffer" contents :: IO FBuffer s <- elemsB b assertEqual s contents testHNewB = do b <- newB "testbuffer" contents :: IO FBuffer b' <- hNewB "data" :: IO FBuffer s <- elemsB b s' <- elemsB b assertEqual s s' assertEqual s contents testName = do b <- newB "testbuffer" contents :: IO FBuffer assertEqual (nameB b) "testbuffer" testSize = do b <- newB "testbuffer" contents :: IO FBuffer i <- sizeB b assertEqual i (length contents) testWriteFile = do b <- newB "testbuffer" contents :: IO FBuffer let f = "testWriteFile.file" hPutB b f s <- readFile f removeFile f assertEqual s contents testGetFileNameB = do b <- hNewB "../README" :: IO FBuffer m <- getfileB b assertEqual m (Just "../README") testSetFileNameB = do b <- newB "testbuffer" contents :: IO FBuffer setfileB b "../README" m <- getfileB b assertEqual m (Just "../README") testLotsOfBuffers = do bs <- sequence [ hNewB "data" :: IO FBuffer | x <- [1..10] ] -- create a 1000 buffers bs' <- mapM elemsB bs assertEqual (length . nub . sort $ map keyB bs) (length bs) assertEqual 1 (length . nub . sort $ bs') assert (all (==contents) bs') testMoveTo = do b <- hNewB "data" :: IO FBuffer ps <- sequence [ moveTo b i >> pointB b >>= \j -> return (i,j) | i <- [0 .. 4000] ] let (l1,l2) = unzip ps assertEqual l1 l2 testMovement = do b <- hNewB "data" :: IO FBuffer moveTo b 1000 leftB b rightB b i <- pointB b -- should be 1000 rightB b leftB b j <- pointB b rightN b 1000 k <- pointB b leftN b 2000 l <- pointB b rightN b 1000000 -- moving past end of buffer should only go to end m <- pointB b s <- sizeB b leftN b 1000000 n <- pointB b assertEqual i 1000 assertEqual j i assertEqual k (1000+1000) assertEqual l 0 assertEqual m (s-1) assertEqual n 0 testRead = do b <- hNewB "data" :: IO FBuffer c <- readAtB b 1000 moveTo b 1000 c' <- readB b writeB b 'X' c'' <- readB b assertEqual c c' assertEqual c'' 'X' testInsert = do b <- hNewB "data" :: IO FBuffer s <- sizeB b moveTo b 1000 p <- pointB b insertB b 'X' p' <- pointB b s' <- sizeB b c <- readB b moveTo b s' let str = "haskell string\n\nanother string" insertN b str s'' <- sizeB b assertEqual (s+1) s' assertEqual p p' assertEqual c 'X' assertEqual s'' (s' + length str) testDelete = do b <- hNewB "data" :: IO FBuffer moveTo b 10000 p <- pointB b c <- readB b -- read a char s <- sizeB b deleteB b c' <- readB b -- read this char p' <- pointB b s' <- sizeB b moveTo b 0 deleteN b 10000000 s'' <- sizeB b p'' <- pointB b c'' <- readB b -- unsafe/should fail (empty buffer) writeB b 'X' -- unsafe/should fail insertN b contents s''' <- sizeB b deleteN b s''' t <- sizeB b insertN b contents deleteNAt b (s - 100) 100 t' <- sizeB b assert (c /= c') assertEqual p p' assertEqual s (s'+1) assertEqual s'' 0 assertEqual p'' 0 assertEqual c'' (chr 0) -- should throw an exception really assertEqual s s''' assertEqual t 0 assertEqual t' 100 testUndo = do b <- hNewB "data" :: IO FBuffer s <- sizeB b deleteN b s s' <- sizeB b undo b s'' <-sizeB b t <- elemsB b redo b >> redo b s'''<- sizeB b assertEqual s s'' assertEqual t contents -- contents after undo should equal original contents assertEqual s' s''' testMoveToSol = do b <- newB "testbuffer" "\n\nabc\n\ndef\n" :: IO FBuffer -- expected sol points let pure = [0,1,2,2,2,2,6,7,7,7,7] impure <- sequence [ do moveTo b i moveToSol b pointB b | i <- [ 0 .. length pure - 1] ] assertEqual pure impure testMoveToEol = do b <- newB "testbuffer" "\n\nabc\n\ndef\n" :: IO FBuffer -- expected eol points let pure = [0,1,5,5,5,5,6,10,10,10,10] impure <- sequence [ do moveTo b i moveToEol b pointB b | i <- [ 0 .. (length pure - 1) ] ] assertEqual pure impure testAtSol = do b <- newB "testbuffer" str :: IO FBuffer -- points where atSol is true let pure = [0,1,2,6,7] impure <- sequence [ do moveTo b i b <- atSol b return $ if b then Just i else Nothing | i <- [ 0 .. (lenstr - 1) ] ] assertEqual pure (map fromJust $ filter isJust impure) testAtEol = do b <- newB "testbuffer" str :: IO FBuffer -- points where atEol is true let pure = [0,1,5,6,10] impure <- sequence [ do moveTo b i b <- atEol b return $ if b then Just i else Nothing | i <- [ 0 .. (lenstr - 1) ] ] assertEqual pure (map fromJust $ filter isJust impure) testAtSof = do b <- newB "testbuffer" str :: IO FBuffer -- points where atSof is true impure <- sequence [ do moveTo b i b <- atSof b return $ if b then Just i else Nothing | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [0] (map fromJust $ filter isJust impure) testHardAtSof = do b <- hNewB "data" :: IO FBuffer -- points where atSof is true impure <- sequence [ do moveTo b i b <- atSof b return $ if b then Just i else Nothing | i <- [ 0 .. (lendata - 1) ] ] assertEqual [0] (map fromJust $ filter isJust impure) testAtEof = do b <- newB "testbuffer" str :: IO FBuffer -- points where atEof is true impure <- sequence [ do moveTo b i b <- atEof b return $ if b then Just i else Nothing | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [10] (map fromJust $ filter isJust impure) testHardAtEof = do b <- hNewB "data" :: IO FBuffer impure <- sequence [ do moveTo b i b <- atEof b return $ if b then Just i else Nothing | i <- [ 0 .. (lendata - 1) ] ] assertEqual [lendata - 1] (map fromJust $ filter isJust impure) testAtLastLine = do b <- newB "testbuffer" str :: IO FBuffer -- points where atEof is true impure <- sequence [ do moveTo b i b <- atLastLine b return $ if b then Just i else Nothing | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [7,8,9,10] (map fromJust $ filter isJust impure) testHardAtLastLine = do b <- hNewB "data" :: IO FBuffer -- points where atEof is true impure <- sequence [ do moveTo b i b <- atLastLine b return $ if b then Just i else Nothing | i <- [ 0 .. (lendata - 1) ] ] assertEqual [256927] (map fromJust $ filter isJust impure) testOffsetFromSol = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ moveTo b i >> offsetFromSol b | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [0,0,0,1,2,3,0,0,1,2,3] impure testIndexOfSol = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ moveTo b i >> indexOfSol b | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [0,1,2,2,2,2,6,7,7,7,7] impure testIndexOfEol = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ moveTo b i >> indexOfEol b | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [0,1,5,5,5,5,6,10,10,10,10] impure -- the point of the next line down testIndexOfNLFrom = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ indexOfNLFrom b i | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [1,2,6,6,6,6,7,10,10,10,10] impure testMoveAXuntil = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ do moveTo b i moveAXuntil b rightB 2 ((('\n' ==) `fmap`) . readB) pointB b | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [0,1,4,5,5,5,6,9,10,10,10] impure testDeleteToEol = do impure <- sequence [ do b <- newB "testbuffer" str :: IO FBuffer moveTo b i deleteToEol b elemsB b | i <- [ 0 .. (lenstr - 1) ] ] let pure = ["\n\nabc\n\ndef\n", "\n\nabc\n\ndef\n", "\n\n\n\ndef\n", "\n\na\n\ndef\n", "\n\nab\n\ndef\n", "\n\nabc\n\ndef\n", "\n\nabc\n\ndef\n", "\n\nabc\n\n\n", "\n\nabc\n\nd\n", "\n\nabc\n\nde\n", "\n\nabc\n\ndef\n"] assertEqual pure impure testLineUp = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ do moveTo b i lineUp b pointB b | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [0,0,1,1,1,1,2,6,6,6,6] impure testLineDown = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ do moveTo b i lineDown b pointB b | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [1,2,6,6,6,6,7,10,10,10,10] impure testCurLn = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ moveTo b i >> curLn b | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [1,2,3,3,3,3,4,5,5,5,5] impure testGotoLn = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ moveTo b i >> gotoLn b 4 | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [4,4,4,4,4,4,4,4,4,4,4] impure testHardGotoLn = do b <- hNewB "data" :: IO FBuffer impure <- sequence [ moveTo b i >> gotoLn b 4 | i <- [ 0 .. (lendata - 1) ] ] assertEqual (replicate lendata 4) impure testGotoLnFrom = do b <- newB "testbuffer" str :: IO FBuffer impure <- sequence [ gotoLnFrom b i | i <- [ 0 .. (lenstr - 1) ] ] assertEqual [1,1,3,4,4,4,4,4,4,4,4] impure testHardGotoLnFrom = do b <- hNewB "data" :: IO FBuffer impure <- sequence [ gotoLnFrom b 100 | i <- [ 1 .. length [100, 200 .. 3900 ] ] ] assertEqual [100,200..3900] impure testSearch = do b <- newB "T" contents :: IO FBuffer let loop = do r <- searchB b "Utopia" case r of Nothing -> return [] Just i -> do moveTo b (i+1) is <- loop return (i : is) rs <- loop assertEqual [29,339,1634,4945,5971,6205,7310,7379,7961,17241,56306,65159,69398,73199,77132,80891,97946,101903,103878,110169,121298,125041,126151,126749,127213,127445,129210,129293,143137,145856,146655,148945,160049,175824,176122,176860,179745,183199,183825,185498,187063,189432,191387,191468,191960,200269,208806,214785,219347,229205,233376,235247,235922,238163] rs |])
codemac/yi-editor
attic/testsuite/Tests/Buffer.hs
gpl-2.0
13,394
0
13
5,596
181
98
83
-1
-1
-- | The 'CombatState' module contains code that is stateful in the sense -- that it applies various modifiers to the player and the monster, such -- as checking whether the player has enough light to see the monster and -- modifying evasion and accuracy accordingly. module CombatState(CombatState(), modifyPlayer, modifyMonster, applyCombatModifiers) where import qualified Monster as M import qualified Player as P import qualified Data.Map as Map import Types as T import Rdice import Control.Monad.State import Control.Monad import Data.Maybe(isJust,fromJust) -- | 'CombatState' represents the state of the player and the monster. type CombatState = State (P.Player, M.Monster) -- | Apply a function @f@ to the current state of the player and set -- the state to the result of the function. modifyPlayer :: (P.Player -> P.Player) -> CombatState () modifyPlayer f = get >>= \(p,m) -> put $ (f p, m) -- | Apply a function @f@ to the current state of the monster and set -- the state to the result of the function. modifyMonster :: (M.Monster -> M.Monster) -> CombatState () modifyMonster f = get >>= \(p,m) -> put $ (p, f m) -- | Calculate and apply all modifiers relevant to combat: songs, alertness, --stealth, etc applyCombatModifiers :: CombatState () applyCombatModifiers = do applySongs applySlays --applied here because it affects light radius updateDarkResistance applyLightPenalties applyAssassination applyHardiness applyAlertness applyBrands applyCritAbilities applyCritRes divBy x y = y `quot` x --Net light strength on the player's square playerNetLight :: P.Player -> M.Monster -> Int playerNetLight p m = P.playerLight p + P.dungeonLight p + M.lightRadius m --Net light strength on the monster's square monsterNetLight :: P.Player -> M.Monster -> Int monsterNetLight p m = --glowing monsters are always visible if M.glows m then 1 else P.playerLight p - 1 + M.dungeonLight m + monsterLight where monsterGlow = if M.glows m then 1 else 0 monsterLight | M.lightRadius m < 0 = M.lightRadius m - 1 | M.lightRadius m > 0 = M.lightRadius m + 1 | otherwise = 0 --Apply player abilities that modify the player's critical --threshold. applyCritAbilities :: CombatState () applyCritAbilities = do (p,_) <- get let critMod = P.playerCritMods p modifyPlayer $ P.modifyCritThreshold (+ critMod) --Apply player and monster critical resistance. applyCritRes :: CombatState () applyCritRes = do (p,m) <- get when (p `P.hasAbility` T.CritRes) $ do let penalty = fromIntegral $ max 0 $ (P.will p) `quot` 5 modifyMonster $ M.modifyCritThreshold (+ penalty) --Doubling the critical threshold is equivalent with halving the number --of crit bonus dice and rounding downwards. when (M.CritResistant == M.criticalRes m) $ do modifyPlayer $ P.modifyCritThreshold (* 2) when (M.CritImmune == M.criticalRes m) $ do let pAttacks = map setNoCrit (P.attacks p) setNoCrit a = a {T.canCrit = False} modifyPlayer $ \p -> p {P.attacks = pAttacks} --Apply bonuses for the Assassination ability if the player --has it and the monster is unaware or asleep. applyAssassination :: CombatState () applyAssassination = do (p,m) <- get when ((M.seenByPlayer m) && M.Alert /= M.alertness m && p `P.hasAbility` T.Assassination) $ modifyPlayer $ P.modifyAccuracyWith (+ (P.stealth p)) --Add damage dice for brands that the attacker has and which --the defender does not resist. No extra dice if the defender --is resistant; one extra die if the defender has 0 resistance; and --two extra dice if the defender is vulnerable. applyBrands :: CombatState () applyBrands = do (p,m) <- get let pRes = P.resistances p mRes = M.resistances m monsterAttacks = map (applyBrand pRes) (M.attacks m) playerAttacks = map (applyBrand mRes) (P.attacks p) modifyPlayer $ \p -> p {P.attacks = playerAttacks} modifyMonster $ \m -> m {M.attacks = monsterAttacks} applyBrand :: Map.Map T.Element Int -> T.Attack -> T.Attack applyBrand rMap attack = let brands = T.brands attack damDice = T.damage attack totalExtraDice = sum $ (map getExtraDice) brands getExtraDice element | (rMap Map.! element) == 0 = 1 | (rMap Map.! element) < 0 = 2 | otherwise = 0 in attack { T.damage = addDice totalExtraDice damDice } --Monsters take evasion penalties for being unwary or asleep. --(This is separate from the assassination bonus that a player with --the Assassination ability gets.) applyAlertness :: CombatState () applyAlertness = do (_,m) <- get case (M.alertness m) of M.Alert -> return () M.Unwary -> modifyMonster $ M.modifyEvasionWith (divBy 2) M.Sleeping -> modifyMonster $ \m -> m { M.evasion = -5} --Extra protection if the player has the ability Hardiness applyHardiness :: CombatState () applyHardiness = do (p,_) <- get let currentProt = P.protDice p extraProtSides = (P.will p) `quot` 6 extraProt = 1 `d` extraProtSides updatedProt = extraProt : currentProt when (p `P.hasAbility` T.Hardiness) $ modifyPlayer $ \p -> p {P.protDice = updatedProt} --Apply song effects applySongs :: CombatState () applySongs = do (p,_) <- get when (SongTrees `P.isActiveSong` p) $ modifyPlayer P.applySongTrees when (SongStay `P.isActiveSong` p) $ modifyPlayer P.applySongStay when (SongSharp `P.isActiveSong` p) $ modifyPlayer P.applySongSharp --All light calculations assume that there is only one monster nearby --and that the player is standing next to that monster. updateDarkResistance :: CombatState () updateDarkResistance = do (p,m) <- get let darkRes = max 0 $ (playerNetLight p m) - 2 newMap = (Map.insert Dark darkRes) (P.resistances p) put $ (p {P.resistances = newMap}, m) --Apply penalties due to light applyLightPenalties :: CombatState () applyLightPenalties = do (p,m) <- get let monsterVisibilityThreshold = if p `P.hasAbility` T.KeenSenses then -1 else 0 --Can the player see the monster? If the monster's square is too dark, or --if the monster has been forced to be invisible with the --minvisible --command line flag, halve player's melee and evasion scores when (monsterNetLight p m < monsterVisibilityThreshold || not (M.seenByPlayer m)) $ do modifyPlayer $ P.modifyEvasionWith (divBy 2) modifyPlayer $ P.modifyAccuracyWith (divBy 2) modifyMonster $ \m -> m {M.seenByPlayer = False} when (M.hatesLight m) $ do let lightPenalty = max 0 $ monsterNetLight p m - 2 applyPenalty = (\s -> s - lightPenalty) modifyMonster $ M.modifyEvasionWith applyPenalty modifyMonster $ M.modifyAccuracyWith applyPenalty --If the player is wielding a weapon that slays the monster, add --a damage die and increase the player's light radius applySlays :: CombatState () applySlays = do (p,_) <- get adjustedAttacks <- mapM applySlay (P.attacks p) modifyPlayer $ \p -> p {P.attacks = adjustedAttacks} applySlay :: Attack -> CombatState Attack applySlay attack = do (p,m) <- get let slainBy = M.slainBy m weaponSlays = T.slays attack newDamage = addDice 1 (T.damage attack) newLightRad = P.lightRadius p + 1 if (isJust slainBy && (fromJust slainBy) `elem` weaponSlays) then do modifyPlayer $ \p -> p {P.lightRadius = newLightRad} return $ attack {T.damage = newDamage} else return attack
kryft/fsil
CombatState.hs
gpl-2.0
7,558
0
17
1,613
2,104
1,097
1,007
147
3
-------------------------------------------------------------------------------- -- This file is part of diplomarbeit ("Diplomarbeit Johannes Weiß"). -- -- -- -- diplomarbeit 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. -- -- -- -- diplomarbeit 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 diplomarbeit. If not, see <http://www.gnu.org/licenses/>. -- -- -- -- Copyright 2012, Johannes Weiß -- -------------------------------------------------------------------------------- module StaticConfiguration where import qualified Data.Conduit.Network as CN import Data.ExpressionTypes import Data.String import qualified Data.ByteString.Char8 as BS8 import Math.FiniteFields.F2Pow256 type Element = F2Pow256 --import Math.FiniteFields.F97 --type Element = F97 --import Math.FiniteFields.DebugField --type Element = DebugField _X_ :: Num a => Expr a _X_ = Var "x" -- Goliath --> Token _CLIENT_CONF_GOLIATH_TO_TOKEN_ :: CN.ClientSettings _CLIENT_CONF_GOLIATH_TO_TOKEN_ = CN.clientSettings 23120 (BS8.pack "127.0.0.1") _SRV_CONF_TOKEN_FROM_GOLIATH_ :: CN.ServerSettings _SRV_CONF_TOKEN_FROM_GOLIATH_ = CN.serverSettings 23120 (fromString "*") -- Goliath --> David _CLIENT_CONF_GOLIATH_TO_DAVID_ :: CN.ClientSettings _CLIENT_CONF_GOLIATH_TO_DAVID_ = CN.clientSettings 23102 (BS8.pack "127.0.0.1") _SRV_CONF_DAVID_FROM_GOLIATH_ :: CN.ServerSettings _SRV_CONF_DAVID_FROM_GOLIATH_ = CN.serverSettings 23102 (fromString "*") -- David --> Goliath _CLIENT_CONF_DAVID_TO_GOLIATH_ :: CN.ClientSettings _CLIENT_CONF_DAVID_TO_GOLIATH_ = CN.clientSettings 23201 (BS8.pack "127.0.0.1") _SRV_CONF_GOLIATH_FROM_DAVID_ :: CN.ServerSettings _SRV_CONF_GOLIATH_FROM_DAVID_ = CN.serverSettings 23201 (fromString "*") -- David --> Token _CLIENT_CONF_DAVID_TO_TOKEN_ :: CN.ClientSettings _CLIENT_CONF_DAVID_TO_TOKEN_ = CN.clientSettings 23021 (BS8.pack "127.0.0.1") _SRV_CONF_TOKEN_FROM_DAVID_ :: CN.ServerSettings _SRV_CONF_TOKEN_FROM_DAVID_ = CN.serverSettings 23021 (fromString "*")
weissi/diplomarbeit
programs/StaticConfiguration.hs
gpl-3.0
2,957
0
8
789
301
176
125
25
1
-- Copyright (C) 2014 Google Inc. All rights reserved. -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may not -- use this file except in compliance with the License. You may obtain a copy -- of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations -- under the License. module Test where import Main hiding (main) import Control.Monad import Test.QuickCheck instance Arbitrary Obj where arbitrary = oneof [ null, bools, ints ] where null = elements [ NullObj ] bools = elements [ BoolObj False, BoolObj True ] ints = do i <- choose (-5, 5) return $ IntObj i propSameEverIdentical x = sameEver x x main = do quickCheck propSameEverIdentical
monte-language/masque
Test.hs
gpl-3.0
1,049
0
13
231
151
86
65
14
1
module Sat.GUI.SVGBoardAlt (boardMain,boardMod) where import Text.Blaze (toValue) import Text.Blaze.Renderer.String (renderMarkup) import Text.Blaze.Svg11 ((!), mkPath, l, m, translate, scale) import qualified Text.Blaze.Svg11 as S import qualified Text.Blaze.Svg11.Attributes as A import qualified Data.Map as M import Data.Monoid(mappend) import qualified Data.Colour.Names as Names import Data.Colour(Colour,withOpacity,colourConvert) import Sat.GUI.SVG import Sat.Signatures.Figures suitcase :: S.Svg suitcase = path (unlines [ "m 40,32 0,160 -16,0" , "a 24,24 0 0 1 -24,-24 l 0,-112" , " a 24,24 0 0 1 24,-24 z" ]) `mappend` S.rect ! A.x (intValue 48) ! A.y (intValue 32) ! A.width (intValue 144) ! A.height (intValue 160) `mappend` path (unlines [ "m 200,32 16,0" , "a 24,24 0 0 1 24,24 l 0,112" , "a 24,24 0 0 1 -24,24 l -16,0 z" ]) `mappend` path (unlines [ "m 84,30 0,-12" , " a 18,18 0 0 1 18,-18 l 36,0" , "a 18,18 0 0 1 18,18 l 0,12 -12,0 0,-12" , "a 6,6 0 0 0 -6,-6 l -36,0" , "a 6,6 0 0 0 -6,6 l 0,12 z" ]) ! A.fill (colorValue Names.red) monkey = suitcase ! A.transform (toValue "scale(.5)") fish = suitcase ! A.transform (toValue "scale (.5) rotate(-45) translate(-20)") bird = suitcase ! A.transform (toValue "scale (.5) rotate(45) translate(-20 -40)") redA = colorAlpha Names.red 220 blueA = colorAlpha Names.blue 227 greenA = colorAlpha Names.lightgreen 230 boardMain :: DrawMain boardMain = M.fromList [ (triangulo, suitcase) , (cuadrado, fish) , (circulo, bird) ] -- -- Este mapa asocia cada predicado de la signatura con una función -- -- que agrega atributos SVG para pintar de alguna forma ese predicado. -- -- Si se cambia la signatura, debe modificarse este mapa. boardMod :: M.Map Predicate (S.Svg -> S.Svg) boardMod = M.fromList [ (rojo, redA) , (azul, blueA) , (verde, greenA) , (grande, big) , (mediano, normal) , (chico, small) ]
manugunther/sat
Sat/GUI/SVGBoardAlt.hs
gpl-3.0
2,381
0
16
818
536
315
221
55
1
{-# LANGUAGE FunctionalDependencies #-} module Network.LXD.Client.Internal.Compatibility where class Compatibility a b | a -> b where compat :: a -> b
hverr/haskell-lxd-client
src/Network/LXD/Client/Internal/Compatibility.hs
gpl-3.0
156
0
7
26
36
22
14
-1
-1
{- The algorithms used for constructing the set of LR(0) items from a DCFG. This was created as Project 2 for EECS 665 at the University of Kansas. Author: Ryan Scott -} {-# LANGUAGE FlexibleContexts, OverloadedStrings #-} module LR0ItemSet.Algorithm ( lr0ItemSet , augment , closure , goto ) where import Control.Monad import Control.Monad.Writer import Data.List import Data.Maybe import qualified Data.Set as S import Data.Set (Set) import Data.Text.Lazy.Builder import Data.Text.Lazy.Builder.Int import LR0ItemSet.Data import Text.Printf -- | Constructs the set of LR(0) parse table items from a DCFG. lr0ItemSet :: LR0MonadWriter m => Grammar -> m (Set Items) lr0ItemSet g = do tellLn "Augmented Grammar" tellLn "-----------------" -- First, augment the grammar with a new start production '->S. let g'@(Grammar _ ps') = augment g -- Log the augmented grammar. forM_ ps' $ tellLn . fromString . show tellLn "" -- Compute C = closure({['->@S]}). let i0 = closure g' [dottify $ head ps'] c = S.singleton $ Items 0 i0 -- Pass C to the "for-loop". itemize g' c -- | Do some simple logging before doing the real work in itemize'. itemize :: LR0MonadWriter m => Grammar -> Set Items -> m (Set Items) itemize g c = do tellLn "Sets of LR(0) Items" tellLn "-------------------" itemize' g c c -- | This represents the for-loops in the pseudocode representation of the algorithm. -- In this implementation, a set is used to track newly added sets of items; when -- it is empty, the for-loop has ended. itemize' :: LR0MonadWriter m => Grammar -> Set Items -> Set Items -> m (Set Items) itemize' g c unmarked | S.null unmarked = return c -- If no unmarked states, we're done. | otherwise = do -- Otherwise, go through unmarked states. -- Find the item set with the smallest numeric label... let i@(Items n ps) = S.findMin unmarked -- ...then remove it from the unmarked set. unmarked' = S.delete i unmarked tellLn $ singleton 'I' <> decimal n <> singleton ':' -- Compute the grammar symbols immediately following dots (in the order in which -- they appear in the item set). let xs = nub [x | DotProduction _ _ (x:_) <- ps] -- Log each dotted production, as well as its corresponding goto (if it has not -- been logged previously in the function call). (c', unmarked'', _) <- forFoldM (c, unmarked', xs) ps $ \(c', unmarked'', xs') p@(DotProduction _ _ rhs) -> do tell " " -- If there is a post-dot grammar symbol matching the start of this -- production's post-dot right-hand side... if not (null rhs) && head rhs `elem` xs' then do -- ...then calculate its goto (since it won't be empty)... let symb = head rhs oldMax = itemsNum $ S.findMax c' -- The largest current item set label. newMax = oldMax + 1 -- The label to give the new item set. gotoItemSet = Items newMax $ goto g ps symb -- The goto. -- If the goto is the items set... if inItemsSet gotoItemSet c then do -- ...then indicate which items are already in the set. let n' = itemsNum $ lookupItemsSet gotoItemSet c tellLn . fromString $ printf "%-20s goto(%c)=I%d" (show p) (symbolToChar symb) n' return (c', unmarked'', delete symb xs') else do -- ...otherwise, give the items a new label. tellLn . fromString $ printf "%-20s goto(%c)=I%d" (show p) (symbolToChar symb) newMax return $ (S.insert gotoItemSet c', S.insert gotoItemSet unmarked'', delete symb xs') else do -- ... otherwise, just print out the production. tellLn . fromString $ show p return (c', unmarked'', xs') tellLn "" itemize' g c' unmarked'' -- | Log some output followed by a newline. tellLn :: LR0MonadWriter m => Builder -> m () tellLn = tell . (<> singleton '\n') -- | A more convenient form of 'foldM' for use with do-notation. forFoldM :: Monad m => a -> [b] -> (a -> b -> m a) -> m a forFoldM = flip . flip foldM -- | Checks if some LR(0) items are in a set, ignoring labels. inItemsSet :: Items -> Set Items -> Bool inItemsSet (Items _ ps) = any ((==ps) . itemsProductions) . S.toList -- | Returns the member of a set of LR(0) items that matches the input items, -- ignoring labels. lookupItemsSet :: Items -> Set Items -> Items lookupItemsSet (Items _ ps) = fromJust . find ((==ps) . itemsProductions) . S.toList -- | Attaches a new start production ('->S) to a grammar, where S is the start symbol. augment :: Grammar -> Grammar augment (Grammar sv ps) = Grammar sv $ Production (Nonterm '\'') [SymbolNonterm sv]:ps -- | Computes the dot-closure of a set of dotted DCFG productions. closure :: Grammar -> [DotProduction] -> [DotProduction] closure g jps = let jps' = jps ++ nub [ dotGp | DotProduction _ _ (SymbolNonterm b:_) <- jps , Production b' gamma <- gProductions g , b == b' , let dotGp = DotProduction b' [] gamma , not $ dotGp `elem` jps ] in if jps == jps' then jps' else closure g jps' -- | Computes the dotted productions that result from shifting the dots preceding -- a certain symbol over by one (as well as their closure). goto :: Grammar -> [DotProduction] -> Symbol -> [DotProduction] goto g i x = closure g [ DotProduction a (alpha ++ [x]) beta | DotProduction a alpha (x':beta) <- i , x == x' ]
RyanGlScott/lr0-item-set
src/LR0ItemSet/Algorithm.hs
gpl-3.0
6,020
0
23
1,873
1,347
688
659
84
3
module NoteWindow where import Graphics.UI.Gtk.General.Structs(Rectangle) import Graphics.UI.Gtk.Gdk.Region -- for rect intersect import Graphics.Rendering.Cairo import Graphics.UI.Gtk import Data.IORef -- Everything in here relies on nothing happening whilst drawing a stroke. -- This is *probably* a safe assumption. We'll see how it goes. -- Utility functions data Pt = Pt Double Double unPt f (Pt x y) = f x y getX (Pt x _) = x getY (Pt _ y) = y inside (x,y) (Rectangle bx by bw bh) = (floor x - bx <= bw) && (floor y - by <= bh) intersects (Rectangle ax ay aw ah) (Rectangle bx by bw bh) = not ( (bx + bw < ax) || (ax + aw < bx) || (by + bh < ay) || (ay + ah < by) ) moveToP = unPt moveTo lineToP = unPt lineTo -- Bunch of points and their bounding box data Stroke = Stroke [Pt] Rectangle getRect (Stroke _ rect) = rect -- A notewindow consists of a draw area, some completed strokes and a stroke in progress data NoteWindow = NW DrawingArea (IORef [Stroke]) (IORef [Pt]) makeNoteWindow drawArea = do -- Make the note window r1 <- newIORef [] r2 <- newIORef [] let nw = NW drawArea r1 r2 -- Hook the note window into the drawing area onExposeRect drawArea $ drawNW nw onMotionNotify drawArea True $ \ (Motion _ _ x y _ _ _ _) -> do addPt nw (Pt x y) return True --widgetAddEvents dr [ButtonMotionMask] widgetAddEvents drawArea [Button2MotionMask] widgetDelEvents drawArea [PointerMotionMask] onButtonRelease drawArea $ \ (Button _ _ _ x y _ _ _ _) -> do finishStroke nw return True -- on exit needed as well !!! return nw --disassoc addPt (NW da _ ptsRef) newPt = do pts <- readIORef ptsRef case pts of [] -> writeIORef ptsRef [newPt] (p:ps) -> do writeIORef ptsRef (newPt:p:ps) dw <- widgetGetDrawWindow da renderWithDrawable dw $ do moveToP p lineToP newPt stroke finishStroke (NW _ strokesRef ptsRef) = do strokes <- readIORef strokesRef pts <- readIORef ptsRef case pts of [] -> writeIORef strokesRef strokes pts -> writeIORef strokesRef ( (Stroke pts (bounds pts)) : strokes) writeIORef ptsRef [] bounds pts = let xleft = floor $ minimum $ map (getX) pts xright = ceiling $ maximum $ map (getX) pts ybottom = floor $ minimum $ map (getY) pts ytop = ceiling $ maximum $ map (getY) pts in Rectangle xleft ybottom (xright - xleft) (ytop - ybottom) drawStroke (Stroke [] _) = return () drawStroke (Stroke (p:ps) _) = do moveToP p sequence_ $ map lineToP ps stroke drawStrokes strokes rect = sequence_ $ map drawStroke $ filter (intersects rect . getRect) strokes drawNW (NW da strokeRef _) rect = do strokes <- readIORef strokeRef dw <- widgetGetDrawWindow da renderWithDrawable dw $ drawStrokes strokes rect
jamii/inkling
gnote/NoteWindow.hs
gpl-3.0
2,750
44
15
602
1,085
540
545
72
2
{-| Module : Css.Post Description : Defines the CSS for the post page. The post page is navigated to by clicking Check My POSt located at the top of any Courseography page. -} module Css.Post (postStyles) where import Clay import Prelude hiding ((**)) import Css.Constants -- |Defines the CSS for the post page. postStyles :: Css postStyles = do body ? do color grey1 fontWeight normal tabsCSS postCSS tabsCSS :: Css tabsCSS = do "#posts" & do fontFamily ["HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", "Lucida Grande"][sansSerif] fontSize (px 17) width (pct 97) backgroundColor white border solid (px 1) grey2 "border-radius" -: "4px" "box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)" display block overflow hidden margin (px 8) (px 22) (px 8) (px 22) ul ? do width $ (pct 100) margin0 li ? do "list-style-type" -: "none" display inlineBlock width (pct 32) --textAlign $ alignSide sideCenter "-webkit-transition" -: "all 0.2s" "-moz-transition" -: "all 0.2s" "-ms-transition" -: "all 0.2s" "-o-transition" -: "all 0.2s" "transition" -: "all 0.2s" ":hover" & do "background-color" -: "#9C9C9C !important" a ? do "color" -: "white !important" cursor pointer a ? do color black display inlineBlock lineHeight (px 50) paddingLeft (px 24) width (pct 70) textDecoration none ".nav_selected" ? do backgroundColor grey6 ".nav_not_selected" ? do backgroundColor white ".credits_completed" ? do color green ".credits_not_completed" ? do color red postCSS :: Css postCSS = do "input" ? do fontSize (px 14) "#button_wrapper" ? do textAlign $ alignSide sideCenter height (px 50) paddingLeft (px 20) "#update" ? do height (px 40) fontSize (px 14) cursor pointer semiVisible ":hover" & do fullyVisible ".selected" ? do ".code" ? do backgroundColor green2 ".full_name" ? do backgroundColor green1 "div" ? do ".code" ? do backgroundColor beige1 fontFamily ["HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", "Lucida Grande"][sansSerif] fontSize (px 20) paddingLeft (px 20) "box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)" borderBottom solid (px 1) grey5 lineHeight (px 50) "list-style-type" -: "none" textAlign $ alignSide sideCenter margin0 width (pct 99) "margin-right" -: "10px" "-webkit-transition" -: "all 0.2s" "-moz-transition" -: "all 0.2s" "-ms-transition" -: "all 0.2s" "-o-transition" -: "all 0.2s" "transition" -: "all 0.2s" ".courseName" ? do display inlineBlock fontFamily ["HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", "Lucida Grande"][sansSerif] lineHeight (px 50) paddingLeft (px 5) paddingRight (px 5) cursor pointer ":hover" & do fontWeight bold i ? do color red "#post_specialist, #post_major, #post_minor" ? do position absolute "margin-above" -: "30px" paddingBottom (px 30) height (pct 70) marginLeft (px 25) width (pct 97) "#spec_creds, #maj_creds, #min_creds" ? do display inlineBlock marginLeft nil ".more-info" ? do cursor pointer border solid (px 2) grey3 "border-radius" -: "4px" backgroundColor grey4 "box-shadow" -: "0 2px 2px -1px rgba(0, 0, 0, 0.055)" lineHeight (px 40) "list-style-type" -: "none" textAlign $ alignSide sideCenter margin0 display none "margin-right" -: "10px" "-webkit-transition" -: "all 0.2s" "-moz-transition" -: "all 0.2s" "-ms-transition" -: "all 0.2s" "-o-transition" -: "all 0.2s" "transition" -: "all 0.2s" ".info_opened > div" ? do display block ".full_name" ? do paddingLeft (px 20) textAlign $ alignSide sideCenter margin0 "input" ? do textAlign $ alignSide sideCenter height $ (px 40) "#notes" ? do textAlign $ alignSide sideCenter ".valid_extra_course" ? do color green ".not_valid_extra_course" ? do color red ".post_selected" ? do display block ".post_not_selected" ? do display none
hermish/courseography
app/Css/Post.hs
gpl-3.0
5,207
0
22
2,047
1,246
534
712
153
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionTargetHTTPSProxies.SetURLMap -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Changes the URL map for TargetHttpsProxy. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionTargetHttpsProxies.setUrlMap@. module Network.Google.Resource.Compute.RegionTargetHTTPSProxies.SetURLMap ( -- * REST Resource RegionTargetHTTPSProxiesSetURLMapResource -- * Creating a Request , regionTargetHTTPSProxiesSetURLMap , RegionTargetHTTPSProxiesSetURLMap -- * Request Lenses , rthpsumRequestId , rthpsumProject , rthpsumPayload , rthpsumRegion , rthpsumTargetHTTPSProxy ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionTargetHttpsProxies.setUrlMap@ method which the -- 'RegionTargetHTTPSProxiesSetURLMap' request conforms to. type RegionTargetHTTPSProxiesSetURLMapResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "targetHttpsProxies" :> Capture "targetHttpsProxy" Text :> "setUrlMap" :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] URLMapReference :> Post '[JSON] Operation -- | Changes the URL map for TargetHttpsProxy. -- -- /See:/ 'regionTargetHTTPSProxiesSetURLMap' smart constructor. data RegionTargetHTTPSProxiesSetURLMap = RegionTargetHTTPSProxiesSetURLMap' { _rthpsumRequestId :: !(Maybe Text) , _rthpsumProject :: !Text , _rthpsumPayload :: !URLMapReference , _rthpsumRegion :: !Text , _rthpsumTargetHTTPSProxy :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionTargetHTTPSProxiesSetURLMap' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rthpsumRequestId' -- -- * 'rthpsumProject' -- -- * 'rthpsumPayload' -- -- * 'rthpsumRegion' -- -- * 'rthpsumTargetHTTPSProxy' regionTargetHTTPSProxiesSetURLMap :: Text -- ^ 'rthpsumProject' -> URLMapReference -- ^ 'rthpsumPayload' -> Text -- ^ 'rthpsumRegion' -> Text -- ^ 'rthpsumTargetHTTPSProxy' -> RegionTargetHTTPSProxiesSetURLMap regionTargetHTTPSProxiesSetURLMap pRthpsumProject_ pRthpsumPayload_ pRthpsumRegion_ pRthpsumTargetHTTPSProxy_ = RegionTargetHTTPSProxiesSetURLMap' { _rthpsumRequestId = Nothing , _rthpsumProject = pRthpsumProject_ , _rthpsumPayload = pRthpsumPayload_ , _rthpsumRegion = pRthpsumRegion_ , _rthpsumTargetHTTPSProxy = pRthpsumTargetHTTPSProxy_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). rthpsumRequestId :: Lens' RegionTargetHTTPSProxiesSetURLMap (Maybe Text) rthpsumRequestId = lens _rthpsumRequestId (\ s a -> s{_rthpsumRequestId = a}) -- | Project ID for this request. rthpsumProject :: Lens' RegionTargetHTTPSProxiesSetURLMap Text rthpsumProject = lens _rthpsumProject (\ s a -> s{_rthpsumProject = a}) -- | Multipart request metadata. rthpsumPayload :: Lens' RegionTargetHTTPSProxiesSetURLMap URLMapReference rthpsumPayload = lens _rthpsumPayload (\ s a -> s{_rthpsumPayload = a}) -- | Name of the region scoping this request. rthpsumRegion :: Lens' RegionTargetHTTPSProxiesSetURLMap Text rthpsumRegion = lens _rthpsumRegion (\ s a -> s{_rthpsumRegion = a}) -- | Name of the TargetHttpsProxy to set a URL map for. rthpsumTargetHTTPSProxy :: Lens' RegionTargetHTTPSProxiesSetURLMap Text rthpsumTargetHTTPSProxy = lens _rthpsumTargetHTTPSProxy (\ s a -> s{_rthpsumTargetHTTPSProxy = a}) instance GoogleRequest RegionTargetHTTPSProxiesSetURLMap where type Rs RegionTargetHTTPSProxiesSetURLMap = Operation type Scopes RegionTargetHTTPSProxiesSetURLMap = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient RegionTargetHTTPSProxiesSetURLMap'{..} = go _rthpsumProject _rthpsumRegion _rthpsumTargetHTTPSProxy _rthpsumRequestId (Just AltJSON) _rthpsumPayload computeService where go = buildClient (Proxy :: Proxy RegionTargetHTTPSProxiesSetURLMapResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionTargetHTTPSProxies/SetURLMap.hs
mpl-2.0
5,951
0
19
1,321
636
378
258
107
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Genomics.DataSets.GetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the access control policy for the dataset. This is empty if the -- policy or resource does not exist. See -- </iam/docs/managing-policies#getting_a_policy Getting a Policy> for more -- information. For the definitions of datasets and other genomics -- resources, see [Fundamentals of Google -- Genomics](https:\/\/cloud.google.com\/genomics\/fundamentals-of-google-genomics) -- -- /See:/ <https://cloud.google.com/genomics Genomics API Reference> for @genomics.datasets.getIamPolicy@. module Network.Google.Resource.Genomics.DataSets.GetIAMPolicy ( -- * REST Resource DataSetsGetIAMPolicyResource -- * Creating a Request , dataSetsGetIAMPolicy , DataSetsGetIAMPolicy -- * Request Lenses , dsgipXgafv , dsgipUploadProtocol , dsgipPp , dsgipAccessToken , dsgipUploadType , dsgipPayload , dsgipBearerToken , dsgipResource , dsgipCallback ) where import Network.Google.Genomics.Types import Network.Google.Prelude -- | A resource alias for @genomics.datasets.getIamPolicy@ method which the -- 'DataSetsGetIAMPolicy' request conforms to. type DataSetsGetIAMPolicyResource = "v1" :> CaptureMode "resource" "getIamPolicy" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GetIAMPolicyRequest :> Post '[JSON] Policy -- | Gets the access control policy for the dataset. This is empty if the -- policy or resource does not exist. See -- </iam/docs/managing-policies#getting_a_policy Getting a Policy> for more -- information. For the definitions of datasets and other genomics -- resources, see [Fundamentals of Google -- Genomics](https:\/\/cloud.google.com\/genomics\/fundamentals-of-google-genomics) -- -- /See:/ 'dataSetsGetIAMPolicy' smart constructor. data DataSetsGetIAMPolicy = DataSetsGetIAMPolicy' { _dsgipXgafv :: !(Maybe Xgafv) , _dsgipUploadProtocol :: !(Maybe Text) , _dsgipPp :: !Bool , _dsgipAccessToken :: !(Maybe Text) , _dsgipUploadType :: !(Maybe Text) , _dsgipPayload :: !GetIAMPolicyRequest , _dsgipBearerToken :: !(Maybe Text) , _dsgipResource :: !Text , _dsgipCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DataSetsGetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dsgipXgafv' -- -- * 'dsgipUploadProtocol' -- -- * 'dsgipPp' -- -- * 'dsgipAccessToken' -- -- * 'dsgipUploadType' -- -- * 'dsgipPayload' -- -- * 'dsgipBearerToken' -- -- * 'dsgipResource' -- -- * 'dsgipCallback' dataSetsGetIAMPolicy :: GetIAMPolicyRequest -- ^ 'dsgipPayload' -> Text -- ^ 'dsgipResource' -> DataSetsGetIAMPolicy dataSetsGetIAMPolicy pDsgipPayload_ pDsgipResource_ = DataSetsGetIAMPolicy' { _dsgipXgafv = Nothing , _dsgipUploadProtocol = Nothing , _dsgipPp = True , _dsgipAccessToken = Nothing , _dsgipUploadType = Nothing , _dsgipPayload = pDsgipPayload_ , _dsgipBearerToken = Nothing , _dsgipResource = pDsgipResource_ , _dsgipCallback = Nothing } -- | V1 error format. dsgipXgafv :: Lens' DataSetsGetIAMPolicy (Maybe Xgafv) dsgipXgafv = lens _dsgipXgafv (\ s a -> s{_dsgipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). dsgipUploadProtocol :: Lens' DataSetsGetIAMPolicy (Maybe Text) dsgipUploadProtocol = lens _dsgipUploadProtocol (\ s a -> s{_dsgipUploadProtocol = a}) -- | Pretty-print response. dsgipPp :: Lens' DataSetsGetIAMPolicy Bool dsgipPp = lens _dsgipPp (\ s a -> s{_dsgipPp = a}) -- | OAuth access token. dsgipAccessToken :: Lens' DataSetsGetIAMPolicy (Maybe Text) dsgipAccessToken = lens _dsgipAccessToken (\ s a -> s{_dsgipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). dsgipUploadType :: Lens' DataSetsGetIAMPolicy (Maybe Text) dsgipUploadType = lens _dsgipUploadType (\ s a -> s{_dsgipUploadType = a}) -- | Multipart request metadata. dsgipPayload :: Lens' DataSetsGetIAMPolicy GetIAMPolicyRequest dsgipPayload = lens _dsgipPayload (\ s a -> s{_dsgipPayload = a}) -- | OAuth bearer token. dsgipBearerToken :: Lens' DataSetsGetIAMPolicy (Maybe Text) dsgipBearerToken = lens _dsgipBearerToken (\ s a -> s{_dsgipBearerToken = a}) -- | REQUIRED: The resource for which policy is being specified. Format is -- \`datasets\/\`. dsgipResource :: Lens' DataSetsGetIAMPolicy Text dsgipResource = lens _dsgipResource (\ s a -> s{_dsgipResource = a}) -- | JSONP dsgipCallback :: Lens' DataSetsGetIAMPolicy (Maybe Text) dsgipCallback = lens _dsgipCallback (\ s a -> s{_dsgipCallback = a}) instance GoogleRequest DataSetsGetIAMPolicy where type Rs DataSetsGetIAMPolicy = Policy type Scopes DataSetsGetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/genomics"] requestClient DataSetsGetIAMPolicy'{..} = go _dsgipResource _dsgipXgafv _dsgipUploadProtocol (Just _dsgipPp) _dsgipAccessToken _dsgipUploadType _dsgipBearerToken _dsgipCallback (Just AltJSON) _dsgipPayload genomicsService where go = buildClient (Proxy :: Proxy DataSetsGetIAMPolicyResource) mempty
rueshyna/gogol
gogol-genomics/gen/Network/Google/Resource/Genomics/DataSets/GetIAMPolicy.hs
mpl-2.0
6,668
0
18
1,524
944
552
392
136
1
-- Map loc is read-inly. All dynamic information get fixed with Overlays on the MapBoard of the Battlespace module Loc where import Data.Char import Terrain import Elevation data Loc = Loc { lcTerrain :: Terrain, lcElevation :: Elevation, lcTextRepresentation :: String } deriving (Show) -- | create a Loc with clear, flat terrain createClearLoc :: Loc createClearLoc = Loc t e (makeTextRepresentation t e) where t = Terrain Clear [] e = E0 -- | create a Loc with Terrain and Elevation createLoc :: Terrain -> Elevation -> Loc createLoc t e = Loc t e (makeTextRepresentation t e) -- | create a list of clear locs createClearLocList :: Int -> [Loc] createClearLocList n | n <= 0 = [] | otherwise = createClearLoc : createClearLocList (n - 1) -- | get text representation of a Loc: code its terrain and elevation information makeTextRepresentation :: Terrain -> Elevation -> String makeTextRepresentation t e = case e of E1 -> map toUpper (textOfTerrain t) _ -> map toLower (textOfTerrain t)
nbrk/datmap2html
Loc.hs
unlicense
1,109
0
10
288
252
135
117
23
2
module Problem12 where main = print $ repli "abc" 3 repli as 0 = [] repli as n = as ++ repli as (n - 1)
vasily-kartashov/playground
99-problems/problem-15.hs
apache-2.0
109
0
8
31
56
29
27
5
1
module Propellor.Property.SiteSpecific.Branchable where import Propellor.Base import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.File as File import qualified Propellor.Property.User as User import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Postfix as Postfix import qualified Propellor.Property.Gpg as Gpg import qualified Propellor.Property.Sudo as Sudo server :: [Host] -> Property (HasInfo + DebianLike) server hosts = propertyList "branchable server" $ props & "/etc/timezone" `File.hasContent` ["Etc/UTC"] & "/etc/locale.gen" `File.containsLines` [ "en_GB.UTF-8 UTF-8" , "en_US.UTF-8 UTF-8" , "fi_FI.UTF-8 UTF-8" ] `onChange` (cmdProperty "locale-gen" [] `assume` MadeChange) & Apt.installed ["etckeeper", "ssh", "popularity-contest"] & Apt.serviceInstalledRunning "apache2" & Apt.serviceInstalledRunning "ntp" & Apt.serviceInstalledRunning "openssh-server" & Ssh.passwordAuthentication False & Ssh.hostKeys (Context "branchable.com") [ (SshDsa, "ssh-dss AAAAB3NzaC1kc3MAAACBAK9HnfpyIm8aEhKuF5oz6KyaLwFs2oWeToVkqVuykyy5Y8jWDZPtkpv+1TeOnjcOvJSZ1cCqB8iXlsP9Dr5z98w5MfzsRQM2wIw0n+wvmpPmUhjVdGh+wTpfP9bcyFHhj/f1Ymdq9hEWB26bnf4pbTbJW2ip8ULshMvn5CQ/ugV3AAAAFQCAjpRd1fquRiIuLJMwej0VcyoZKQAAAIBe91Grvz/icL3nlqXYrifXyr9dsw8bPN+BMu+hQtFsQXNJBylxwf8FtbRlmvZXmRjdVYqFVyxSsrL2pMsWlds51iXOr9pdsPG5a4OgJyRHsveBz3tz6HgYYPcr3Oxp7C6G6wrzwsaGK862SgRp/bbD226k9dODRBy3ogMhk/MvAgAAAIEApfknql3vZbDVa88ZnwbNKDOv8L1hb6blbKAMt2vJbqJMvu3EP9CsP9hGyEQh5YCAl2F9KEU3bJXN1BG76b7CiYtWK95lpL1XmCCWnJBCcdEhw998GfJS424frPw7qGmXLxJKYxEyioB90/IDp2dC+WaLcLOYHM9SroCQTIK5A1g= root@pell") , (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1M0aNLgcgcgf0tkmt/8vCDZLok8Xixz7Nun9wB6NqVXxfzAR4te+zyO7FucVwyTY5QHmiwwpmyNfaC21AAILhXGm12SUKSAirF9BkQk7bhQuz4T/dPlEt3d3SxQ3OZlXtPp4LzXWOyS0OXSzIb+HeaDA+hFXlQnp/gE7RyAzR1+xhWPO7Mz1q5O/+4dXANnW32t6P7Puob6NsglVDpLrMRYjkO+0RgCVbYMzB5+UnkthkZsIINaYwsNhW2GKMKbRZeyp5en5t1NJprGXdw0BqdBqd/rcBpOxmhHE1U7rw+GS1uZwCFWWv0aZbaXEJ6wY7mETFkqs0QXi5jtoKn95Gw== root@pell") ] & Apt.installed ["procmail", "bsd-mailx"] & "/etc/aliases" `File.hasPrivContentExposed` (Context "branchable.com") `onChange` Postfix.newaliases & "/etc/mailname" `File.hasContent` ["branchable.com"] & Postfix.installed & Postfix.mainCf ("mailbox_command", "procmail -a \"$EXTENSION\"") -- Obnam is run by a cron job in ikiwiki-hosting. & "/etc/obnam.conf" `File.hasContent` [ "[config]" , "repository = sftp://[email protected]/home/joey/lib/backup/pell.obnam" , "log = /var/log/obnam.log" , "encrypt-with = " ++ obnamkey , "log-level = info" , "log-max = 1048576" , "keep = 7d,5w,12m" , "upload-queue-size = 128" , "lru-size = 128" ] & Gpg.keyImported (Gpg.GpgKeyId obnamkey) (User "root") & Ssh.userKeys (User "root") (Context "branchable.com") [ (SshRsa, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2PqTSupwncqeffNwZQXacdEWp7L+TxllIxH7WjfRMb3U74mQxWI0lwqLVW6Fox430DvhSqF1y5rJBvTHh4i49Tc9lZ7mwAxA6jNOP6bmdfteaKKYmUw5qwtJW0vISBFu28qBO11Nq3uJ1D3Oj6N+b3mM/0D3Y3NoGgF8+2dLdi81u9+l6AQ5Jsnozi2Ni/Osx2oVGZa+IQDO6gX8VEP4OrcJFNJe8qdnvItcGwoivhjbIfzaqNNvswKgGzhYLOAS5KT8HsjvIpYHWkyQ5QUX7W/lqGSbjP+6B8C3tkvm8VLXbmaD+aSkyCaYbuoXC2BoJdS7Jh8phKMwPJmdYVepn") ] & Ssh.knownHost hosts "eubackup.kitenet.net" (User "root") & Ssh.knownHost hosts "usw-s002.rsync.net" (User "root") & adminuser "joey" & adminuser "liw" where obnamkey = "41E1A9B9" adminuser u = propertyList ("admin user " ++ u) $ props & User.accountFor (User u) & User.hasSomePassword (User u) & Sudo.enabledFor (User u) & User.hasGroup (User u) (Group "adm") & User.hasGroup (User u) (Group "systemd-journal")
ArchiveTeam/glowing-computing-machine
src/Propellor/Property/SiteSpecific/Branchable.hs
bsd-2-clause
3,677
20
33
343
632
351
281
-1
-1
import Data.Array import qualified Data.Map as M --import System.IO.Unsafe -- SegTree data SegTree a = StLeaf Int a | StNode Int Int a (SegTree a) (SegTree a) deriving (Eq, Ord, Show) buildrmq acc cs lvs x = acc' where updacc (lstseq, lstmap, ix) = (lstseq', lstmap', succ ix) where lstseq' = (ix, ((lvs ! x), x)) : lstseq lstmap' = (x, ix) : lstmap f acc c = updacc acc' where acc' = buildrmq acc cs lvs c acc' = foldl f (updacc acc) (cs ! x) buildst arrseq a b = if a == b then let minx = arrseq ! a in (minx, StLeaf a minx) else let midp = cmidp a b (minl, lt) = buildst arrseq a (midp - 1) (minr, rt) = buildst arrseq midp b minx = min minl minr in (minx, StNode a b minx lt rt) lcast (StLeaf _ x) _ _ = x lcast (StNode l r x lt rt) a b = if a <= l && r <= b then x else minimum $ (\(_, t) -> lcast t a b) `map` rs where midp = cmidp l r rs = (((a, b) `intersects`) . fst) `filter` [((l, midp - 1), lt), ((midp, r), rt)] lca (st, lm, rm) a b = --(unsafePerformIO $ putStrLn $ show (al, ar, bl, br)) `seq` if al <= bl && br <= ar then a else if bl <= al && ar <= br then b else if al < bl then snd $ lcast st ar bl else snd $ lcast st br al where al = lm ! a ar = rm ! a bl = lm ! b br = rm ! b -- CTree data CTree = CtNone Int Int | CtAll Int Int | CtNode Int Int Int CTree CTree deriving (Eq, Ord, Show) ctmidp (CtNone a b) = cmidp a b ctmidp (CtAll a b) = cmidp a b ctmidp (CtNode a b _ _ _) = cmidp a b t@(CtNone a b) `ctins` x = if a == b then CtAll a b else if x < midp then CtNode a b 1 ((CtNone a (midp - 1)) `ctins` x) (CtNone midp b) else CtNode a b 1 (CtNone a (midp - 1)) ((CtNone midp b) `ctins` x) where midp = ctmidp t t@(CtNode a b n lt rt) `ctins` x = if b - a == n then CtAll a b else if x < midp then CtNode a b (n + 1) (lt `ctins` x) rt else CtNode a b (n + 1) lt (rt `ctins` x) where midp = ctmidp t cntrng (CtNone _ _) _ _ = 0 cntrng (CtAll a b) l r = if l <= a && b <= r then b - a + 1 else if a <= l && r <= b then r - l + 1 else if a <= l && l <= b then b - l + 1 else if a <= r && r <= b then r - a + 1 else 0 cntrng (CtNode a b n lt rt) l r = if l <= a && b <= r then n else if (a <= l && l <= b) || (a <= r && r <= b) then cntrng lt l r + cntrng rt l r else 0 buildns t cs x = (x, t') : cts where t' = t `ctins` x cts = (cs ! x) >>= (buildns t' cs) -- Misc (a1, b1) `intersects` (a2, b2) = (a2 <= a1 && a1 <= b2) || (a2 <= b1 && b1 <= b2) || (a1 <= a2 && a2 <= b1) cmidp a b = (a + b) `div` 2 + 1 buildlvs cs lv x = (x, lv) : ((cs ! x) >>= (buildlvs cs (succ lv))) swap (x, y) = (y, x) readLst = return . (read `map`) . words -- tst _ 0 = return () tst pc@(arrns, lcas) m = do (x : y : l : r : _) <- getLine >>= readLst let xyLca = lca lcas x y --putStrLn $ "LCA: " ++ show xyLca putStrLn $ show (cntrng (arrns ! x) l r + cntrng (arrns ! y) l r - (2 * cntrng (arrns ! xyLca) l r) + if l <= xyLca && xyLca <= r then 1 else 0) tst pc (pred m) main = do (n : m : _) <- getLine >>= readLst ps <- getLine >>= readLst let lstcs = [1 .. n] `zip` [[] | _ <- [1 ..]] ++ ps `zip` ((: []) `map` [2 ..]) let mcs = M.fromListWith (flip (++)) lstcs let arrcs = array (1, n) (M.toList mcs) let lstlvs = buildlvs arrcs 1 1 let arrlvs = array (1, n) lstlvs let lstns = buildns (CtNone 1 n) arrcs 1 let arrns = array (1, n) lstns --putStrLn $ show arrns let (lstseq, lstmap, finalix) = buildrmq ([], [], 1) arrcs arrlvs 1 let arrseq = array (1, finalix - 1) lstseq let leftmap = M.toList $ M.fromListWith min lstmap let rightmap = M.toList $ M.fromListWith max lstmap let arrlm = array (1, n) leftmap let arrrm = array (1, n) rightmap let (minn, lcast) = buildst arrseq 1 (pred finalix) tst (arrns, (lcast, arrlm, arrrm)) m --return ()
pbl64k/HackerRank-Contests
2014-09-05-FP/ApeWar/aw.ct.hs
bsd-2-clause
4,677
22
17
1,925
2,261
1,169
1,092
108
7
{-# LANGUAGE OverloadedStrings #-} -- |Small helper for saving "cleaned up" point cloud data. The idea is -- that a PCD file is loaded, some processig is done to it, and we -- want to save the new point set. module PCDCleaner where import qualified Data.Vector.Storable as V import Linear.V3 (V3) import PCD.Data (saveBinaryPcd) import PCD.Header (Header(..), DimType(..), DataFormat(..)) import System.FilePath (splitExtension, addExtension) -- |@saveCleanPCD originalFile newPts@ saves @newPts@ as a new PCD -- file with name @\"originalFile_clean.pcd\"@. Only XYZ coordinates -- are saved! saveCleanPCD :: FilePath -> V.Vector (V3 Float) -> IO () saveCleanPCD f v = saveBinaryPcd f' h v where f' = let (fn,e) = splitExtension f in addExtension (fn++"_clean") e n = fromIntegral $ V.length v h = Header "0.7" ["x","y","z"] [4,4,4] [F,F,F] [1,1,1] n 1 (0,1) n Binary
acowley/PcdViewer
src/PCDCleaner.hs
bsd-3-clause
900
0
11
165
249
146
103
13
1
module Challenges.Challenge4 where import Lib (breakCipher) import Data.HexString import System.Environment import Data.Maybe import System.Exit import System.IO (IOMode(ReadMode), openFile, Handle, hIsEOF) import qualified Data.ByteString as BS import Control.Monad secondArg :: [String] -> Maybe String secondArg (_:fp:_) = Just fp secondArg _ = Nothing eachLine :: Handle -> IO () eachLine h = do eof <- hIsEOF h unless eof $ do mapM_ print =<< (breakCipher . hexString . BS.init) <$> BS.hGetLine h putStrLn "" eachLine h challenge4 :: IO () challenge4 = do mbArg <- secondArg <$> getArgs when (isNothing mbArg) $ do putStrLn "No second argument supplied. Need filepath" exitSuccess eachLine =<< openFile (fromJust mbArg) ReadMode
caneroj1/Crypto-hs
app/Challenges/Challenge4.hs
bsd-3-clause
775
0
14
147
270
137
133
26
1
-- | This module provides various utility functions for dealing with -- directory manipulations module Scoutess.Utils.Directory (copyDir) where import System.Directory import System.FilePath import qualified Codec.Archive.Tar as Tar import qualified Data.ByteString.Lazy as L -- | Copies the content of a directory into another copyDir :: FilePath -> FilePath -> IO () copyDir from to = do dirContent <- filter pred `fmap` getDirectoryContents from taredEntries <- Tar.pack from dirContent Tar.unpack to $ Tar.read (Tar.write taredEntries) where pred x = not (x `elem` [".", ".."])
cartazio/scoutess
Scoutess/Utils/Directory.hs
bsd-3-clause
599
0
11
99
157
87
70
11
1
-- | Functions for dealing with lists. module Data.Lists ( -- * Re-exports module Data.List ,module Data.List.Split ,module Data.List.Extras -- * List operations ,list ,unionOf ,for ,lastToMaybe ,firstOr ,maxList ,powerslice ,merge ,mergeBy ,hasAny ,takeWhileList ,dropWhileList ,spanList ,keysAL ,valuesAL ,breakList ,replace ,genericJoin ,addToAL ,delFromAL ,hasKeyAL ,flipAL ,strToAL ,strFromAL ,countElem ,elemRIndex ,alwaysElemRIndex ,seqList) where import Data.List import Data.List.Extras hiding (list) import Data.List.Split import Data.Maybe -- | When a list is non-null, pass it to a function, otherwise use the -- default. list :: b -> ([a] -> b) -> [a] -> b list nil _ [] = nil list _ cons xs = cons xs -- | Get the union of the given lists. unionOf :: (Eq a) => [[a]] -> [a] unionOf = foldr union [] -- | Opposite of map. for :: [a] -> (a -> b) -> [b] for = flip map -- | Maybe get the last element in the list. lastToMaybe :: [a] -> Maybe a lastToMaybe [x] = Just x lastToMaybe (_:xs) = lastToMaybe xs lastToMaybe [] = Nothing -- | Return the first item of a list or something else. firstOr :: a -> [a] -> a firstOr n = fromMaybe n . listToMaybe -- | Get the maximum of a list or return zero. maxList :: (Num t, Ord t) => [t] -> t maxList [] = 0 maxList xs = maximum xs -- | Essentially a powerset but retaining contiguously ordererd subsets. powerslice :: [a] -> [[a]] powerslice xs = [] : concatMap (tail . inits) (tails xs) {- | Merge two sorted lists into a single, sorted whole. Example: > merge [1,3,5] [1,2,4,6] -> [1,1,2,3,4,5,6] QuickCheck test property: prop_merge xs ys = merge (sort xs) (sort ys) == sort (xs ++ ys) where types = xs :: [Int] -} merge :: (Ord a) => [a] -> [a] -> [a] merge = mergeBy (compare) {- | Merge two sorted lists using into a single, sorted whole, allowing the programmer to specify the comparison function. QuickCheck test property: prop_mergeBy xs ys = mergeBy cmp (sortBy cmp xs) (sortBy cmp ys) == sortBy cmp (xs ++ ys) where types = xs :: [ (Int, Int) ] cmp (x1,_) (x2,_) = compare x1 x2 -} mergeBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a] mergeBy _cmp [] ys = ys mergeBy _cmp xs [] = xs mergeBy cmp (allx@(x:xs)) (ally@(y:ys)) -- Ordering derives Eq, Ord, so the comparison below is valid. -- Explanation left as an exercise for the reader. -- Someone please put this code out of its misery. | (x `cmp` y) <= EQ = x : mergeBy cmp xs ally | otherwise = y : mergeBy cmp allx ys {- | Returns true if the given list contains any of the elements in the search list. -} hasAny :: Eq a => [a] -- ^ List of elements to look for -> [a] -- ^ List to search -> Bool -- ^ Result hasAny [] _ = False -- An empty search list: always false hasAny _ [] = False -- An empty list to scan: always false hasAny search (x:xs) = if x `elem` search then True else hasAny search xs {- | Similar to Data.List.takeWhile, takes elements while the func is true. The function is given the remainder of the list to examine. -} takeWhileList :: ([a] -> Bool) -> [a] -> [a] takeWhileList _ [] = [] takeWhileList func list'@(x:xs) = if func list' then x : takeWhileList func xs else [] {- | Similar to Data.List.dropWhile, drops elements while the func is true. The function is given the remainder of the list to examine. -} dropWhileList :: ([a] -> Bool) -> [a] -> [a] dropWhileList _ [] = [] dropWhileList func list'@(_:xs) = if func list' then dropWhileList func xs else list' {- | Similar to Data.List.span, but performs the test on the entire remaining list instead of just one element. @spanList p xs@ is the same as @(takeWhileList p xs, dropWhileList p xs)@ -} spanList :: ([a] -> Bool) -> [a] -> ([a], [a]) spanList _ [] = ([],[]) spanList func list'@(x:xs) = if func list' then (x:ys,zs) else ([],list') where (ys,zs) = spanList func xs {- | Similar to Data.List.break, but performs the test on the entire remaining list instead of just one element. -} breakList :: ([a] -> Bool) -> [a] -> ([a], [a]) breakList func = spanList (not . func) {- | Given a list and a replacement list, replaces each occurance of the search list with the replacement list in the operation list. Example: >replace "," "." "127,0,0,1" -> "127.0.0.1" This could logically be thought of as: >replace old new l = join new . split old $ l -} replace :: Eq a => [a] -> [a] -> [a] -> [a] replace old new l = intercalate new . splitOn old $ l {- | Like 'intercalate', but works with a list of anything showable, converting it to a String. Examples: > genericJoin ", " [1, 2, 3, 4] -> "1, 2, 3, 4" > genericJoin "|" ["foo", "bar", "baz"] -> "\"foo\"|\"bar\"|\"baz\"" -} genericJoin :: Show a => String -> [a] -> String genericJoin delim l = intercalate delim (map show l) {- | Adds the specified (key, value) pair to the given list, removing any existing pair with the same key already present. -} addToAL :: Eq key => [(key, elt)] -> key -> elt -> [(key, elt)] addToAL l key value = (key, value) : delFromAL l key {- | Removes all (key, value) pairs from the given list where the key matches the given one. -} delFromAL :: Eq key => [(key, a)] -> key -> [(key, a)] delFromAL l key = filter (\a -> (fst a) /= key) l {- | Returns the keys that comprise the (key, value) pairs of the given AL. Same as: >map fst -} keysAL :: [(key, a)] -> [key] keysAL = map fst {- | Returns the values the comprise the (key, value) pairs of the given AL. Same as: >map snd -} valuesAL :: [(a, value)] -> [value] valuesAL = map snd {- | Indicates whether or not the given key is in the AL. -} hasKeyAL :: Eq a => a -> [(a, b)] -> Bool hasKeyAL key list' = elem key (keysAL list') {- | Flips an association list. Converts (key1, val), (key2, val) pairs to (val, [key1, key2]). -} flipAL :: (Eq key, Eq val) => [(key, val)] -> [(val, [key])] flipAL oldl = let worker :: (Eq key, Eq val) => [(key, val)] -> [(val, [key])] -> [(val, [key])] worker [] accum = accum worker ((k, v):xs) accum = case lookup v accum of Nothing -> worker xs ((v, [k]) : accum) Just y -> worker xs (addToAL accum v (k:y)) in worker oldl [] {- | Converts an association list to a string. The string will have one pair per line, with the key and value both represented as a Haskell string. This function is designed to work with [(String, String)] association lists, but may work with other types as well. -} strFromAL :: (Show a, Show b) => [(a, b)] -> String strFromAL inp = let worker (key, val) = show key ++ "," ++ show val in unlines . map worker $ inp {- | The inverse of 'strFromAL', this function reads a string and outputs the appropriate association list. Like 'strFromAL', this is designed to work with [(String, String)] association lists but may also work with other objects with simple representations. -} strToAL :: (Read a, Read b) => String -> [(a, b)] strToAL inp = let worker line = case reads line of [(key, remainder)] -> case remainder of ',':valstr -> (key, read valstr) _ -> error "Data.List.Utils.strToAL: Parse error on value" _ -> error "Data.List.Utils.strToAL: Parse error on key" in map worker (lines inp) {- FIXME TODO: sub -} {- | Returns a count of the number of times the given element occured in the given list. -} countElem :: Eq a => a -> [a] -> Int countElem i = length . filter (i==) {- | Returns the rightmost index of the given element in the given list. -} elemRIndex :: Eq a => a -> [a] -> Maybe Int elemRIndex item l = case reverse $ elemIndices item l of [] -> Nothing (x:_) -> Just x {- | Like elemRIndex, but returns -1 if there is nothing found. -} alwaysElemRIndex :: Eq a => a -> [a] -> Int alwaysElemRIndex item list' = case elemRIndex item list' of Nothing -> -1 Just x -> x {- | Forces the evaluation of the entire list. -} seqList :: [a] -> [a] seqList [] = [] seqList list'@(_:xs) = seq (seqList xs) list'
chrisdone/lists
src/Data/Lists.hs
bsd-3-clause
8,330
0
16
2,076
2,158
1,193
965
142
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} module Gli.Types where import Data.Aeson import qualified Data.ByteString.Char8 as B import Data.Map.Strict as M import qualified Data.Text as T import Data.Time import GHC.Generics (Generic) data Setup = Setup { keyFile :: String } deriving (Show) data Commands = CmdSetup Setup | CmdPrs deriving (Show) data Project = Project { id :: Int , description :: Maybe T.Text , name :: T.Text , ssh_url_to_repo :: T.Text } deriving (Generic) instance Show Project where show (Project pid pdescription pname purl) = unlines [ "GitLab Project" , "Id: " ++ show pid , "Name: " ++ show pname , "Descripion: " ++ justOrEmpty pdescription , "Git Url: " ++ show purl , "" ] data MergeRequest = MergeRequest { id :: Int , title :: Maybe T.Text , iid :: Int , project_id :: Int , description :: Maybe T.Text , source_branch :: T.Text , upvotes :: Int , downvotes :: Int , author :: User , assignee :: Maybe User , source_project_id :: Int , target_project_id :: Int , labels :: [Maybe T.Text] , work_in_progress :: Bool , milestone :: Maybe T.Text , merge_when_build_succeeds :: Bool , merge_status :: T.Text , subscribed :: Maybe Bool , web_url :: T.Text , sha :: T.Text , created_at :: UTCTime , updated_at :: UTCTime } deriving (Generic) instance Show MergeRequest where show (MergeRequest mid mtitle _ _ mdescription msource_branch _ _ mauthor massignee _ _ _ mwork_in_progress _ _ mmerge_status _ mweb_url _ mcreated mupdated) = unlines [ "ID: " ++ show mid , "URL: " ++ show mweb_url , "Title: " ++ justOrEmpty mtitle , "Descripion: " ++ justOrEmpty mdescription , "Author: " ++ show mauthor , "Assignee: " ++ justOrEmpty massignee , "WIP: " ++ show mwork_in_progress , "Status: " ++ show mmerge_status , "Branch: " ++ show msource_branch ] data Build = Build { id :: Int , name :: T.Text , user :: User , status :: T.Text , created_at :: UTCTime , finished_at :: Maybe UTCTime } deriving (Generic) instance Show Build where show (Build _ bname buser bstatus _ _) = unlines [ " Status: " ++ show bstatus , " Name: " ++ show bname , " Started by: " ++ show buser ] data User = User { name :: T.Text , username :: T.Text } deriving (Generic) instance Show User where show (User _ uusername) = show uusername data GliCfg = GliCfg { accounts :: Account } deriving (Generic, Show) newtype Account = Account (Map T.Text AccountConfig) deriving (Generic, Show) data AccountConfig = AccountConfig { key :: String , url :: String } deriving (Generic, Show) type GitlabAccountConfig = (String, B.ByteString) data GitUrl = GitUrl { domain :: T.Text , repo :: T.Text } data LocalYmlContent = LocalYmlContent { masterFileConfig :: MasterFileConfig , project :: Project } deriving (Generic, Show) data MasterFileConfig = MasterFileConfig { file :: FilePath , key :: T.Text } deriving (Generic, Show) instance Show GitUrl where show (GitUrl gdomain grepo) = unlines [ "Git Project Found" , "Domain: " ++ show gdomain , "Repo: " ++ show grepo ] instance ToJSON MergeRequest where toEncoding = genericToEncoding defaultOptions instance ToJSON Build where toEncoding = genericToEncoding defaultOptions instance ToJSON User where toEncoding = genericToEncoding defaultOptions instance ToJSON Project where toEncoding = genericToEncoding defaultOptions instance ToJSON Account where toEncoding = genericToEncoding defaultOptions instance ToJSON AccountConfig where toEncoding = genericToEncoding defaultOptions instance ToJSON LocalYmlContent where toEncoding = genericToEncoding defaultOptions instance ToJSON MasterFileConfig where toEncoding = genericToEncoding defaultOptions instance FromJSON MergeRequest instance FromJSON Build instance FromJSON User instance FromJSON GliCfg instance FromJSON Account instance FromJSON AccountConfig instance FromJSON Project instance FromJSON LocalYmlContent instance FromJSON MasterFileConfig justOrEmpty :: Show a => Maybe a -> String justOrEmpty (Just a) = show a justOrEmpty Nothing = "" localYmlFile :: FilePath localYmlFile = "gli.yml" gitInfoExcludeFile :: FilePath gitInfoExcludeFile = ".git/info/exclude"
goromlagche/gli
src/gli/types.hs
bsd-3-clause
6,451
0
11
2,991
1,242
682
560
135
1
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Parallel.MPI.Fast import Data.Array.Storable import Foreign.C.Types (CInt) import Control.Monad (forM_) type Msg = StorableArray Int CInt bounds :: (Int, Int) bounds@(lo,hi) = (1,100) tag :: Tag tag = 0 main :: IO () main = mpiWorld $ \size rank -> do putStrLn $ "Haskell process with rank " ++ show rank ++ " world with size " ++ show size if rank == 1 then do (msg :: Msg) <- newArray bounds 0 _status <- recv commWorld 0 tag msg forM_ [lo .. hi] $ \i -> do val <- readArray msg i writeArray msg i (val*val) send commWorld 0 tag msg else putStrLn "This program must be rank 1"
bjpop/haskell-mpi
test/examples/HaskellAndC/Rank1.hs
bsd-3-clause
739
0
18
207
258
137
121
23
2
----------------------------------------------------------------------------- -- | -- Module : Data.SBV.Examples.CodeGeneration.Fibonacci -- Copyright : (c) Lee Pike, Levent Erkok -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- -- Computing Fibonacci numbers and generating C code. Inspired by Lee Pike's -- original implementation, modified for inclusion in the package. It illustrates -- symbolic termination issues one can have when working with recursive algorithms -- and how to deal with such, eventually generating good C code. ----------------------------------------------------------------------------- module Data.SBV.Examples.CodeGeneration.Fibonacci where import Data.SBV import Data.SBV.Tools.CodeGen ----------------------------------------------------------------------------- -- * A naive implementation ----------------------------------------------------------------------------- -- | This is a naive implementation of fibonacci, and will work fine (albeit slow) -- for concrete inputs: -- -- >>> map fib0 [0..6] -- [0 :: SWord64,1 :: SWord64,1 :: SWord64,2 :: SWord64,3 :: SWord64,5 :: SWord64,8 :: SWord64] -- -- However, it is not suitable for doing proofs or generating code, as it is not -- symbolically terminating when it is called with a symbolic value @n@. When we -- recursively call @fib0@ on @n-1@ (or @n-2@), the test against @0@ will always -- explore both branches since the result will be symbolic, hence will not -- terminate. (An integrated theorem prover can establish termination -- after a certain number of unrollings, but this would be quite expensive to -- implement, and would be impractical.) fib0 :: SWord64 -> SWord64 fib0 n = ite (n .== 0 ||| n .== 1) n (fib0 (n-1) + fib0 (n-2)) ----------------------------------------------------------------------------- -- * Using a recursion depth, and accumulating parameters ----------------------------------------------------------------------------- {- $genLookup One way to deal with symbolic termination is to limit the number of recursive calls. In this version, we impose a limit on the index to the function, working correctly upto that limit. If we use a compile-time constant, then SBV's code generator can produce code as the unrolling will eventually stop. -} -- | The recursion-depth limited version of fibonacci. Limiting the maximum number to be 20, we can say: -- -- >>> map (fib1 20) [0..6] -- [0 :: SWord64,1 :: SWord64,1 :: SWord64,2 :: SWord64,3 :: SWord64,5 :: SWord64,8 :: SWord64] -- -- The function will work correctly, so long as the index we query is at most @top@, and otherwise -- will return the value at @top@. Note that we also use accumulating parameters here for efficiency, -- although this is orthogonal to the termination concern. -- -- A note on modular arithmetic: The 64-bit word we use to represent the values will of course -- eventually overflow, beware! Fibonacci is a fast growing function.. fib1 :: SWord64 -> SWord64 -> SWord64 fib1 top n = fib' 0 1 0 where fib' :: SWord64 -> SWord64 -> SWord64 -> SWord64 fib' prev' prev m = ite (m .== top ||| m .== n) -- did we reach recursion depth, or the index we're looking for prev' -- stop and return the result (fib' prev (prev' + prev) (m+1)) -- otherwise recurse -- | We can generate code for 'fib1' using the 'genFib1' action. Note that the -- generated code will grow larger as we pick larger values of @top@, but only linearly, -- thanks to the accumulating parameter trick used by 'fib1'. The following is an excerpt -- from the code generated for the call @genFib1 10@, where the code will work correctly -- for indexes up to 10: -- -- > SWord64 fib1(const SWord64 x) -- > { -- > const SWord64 s0 = x; -- > const SBool s2 = s0 == 0x0000000000000000ULL; -- > const SBool s4 = s0 == 0x0000000000000001ULL; -- > const SBool s6 = s0 == 0x0000000000000002ULL; -- > const SBool s8 = s0 == 0x0000000000000003ULL; -- > const SBool s10 = s0 == 0x0000000000000004ULL; -- > const SBool s12 = s0 == 0x0000000000000005ULL; -- > const SBool s14 = s0 == 0x0000000000000006ULL; -- > const SBool s17 = s0 == 0x0000000000000007ULL; -- > const SBool s19 = s0 == 0x0000000000000008ULL; -- > const SBool s22 = s0 == 0x0000000000000009ULL; -- > const SWord64 s25 = s22 ? 0x0000000000000022ULL : 0x0000000000000037ULL; -- > const SWord64 s26 = s19 ? 0x0000000000000015ULL : s25; -- > const SWord64 s27 = s17 ? 0x000000000000000dULL : s26; -- > const SWord64 s28 = s14 ? 0x0000000000000008ULL : s27; -- > const SWord64 s29 = s12 ? 0x0000000000000005ULL : s28; -- > const SWord64 s30 = s10 ? 0x0000000000000003ULL : s29; -- > const SWord64 s31 = s8 ? 0x0000000000000002ULL : s30; -- > const SWord64 s32 = s6 ? 0x0000000000000001ULL : s31; -- > const SWord64 s33 = s4 ? 0x0000000000000001ULL : s32; -- > const SWord64 s34 = s2 ? 0x0000000000000000ULL : s33; -- > -- > return s34; -- > } genFib1 :: SWord64 -> IO () genFib1 top = compileToC Nothing "fib1" $ do x <- cgInput "x" cgReturn $ fib1 top x ----------------------------------------------------------------------------- -- * Generating a look-up table ----------------------------------------------------------------------------- {- $genLookup While 'fib1' generates good C code, we can do much better by taking advantage of the inherent partial-evaluation capabilities of SBV to generate a look-up table, as follows. -} -- | Compute the fibonacci numbers statically at /code-generation/ time and -- put them in a table, accessed by the 'select' call. fib2 :: SWord64 -> SWord64 -> SWord64 fib2 top = select table 0 where table = map (fib1 top) [0 .. top] -- | Once we have 'fib2', we can generate the C code straightforwardly. Below -- is an excerpt from the code that SBV generates for the call @genFib2 64@. Note -- that this code is a constant-time look-up table implementation of fibonacci, -- with no run-time overhead. The index can be made arbitrarily large, -- naturally. (Note that this function returns @0@ if the index is larger -- than 64, as specified by the call to 'select' with default @0@.) -- -- > SWord64 fibLookup(const SWord64 x) -- > { -- > const SWord64 s0 = x; -- > static const SWord64 table0[] = { -- > 0x0000000000000000ULL, 0x0000000000000001ULL, -- > 0x0000000000000001ULL, 0x0000000000000002ULL, -- > 0x0000000000000003ULL, 0x0000000000000005ULL, -- > 0x0000000000000008ULL, 0x000000000000000dULL, -- > 0x0000000000000015ULL, 0x0000000000000022ULL, -- > 0x0000000000000037ULL, 0x0000000000000059ULL, -- > 0x0000000000000090ULL, 0x00000000000000e9ULL, -- > 0x0000000000000179ULL, 0x0000000000000262ULL, -- > 0x00000000000003dbULL, 0x000000000000063dULL, -- > 0x0000000000000a18ULL, 0x0000000000001055ULL, -- > 0x0000000000001a6dULL, 0x0000000000002ac2ULL, -- > 0x000000000000452fULL, 0x0000000000006ff1ULL, -- > 0x000000000000b520ULL, 0x0000000000012511ULL, -- > 0x000000000001da31ULL, 0x000000000002ff42ULL, -- > 0x000000000004d973ULL, 0x000000000007d8b5ULL, -- > 0x00000000000cb228ULL, 0x0000000000148addULL, -- > 0x0000000000213d05ULL, 0x000000000035c7e2ULL, -- > 0x00000000005704e7ULL, 0x00000000008cccc9ULL, -- > 0x0000000000e3d1b0ULL, 0x0000000001709e79ULL, -- > 0x0000000002547029ULL, 0x0000000003c50ea2ULL, -- > 0x0000000006197ecbULL, 0x0000000009de8d6dULL, -- > 0x000000000ff80c38ULL, 0x0000000019d699a5ULL, -- > 0x0000000029cea5ddULL, 0x0000000043a53f82ULL, -- > 0x000000006d73e55fULL, 0x00000000b11924e1ULL, -- > 0x000000011e8d0a40ULL, 0x00000001cfa62f21ULL, -- > 0x00000002ee333961ULL, 0x00000004bdd96882ULL, -- > 0x00000007ac0ca1e3ULL, 0x0000000c69e60a65ULL, -- > 0x0000001415f2ac48ULL, 0x000000207fd8b6adULL, -- > 0x0000003495cb62f5ULL, 0x0000005515a419a2ULL, -- > 0x00000089ab6f7c97ULL, 0x000000dec1139639ULL, -- > 0x000001686c8312d0ULL, 0x000002472d96a909ULL, -- > 0x000003af9a19bbd9ULL, 0x000005f6c7b064e2ULL, 0x000009a661ca20bbULL -- > }; -- > const SWord64 s65 = s0 >= 65 ? 0x0000000000000000ULL : table0[s0]; -- > -- > return s65; -- > } genFib2 :: SWord64 -> IO () genFib2 top = compileToC Nothing "fibLookup" $ do cgPerformRTCs True -- protect against potential overflow, our table is not big enough x <- cgInput "x" cgReturn $ fib2 top x
josefs/sbv
Data/SBV/Examples/CodeGeneration/Fibonacci.hs
bsd-3-clause
8,630
0
11
1,671
490
314
176
25
1
module Context ( -- * Context Context (..), vanillaContext, stageContext, -- * Expressions getStage, getPackage, getWay, getStagedSettingList, getBuildPath, withHsPackage, -- * Paths contextDir, buildPath, buildDir, pkgInplaceConfig, pkgSetupConfigFile, pkgHaddockFile, pkgLibraryFile, pkgGhciLibraryFile, pkgConfFile, objectPath, contextPath, getContextPath, libDir, libPath ) where import Base import Context.Paths import Context.Type import Hadrian.Expression import Hadrian.Haskell.Cabal import Oracles.Setting -- | Most targets are built only one way, hence the notion of 'vanillaContext'. vanillaContext :: Stage -> Package -> Context vanillaContext s p = Context s p vanilla -- | Partial context with undefined 'Package' field. Useful for 'Packages' -- expressions that only read the environment and current 'Stage'. stageContext :: Stage -> Context stageContext s = vanillaContext s $ error "stageContext: package not set" -- | Get the 'Stage' of the current 'Context'. getStage :: Expr Context b Stage getStage = stage <$> getContext -- | Get the 'Package' of the current 'Context'. getPackage :: Expr Context b Package getPackage = package <$> getContext -- | Get the 'Way' of the current 'Context'. getWay :: Expr Context b Way getWay = way <$> getContext -- | Get a list of configuration settings for the current stage. getStagedSettingList :: (Stage -> SettingList) -> Args Context b getStagedSettingList f = getSettingList . f =<< getStage -- | Construct an expression that depends on the Cabal file of the current -- package and is empty in a non-Haskell context. withHsPackage :: (Monoid a, Semigroup a) => (Context -> Expr Context b a) -> Expr Context b a withHsPackage expr = do pkg <- getPackage ctx <- getContext case pkgCabalFile pkg of Just _ -> expr ctx Nothing -> mempty pkgId :: Context -> Action FilePath pkgId ctx@Context {..} = case pkgCabalFile package of Just _ -> pkgIdentifier ctx Nothing -> return (pkgName package) -- Non-Haskell packages, e.g. rts libDir :: Context -> FilePath libDir Context {..} = stageString stage -/- "lib" -- | Path to the directory containg the final artifact in a given 'Context' libPath :: Context -> Action FilePath libPath context = buildRoot <&> (-/- libDir context) pkgFile :: Context -> String -> String -> Action FilePath pkgFile context@Context {..} prefix suffix = do path <- buildPath context pid <- pkgId context return $ path -/- prefix ++ pid ++ suffix -- | Path to inplace package configuration file of a given 'Context'. pkgInplaceConfig :: Context -> Action FilePath pkgInplaceConfig context = do path <- contextPath context return $ path -/- "inplace-pkg-config" -- | Path to the @setup-config@ of a given 'Context'. pkgSetupConfigFile :: Context -> Action FilePath pkgSetupConfigFile context = do path <- contextPath context return $ path -/- "setup-config" -- | Path to the haddock file of a given 'Context', e.g.: -- @_build/stage1/libraries/array/doc/html/array/array.haddock@. pkgHaddockFile :: Context -> Action FilePath pkgHaddockFile Context {..} = do root <- buildRoot let name = pkgName package return $ root -/- "docs/html/libraries" -/- name -/- name <.> "haddock" -- | Path to the library file of a given 'Context', e.g.: -- @_build/stage1/libraries/array/build/libHSarray-0.5.1.0.a@. pkgLibraryFile :: Context -> Action FilePath pkgLibraryFile context@Context {..} = do extension <- libsuf way pkgFile context "libHS" extension -- | Path to the GHCi library file of a given 'Context', e.g.: -- @_build/stage1/libraries/array/build/HSarray-0.5.1.0.o@. pkgGhciLibraryFile :: Context -> Action FilePath pkgGhciLibraryFile context = pkgFile context "HS" ".o" -- | Path to the configuration file of a given 'Context'. pkgConfFile :: Context -> Action FilePath pkgConfFile ctx@Context {..} = do root <- buildRoot pid <- pkgId ctx return $ root -/- relativePackageDbPath stage -/- pid <.> "conf" -- | Given a 'Context' and a 'FilePath' to a source file, compute the 'FilePath' -- to its object file. For example: -- * "Task.c" -> "_build/stage1/rts/Task.thr_o" -- * "_build/stage1/rts/cmm/AutoApply.cmm" -> "_build/stage1/rts/cmm/AutoApply.o" objectPath :: Context -> FilePath -> Action FilePath objectPath context@Context {..} src = do isGenerated <- isGeneratedSource src path <- buildPath context let extension = drop 1 $ takeExtension src obj = src -<.> osuf way result | isGenerated = obj | "*hs*" ?== extension = path -/- obj | otherwise = path -/- extension -/- obj return result
bgamari/shaking-up-ghc
src/Context.hs
bsd-3-clause
4,757
0
13
954
1,022
523
499
-1
-1
{-# LANGUAGE CPP, FlexibleContexts, NoImplicitPrelude, MultiParamTypeClasses, OverloadedStrings, RankNTypes #-} {-# OPTIONS -Wall #-} module Language.Paraiso.Generator.ClarisTrans ( Translatable(..), paren, joinBy, joinEndBy, joinBeginBy, joinBeginEndBy, headerFile, sourceFile, Context, typeRepDB, dynamicDB ) where import Control.Monad import qualified Data.Dynamic as Dyn import qualified Data.List as L import qualified Data.Text as T import Language.Paraiso.Generator.Claris import Language.Paraiso.Name import Language.Paraiso.Prelude import NumericPrelude hiding ((++)) class Translatable a where translate :: Context -> a -> Text data Context = Context { fileType :: FileType, namespace :: [Namespace] -- inner scopes are in head of the list } deriving (Eq, Show) data Namespace = ClassSpace Class deriving (Eq, Show) instance Nameable Namespace where name (ClassSpace x) = name x headerFile :: Context headerFile = Context {fileType = HeaderFile, namespace = []} sourceFile :: Context sourceFile = Context {fileType = SourceFile, namespace = []} instance Translatable Program where translate conf Program{topLevel = xs} = T.unlines $ map (translate conf) xs instance Translatable Statement where translate conf stmt = case stmt of StmtPrpr x -> translate conf x ++ "\n" UsingNamespace x -> "using namespace " ++ nameText x ++ ";" ClassDef x -> translate conf x FuncDef x -> translate conf x VarDef x -> translate conf x ++ ";" VarDefCon x args -> translate conf x ++ paren Paren (joinBy ", " $ map (translate conf) args) ++ ";" VarDefSub x rhs -> translate conf x ++ " = " ++ translate conf rhs ++ ";" StmtExpr x -> translate conf x ++ ";" StmtReturn x -> "return " ++ translate conf x ++ ";" StmtWhile test xs -> "while" ++ paren Paren (translate conf test) ++ paren Brace (joinBeginEndBy "\n" $ map (translate conf) xs) StmtFor ini test inc xs -> "for" ++ paren Paren (joinBy " " [translate conf ini, translate conf test,";", translate conf inc]) ++ paren Brace (joinBeginEndBy "\n" $ map (translate conf) xs) Exclusive file stmt2 -> if file == fileType conf then translate conf stmt2 else "" RawStatement text -> text Comment str -> paren SlashStar str instance Translatable Preprocessing where translate _ prpr = case prpr of PrprInclude par na -> "#include " ++ paren par na PrprPragma str -> "#pragma " ++ str instance Translatable Class where translate conf me@(Class na membs) = if fileType conf == HeaderFile then classDecl else classDef where t :: Translatable a => a -> Text t = translate conf conf' = conf{namespace = ClassSpace me : namespace conf} classDecl = "class " ++ nameText na ++ paren Brace (joinBeginEndBy "\n" $ map memberDecl membs) ++ ";" classDef = joinBeginEndBy "\n" $ map memberDef membs memberDecl x = case x of MemberFunc ac inl f -> if inl then t ac ++ " " ++ translate conf{ fileType = SourceFile } (FuncDef f) else t ac ++ " " ++ t (FuncDef f) MemberVar ac y -> t ac ++ " " ++ t (VarDef y) memberDef x = case x of MemberFunc _ inl f -> if inl then "" else translate conf' (FuncDef f) MemberVar _ _ -> "" instance Translatable AccessModifier where translate _ Private = "private:" translate _ Protected = "protected:" translate _ Public = "public:" instance Translatable Function where translate conf f = ret where ret = if fileType conf == HeaderFile then funcDecl else funcDef funcDecl = T.unwords [ translate conf (funcType f) , funcName' , paren Paren $ joinBy ", " $ map (translate conf) (funcArgs f) , ";"] funcDef = T.unwords [ translate conf (funcType f) , funcName' , paren Paren $ joinBy ", " $ map (translate conf) (funcArgs f) , if null $ funcMemberInitializer f then "" else (": " ++) $ joinBy "," $ map (translate conf) $ funcMemberInitializer f , paren Brace $ joinBeginEndBy "\n" $ map (translate conf) $ funcBody f] funcName' = joinBy "::" $ reverse $ nameText f : map nameText (namespace conf) instance Translatable TypeRep where translate conf trp = case trp of UnitType x -> translate conf x PtrOf x -> translate conf x ++ " *" RefOf x -> translate conf x ++ " &" Const x -> "const " ++ translate conf x TemplateType x ys -> x ++ paren Chevron (joinBy ", " $ map (translate conf) ys) ++ " " QualifiedType qs x -> (joinEndBy " " $ map (translate conf) qs) ++ translate conf x ConstructorType -> "" UnknownType -> error "cannot translate unknown type." instance Translatable Qualifier where translate _ CudaGlobal = "__global__" translate _ CudaDevice = "__device__" translate _ CudaHost = "__host__" translate _ CudaShared = "__shared__" translate _ CudaConst = "__constant__" instance Translatable Dyn.TypeRep where translate _ x = case typeRepDB x of Just str -> str Nothing -> error $ "cannot translate Haskell type: " ++ show x instance Translatable Dyn.Dynamic where translate _ x = case dynamicDB x of Just str -> str Nothing -> error $ "cannot translate value of Haskell type: " ++ show x instance Translatable Var where translate conf (Var typ nam) = T.unwords [translate conf typ, nameText nam] instance Translatable Expr where translate conf expr = ret where pt = paren Paren . translate conf t :: Translatable a => a -> Text t = translate conf ret = case expr of Imm x -> t x VarExpr x -> nameText x FuncCallUsr f args -> (nameText f++) $ paren Paren $ joinBy ", " $ map t args FuncCallStd f args -> (f++) $ paren Paren $ joinBy ", " $ map t args CudaFuncCallUsr f numBlock numThread args -> nameText f ++ paren Chevron3 (t numBlock ++ "," ++ t numThread) ++ (paren Paren $ joinBy ", " $ map t args) MemberAccess x y -> pt x ++ "." ++ t y Op1Prefix op x -> op ++ pt x Op1Postfix op x -> pt x ++ op Op2Infix op x y -> T.unwords [pt x, op, pt y] Op3Infix op1 op2 x y z -> T.unwords [pt x, op1, pt y, op2, pt z] ArrayAccess x y -> pt x ++ paren Bracket (t y) CommentExpr str x -> t x ++ " " ++ paren SlashStar str ++ " " -- | The databeses for Haskell -> Cpp type name translations. typeRepDB:: Dyn.TypeRep -> Maybe Text typeRepDB x = msum $ map (\cand -> fst cand $ x) symbolDB -- | The databeses for Haskell -> Cpp immediate values translations. dynamicDB:: Dyn.Dynamic -> Maybe Text dynamicDB x = msum $ map (\cand -> snd cand $ x) symbolDB -- | The united database for translating Haskell types and immediate values to Cpp symbolDB:: [(Dyn.TypeRep -> Maybe Text, Dyn.Dynamic -> Maybe Text)] symbolDB = [ add "void" (\() -> ""), add "bool" (\x->if x then "true" else "false"), add "int" (showT::Int->Text), add "long long int" (showT::Integer->Text), add "float" ((++"f").showT::Float->Text), add "double" (showT::Double->Text), add "std::string" (showT::String->Text), add "std::string" (showT::Text->Text) ] where add :: (Dyn.Typeable a) => Text -> (a->Text) -> (Dyn.TypeRep -> Maybe Text, Dyn.Dynamic -> Maybe Text) add = add' undefined add' :: (Dyn.Typeable a) => a -> Text -> (a->Text) -> (Dyn.TypeRep -> Maybe Text, Dyn.Dynamic -> Maybe Text) add' dummy typename f = (\tr -> if tr == Dyn.typeOf dummy then Just typename else Nothing, fmap f . Dyn.fromDynamic) -- | an parenthesizer for lazy person. paren :: Parenthesis -> Text -> Text paren p str = prefix ++ str ++ suffix where (prefix,suffix) = case p of Paren -> ("(",")") Bracket -> ("[","]") Brace -> ("{","}") Chevron -> ("<",">") Chevron2 -> ("<<",">>") Chevron3 -> ("<<<",">>>") Quotation -> ("\'","\'") Quotation2 -> ("\"","\"") SlashStar -> ("/*","*/") joinBy :: Text -> [Text] -> Text joinBy sep xs = T.concat $ L.intersperse sep xs joinEndBy :: Text -> [Text] -> Text joinEndBy sep xs = joinBy sep xs ++ sep joinBeginEndBy :: Text -> [Text] -> Text joinBeginEndBy sep xs = sep ++ joinBy sep xs ++ sep joinBeginBy :: Text -> [Text] -> Text joinBeginBy sep xs = sep ++ joinBy sep xs
nushio3/Paraiso
Language/Paraiso/Generator/ClarisTrans.hs
bsd-3-clause
9,109
0
17
2,808
3,041
1,536
1,505
-1
-1
-- | Paragon Parser. Expressions. module Language.Java.Paragon.Parser.Expressions where import Prelude hiding (exp) import Control.Applicative ((<$>)) import Text.ParserCombinators.Parsec import Language.Java.Paragon.Annotation import Language.Java.Paragon.Lexer import Language.Java.Paragon.Syntax.Expressions hiding (clauseHead) import Language.Java.Paragon.SrcPos import Language.Java.Paragon.Parser.Names import Language.Java.Paragon.Parser.Types import Language.Java.Paragon.Parser.Symbols import Language.Java.Paragon.Parser.Helpers stmtExp :: P Exp stmtExp = assignment assignment :: P Exp assignment = do startPos <- getStartPos lhs <- assignmentLhs op <- assignmentOp e <- assignmentExp endPos <- getEndPos return $ Assign (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) lhs op e assignmentLhs :: P Lhs assignmentLhs = NameLhs <$> name expName assignmentOp :: P AssignOp assignmentOp = EqualA <$> operatorWithSpan Op_Assign exp :: P Exp exp = assignmentExp assignmentExp :: P Exp assignmentExp = Lit <$> literal <|> NameExp <$> name expOrLockName <|> PolicyExp <$> policyExp <?> "expression" literal :: P Literal literal = tokWithSpanTest $ \t sp -> let spa = srcSpanToAnn sp in case t of IntLit i -> Just $ Int spa i LongLit l -> Just $ Long spa l DoubleLit d -> Just $ Double spa d FloatLit f -> Just $ Float spa f CharLit c -> Just $ Char spa c StringLit s -> Just $ String spa s BoolLit b -> Just $ Boolean spa b NullLit -> Just $ Null spa _ -> Nothing policy :: P Policy policy = exp policyExp :: P PolicyExp policyExp = do startPos <- getStartPos cls <- braces (seplist1 clause semiColon <|> (colon >> return [])) endPos <- getEndPos return $ PolicyLit (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) cls clause :: P Clause clause = do startPos <- getStartPos clVarDs <- lopt $ parens $ seplist clauseVarDecl comma clHead <- clauseHead clAtoms <- colon >> lopt (seplist atom comma) endPos <- getEndPos -- TODO: genActorVars return $ Clause (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) clVarDs clHead clAtoms clauseVarDecl :: P ClauseVarDecl clauseVarDecl = do startPos <- getStartPos t <- refType varId <- ident endPos <- getEndPos return $ ClauseVarDecl (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) t varId clauseHead :: P ClauseHead clauseHead = try (ClauseDeclHead <$> clauseVarDecl) <|> ClauseVarHead <$> actor atom :: P Atom atom = do startPos <- getStartPos lName <- name lockName actors <- lopt $ parens $ seplist actor comma endPos <- getEndPos return $ Atom (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) lName actors -- Parse everything as actorName and post-process them into Vars. actor :: P Actor actor = Actor <$> actorName actorName :: P ActorName actorName = ActorName <$> name expName
bvdelft/paragon
src/Language/Java/Paragon/Parser/Expressions.hs
bsd-3-clause
2,935
0
14
603
895
451
444
87
9
{-#LANGUAGE MultiParamTypeClasses #-} {-#LANGUAGE OverloadedStrings #-} module Twilio.UsageRecords ( -- * Resource UsageRecords(..) , Twilio.UsageRecords.get ) where import Control.Applicative import Control.Monad.Catch import Data.Aeson import Data.Maybe import Control.Monad.Twilio import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types import Twilio.UsageRecord {- Resource -} data UsageRecords = UsageRecords { usageRecordsPagingInformation :: PagingInformation , usageRecordList :: [UsageRecord] } deriving (Show, Eq) instance List UsageRecords UsageRecord where getListWrapper = wrap (UsageRecords . fromJust) getList = usageRecordList getPlural = Const "usage_records" instance FromJSON UsageRecords where parseJSON = parseJSONToList instance Get0 UsageRecords where get0 = request parseJSONFromResponse =<< makeTwilioRequest "/Usage/Records.json" -- | Get 'UsageRecords'. get :: MonadThrow m => TwilioT m UsageRecords get = Resource.get
seagreen/twilio-haskell
src/Twilio/UsageRecords.hs
bsd-3-clause
1,024
0
9
146
210
123
87
30
1
{-# LANGUAGE FlexibleContexts #-} module Matrixbmp ( exec) where import ReadDist import System.Environment import Data.Array.Accelerate as A import Data.Array.Accelerate.IO import Data.Array.Accelerate.CUDA import Data.Array.Repa.IO.DevIL import Data.Array.Repa.Repr.ForeignPtr (F) import Data.Array.Repa as R -- | writes a metric to file as an 8-bit PNG. Metric is distance supplied in ReadDist (in our case the Hamming Distance. exec :: IO () exec = do (dim:filename:_) <- getArgs mat <- generateMatrix'' (read dim) -- mat' <- makeImage (generateMatrixCUDA (read dim)) -- runIL $ writeImage (filename Prelude.++"CUDA.png") mat' runIL $ writeImage (filename Prelude.++".png") mat -- | generates a matrix such that a_ij = (hammingDistance i j) generateMatrix' :: Int -> IO Image generateMatrix' a = mat >>= (return . Grey) where mat = (computeP $ R.fromFunction (R.Z R.:.a R.:. a) (\(R.Z R.:.m R.:.n) -> Prelude.fromIntegral (distance m n))) :: IO (R.Array F R.DIM2 Word8) generateMatrix'' :: Int -> IO Image generateMatrix'' dim = mat >>= (return . Grey) where mat = (computeP $ R.fromFunction (R.Z R.:.dim R.:. dim) (\(R.Z R.:.m R.:.n) -> Prelude.fromIntegral (hammingDistance' m n p))) :: IO (R.Array F R.DIM2 Word8) p = powers nodes nodes = Prelude.floor (logBase 2 (Prelude.fromIntegral dim)):: Int makeImage :: Acc (A.Array A.DIM2 Word8) -> IO Image makeImage mat = repamat >>= (return . Grey) where repamat = copyP (toRepa $ run mat) :: IO (R.Array F R.DIM2 Word8) generateMatrixCUDA :: Int -> Acc (A.Array A.DIM2 Word8) generateMatrixCUDA dim = fold (+) (constant 0) cube where cube = generate (index3 dim dim nodes) (\ix -> let (A.Z A.:. m A.:. n A.:. t) = unlift ix in (let p = extension A.! (index1 t) in ((m `mod` (2*p) >=* p)==*(n `mod` (2*p) >=* p)) ? (0,1))) extension = toVect (Prelude.map (2^) [0..nodes] :: [Int]) nodes = Prelude.floor (logBase 2 (Prelude.fromIntegral dim)) :: Int index3 i j k= lift (A.Z A.:. i A.:. j A.:. k)
vmchale/EMD
src/Matrixbmp.hs
bsd-3-clause
2,044
0
22
404
820
440
380
34
1
{-# LANGUAGE Rank2Types, TypeOperators, FlexibleInstances #-} module Core.Size where import Core.FreeVars import Core.Syntax import Utilities type SizedTerm = Sized (TermF Sized) type SizedFVedTerm = (Sized :.: FVed) (TermF (Sized :.: FVed)) type SizedFVedAlt = AltF (Sized :.: FVed) type SizedFVedValue = ValueF (Sized :.: FVed) type TaggedSizedFVedTerm = (Tagged :.: Sized :.: FVed) (TermF (Tagged :.: Sized :.: FVed)) type TaggedSizedFVedAlt = AltF (Tagged :.: Sized :.: FVed) type TaggedSizedFVedValue = ValueF (Tagged :.: Sized :.: FVed) (varSize', termSize, termSize', altsSize, valueSize, valueSize') = mkSize (\f (I e) -> f e) (fvedVarSize', fvedTermSize, fvedTermSize', fvedAltsSize, fvedValueSize, fvedValueSize') = mkSize (\f (FVed _ e) -> f e) (sizedVarSize', sizedTermSize, sizedTermSize', sizedAltsSize, sizedValueSize, sizedValueSize') = mkSize (\_ (Sized sz _) -> sz) (sizedFVedVarSize', sizedFVedTermSize, sizedFVedTermSize', sizedFVedAltsSize, sizedFVedValueSize, sizedFVedValueSize') = mkSize (\_ (Comp (Sized sz (FVed _ _))) -> sz) (taggedSizedFVedVarSize', taggedSizedFVedTermSize, taggedSizedFVedTermSize', taggedSizedFVedAltsSize, taggedSizedFVedValueSize, taggedSizedFVedValueSize') = mkSize (\_ (Comp (Tagged _ (Comp (Sized sz (FVed _ _))))) -> sz) {-# INLINE mkSize #-} mkSize :: (forall a. (a -> Size) -> ann a -> Size) -> (Var -> Size, ann (TermF ann) -> Size, TermF ann -> Size, [AltF ann] -> Size, ann (ValueF ann) -> Size, ValueF ann -> Size) mkSize rec = (var', term, term', alternatives, value, value') where var' = const 0 term = rec term' term' e = 1 + case e of Var x -> var' x Value v -> value' v - 1 -- Slight hack here so that we don't get +2 size on values App e x -> term e + var' x PrimOp _ es -> sum (map term es) Case e alts -> term e + alternatives alts LetRec xes e -> sum (map (term . snd) xes) + term e value = rec value' value' v = 1 + case v of Indirect _ -> 0 Lambda _ e -> term e Data _ _ -> 0 Literal _ -> 0 alternatives = sum . map alternative alternative = term . snd instance Symantics Sized where var = sizedTerm . Var value = sizedTerm . Value app e = sizedTerm . App e primOp pop = sizedTerm . PrimOp pop case_ e = sizedTerm . Case e letRec xes e = sizedTerm (LetRec xes e) sizedTerm :: TermF Sized -> SizedTerm sizedTerm e = Sized (sizedTermSize' e) e instance Symantics (Sized :.: FVed) where var = sizedFVedTerm . Var value = sizedFVedTerm . Value app e = sizedFVedTerm . App e primOp pop = sizedFVedTerm . PrimOp pop case_ e = sizedFVedTerm . Case e letRec xes e = sizedFVedTerm (LetRec xes e) sizedFVedVar :: Var -> (Sized :.: FVed) Var sizedFVedVar x = Comp (Sized (sizedFVedVarSize' x) (FVed (sizedFVedVarFreeVars' x) x)) sizedFVedValue :: SizedFVedValue -> (Sized :.: FVed) SizedFVedValue sizedFVedValue v = Comp (Sized (sizedFVedValueSize' v) (FVed (sizedFVedValueFreeVars' v) v)) sizedFVedTerm :: TermF (Sized :.: FVed) -> SizedFVedTerm sizedFVedTerm e = Comp (Sized (sizedFVedTermSize' e) (FVed (sizedFVedTermFreeVars' e) e))
batterseapower/chsc
Core/Size.hs
bsd-3-clause
3,560
0
17
1,053
1,225
635
590
65
9
module Model.Parser where import Text.ParserCombinators.ReadP import Control.Monad.IO.Class import Model.Sudoku isNumber :: Char -> Bool isNumber char = elem char ['1'..'9'] number :: ReadP Char number = satisfy isNumber digit :: ReadP Digit digit = number >>= (\i -> case charToDigit i of Just d -> return d Nothing -> pfail) charToDigit :: Char -> Maybe Digit charToDigit '1' = Just D1 charToDigit '2' = Just D2 charToDigit '3' = Just D3 charToDigit '4' = Just D4 charToDigit '5' = Just D5 charToDigit '6' = Just D6 charToDigit '7' = Just D7 charToDigit '8' = Just D8 charToDigit '9' = Just D9 charToDigit _ = Nothing sudokuParser :: ReadP [[Digit]] sudokuParser = count 9 (count 9 digit) readSudoku :: String -> [([[Digit]], String)] readSudoku = readP_to_S sudokuParser
Bratiakina/sudoku-hs
src/Model/Parser.hs
bsd-3-clause
829
0
11
181
300
154
146
27
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} -- | A simple interpreter for a subset of Ivory. module Ivory.Eval ( runEval , runEvalStartingFrom , Error , Eval , EvalState(EvalState) , Value(..) , initState , openModule , evalAssert , evalBlock , evalCond , evalDeref , evalExpr , evalInit , evalLit , evalOp , evalRequires , evalStmt ) where import Control.Applicative import Data.Maybe import qualified Prelude import Prelude hiding (negate, div, mod, not, and, or, mapM) import Data.Int import qualified Data.Map as Map import qualified Data.Sequence as Seq import Data.Traversable (mapM) import Data.Word import MonadLib.Monads hiding (mapM) import Ivory.Language.Syntax.Concrete.Location import qualified Ivory.Language.Array as I import qualified Ivory.Language.Syntax as I -- XXX: DEBUG -- import Debug.Trace type Error = String type Eval a = StateT EvalState (Exception Error) a runEval :: Eval a -> Either Error a runEval doThis = fmap fst (runEvalStartingFrom (initState Map.empty) doThis) runEvalStartingFrom :: EvalState -> Eval a -> Either Error (a, EvalState) runEvalStartingFrom st doThis = runException (runStateT st doThis) data EvalState = EvalState { store :: Map.Map I.Sym Value , loc :: SrcLoc , structs :: Map.Map I.Sym I.Struct } deriving Show initState :: Map.Map I.Sym Value -> EvalState initState st = EvalState st NoLoc Map.empty -- | Run an action inside the scope of a given module. openModule :: I.Module -> Eval a -> Eval a openModule (I.Module {..}) doThis = do oldStrs <- fmap structs get sets_ (\s -> s { structs = Map.union (structs s) newStructs }) res <- doThis sets_ (\s -> s { structs = oldStrs }) return res where newStructs = Map.fromList [ (sym, struct) | struct@(I.Struct sym _) <- I.public modStructs ++ I.private modStructs ] data Value = Sint8 Int8 | Sint16 Int16 | Sint32 Int32 | Sint64 Int64 | Uint8 Word8 | Uint16 Word16 | Uint32 Word32 | Uint64 Word64 | Float Float | Double Double | Char Char | String String | Bool Bool | Array (Seq.Seq Value) | Struct (Map.Map I.Sym Value) | Ref I.Sym deriving (Show, Eq) eq :: Value -> Value -> Value eq x y = Bool (x == y) neq :: Value -> Value -> Value neq x y = Bool (x /= y) not :: Value -> Value not (Bool x) = Bool (Prelude.not x) not x = error $ "invalid operands to `not`: " ++ show x and :: Value -> Value -> Value and (Bool x) (Bool y) = Bool (x && y) and x y = error $ "invalid operands to `and`: " ++ show (x,y) or :: Value -> Value -> Value or (Bool x) (Bool y) = Bool (x || y) or x y = error $ "invalid operors to `or`: " ++ show (x,y) ordOp :: (forall a. Ord a => a -> a -> Bool) -> Value -> Value -> Value ordOp op (Sint8 x) (Sint8 y) = Bool (op x y) ordOp op (Sint16 x) (Sint16 y) = Bool (op x y) ordOp op (Sint32 x) (Sint32 y) = Bool (op x y) ordOp op (Sint64 x) (Sint64 y) = Bool (op x y) ordOp op (Uint8 x) (Uint8 y) = Bool (op x y) ordOp op (Uint16 x) (Uint16 y) = Bool (op x y) ordOp op (Uint32 x) (Uint32 y) = Bool (op x y) ordOp op (Uint64 x) (Uint64 y) = Bool (op x y) ordOp op (Float x) (Float y) = Bool (op x y) ordOp op (Double x) (Double y) = Bool (op x y) ordOp op (Char x) (Char y) = Bool (op x y) ordOp _ x y = error $ "invalid operands to `ordOp`: " ++ show (x,y) gt :: Value -> Value -> Value gt = ordOp (>) gte :: Value -> Value -> Value gte = ordOp (>=) lt :: Value -> Value -> Value lt = ordOp (<) lte :: Value -> Value -> Value lte = ordOp (<=) numUnOp :: (forall a. Num a => a -> a) -> Value -> Value numUnOp op (Sint8 x) = Sint8 (op x) numUnOp op (Sint16 x) = Sint16 (op x) numUnOp op (Sint32 x) = Sint32 (op x) numUnOp op (Sint64 x) = Sint64 (op x) numUnOp op (Uint8 x) = Uint8 (op x) numUnOp op (Uint16 x) = Uint16 (op x) numUnOp op (Uint32 x) = Uint32 (op x) numUnOp op (Uint64 x) = Uint64 (op x) numUnOp op (Float x) = Float (op x) numUnOp op (Double x) = Double (op x) numUnOp _ x = error $ "invalid operands to `numUnOp`: " ++ show x negate :: Value -> Value negate = numUnOp Prelude.negate numBinOp :: (forall a. Num a => a -> a -> a) -> Value -> Value -> Value numBinOp op (Sint8 x) (Sint8 y) = Sint8 (op x y) numBinOp op (Sint16 x) (Sint16 y) = Sint16 (op x y) numBinOp op (Sint32 x) (Sint32 y) = Sint32 (op x y) numBinOp op (Sint64 x) (Sint64 y) = Sint64 (op x y) numBinOp op (Uint8 x) (Uint8 y) = Uint8 (op x y) numBinOp op (Uint16 x) (Uint16 y) = Uint16 (op x y) numBinOp op (Uint32 x) (Uint32 y) = Uint32 (op x y) numBinOp op (Uint64 x) (Uint64 y) = Uint64 (op x y) numBinOp op (Float x) (Float y) = Float (op x y) numBinOp op (Double x) (Double y) = Double (op x y) numBinOp _ x y = error $ "invalid operands to `numBinOp`: " ++ show (x,y) add :: Value -> Value -> Value add = numBinOp (+) sub :: Value -> Value -> Value sub = numBinOp (-) mul :: Value -> Value -> Value mul = numBinOp (*) div :: Value -> Value -> Value (Sint8 x) `div` (Sint8 y) = Sint8 (x `Prelude.div` y) (Sint16 x) `div` (Sint16 y) = Sint16 (x `Prelude.div` y) (Sint32 x) `div` (Sint32 y) = Sint32 (x `Prelude.div` y) (Sint64 x) `div` (Sint64 y) = Sint64 (x `Prelude.div` y) (Uint8 x) `div` (Uint8 y) = Uint8 (x `Prelude.div` y) (Uint16 x) `div` (Uint16 y) = Uint16 (x `Prelude.div` y) (Uint32 x) `div` (Uint32 y) = Uint32 (x `Prelude.div` y) (Uint64 x) `div` (Uint64 y) = Uint64 (x `Prelude.div` y) (Float x) `div` (Float y) = Float (x / y) (Double x) `div` (Double y) = Double (x / y) x `div` y = error $ "invalid operands to `div`: " ++ show (x,y) mod :: Value -> Value -> Value (Sint8 x) `mod` (Sint8 y) = Sint8 (x `Prelude.mod` y) (Sint16 x) `mod` (Sint16 y) = Sint16 (x `Prelude.mod` y) (Sint32 x) `mod` (Sint32 y) = Sint32 (x `Prelude.mod` y) (Sint64 x) `mod` (Sint64 y) = Sint64 (x `Prelude.mod` y) (Uint8 x) `mod` (Uint8 y) = Uint8 (x `Prelude.mod` y) (Uint16 x) `mod` (Uint16 y) = Uint16 (x `Prelude.mod` y) (Uint32 x) `mod` (Uint32 y) = Uint32 (x `Prelude.mod` y) (Uint64 x) `mod` (Uint64 y) = Uint64 (x `Prelude.mod` y) -- (Float x) `mod` (Float y) = Float (x `Prelude.mod` y) -- (Double x) `mod` (Double y) = Double (x `Prelude.mod` y) x `mod` y = error $ "invalid operands to `mod`: " ++ show (x,y) readStore :: I.Sym -> Eval Value readStore sym = do st <- fmap store get case Map.lookup sym st of Nothing -> raise $ "Unbound variable: `" ++ sym ++ "'!" Just v -> return v writeStore :: I.Sym -> Value -> Eval () writeStore sym val = sets_ (\s -> s { store = Map.insert sym val (store s) }) modifyStore :: I.Sym -> (Value -> Value) -> Eval () modifyStore sym f = sets_ (\s -> s { store = Map.update (Just . f) sym (store s) }) updateLoc :: SrcLoc -> Eval () updateLoc loc = sets_ (\ s -> s { loc = loc }) lookupStruct :: String -> Eval I.Struct lookupStruct str = do structs <- fmap structs get case Map.lookup str structs of Nothing -> raise $ "Couldn't find struct: " ++ str Just str -> return str ---------------------------------------------------------------------- -- | Main Evaluator ---------------------------------------------------------------------- evalBlock :: I.Block -> Eval () evalBlock = mapM_ evalStmt evalRequires :: [I.Require] -> Eval Bool evalRequires = fmap Prelude.and . mapM (evalCond . I.getRequire) evalCond :: I.Cond -> Eval Bool evalCond cond = case cond of I.CondBool expr -> do val <- evalExpr I.TyBool expr case val of Bool True -> return True Bool False -> return False _ -> raise $ "evalCond: expected boolean, got: " ++ show val I.CondDeref ty expr var cond -> do evalStmt (I.Deref ty var expr) evalCond cond evalStmt :: I.Stmt -> Eval () evalStmt stmt = case stmt of I.Comment (I.SourcePos loc) -> updateLoc loc I.Assert expr -> evalAssert expr I.CompilerAssert expr -> evalAssert expr I.IfTE cond true false -> do b <- evalExpr I.TyBool cond case b of Bool True -> evalBlock true Bool False -> evalBlock false _ -> raise $ "evalStmt: IfTE: expected true or false, got: " ++ show b I.Deref _ty var expr -> do val <- evalDeref _ty expr case val of Ref ref -> do val <- readStore ref writeStore (varSym var) val _ -> writeStore (varSym var) val I.Assign _ty var expr -> do val <- evalExpr _ty expr writeStore (varSym var) val I.Local ty var init -> do val <- evalInit ty init writeStore (varSym var) val I.AllocRef _ty var ref -> writeStore (varSym var) (Ref $ nameSym ref) I.Loop var expr incr body -> do val <- evalExpr I.ixRep expr writeStore (varSym var) val let (stepFn, doneExpr) = case incr of I.IncrTo expr -> ((`add` Sint32 1), expr) -- XXX: don't hard-code ixrep I.DecrTo expr -> ((`sub` Sint32 1), expr) let step = modifyStore (varSym var) stepFn let done = do curVal <- readStore (varSym var) doneVal <- evalExpr I.ixRep doneExpr return (curVal == doneVal) untilM done (evalBlock body >> step) I.Return (I.Typed _ty expr) -> void $ evalExpr _ty expr I.Store _ty (I.ExpAddrOfGlobal dst) expr -> do val <- evalExpr _ty expr writeStore dst val I.Store _ty (I.ExpVar dst) expr -> do val <- evalExpr _ty expr Ref ref <- readStore (varSym dst) writeStore ref val I.RefCopy _ty (I.ExpAddrOfGlobal dst) expr -> do val <- evalExpr _ty expr writeStore dst val _ -> error $ show stmt evalDeref :: I.Type -> I.Expr -> Eval Value evalDeref _ty expr = case expr of I.ExpSym sym -> readRef sym I.ExpVar var -> readRef (varSym var) I.ExpAddrOfGlobal sym -> readStore sym I.ExpIndex tarr arr tidx idx -> do Array arr <- evalDeref tarr arr Sint32 idx <- evalExpr tidx idx return (arr `Seq.index` fromIntegral idx) I.ExpLabel tstr str lab -> do Struct str <- evalDeref tstr str return (fromJust $ Map.lookup lab str) _ -> error $ show expr readRef :: I.Sym -> Eval Value readRef sym = do val <- readStore sym case val of Ref ref -> readStore ref _ -> raise $ "Expected Ref, got: " ++ show val evalAssert :: I.Expr -> Eval () evalAssert asrt = do b <- evalExpr I.TyBool asrt case b of Bool True -> return () _ -> raise $ "Assertion failed: " ++ show (b,asrt) evalExpr :: I.Type -> I.Expr -> Eval Value evalExpr ty expr = case expr of I.ExpSym sym -> readStore sym I.ExpVar var -> readStore (varSym var) I.ExpLit lit -> evalLit ty lit I.ExpOp op exprs -> do let opTy = case op of I.ExpEq t -> t I.ExpNeq t -> t I.ExpGt _ t -> t I.ExpLt _ t -> t I.ExpIsNan t -> t I.ExpIsInf t -> t _ -> ty vals <- mapM (evalExpr opTy) exprs evalOp op vals I.ExpSafeCast fromTy expr -> do val <- evalExpr fromTy expr return (cast ty fromTy val) I.ExpToIx expr max -> fmap (`mod` Sint32 (fromInteger max)) (evalExpr I.ixRep expr) _ -> error $ show expr cast :: I.Type -> I.Type -> Value -> Value cast toTy _fromTy val = mkVal toTy integer where integer = case val of Sint8 i -> toInteger i Sint16 i -> toInteger i Sint32 i -> toInteger i Sint64 i -> toInteger i Uint8 i -> toInteger i Uint16 i -> toInteger i Uint32 i -> toInteger i Uint64 i -> toInteger i _ -> error $ "Expected number, got: " ++ show val evalLit :: I.Type -> I.Literal -> Eval Value evalLit ty lit = case lit of I.LitInteger i -> return (mkVal ty i) I.LitFloat c -> return (Float c) I.LitDouble c -> return (Double c) I.LitChar c -> return (Char c) I.LitBool b -> return (Bool b) I.LitString s -> return (String s) _ -> raise $ "evalLit: can't handle: " ++ show lit mkVal :: I.Type -> Integer -> Value mkVal ty = case ty of I.TyInt I.Int8 -> Sint8 . fromInteger I.TyInt I.Int16 -> Sint16 . fromInteger I.TyInt I.Int32 -> Sint32 . fromInteger I.TyInt I.Int64 -> Sint64 . fromInteger I.TyWord I.Word8 -> Uint8 . fromInteger I.TyWord I.Word16 -> Uint16 . fromInteger I.TyWord I.Word32 -> Uint32 . fromInteger I.TyWord I.Word64 -> Uint64 . fromInteger I.TyIndex _ -> Sint32 . fromInteger -- XXX: don't hard-code index rep I.TyFloat -> Float . fromInteger I.TyDouble -> Double . fromInteger I.TyBool -> Bool . toEnum . fromInteger I.TyChar -> Char . toEnum . fromInteger _ -> error $ "mkVal: " ++ show ty evalOp :: I.ExpOp -> [Value] -> Eval Value evalOp (I.ExpEq _) [x, y] = return (x `eq` y) evalOp (I.ExpNeq _) [x, y] = return (x `neq` y) evalOp (I.ExpGt True _) [x, y] = return (x `gte` y) evalOp (I.ExpGt False _) [x, y] = return (x `gt` y) evalOp (I.ExpLt True _) [x, y] = return (x `lte` y) evalOp (I.ExpLt False _) [x, y] = return (x `lt` y) evalOp I.ExpAdd [x, y] = return (x `add` y) evalOp I.ExpSub [x, y] = return (x `sub` y) evalOp I.ExpMul [x, y] = return (x `mul` y) evalOp I.ExpDiv [x, y] = return (x `div` y) evalOp I.ExpMod [x, y] = return (x `mod` y) evalOp I.ExpNegate [x] = return (negate x) evalOp I.ExpNot [x] = return (not x) evalOp I.ExpAnd [x, y] = return (x `and` y) evalOp I.ExpOr [x, y] = return (x `or` y) evalOp I.ExpCond [cond, true, false] = case cond of Bool True -> return true Bool False -> return false _ -> raise $ "evalOp: ExpCond: expected true or false, got: " ++ show cond evalOp op args = raise $ "evalOp: can't handle: " ++ show (op, args) evalInit :: I.Type -> I.Init -> Eval Value evalInit ty init = case init of I.InitZero -> case ty of I.TyArr _ _ -> evalInit ty (I.InitArray []) I.TyStruct _ -> evalInit ty (I.InitStruct []) _ -> return (mkVal ty 0) I.InitExpr ty expr -> evalExpr ty expr I.InitArray inits -> case ty of I.TyArr len ty -> Array . Seq.fromList <$> mapM (evalInit ty) (take len $ inits ++ repeat I.InitZero) _ -> raise $ "evalInit: InitArray: unexpected type: " ++ show ty I.InitStruct inits -> case ty of I.TyStruct str -> do I.Struct _ fields <- lookupStruct str zstr <- foldM (\ str (I.Typed ty fld) -> do val <- evalInit ty I.InitZero return (Map.insert fld val str)) Map.empty fields str <- foldM (\ str (fld, init) -> do val <- evalInit (lookupTyped fld fields) init return (Map.insert fld val str)) zstr inits return $ Struct str _ -> raise $ "evalInit: InitStruct: unexpected type: " ++ show ty lookupTyped :: (Show a, Eq a) => a -> [I.Typed a] -> I.Type lookupTyped a [] = error $ "lookupTyped: couldn't find: " ++ show a lookupTyped a (I.Typed t x : xs) | a == x = t | otherwise = lookupTyped a xs varSym :: I.Var -> I.Sym varSym (I.VarName sym) = sym varSym (I.VarInternal sym) = sym varSym (I.VarLitName sym) = sym nameSym :: I.Name -> I.Sym nameSym (I.NameSym sym) = sym nameSym (I.NameVar var) = varSym var ---------------------------------------------------------------------- -- | Utilities ---------------------------------------------------------------------- untilM :: Monad m => m Bool -> m () -> m () untilM done doThis = do b <- done unless b (doThis >> untilM done doThis)
Hodapp87/ivory
ivory-eval/src/Ivory/Eval.hs
bsd-3-clause
16,177
0
22
4,637
6,966
3,489
3,477
404
18
{-# LANGUAGE QuasiQuotes #-} -- | This module defines a generator for @getopt_long@ based command -- line argument parsing. Each option is associated with arbitrary C -- code that will perform side effects, usually by setting some global -- variables. module Futhark.CodeGen.Backends.GenericC.Options ( Option (..) , OptionArgument (..) , generateOptionParser ) where import Data.Maybe import qualified Language.C.Syntax as C import qualified Language.C.Quote.C as C -- | Specification if a single command line option. The option must -- have a long name, and may also have a short name. -- -- In the action, the option argument (if any) is stored as in the -- @char*@-typed variable @optarg@. data Option = Option { optionLongName :: String , optionShortName :: Maybe Char , optionArgument :: OptionArgument , optionAction :: C.Stm } -- | Whether an option accepts an argument. data OptionArgument = NoArgument | RequiredArgument | OptionalArgument -- | Generate an option parser as a function of the given name, that -- accepts the given command line options. The result is a function -- that should be called with @argc@ and @argv@. The function returns -- the number of @argv@ elements that have been processed. -- -- If option parsing fails for any reason, the entire process will -- terminate with error code 1. generateOptionParser :: String -> [Option] -> C.Func generateOptionParser fname options = [C.cfun|int $id:fname(int argc, char* const argv[]) { int $id:chosen_option; static struct option long_options[] = { $inits:option_fields, {0, 0, 0, 0} }; while (($id:chosen_option = getopt_long(argc, argv, $string:option_string, long_options, NULL)) != -1) { $stms:option_applications if ($id:chosen_option == ':') { panic(-1, "Missing argument for option %s", argv[optind-1]); } if ($id:chosen_option == '?') { panic(-1, "Unknown option %s", argv[optind-1]); } } return optind; } |] where chosen_option = "ch" option_string = ':' : optionString options option_applications = optionApplications chosen_option options option_fields = optionFields options optionFields :: [Option] -> [C.Initializer] optionFields = zipWith field [(1::Int)..] where field i option = [C.cinit| { $string:(optionLongName option), $id:arg, NULL, $int:i } |] where arg = case optionArgument option of NoArgument -> "no_argument" RequiredArgument -> "required_argument" OptionalArgument -> "optional_argument" optionApplications :: String -> [Option] -> [C.Stm] optionApplications chosen_option = zipWith check [(1::Int)..] where check i option = [C.cstm|if ($exp:cond) $stm:(optionAction option)|] where cond = case optionShortName option of Nothing -> [C.cexp|$id:chosen_option == $int:i|] Just c -> [C.cexp|($id:chosen_option == $int:i) || ($id:chosen_option == $char:c)|] optionString :: [Option] -> String optionString = concat . mapMaybe optionStringChunk where optionStringChunk option = do short <- optionShortName option return $ short : case optionArgument option of NoArgument -> "" RequiredArgument -> ":" OptionalArgument -> "::"
mrakgr/futhark
src/Futhark/CodeGen/Backends/GenericC/Options.hs
bsd-3-clause
3,659
0
12
1,057
460
272
188
46
3
module VSimR.Ptr where import Control.Monad.Trans import Data.IORef import System.IO import System.IO.Unsafe type Ptr x = IORef x alloc :: (MonadIO m) => a -> m (Ptr a) alloc a = liftIO $ newIORef a write :: (MonadIO m) => Ptr a -> a -> m () write ptr a = liftIO $ writeIORef ptr a deref :: (MonadIO m) => Ptr a -> m a deref ptr = liftIO $ readIORef ptr -- modify :: (MonadIO m) => (a->a) -> Ptr a -> m () -- modify f ptr = read ptr >>= write . f instance (Show x) => Show (IORef x) where show x = "@" ++ show (unsafePerformIO $ deref x)
ierton/vsim
src/VSimR/Ptr.hs
bsd-3-clause
576
0
10
152
218
114
104
14
1
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-} {-# OPTIONS_GHC -fcontext-stack49 #-} module Games.Chaos2010.Database.Views where import Games.Chaos2010.Database.Fields import Database.HaskellDB.DBLayout type Views = Record (HCons (LVPair Table_catalog (Expr (Maybe String))) (HCons (LVPair View_name (Expr (Maybe String))) (HCons (LVPair Definition (Expr (Maybe String))) (HCons (LVPair Table_schema (Expr (Maybe String))) (HCons (LVPair Table_name (Expr (Maybe String))) (HCons (LVPair View_definition (Expr (Maybe String))) (HCons (LVPair Check_option (Expr (Maybe String))) (HCons (LVPair Is_updatable (Expr (Maybe String))) (HCons (LVPair Is_insertable_into (Expr (Maybe String))) HNil))))))))) views :: Table Views views = baseTable "views"
JakeWheat/Chaos-2010
Games/Chaos2010/Database/Views.hs
bsd-3-clause
967
0
29
297
300
156
144
19
1
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} module Fragnix.Declaration ( Declaration(..) , Genre(..) , writeDeclarations ) where import Language.Haskell.Exts ( ModuleName(ModuleName),prettyPrint,Extension) import Language.Haskell.Names ( Symbol) import Data.Aeson ( ToJSON(toJSON),object,(.=), FromJSON(parseJSON),withObject,(.:)) import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.ByteString.Lazy as ByteString (writeFile) import Data.Text (Text) import System.Directory (createDirectoryIfMissing) import System.FilePath (dropFileName) import GHC.Generics (Generic) data Declaration = Declaration Genre [Extension] DeclarationAST DeclaredSymbols MentionedSymbols deriving (Show,Eq,Ord,Generic) data Genre = Value | TypeSignature | Type | TypeClass | TypeClassInstance | InfixFixity | DerivingInstance | FamilyInstance | ForeignImport | Other deriving (Show,Eq,Ord,Read,Generic) type DeclarationAST = Text type DeclaredSymbols = [Symbol] type MentionedSymbols = [(Symbol, Maybe (ModuleName ()))] -- readDeclarations :: FilePath -> IO [Declaration] -- readDeclarations declarationspath = do -- declarationsfile <- ByteString.readFile declarationspath -- return (fromMaybe (error "Failed to parse declarations") (decode declarationsfile)) writeDeclarations :: FilePath -> [Declaration] -> IO () writeDeclarations declarationspath declarations = do createDirectoryIfMissing True (dropFileName declarationspath) ByteString.writeFile declarationspath (encodePretty declarations) instance ToJSON Declaration where toJSON (Declaration declarationgenre extensions declarationast declaredsymbols mentionedsymbols) = object [ "declarationgenre" .= show declarationgenre, "declarationextensions" .= map show extensions, "declarationast" .= declarationast, "declaredsymbols" .= declaredsymbols, "mentionedsymbols" .= fmap (fmap (fmap prettyPrint)) mentionedsymbols] instance FromJSON Declaration where parseJSON = withObject "declaration object" (\o -> do declarationgenre <- fmap read (o .: "declarationgenre") declarationextensions <- fmap (map read) (o .: "declarationextensions") declarationast <- o .: "declarationast" declaredsymbols <- o .: "declaredsymbols" mentionedsymbols <- fmap (fmap (fmap (fmap (ModuleName ())))) (o .: "mentionedsymbols") return (Declaration declarationgenre declarationextensions declarationast declaredsymbols mentionedsymbols))
phischu/fragnix
src/Fragnix/Declaration.hs
bsd-3-clause
2,573
0
21
436
613
343
270
54
1
module Kite.Test.Lexer (lexerTests) where import Test.Tasty import Test.Tasty.HUnit import Kite.Test.Exception import Kite.Lexer lexerTests = testGroup "Lexer" [ testCase "Integer" $ alexScanTokens "1" @?= [ TInteger (AlexPn 0 1 1) 1 ] , testCase "Float" $ alexScanTokens "1.0" @?= [ TFloat (AlexPn 0 1 1) 1.0 ] , testCase "String" $ alexScanTokens "\"swag\"" @?= [ TString (AlexPn 0 1 1) "swag" ] , testCase "Symbol" $ alexScanTokens "(1)" @?= [ TSymbol (AlexPn 0 1 1) '(' , TInteger (AlexPn 1 1 2) 1 , TSymbol (AlexPn 2 1 3) ')' ] , testCase "Keyword return" $ alexScanTokens "return foo" @?= [ TKeyword (AlexPn 0 1 1) "return" , TIdentifier (AlexPn 7 1 8) "foo" ] , testCase "Function" $ alexScanTokens "(Int) -> Float" @?= [ TSymbol (AlexPn 0 1 1) '(' , TType (AlexPn 1 1 2) "Int" , TSymbol (AlexPn 4 1 5) ')' , TOperator (AlexPn 6 1 7) "->" , TType (AlexPn 9 1 10) "Float" ] , testCase "Comment infix" $ alexScanTokens "2 {- -}; foo" @?= [ TInteger (AlexPn 0 1 1) 2 , TSymbol (AlexPn 7 1 8) ';' , TIdentifier (AlexPn 9 1 10) "foo" ] , testCase "Comment block" $ alexScanTokens "{- \ \test\ \ more test-}" @?= [] , testCase "Comment suffix" $ alexScanTokens "1337 -- a comment \n\ \ 42" @?= [ TInteger (AlexPn 0 1 1) 1337 , TInteger (AlexPn 20 2 2) 42 ] ]
kite-lang/kite
tests/Kite/Test/Lexer.hs
mit
1,793
0
11
769
523
262
261
37
1
module Oden.Output.Parser where import qualified Data.Set as Set import Text.PrettyPrint.Leijen import Text.Parsec hiding (unexpected) import Text.Parsec.Error import Oden.Output as Output import Oden.SourceInfo type ExpectedParts = Set.Set String type UnexpectedPart = Maybe String data CondensedMessage = CondensedMessage ExpectedParts UnexpectedPart condense :: ParseError -> CondensedMessage condense e = foldl iter (CondensedMessage Set.empty Nothing) (errorMessages e) where iter (CondensedMessage ex _) (SysUnExpect s) = CondensedMessage ex (Just s) iter (CondensedMessage ex _) (UnExpect s) = CondensedMessage ex (Just s) iter c@(CondensedMessage ex u) (Expect s) | s == "" = c | otherwise = CondensedMessage (Set.insert s ex) u iter c _ = c commaOr :: [String] -> Doc commaOr [] = empty commaOr [x] = text x commaOr xs = hcat (punctuate (text ", ") (map text (init xs))) <+> text "or" <+> text (last xs) errorSourceInfo :: ParseError -> SourceInfo errorSourceInfo e = let pos = errorPos e in SourceInfo (Position (sourceName pos) (sourceLine pos) (sourceColumn pos)) instance OdenOutput ParseError where outputType _ = Output.Error name _ = "Parser.ParseError" header e _ = case condense e of (CondensedMessage ex Nothing) -> text "Expected" <+> hcat (punctuate (text ", ") (map text (Set.toList ex))) (CondensedMessage ex (Just unEx)) -> text "Expected" <+> commaOr (Set.toList ex) <+> text "but got:" <+> text unEx details _ _ = empty sourceInfo e = Just (errorSourceInfo e)
AlbinTheander/oden
src/Oden/Output/Parser.hs
mit
1,645
0
17
380
597
301
296
43
4
{-# LANGUAGE DeriveDataTypeable #-} {- Copyright (C) 2006-2010 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Shared Copyright : Copyright (C) 2006-2010 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Utility functions and definitions used by the various Pandoc modules. -} module Text.Pandoc.Shared ( -- * List processing splitBy, splitByIndices, substitute, -- * Text processing backslashEscapes, escapeStringUsing, stripTrailingNewlines, removeLeadingTrailingSpace, removeLeadingSpace, removeTrailingSpace, stripFirstAndLast, camelCaseToHyphenated, toRomanNumeral, escapeURI, unescapeURI, tabFilter, -- * Pandoc block and inline list processing orderedListMarkers, normalizeSpaces, normalize, stringify, compactify, Element (..), hierarchicalize, uniqueIdent, isHeaderBlock, headerShift, -- * Writer options HTMLMathMethod (..), CiteMethod (..), ObfuscationMethod (..), HTMLSlideVariant (..), WriterOptions (..), defaultWriterOptions, -- * File handling inDirectory, findDataFile, readDataFile, ) where import Text.Pandoc.Definition import Text.Pandoc.Generic import qualified Text.Pandoc.UTF8 as UTF8 (readFile) import Data.Char ( toLower, isLower, isUpper, isAlpha, isAscii, isLetter, isDigit ) import Data.List ( find, isPrefixOf, intercalate ) import Network.URI ( isAllowedInURI, escapeURIString, unEscapeString ) import Codec.Binary.UTF8.String ( encodeString, decodeString ) import System.Directory import System.FilePath ( (</>) ) import Data.Generics (Typeable, Data) import qualified Control.Monad.State as S import Paths_pandoc (getDataFileName) -- -- List processing -- -- | Split list by groups of one or more sep. splitBy :: (a -> Bool) -> [a] -> [[a]] splitBy _ [] = [] splitBy isSep lst = let (first, rest) = break isSep lst rest' = dropWhile isSep rest in first:(splitBy isSep rest') -- | Split list into chunks divided at specified indices. splitByIndices :: [Int] -> [a] -> [[a]] splitByIndices [] lst = [lst] splitByIndices (x:xs) lst = let (first, rest) = splitAt x lst in first:(splitByIndices (map (\y -> y - x) xs) rest) -- | Replace each occurrence of one sublist in a list with another. substitute :: (Eq a) => [a] -> [a] -> [a] -> [a] substitute _ _ [] = [] substitute [] _ xs = xs substitute target replacement lst@(x:xs) = if target `isPrefixOf` lst then replacement ++ substitute target replacement (drop (length target) lst) else x : substitute target replacement xs -- -- Text processing -- -- | Returns an association list of backslash escapes for the -- designated characters. backslashEscapes :: [Char] -- ^ list of special characters to escape -> [(Char, String)] backslashEscapes = map (\ch -> (ch, ['\\',ch])) -- | Escape a string of characters, using an association list of -- characters and strings. escapeStringUsing :: [(Char, String)] -> String -> String escapeStringUsing _ [] = "" escapeStringUsing escapeTable (x:xs) = case (lookup x escapeTable) of Just str -> str ++ rest Nothing -> x:rest where rest = escapeStringUsing escapeTable xs -- | Strip trailing newlines from string. stripTrailingNewlines :: String -> String stripTrailingNewlines = reverse . dropWhile (== '\n') . reverse -- | Remove leading and trailing space (including newlines) from string. removeLeadingTrailingSpace :: String -> String removeLeadingTrailingSpace = removeLeadingSpace . removeTrailingSpace -- | Remove leading space (including newlines) from string. removeLeadingSpace :: String -> String removeLeadingSpace = dropWhile (`elem` " \n\t") -- | Remove trailing space (including newlines) from string. removeTrailingSpace :: String -> String removeTrailingSpace = reverse . removeLeadingSpace . reverse -- | Strip leading and trailing characters from string stripFirstAndLast :: String -> String stripFirstAndLast str = drop 1 $ take ((length str) - 1) str -- | Change CamelCase word to hyphenated lowercase (e.g., camel-case). camelCaseToHyphenated :: String -> String camelCaseToHyphenated [] = "" camelCaseToHyphenated (a:b:rest) | isLower a && isUpper b = a:'-':(toLower b):(camelCaseToHyphenated rest) camelCaseToHyphenated (a:rest) = (toLower a):(camelCaseToHyphenated rest) -- | Convert number < 4000 to uppercase roman numeral. toRomanNumeral :: Int -> String toRomanNumeral x = if x >= 4000 || x < 0 then "?" else case x of _ | x >= 1000 -> "M" ++ toRomanNumeral (x - 1000) _ | x >= 900 -> "CM" ++ toRomanNumeral (x - 900) _ | x >= 500 -> "D" ++ toRomanNumeral (x - 500) _ | x >= 400 -> "CD" ++ toRomanNumeral (x - 400) _ | x >= 100 -> "C" ++ toRomanNumeral (x - 100) _ | x >= 90 -> "XC" ++ toRomanNumeral (x - 90) _ | x >= 50 -> "L" ++ toRomanNumeral (x - 50) _ | x >= 40 -> "XL" ++ toRomanNumeral (x - 40) _ | x >= 10 -> "X" ++ toRomanNumeral (x - 10) _ | x >= 9 -> "IX" ++ toRomanNumeral (x - 5) _ | x >= 5 -> "V" ++ toRomanNumeral (x - 5) _ | x >= 4 -> "IV" ++ toRomanNumeral (x - 4) _ | x >= 1 -> "I" ++ toRomanNumeral (x - 1) _ -> "" -- | Escape unicode characters in a URI. Characters that are -- already valid in a URI, including % and ?, are left alone. escapeURI :: String -> String escapeURI = escapeURIString isAllowedInURI . encodeString -- | Unescape unicode and some special characters in a URI, but -- without introducing spaces. unescapeURI :: String -> String unescapeURI = escapeURIString (\c -> isAllowedInURI c || not (isAscii c)) . decodeString . unEscapeString -- | Convert tabs to spaces and filter out DOS line endings. -- Tabs will be preserved if tab stop is set to 0. tabFilter :: Int -- ^ Tab stop -> String -- ^ Input -> String tabFilter tabStop = let go _ [] = "" go _ ('\n':xs) = '\n' : go tabStop xs go _ ('\r':'\n':xs) = '\n' : go tabStop xs go _ ('\r':xs) = '\n' : go tabStop xs go spsToNextStop ('\t':xs) = if tabStop == 0 then '\t' : go tabStop xs else replicate spsToNextStop ' ' ++ go tabStop xs go 1 (x:xs) = x : go tabStop xs go spsToNextStop (x:xs) = x : go (spsToNextStop - 1) xs in go tabStop -- -- Pandoc block and inline list processing -- -- | Generate infinite lazy list of markers for an ordered list, -- depending on list attributes. orderedListMarkers :: (Int, ListNumberStyle, ListNumberDelim) -> [String] orderedListMarkers (start, numstyle, numdelim) = let singleton c = [c] nums = case numstyle of DefaultStyle -> map show [start..] Example -> map show [start..] Decimal -> map show [start..] UpperAlpha -> drop (start - 1) $ cycle $ map singleton ['A'..'Z'] LowerAlpha -> drop (start - 1) $ cycle $ map singleton ['a'..'z'] UpperRoman -> map toRomanNumeral [start..] LowerRoman -> map (map toLower . toRomanNumeral) [start..] inDelim str = case numdelim of DefaultDelim -> str ++ "." Period -> str ++ "." OneParen -> str ++ ")" TwoParens -> "(" ++ str ++ ")" in map inDelim nums -- | Normalize a list of inline elements: remove leading and trailing -- @Space@ elements, collapse double @Space@s into singles, and -- remove empty Str elements. normalizeSpaces :: [Inline] -> [Inline] normalizeSpaces = cleanup . dropWhile isSpaceOrEmpty where cleanup [] = [] cleanup (Space:rest) = let rest' = dropWhile isSpaceOrEmpty rest in case rest' of [] -> [] _ -> Space : cleanup rest' cleanup ((Str ""):rest) = cleanup rest cleanup (x:rest) = x : cleanup rest isSpaceOrEmpty :: Inline -> Bool isSpaceOrEmpty Space = True isSpaceOrEmpty (Str "") = True isSpaceOrEmpty _ = False -- | Normalize @Pandoc@ document, consolidating doubled 'Space's, -- combining adjacent 'Str's and 'Emph's, remove 'Null's and -- empty elements, etc. normalize :: (Eq a, Data a) => a -> a normalize = topDown removeEmptyBlocks . topDown consolidateInlines . bottomUp (removeEmptyInlines . removeTrailingInlineSpaces) removeEmptyBlocks :: [Block] -> [Block] removeEmptyBlocks (Null : xs) = removeEmptyBlocks xs removeEmptyBlocks (BulletList [] : xs) = removeEmptyBlocks xs removeEmptyBlocks (OrderedList _ [] : xs) = removeEmptyBlocks xs removeEmptyBlocks (DefinitionList [] : xs) = removeEmptyBlocks xs removeEmptyBlocks (RawBlock _ [] : xs) = removeEmptyBlocks xs removeEmptyBlocks (x:xs) = x : removeEmptyBlocks xs removeEmptyBlocks [] = [] removeEmptyInlines :: [Inline] -> [Inline] removeEmptyInlines (Emph [] : zs) = removeEmptyInlines zs removeEmptyInlines (Strong [] : zs) = removeEmptyInlines zs removeEmptyInlines (Subscript [] : zs) = removeEmptyInlines zs removeEmptyInlines (Superscript [] : zs) = removeEmptyInlines zs removeEmptyInlines (SmallCaps [] : zs) = removeEmptyInlines zs removeEmptyInlines (Strikeout [] : zs) = removeEmptyInlines zs removeEmptyInlines (RawInline _ [] : zs) = removeEmptyInlines zs removeEmptyInlines (Code _ [] : zs) = removeEmptyInlines zs removeEmptyInlines (Str "" : zs) = removeEmptyInlines zs removeEmptyInlines (x : xs) = x : removeEmptyInlines xs removeEmptyInlines [] = [] removeTrailingInlineSpaces :: [Inline] -> [Inline] removeTrailingInlineSpaces = reverse . removeLeadingInlineSpaces . reverse removeLeadingInlineSpaces :: [Inline] -> [Inline] removeLeadingInlineSpaces = dropWhile isSpaceOrEmpty consolidateInlines :: [Inline] -> [Inline] consolidateInlines (Str x : ys) = case concat (x : map fromStr strs) of "" -> consolidateInlines rest n -> Str n : consolidateInlines rest where (strs, rest) = span isStr ys isStr (Str _) = True isStr _ = False fromStr (Str z) = z fromStr _ = error "consolidateInlines - fromStr - not a Str" consolidateInlines (Space : ys) = Space : rest where isSpace Space = True isSpace _ = False rest = consolidateInlines $ dropWhile isSpace ys consolidateInlines (Emph xs : Emph ys : zs) = consolidateInlines $ Emph (xs ++ ys) : zs consolidateInlines (Strong xs : Strong ys : zs) = consolidateInlines $ Strong (xs ++ ys) : zs consolidateInlines (Subscript xs : Subscript ys : zs) = consolidateInlines $ Subscript (xs ++ ys) : zs consolidateInlines (Superscript xs : Superscript ys : zs) = consolidateInlines $ Superscript (xs ++ ys) : zs consolidateInlines (SmallCaps xs : SmallCaps ys : zs) = consolidateInlines $ SmallCaps (xs ++ ys) : zs consolidateInlines (Strikeout xs : Strikeout ys : zs) = consolidateInlines $ Strikeout (xs ++ ys) : zs consolidateInlines (RawInline f x : RawInline f' y : zs) | f == f' = consolidateInlines $ RawInline f (x ++ y) : zs consolidateInlines (Code a1 x : Code a2 y : zs) | a1 == a2 = consolidateInlines $ Code a1 (x ++ y) : zs consolidateInlines (x : xs) = x : consolidateInlines xs consolidateInlines [] = [] -- | Convert list of inlines to a string with formatting removed. stringify :: [Inline] -> String stringify = queryWith go where go :: Inline -> [Char] go Space = " " go (Str x) = x go (Code _ x) = x go (Math _ x) = x go EmDash = "--" go EnDash = "-" go Apostrophe = "'" go Ellipses = "..." go LineBreak = " " go _ = "" -- | Change final list item from @Para@ to @Plain@ if the list contains -- no other @Para@ blocks. compactify :: [[Block]] -- ^ List of list items (each a list of blocks) -> [[Block]] compactify [] = [] compactify items = case (init items, last items) of (_,[]) -> items (others, final) -> case last final of Para a -> case (filter isPara $ concat items) of -- if this is only Para, change to Plain [_] -> others ++ [init final ++ [Plain a]] _ -> items _ -> items isPara :: Block -> Bool isPara (Para _) = True isPara _ = False -- | Data structure for defining hierarchical Pandoc documents data Element = Blk Block | Sec Int [Int] String [Inline] [Element] -- lvl num ident label contents deriving (Eq, Read, Show, Typeable, Data) -- | Convert Pandoc inline list to plain text identifier. HTML -- identifiers must start with a letter, and may contain only -- letters, digits, and the characters _-. inlineListToIdentifier :: [Inline] -> String inlineListToIdentifier = dropWhile (not . isAlpha) . intercalate "-" . words . map (nbspToSp . toLower) . filter (\c -> isLetter c || isDigit c || c `elem` "_-. ") . stringify where nbspToSp '\160' = ' ' nbspToSp x = x -- | Convert list of Pandoc blocks into (hierarchical) list of Elements hierarchicalize :: [Block] -> [Element] hierarchicalize blocks = S.evalState (hierarchicalizeWithIds blocks) ([],[]) hierarchicalizeWithIds :: [Block] -> S.State ([Int],[String]) [Element] hierarchicalizeWithIds [] = return [] hierarchicalizeWithIds ((Header level title'):xs) = do (lastnum, usedIdents) <- S.get let ident = uniqueIdent title' usedIdents let lastnum' = take level lastnum let newnum = if length lastnum' >= level then init lastnum' ++ [last lastnum' + 1] else lastnum ++ replicate (level - length lastnum - 1) 0 ++ [1] S.put (newnum, (ident : usedIdents)) let (sectionContents, rest) = break (headerLtEq level) xs sectionContents' <- hierarchicalizeWithIds sectionContents rest' <- hierarchicalizeWithIds rest return $ Sec level newnum ident title' sectionContents' : rest' hierarchicalizeWithIds (x:rest) = do rest' <- hierarchicalizeWithIds rest return $ (Blk x) : rest' headerLtEq :: Int -> Block -> Bool headerLtEq level (Header l _) = l <= level headerLtEq _ _ = False -- | Generate a unique identifier from a list of inlines. -- Second argument is a list of already used identifiers. uniqueIdent :: [Inline] -> [String] -> String uniqueIdent title' usedIdents = let baseIdent = case inlineListToIdentifier title' of "" -> "section" x -> x numIdent n = baseIdent ++ "-" ++ show n in if baseIdent `elem` usedIdents then case find (\x -> numIdent x `notElem` usedIdents) ([1..60000] :: [Int]) of Just x -> numIdent x Nothing -> baseIdent -- if we have more than 60,000, allow repeats else baseIdent -- | True if block is a Header block. isHeaderBlock :: Block -> Bool isHeaderBlock (Header _ _) = True isHeaderBlock _ = False -- | Shift header levels up or down. headerShift :: Int -> Pandoc -> Pandoc headerShift n = bottomUp shift where shift :: Block -> Block shift (Header level inner) = Header (level + n) inner shift x = x -- -- Writer options -- data HTMLMathMethod = PlainMath | LaTeXMathML (Maybe String) -- url of LaTeXMathML.js | JsMath (Maybe String) -- url of jsMath load script | GladTeX | WebTeX String -- url of TeX->image script. | MathML (Maybe String) -- url of MathMLinHTML.js | MathJax String -- url of MathJax.js deriving (Show, Read, Eq) data CiteMethod = Citeproc -- use citeproc to render them | Natbib -- output natbib cite commands | Biblatex -- output biblatex cite commands deriving (Show, Read, Eq) -- | Methods for obfuscating email addresses in HTML. data ObfuscationMethod = NoObfuscation | ReferenceObfuscation | JavascriptObfuscation deriving (Show, Read, Eq) -- | Varieties of HTML slide shows. data HTMLSlideVariant = S5Slides | SlidySlides | NoSlides deriving (Show, Read, Eq) -- | Options for writers data WriterOptions = WriterOptions { writerStandalone :: Bool -- ^ Include header and footer , writerTemplate :: String -- ^ Template to use in standalone mode , writerVariables :: [(String, String)] -- ^ Variables to set in template , writerEPUBMetadata :: String -- ^ Metadata to include in EPUB , writerTabStop :: Int -- ^ Tabstop for conversion btw spaces and tabs , writerTableOfContents :: Bool -- ^ Include table of contents , writerSlideVariant :: HTMLSlideVariant -- ^ Are we writing S5 or Slidy? , writerIncremental :: Bool -- ^ True if lists should be incremental , writerXeTeX :: Bool -- ^ Create latex suitable for use by xetex , writerHTMLMathMethod :: HTMLMathMethod -- ^ How to print math in HTML , writerIgnoreNotes :: Bool -- ^ Ignore footnotes (used in making toc) , writerNumberSections :: Bool -- ^ Number sections in LaTeX , writerSectionDivs :: Bool -- ^ Put sections in div tags in HTML , writerStrictMarkdown :: Bool -- ^ Use strict markdown syntax , writerReferenceLinks :: Bool -- ^ Use reference links in writing markdown, rst , writerWrapText :: Bool -- ^ Wrap text to line length , writerColumns :: Int -- ^ Characters in a line (for text wrapping) , writerLiterateHaskell :: Bool -- ^ Write as literate haskell , writerEmailObfuscation :: ObfuscationMethod -- ^ How to obfuscate emails , writerIdentifierPrefix :: String -- ^ Prefix for section & note ids in HTML , writerSourceDirectory :: FilePath -- ^ Directory path of 1st source file , writerUserDataDir :: Maybe FilePath -- ^ Path of user data directory , writerCiteMethod :: CiteMethod -- ^ How to print cites , writerBiblioFiles :: [FilePath] -- ^ Biblio files to use for citations , writerHtml5 :: Bool -- ^ Produce HTML5 , writerChapters :: Bool -- ^ Use "chapter" for top-level sects , writerListings :: Bool -- ^ Use listings package for code , writerAscii :: Bool -- ^ Avoid non-ascii characters } deriving Show {-# DEPRECATED writerXeTeX "writerXeTeX no longer does anything" #-} -- | Default writer options. defaultWriterOptions :: WriterOptions defaultWriterOptions = WriterOptions { writerStandalone = False , writerTemplate = "" , writerVariables = [] , writerEPUBMetadata = "" , writerTabStop = 4 , writerTableOfContents = False , writerSlideVariant = NoSlides , writerIncremental = False , writerXeTeX = False , writerHTMLMathMethod = PlainMath , writerIgnoreNotes = False , writerNumberSections = False , writerSectionDivs = False , writerStrictMarkdown = False , writerReferenceLinks = False , writerWrapText = True , writerColumns = 72 , writerLiterateHaskell = False , writerEmailObfuscation = JavascriptObfuscation , writerIdentifierPrefix = "" , writerSourceDirectory = "." , writerUserDataDir = Nothing , writerCiteMethod = Citeproc , writerBiblioFiles = [] , writerHtml5 = False , writerChapters = False , writerListings = False , writerAscii = False } -- -- File handling -- -- | Perform an IO action in a directory, returning to starting directory. inDirectory :: FilePath -> IO a -> IO a inDirectory path action = do oldDir <- getCurrentDirectory setCurrentDirectory path result <- action setCurrentDirectory oldDir return result -- | Get file path for data file, either from specified user data directory, -- or, if not found there, from Cabal data directory. findDataFile :: Maybe FilePath -> FilePath -> IO FilePath findDataFile Nothing f = getDataFileName f findDataFile (Just u) f = do ex <- doesFileExist (u </> f) if ex then return (u </> f) else getDataFileName f -- | Read file from specified user data directory or, if not found there, from -- Cabal data directory. readDataFile :: Maybe FilePath -> FilePath -> IO String readDataFile userDir fname = findDataFile userDir fname >>= UTF8.readFile
Lythimus/lptv
sites/all/modules/jgm-pandoc-8be6cc2/src/Text/Pandoc/Shared.hs
gpl-2.0
22,997
0
18
7,073
5,335
2,863
2,472
403
15
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CloudTrail.CreateTrail -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | From the command line, use 'create-subscription'. -- -- Creates a trail that specifies the settings for delivery of log data to an -- Amazon S3 bucket. -- -- <http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_CreateTrail.html> module Network.AWS.CloudTrail.CreateTrail ( -- * Request CreateTrail -- ** Request constructor , createTrail -- ** Request lenses , ctCloudWatchLogsLogGroupArn , ctCloudWatchLogsRoleArn , ctIncludeGlobalServiceEvents , ctName , ctS3BucketName , ctS3KeyPrefix , ctSnsTopicName -- * Response , CreateTrailResponse -- ** Response constructor , createTrailResponse -- ** Response lenses , ctrCloudWatchLogsLogGroupArn , ctrCloudWatchLogsRoleArn , ctrIncludeGlobalServiceEvents , ctrName , ctrS3BucketName , ctrS3KeyPrefix , ctrSnsTopicName ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CloudTrail.Types import qualified GHC.Exts data CreateTrail = CreateTrail { _ctCloudWatchLogsLogGroupArn :: Maybe Text , _ctCloudWatchLogsRoleArn :: Maybe Text , _ctIncludeGlobalServiceEvents :: Maybe Bool , _ctName :: Text , _ctS3BucketName :: Text , _ctS3KeyPrefix :: Maybe Text , _ctSnsTopicName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'CreateTrail' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ctCloudWatchLogsLogGroupArn' @::@ 'Maybe' 'Text' -- -- * 'ctCloudWatchLogsRoleArn' @::@ 'Maybe' 'Text' -- -- * 'ctIncludeGlobalServiceEvents' @::@ 'Maybe' 'Bool' -- -- * 'ctName' @::@ 'Text' -- -- * 'ctS3BucketName' @::@ 'Text' -- -- * 'ctS3KeyPrefix' @::@ 'Maybe' 'Text' -- -- * 'ctSnsTopicName' @::@ 'Maybe' 'Text' -- createTrail :: Text -- ^ 'ctName' -> Text -- ^ 'ctS3BucketName' -> CreateTrail createTrail p1 p2 = CreateTrail { _ctName = p1 , _ctS3BucketName = p2 , _ctS3KeyPrefix = Nothing , _ctSnsTopicName = Nothing , _ctIncludeGlobalServiceEvents = Nothing , _ctCloudWatchLogsLogGroupArn = Nothing , _ctCloudWatchLogsRoleArn = Nothing } -- | Specifies a log group name using an Amazon Resource Name (ARN), a unique -- identifier that represents the log group to which CloudTrail logs will be -- delivered. Not required unless you specify CloudWatchLogsRoleArn. ctCloudWatchLogsLogGroupArn :: Lens' CreateTrail (Maybe Text) ctCloudWatchLogsLogGroupArn = lens _ctCloudWatchLogsLogGroupArn (\s a -> s { _ctCloudWatchLogsLogGroupArn = a }) -- | Specifies the role for the CloudWatch Logs endpoint to assume to write to a -- user’s log group. ctCloudWatchLogsRoleArn :: Lens' CreateTrail (Maybe Text) ctCloudWatchLogsRoleArn = lens _ctCloudWatchLogsRoleArn (\s a -> s { _ctCloudWatchLogsRoleArn = a }) -- | Specifies whether the trail is publishing events from global services such as -- IAM to the log files. ctIncludeGlobalServiceEvents :: Lens' CreateTrail (Maybe Bool) ctIncludeGlobalServiceEvents = lens _ctIncludeGlobalServiceEvents (\s a -> s { _ctIncludeGlobalServiceEvents = a }) -- | Specifies the name of the trail. ctName :: Lens' CreateTrail Text ctName = lens _ctName (\s a -> s { _ctName = a }) -- | Specifies the name of the Amazon S3 bucket designated for publishing log -- files. ctS3BucketName :: Lens' CreateTrail Text ctS3BucketName = lens _ctS3BucketName (\s a -> s { _ctS3BucketName = a }) -- | Specifies the Amazon S3 key prefix that precedes the name of the bucket you -- have designated for log file delivery. ctS3KeyPrefix :: Lens' CreateTrail (Maybe Text) ctS3KeyPrefix = lens _ctS3KeyPrefix (\s a -> s { _ctS3KeyPrefix = a }) -- | Specifies the name of the Amazon SNS topic defined for notification of log -- file delivery. ctSnsTopicName :: Lens' CreateTrail (Maybe Text) ctSnsTopicName = lens _ctSnsTopicName (\s a -> s { _ctSnsTopicName = a }) data CreateTrailResponse = CreateTrailResponse { _ctrCloudWatchLogsLogGroupArn :: Maybe Text , _ctrCloudWatchLogsRoleArn :: Maybe Text , _ctrIncludeGlobalServiceEvents :: Maybe Bool , _ctrName :: Maybe Text , _ctrS3BucketName :: Maybe Text , _ctrS3KeyPrefix :: Maybe Text , _ctrSnsTopicName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'CreateTrailResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ctrCloudWatchLogsLogGroupArn' @::@ 'Maybe' 'Text' -- -- * 'ctrCloudWatchLogsRoleArn' @::@ 'Maybe' 'Text' -- -- * 'ctrIncludeGlobalServiceEvents' @::@ 'Maybe' 'Bool' -- -- * 'ctrName' @::@ 'Maybe' 'Text' -- -- * 'ctrS3BucketName' @::@ 'Maybe' 'Text' -- -- * 'ctrS3KeyPrefix' @::@ 'Maybe' 'Text' -- -- * 'ctrSnsTopicName' @::@ 'Maybe' 'Text' -- createTrailResponse :: CreateTrailResponse createTrailResponse = CreateTrailResponse { _ctrName = Nothing , _ctrS3BucketName = Nothing , _ctrS3KeyPrefix = Nothing , _ctrSnsTopicName = Nothing , _ctrIncludeGlobalServiceEvents = Nothing , _ctrCloudWatchLogsLogGroupArn = Nothing , _ctrCloudWatchLogsRoleArn = Nothing } -- | Specifies the Amazon Resource Name (ARN) of the log group to which CloudTrail -- logs will be delivered. ctrCloudWatchLogsLogGroupArn :: Lens' CreateTrailResponse (Maybe Text) ctrCloudWatchLogsLogGroupArn = lens _ctrCloudWatchLogsLogGroupArn (\s a -> s { _ctrCloudWatchLogsLogGroupArn = a }) -- | Specifies the role for the CloudWatch Logs endpoint to assume to write to a -- user’s log group. ctrCloudWatchLogsRoleArn :: Lens' CreateTrailResponse (Maybe Text) ctrCloudWatchLogsRoleArn = lens _ctrCloudWatchLogsRoleArn (\s a -> s { _ctrCloudWatchLogsRoleArn = a }) -- | Specifies whether the trail is publishing events from global services such as -- IAM to the log files. ctrIncludeGlobalServiceEvents :: Lens' CreateTrailResponse (Maybe Bool) ctrIncludeGlobalServiceEvents = lens _ctrIncludeGlobalServiceEvents (\s a -> s { _ctrIncludeGlobalServiceEvents = a }) -- | Specifies the name of the trail. ctrName :: Lens' CreateTrailResponse (Maybe Text) ctrName = lens _ctrName (\s a -> s { _ctrName = a }) -- | Specifies the name of the Amazon S3 bucket designated for publishing log -- files. ctrS3BucketName :: Lens' CreateTrailResponse (Maybe Text) ctrS3BucketName = lens _ctrS3BucketName (\s a -> s { _ctrS3BucketName = a }) -- | Specifies the Amazon S3 key prefix that precedes the name of the bucket you -- have designated for log file delivery. ctrS3KeyPrefix :: Lens' CreateTrailResponse (Maybe Text) ctrS3KeyPrefix = lens _ctrS3KeyPrefix (\s a -> s { _ctrS3KeyPrefix = a }) -- | Specifies the name of the Amazon SNS topic defined for notification of log -- file delivery. ctrSnsTopicName :: Lens' CreateTrailResponse (Maybe Text) ctrSnsTopicName = lens _ctrSnsTopicName (\s a -> s { _ctrSnsTopicName = a }) instance ToPath CreateTrail where toPath = const "/" instance ToQuery CreateTrail where toQuery = const mempty instance ToHeaders CreateTrail instance ToJSON CreateTrail where toJSON CreateTrail{..} = object [ "Name" .= _ctName , "S3BucketName" .= _ctS3BucketName , "S3KeyPrefix" .= _ctS3KeyPrefix , "SnsTopicName" .= _ctSnsTopicName , "IncludeGlobalServiceEvents" .= _ctIncludeGlobalServiceEvents , "CloudWatchLogsLogGroupArn" .= _ctCloudWatchLogsLogGroupArn , "CloudWatchLogsRoleArn" .= _ctCloudWatchLogsRoleArn ] instance AWSRequest CreateTrail where type Sv CreateTrail = CloudTrail type Rs CreateTrail = CreateTrailResponse request = post "CreateTrail" response = jsonResponse instance FromJSON CreateTrailResponse where parseJSON = withObject "CreateTrailResponse" $ \o -> CreateTrailResponse <$> o .:? "CloudWatchLogsLogGroupArn" <*> o .:? "CloudWatchLogsRoleArn" <*> o .:? "IncludeGlobalServiceEvents" <*> o .:? "Name" <*> o .:? "S3BucketName" <*> o .:? "S3KeyPrefix" <*> o .:? "SnsTopicName"
kim/amazonka
amazonka-cloudtrail/gen/Network/AWS/CloudTrail/CreateTrail.hs
mpl-2.0
9,457
0
21
2,189
1,333
791
542
140
1
-- | Maintainer: Zihao Wang <[email protected]> -- -- Support for the Pacman package manager <https://www.archlinux.org/pacman/> module Propellor.Property.Pacman where import Propellor.Base runPacman :: [String] -> UncheckedProperty ArchLinux runPacman ps = tightenTargets $ cmdProperty "pacman" ps -- | Have pacman update its lists of packages, but without upgrading anything. update :: Property ArchLinux update = combineProperties ("pacman update") $ props & runPacman ["-Sy", "--noconfirm"] `assume` MadeChange upgrade :: Property ArchLinux upgrade = combineProperties ("pacman upgrade") $ props & runPacman ["-Syu", "--noconfirm"] `assume` MadeChange type Package = String installed :: [Package] -> Property ArchLinux installed = installed' ["--noconfirm"] installed' :: [String] -> [Package] -> Property ArchLinux installed' params ps = check (not <$> isInstalled' ps) go `describe` unwords ("pacman installed":ps) where go = runPacman (params ++ ["-S"] ++ ps) removed :: [Package] -> Property ArchLinux removed ps = check (any (== IsInstalled) <$> getInstallStatus ps) (runPacman (["-R", "--noconfirm"] ++ ps)) `describe` unwords ("pacman removed":ps) isInstalled :: Package -> IO Bool isInstalled p = isInstalled' [p] isInstalled' :: [Package] -> IO Bool isInstalled' ps = all (== IsInstalled) <$> getInstallStatus ps data InstallStatus = IsInstalled | NotInstalled deriving (Show, Eq) {- Returns the InstallStatus of packages that are installed - or known and not installed. If a package is not known at all to apt - or dpkg, it is not included in the list. -} getInstallStatus :: [Package] -> IO [InstallStatus] getInstallStatus ps = mapMaybe id <$> mapM status ps where status :: Package -> IO (Maybe InstallStatus) status p = do ifM (succeeds "pacman" ["-Q", p]) (return (Just IsInstalled), ifM (succeeds "pacman" ["-Sp", p]) (return (Just NotInstalled), return Nothing)) succeeds :: String -> [String] -> IO Bool succeeds cmd args = (quietProcess >> return True) `catchIO` (\_ -> return False) where quietProcess :: IO () quietProcess = withQuietOutput createProcessSuccess p p = (proc cmd args)
ArchiveTeam/glowing-computing-machine
src/Propellor/Property/Pacman.hs
bsd-2-clause
2,178
22
15
377
669
356
313
44
1
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-} module Main where import BasePrelude hiding (for_) import Data.Text (Text) import Lucid import Models data Comment = Comment { _commentID :: ID , _commentBody :: Text , _commentParentID :: ID , _commentStoryID :: ID } -- (add-hook 'after-save-hook 'haskell-process-load-or-reload) header :: Html () header = with nav_ [class_ "typ-nav"] (do headerleft headerright) where headerleft = ul_ (do link "/" "Home" link "/hottest" "Spiciest" link "/comments" "Talk of the Town" link "/search" "Search") headerright = ul_ (do link "/threads" "Your Replies" link "/messages" "Your Messages" link "/settinsg" "hao (155)" link "/logout" "^D") link path text = li_ (with a_ [href_ path] text) post :: Html () -> Html () -> Html () post title copy = do with div_ [class_ "typ-user-meta"] meta with header_ [class_ "typ-user-header"] (h2_ title) with main_ [class_ "typ-user-article"] copy where meta = ul_ (do li_ "hao 12 hours ago" li_ "edit . delete . flag" li_ "all quiet") s :: Html () s = "commit ffea4ca34c05e229615b2e40a7b3839bd21e78f8\nAuthor: Doug Patti <[email protected]>\nDate: Fri Jun 1 00:05:20 2012 +0400\n\n Fix duplicate key for subscriptions test\n\ndiff --git a/unitTests/api_cards.coffee b/unitTests/api_cards.coffee\nindex 86d5..48807 100644\n--- a/unitTests/api_cards.coffee\n+++ b/unitTests/api_cards.coffee\n@@ -438,7 +438,7 @@ exports.tests =\n ], next\n , next\n\n- subscriptions: (next) ->\n+ subscriptions2: (next) ->^M\n date = new Date()\n" posts :: Html () posts = with section_ [id_ "posts"] $ do article_ (post title0 copy0) article_ (post title1 copy1) where title0 = "Code rant: The Lava Layer Anti-Pattern" copy0 = do blockquote_ (p_ "TL:DR Successive, well intentioned, changes to architecture and technology throughout the lifetime of an application can lead to a fragmented and hard to maintain code base. Sometimes it is better to favour consistent legacy technology over fragmentation.") blockquote_ (p_ "short") p_ "In a way this describes the server codebase, though we haven’t been through massive leadership changes. What’s the right way to avoid this? It feels like a non-problem, but I also feel like I’d be foolish to dismiss it entirely." (pre_ . code_) s title1 = "here is a title" copy1 = do p_ "After a weekend of cabal and bundler hell, we’re now one square ahead on our journey toward a time-wasting, completely Haskellized Barnacles. One day Haskell will have amazing OpenSSL bindings, guys, but until then we have authd to do Rails' bonkers cookie authentication and decryption." p_ "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" quickpost :: Html () quickpost = with section_ [id_ "quickpost", class_ "typ-quickpost"] $ do h2_ "Make a Barnacle" with p_ [class_ "typ-has-url"] $ do input_ [type_ "radio", id_ "no-url", name_ "has-url", value_ "0"] with label_ [for_ "no-url"] "No URL" input_ [type_ "radio", id_ "yes-url", name_ "has-url", value_ "1"] with label_ [for_ "yes-url"] "URL" input_ [type_ "url", id_ "url", name_ "url"] p_ $ do with label_ [for_ "url"] "Title" input_ [type_ "input", id_ "title", name_ "title", placeholder_ "Ask Barnacles: what's up?"] p_ $ do with label_ [for_ "story"] "Description" with textarea_ [placeholder_ "Tell us a story..."] "" home :: Html () home = doctype_ <> with html_ [class_ "typ-body"] (do head_ (do title_ "Barnacles" css "css/css.css.css" meta_ [charset_ "utf-8"]) body_ (do header quickpost posts)) where css path = link_ [rel_ "stylesheet", href_ path] main :: IO () main = renderToFile "index.html" home
hlian/barnacles
ng/src/Main.hs
bsd-3-clause
4,102
0
16
1,024
890
418
472
87
1
module Usage where import qualified Definition as D test :: Int test = D.s<caret>even + 1
charleso/intellij-haskforce
tests/gold/codeInsight/QualifiedImport/Usage.hs
apache-2.0
93
0
8
19
34
21
13
-1
-1
{-# LANGUAGE DeriveAnyClass,DeriveGeneric #-} module Herbie.MathExpr where import Control.DeepSeq import Data.List import Data.Maybe import GHC.Generics import Debug.Trace import Prelude ifThenElse True t f = t ifThenElse False t f = f ------------------------------------------------------------------------------- -- constants that define valid math expressions monOpList = [ "cos" , "sin" , "tan" , "acos" , "asin" , "atan" , "cosh" , "sinh" , "tanh" , "exp" , "log" , "sqrt" , "abs" , "size" ] binOpList = [ "^", "**", "^^", "/", "-", "expt" ] ++ commutativeOpList commutativeOpList = [ "*", "+"] -- , "max", "min" ] -------------------------------------------------------------------------------- -- | Stores the AST for a math expression in a generic form that requires no knowledge of Core syntax. data MathExpr = EBinOp String MathExpr MathExpr | EMonOp String MathExpr | EIf MathExpr MathExpr MathExpr | ELit Rational | ELeaf String deriving (Show,Eq,Generic,NFData) instance Ord MathExpr where compare (ELeaf _) (ELeaf _) = EQ compare (ELeaf _) _ = LT compare (ELit r1) (ELit r2) = compare r1 r2 compare (ELit _ ) (ELeaf _) = GT compare (ELit _ ) _ = LT compare (EMonOp op1 e1) (EMonOp op2 e2) = case compare op1 op2 of EQ -> compare e1 e2 x -> x compare (EMonOp _ _) (ELeaf _) = GT compare (EMonOp _ _) (ELit _) = GT compare (EMonOp _ _) _ = LT compare (EBinOp op1 e1a e1b) (EBinOp op2 e2a e2b) = case compare op1 op2 of EQ -> case compare e1a e2a of EQ -> compare e1b e2b _ -> EQ _ -> EQ compare (EBinOp _ _ _) _ = LT -- | Converts all Haskell operators in the MathExpr into Herbie operators haskellOpsToHerbieOps :: MathExpr -> MathExpr haskellOpsToHerbieOps = go where go (EBinOp op e1 e2) = EBinOp op' (go e1) (go e2) where op' = case op of "**" -> "expt" "^^" -> "expt" "^" -> "expt" x -> x go (EMonOp op e1) = EMonOp op' (go e1) where op' = case op of "size" -> "abs" x -> x go (EIf cond e1 e2) = EIf (go cond) (go e1) (go e2) go x = x -- | Converts all Herbie operators in the MathExpr into Haskell operators herbieOpsToHaskellOps :: MathExpr -> MathExpr herbieOpsToHaskellOps = go where go (EBinOp op e1 e2) = EBinOp op' (go e1) (go e2) where op' = case op of "^" -> "**" "expt" -> "**" x -> x go (EMonOp "sqr" e1) = EBinOp "*" (go e1) (go e1) go (EMonOp op e1) = EMonOp op' (go e1) where op' = case op of "-" -> "negate" "abs" -> "size" x -> x go (EIf cond e1 e2) = EIf (go cond) (go e1) (go e2) go x = x -- | Replace all the variables in the MathExpr with canonical names (x0,x1,x2...) -- and reorder commutative binary operations. -- This lets us more easily compare MathExpr's based on their structure. -- The returned map lets us convert the canoncial MathExpr back into the original. toCanonicalMathExpr :: MathExpr -> (MathExpr,[(String,String)]) toCanonicalMathExpr e = go [] e where go :: [(String,String)] -> MathExpr -> (MathExpr,[(String,String)]) go acc (EBinOp op e1 e2) = (EBinOp op e1' e2',acc2') where (e1_,e2_) = if op `elem` commutativeOpList then (min e1 e2,max e1 e2) else (e1,e2) (e1',acc1') = go acc e1_ (e2',acc2') = go acc1' e2_ go acc (EMonOp op e1) = (EMonOp op e1', acc1') where (e1',acc1') = go acc e1 go acc (ELit r) = (ELit r,acc) go acc (ELeaf str) = (ELeaf str',acc') where (acc',str') = case lookup str acc of Nothing -> ((str,"herbie"++show (length acc)):acc, "herbie"++show (length acc)) Just x -> (acc,x) -- | Convert a canonical MathExpr into its original form. -- -- FIXME: -- A bug in Herbie causes it to sometimes output infinities, -- which break this function and cause it to error. fromCanonicalMathExpr :: (MathExpr,[(String,String)]) -> MathExpr fromCanonicalMathExpr (e,xs) = go e where xs' = map (\(a,b) -> (b,a)) xs go (EMonOp op e1) = EMonOp op (go e1) go (EBinOp op e1 e2) = EBinOp op (go e1) (go e2) go (EIf (EBinOp "<" _ (ELeaf "-inf.0")) e1 e2) = go e2 -- FIXME: added due to bug above go (EIf cond e1 e2) = EIf (go cond) (go e1) (go e2) go (ELit r) = ELit r go (ELeaf str) = case lookup str xs' of Just x -> ELeaf x Nothing -> error $ "fromCanonicalMathExpr: str="++str++"; xs="++show xs' -- | Calculates the maximum depth of the AST. mathExprDepth :: MathExpr -> Int mathExprDepth (EBinOp _ e1 e2) = 1+max (mathExprDepth e1) (mathExprDepth e2) mathExprDepth (EMonOp _ e1 ) = 1+mathExprDepth e1 mathExprDepth _ = 0 -------------------------------------------------------------------------------- -- functions for manipulating math expressions in lisp form getCanonicalLispCmd :: MathExpr -> (String,[(String,String)]) getCanonicalLispCmd me = (mathExpr2lisp me',varmap) where (me',varmap) = toCanonicalMathExpr me fromCanonicalLispCmd :: (String,[(String,String)]) -> MathExpr fromCanonicalLispCmd (lisp,varmap) = fromCanonicalMathExpr (lisp2mathExpr lisp,varmap) -- | Converts MathExpr into a lisp command suitable for passing to Herbie mathExpr2lisp :: MathExpr -> String mathExpr2lisp = go where go (EBinOp op a1 a2) = "("++op++" "++go a1++" "++go a2++")" go (EMonOp op a) = "("++op++" "++go a++")" go (EIf cond e1 e2) = "(if "++go cond++" "++go e1++" "++go e2++")" go (ELeaf e) = e go (ELit r) = if (toRational (floor r::Integer) == r) then show (floor r :: Integer) else show (fromRational r :: Double) -- | Converts a lisp command into a MathExpr lisp2mathExpr :: String -> MathExpr lisp2mathExpr ('-':xs) = EMonOp "negate" (lisp2mathExpr xs) lisp2mathExpr ('(':xs) = if length xs > 1 && last xs==')' then case groupByParens $ init xs of [op,e1] -> EMonOp op (lisp2mathExpr e1) [op,e1,e2] -> EBinOp op (lisp2mathExpr e1) (lisp2mathExpr e2) ["if",cond,e1,e2] -> EIf (lisp2mathExpr cond) (lisp2mathExpr e1) (lisp2mathExpr e2) _ -> error $ "lisp2mathExpr: "++xs else error $ "lisp2mathExpr: malformed input '("++xs++"'" lisp2mathExpr xs = case readMaybe xs :: Maybe Double of Just x -> ELit $ toRational x Nothing -> ELeaf xs -- | Extracts all the variables from the lisp commands with no duplicates. lisp2vars :: String -> [String] lisp2vars = nub . lisp2varsNoNub -- | Extracts all the variables from the lisp commands. -- Each variable occurs once in the output for each time it occurs in the input. lisp2varsNoNub :: String -> [String] lisp2varsNoNub lisp = sort $ filter (\x -> x/="(" && x/=")" && not (x `elem` binOpList) && not (x `elem` monOpList) && not (head x `elem` ("1234567890"::String)) ) $ tokenize lisp :: [String] where -- We just need to add spaces around the parens before calling "words" tokenize :: String -> [String] tokenize = words . concat . map go where go '(' = " ( " go ')' = " ) " go x = [x] lispHasRepeatVars :: String -> Bool lispHasRepeatVars lisp = length (lisp2vars lisp) /= length (lisp2varsNoNub lisp) ------------------------------------------------------------------------------- -- utilities readMaybe :: Read a => String -> Maybe a readMaybe = fmap fst . listToMaybe . reads -- | Given an expression, break it into tokens only outside parentheses groupByParens :: String -> [String] groupByParens str = go 0 str [] [] where go 0 (' ':xs) [] ret = go 0 xs [] ret go 0 (' ':xs) acc ret = go 0 xs [] (ret++[acc]) go 0 (')':xs) acc ret = go 0 xs [] (ret++[acc]) go i (')':xs) acc ret = go (i-1) xs (acc++")") ret go i ('(':xs) acc ret = go (i+1) xs (acc++"(") ret go i (x :xs) acc ret = go i xs (acc++[x]) ret go _ [] acc ret = ret++[acc]
madebyjeffrey/HerbiePlugin
src/Herbie/MathExpr.hs
bsd-3-clause
8,749
0
18
2,749
2,893
1,519
1,374
167
9
module OldSyntaxRec where import SyntaxRec -- For backward compatibility: type HsPat = HsPatI HsName type HsType = HsTypeI HsName type HsExp = HsExpI HsName type HsDecl = HsDeclI HsName type HsModuleR = HsModuleRI HsName type BaseDecl = BaseDeclI HsName type BaseExp = BaseExpI HsName type BasePat = BasePatI HsName type BaseType = BaseTypeI HsName type HsModuleRI i = HsModuleI i [HsDeclI i] type HsStmtR = HsStmt HsExp HsPat [HsDecl] type HsAltR = HsAlt HsExp HsPat [HsDecl]
forste/haReFork
tools/base/syntax/OldSyntaxRec.hs
bsd-3-clause
491
0
7
90
139
79
60
14
0
module Distribution.Client.Mirror.State ( MirrorState(..) , MirrorEnv(..) , mirrorInit , savePackagesState , toErrorState , fromErrorState ) where -- stdlib import Control.Exception import Control.Monad import Data.Maybe (catMaybes) import Data.Set (Set) import Network.URI import System.Directory import System.FilePath import qualified Data.Set as Set -- Cabal import Distribution.Package import Distribution.Simple.Utils hiding (warn) import Distribution.Text import Distribution.Verbosity -- hackage import Distribution.Client.Mirror.CmdLine import Distribution.Client.Mirror.Config import Distribution.Client.Mirror.Session {------------------------------------------------------------------------------- Mirror state -------------------------------------------------------------------------------} data MirrorState = MirrorState { ms_missingPkgs :: Set PackageId, ms_unmirrorablePkgs :: Set PackageId } deriving (Eq, Show) data MirrorEnv = MirrorEnv { me_srcCacheDir :: FilePath, me_dstCacheDir :: FilePath, me_missingPkgsFile :: FilePath, me_unmirrorablePkgsFile :: FilePath } deriving Show {------------------------------------------------------------------------------- Initialization and termination -------------------------------------------------------------------------------} mirrorInit :: Verbosity -> MirrorOpts -> IO (MirrorEnv, MirrorState) mirrorInit verbosity opts = do let srcName = preRepoName $ mirrorSource (mirrorConfig opts) dstName = preRepoName $ mirrorTarget (mirrorConfig opts) srcCacheDir = stateDir opts </> srcName dstCacheDir = stateDir opts </> dstName when (srcCacheDir == dstCacheDir) $ die "source and destination cache files clash" when (continuous opts == Just 0) $ warn verbosity "A sync interval of zero is a seriously bad idea!" when (isCentralHackage (mirrorSource (mirrorConfig opts)) && maybe False (<5) (continuous opts)) $ die $ "Please don't hit the central hackage.haskell.org " ++ "more frequently than every 5 minutes." createDirectoryIfMissing False (stateDir opts) createDirectoryIfMissing False srcCacheDir createDirectoryIfMissing False dstCacheDir let missingPkgsFile = stateDir opts </> "missing-" ++ srcName -- being unmirrorable is a function of the combination of the source and -- destination, so the cache file uses both names. unmirrorablePkgsFile = stateDir opts </> "unmirrorable-" ++ srcName ++ "-" ++ dstName missingPkgs <- readPkgProblemFile missingPkgsFile unmirrorablePkgs <- readPkgProblemFile unmirrorablePkgsFile return ( MirrorEnv { me_srcCacheDir = srcCacheDir , me_dstCacheDir = dstCacheDir , me_missingPkgsFile = missingPkgsFile , me_unmirrorablePkgsFile = unmirrorablePkgsFile } , MirrorState { ms_missingPkgs = missingPkgs , ms_unmirrorablePkgs = unmirrorablePkgs } ) isCentralHackage :: PreRepo -> Bool isCentralHackage PreRepo{..} = let regName = fmap uriRegName . uriAuthority =<< preRepoURI in regName == Just "hackage.haskell.org" savePackagesState :: MirrorEnv -> MirrorState -> IO () savePackagesState (MirrorEnv _ _ missingPkgsFile unmirrorablePkgsFile) (MirrorState missingPkgs unmirrorablePkgs) = do writePkgProblemFile missingPkgsFile missingPkgs writePkgProblemFile unmirrorablePkgsFile unmirrorablePkgs {------------------------------------------------------------------------------- Package problem file -------------------------------------------------------------------------------} readPkgProblemFile :: FilePath -> IO (Set PackageId) readPkgProblemFile file = do exists <- doesFileExist file if exists then evaluate . Set.fromList . catMaybes . map simpleParse . lines =<< readFile file else return Set.empty writePkgProblemFile :: FilePath -> Set PackageId -> IO () writePkgProblemFile file = writeFile file . unlines . map display . Set.toList {------------------------------------------------------------------------------- Errors -------------------------------------------------------------------------------} toErrorState :: MirrorState -> ErrorState toErrorState (MirrorState missing unmirrorable) = ErrorState missing unmirrorable fromErrorState :: ErrorState -> MirrorState fromErrorState (ErrorState missing unmirrorable) = MirrorState missing unmirrorable
ocharles/hackage-server
Distribution/Client/Mirror/State.hs
bsd-3-clause
4,859
0
17
1,127
872
459
413
-1
-1
{-# LANGUAGE MultiParamTypeClasses, DeriveGeneric, DeriveDataTypeable #-} import Control.Applicative import Control.Lens import GHC.Generics import Data.Data import Data.Data.Lens data Expr = Var Int | Pos Expr String | Neg Expr | Add Expr Expr deriving (Eq,Ord,Show,Read,Generic,Data,Typeable) data Stmt = Seq [Stmt] | Sel [Expr] | Let String Expr deriving (Eq,Ord,Show,Read,Generic,Data,Typeable) instance Plated Expr where plate f (Var x ) = pure (Var x) plate f (Pos x y) = Pos <$> f x <*> pure y plate f (Neg x ) = Neg <$> f x plate f (Add x y) = Add <$> f x <*> f y instance Plated Stmt where plate f (Seq xs) = Seq <$> traverse f xs plate f (Sel xs) = pure (Sel xs) plate f (Let x y) = pure (Let x y) exprs :: Traversal' Stmt Expr exprs f (Seq xs) = Seq <$> traverse (exprs f) xs exprs f (Sel xs) = Sel <$> traverse f xs exprs f (Let x y) = Let x <$> f y
danidiaz/lens
examples/Plates.hs
bsd-3-clause
884
0
8
188
446
225
221
21
1
{-# LANGUAGE ImplicitParams, RankNTypes #-} import GHC.Stack foo :: (?callStack :: CallStack) => [Int] foo = map (srcLocStartLine . snd) (getCallStack ?callStack) bar1 :: [Int] bar1 = foo bar2 :: [Int] bar2 = let ?callStack = freezeCallStack ?callStack in foo main :: IO () main = do print bar1 print bar2 withFrozenCallStack (error "look ma, no stack!")
ezyang/ghc
testsuite/tests/typecheck/should_run/T11049.hs
bsd-3-clause
365
0
9
67
126
66
60
13
1
module Main where import Q main = print q
siddhanathan/ghc
testsuite/tests/cabal/cabal06/r/Main.hs
bsd-3-clause
42
0
5
9
15
9
6
3
1
import Data.List (transpose) isTriangle :: (Int, Int, Int) -> Bool isTriangle (a, b, c) = a + b > c && b + c > a && a + c > b toInts :: String -> [Int] toInts line = map (\x -> read x :: Int) $ words line asTriplet :: [Int] -> (Int, Int, Int) asTriplet (a:b:c:_) = (a, b, c) groupBy :: Int -> [String] -> [[String]] groupBy x [] = [] groupBy x items = (transpose $ map words $ take x $ items) ++ groupBy x (drop x items) main = do input <- getContents print $ length $ filter isTriangle $ (map (asTriplet . toInts) $ lines input) print $ length $ filter isTriangle $ map (asTriplet . toInts . unwords) $ groupBy 3 $ lines input
ajm188/advent_of_code
2016/03/Main.hs
mit
677
0
13
182
355
185
170
18
1
-- module Scheme.Eval.LispError where -- import Scheme.Lex.LispVal -- import Control.Monad.Error -- import Text.ParserCombinators.Parsec -- -- Data type for handling Errors -- data LispError = NumArgs Integer [LispVal] -- | TypeMismatch String LispVal -- | Parser ParseError -- | BadSpecialForm String LispVal -- | NotFunction String String -- | UnboundVar String String -- | Default String -- -- Function for evaluating a lisp error -- showError :: LispError -> String -- showError (UnboundVar message varname) = message ++ ": " ++ varname -- showError (BadSpecialForm message form) = message ++ ": " ++ show form -- showError (NotFunction message func) = message ++ ": " ++ show func -- showError (NumArgs expected found) = "Expected " ++ show expected ++ " args; found values \"" ++ unwordsList found ++ "\"" -- showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found -- showError (Parser parseErr) = "Parse error at " ++ show parseErr -- -- Declare LispError type as being showable -- instance Show LispError where show = showError -- -- Have LispError type extend the error type class -- instance Error LispError where -- noMsg = Default "An error has occurred" -- strMsg = Default -- -- Type for returning errors. Type constructors are -- -- curried just like functions, so we can use ThrowsError -- -- to construct a new Either type. -- type ThrowsError = Either LispError -- -- Trap an error -- trapError action = catchError action (return . show) -- -- Extract a value from an Either -- extractValue :: ThrowsError a -> a -- extractValue (Right val) = val
johnellis1392/Haskell-Scheme
old/LispError.hs
mit
1,742
0
2
395
37
36
1
1
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGSVGElement (js_suspendRedraw, suspendRedraw, js_unsuspendRedraw, unsuspendRedraw, js_unsuspendRedrawAll, unsuspendRedrawAll, js_forceRedraw, forceRedraw, js_pauseAnimations, pauseAnimations, js_unpauseAnimations, unpauseAnimations, js_animationsPaused, animationsPaused, js_getCurrentTime, getCurrentTime, js_setCurrentTime, setCurrentTime, js_getIntersectionList, getIntersectionList, js_getEnclosureList, getEnclosureList, js_checkIntersection, checkIntersection, js_checkEnclosure, checkEnclosure, js_deselectAll, deselectAll, js_createSVGNumber, createSVGNumber, js_createSVGLength, createSVGLength, js_createSVGAngle, createSVGAngle, js_createSVGPoint, createSVGPoint, js_createSVGMatrix, createSVGMatrix, js_createSVGRect, createSVGRect, js_createSVGTransform, createSVGTransform, js_createSVGTransformFromMatrix, createSVGTransformFromMatrix, js_getElementById, getElementById, js_getX, getX, js_getY, getY, js_getWidth, getWidth, js_getHeight, getHeight, js_setContentScriptType, setContentScriptType, js_getContentScriptType, getContentScriptType, js_setContentStyleType, setContentStyleType, js_getContentStyleType, getContentStyleType, js_getViewport, getViewport, js_getPixelUnitToMillimeterX, getPixelUnitToMillimeterX, js_getPixelUnitToMillimeterY, getPixelUnitToMillimeterY, js_getScreenPixelToMillimeterX, getScreenPixelToMillimeterX, js_getScreenPixelToMillimeterY, getScreenPixelToMillimeterY, js_getUseCurrentView, getUseCurrentView, js_getCurrentView, getCurrentView, js_setCurrentScale, setCurrentScale, js_getCurrentScale, getCurrentScale, js_getCurrentTranslate, getCurrentTranslate, SVGSVGElement, castToSVGSVGElement, gTypeSVGSVGElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"suspendRedraw\"]($2)" js_suspendRedraw :: JSRef SVGSVGElement -> Word -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.suspendRedraw Mozilla SVGSVGElement.suspendRedraw documentation> suspendRedraw :: (MonadIO m) => SVGSVGElement -> Word -> m Word suspendRedraw self maxWaitMilliseconds = liftIO (js_suspendRedraw (unSVGSVGElement self) maxWaitMilliseconds) foreign import javascript unsafe "$1[\"unsuspendRedraw\"]($2)" js_unsuspendRedraw :: JSRef SVGSVGElement -> Word -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.unsuspendRedraw Mozilla SVGSVGElement.unsuspendRedraw documentation> unsuspendRedraw :: (MonadIO m) => SVGSVGElement -> Word -> m () unsuspendRedraw self suspendHandleId = liftIO (js_unsuspendRedraw (unSVGSVGElement self) suspendHandleId) foreign import javascript unsafe "$1[\"unsuspendRedrawAll\"]()" js_unsuspendRedrawAll :: JSRef SVGSVGElement -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.unsuspendRedrawAll Mozilla SVGSVGElement.unsuspendRedrawAll documentation> unsuspendRedrawAll :: (MonadIO m) => SVGSVGElement -> m () unsuspendRedrawAll self = liftIO (js_unsuspendRedrawAll (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"forceRedraw\"]()" js_forceRedraw :: JSRef SVGSVGElement -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.forceRedraw Mozilla SVGSVGElement.forceRedraw documentation> forceRedraw :: (MonadIO m) => SVGSVGElement -> m () forceRedraw self = liftIO (js_forceRedraw (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"pauseAnimations\"]()" js_pauseAnimations :: JSRef SVGSVGElement -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.pauseAnimations Mozilla SVGSVGElement.pauseAnimations documentation> pauseAnimations :: (MonadIO m) => SVGSVGElement -> m () pauseAnimations self = liftIO (js_pauseAnimations (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"unpauseAnimations\"]()" js_unpauseAnimations :: JSRef SVGSVGElement -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.unpauseAnimations Mozilla SVGSVGElement.unpauseAnimations documentation> unpauseAnimations :: (MonadIO m) => SVGSVGElement -> m () unpauseAnimations self = liftIO (js_unpauseAnimations (unSVGSVGElement self)) foreign import javascript unsafe "($1[\"animationsPaused\"]() ? 1 : 0)" js_animationsPaused :: JSRef SVGSVGElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.animationsPaused Mozilla SVGSVGElement.animationsPaused documentation> animationsPaused :: (MonadIO m) => SVGSVGElement -> m Bool animationsPaused self = liftIO (js_animationsPaused (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"getCurrentTime\"]()" js_getCurrentTime :: JSRef SVGSVGElement -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.getCurrentTime Mozilla SVGSVGElement.getCurrentTime documentation> getCurrentTime :: (MonadIO m) => SVGSVGElement -> m Float getCurrentTime self = liftIO (js_getCurrentTime (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"setCurrentTime\"]($2)" js_setCurrentTime :: JSRef SVGSVGElement -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.setCurrentTime Mozilla SVGSVGElement.setCurrentTime documentation> setCurrentTime :: (MonadIO m) => SVGSVGElement -> Float -> m () setCurrentTime self seconds = liftIO (js_setCurrentTime (unSVGSVGElement self) seconds) foreign import javascript unsafe "$1[\"getIntersectionList\"]($2,\n$3)" js_getIntersectionList :: JSRef SVGSVGElement -> JSRef SVGRect -> JSRef SVGElement -> IO (JSRef NodeList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.getIntersectionList Mozilla SVGSVGElement.getIntersectionList documentation> getIntersectionList :: (MonadIO m, IsSVGElement referenceElement) => SVGSVGElement -> Maybe SVGRect -> Maybe referenceElement -> m (Maybe NodeList) getIntersectionList self rect referenceElement = liftIO ((js_getIntersectionList (unSVGSVGElement self) (maybe jsNull pToJSRef rect) (maybe jsNull (unSVGElement . toSVGElement) referenceElement)) >>= fromJSRef) foreign import javascript unsafe "$1[\"getEnclosureList\"]($2, $3)" js_getEnclosureList :: JSRef SVGSVGElement -> JSRef SVGRect -> JSRef SVGElement -> IO (JSRef NodeList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.getEnclosureList Mozilla SVGSVGElement.getEnclosureList documentation> getEnclosureList :: (MonadIO m, IsSVGElement referenceElement) => SVGSVGElement -> Maybe SVGRect -> Maybe referenceElement -> m (Maybe NodeList) getEnclosureList self rect referenceElement = liftIO ((js_getEnclosureList (unSVGSVGElement self) (maybe jsNull pToJSRef rect) (maybe jsNull (unSVGElement . toSVGElement) referenceElement)) >>= fromJSRef) foreign import javascript unsafe "($1[\"checkIntersection\"]($2,\n$3) ? 1 : 0)" js_checkIntersection :: JSRef SVGSVGElement -> JSRef SVGElement -> JSRef SVGRect -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.checkIntersection Mozilla SVGSVGElement.checkIntersection documentation> checkIntersection :: (MonadIO m, IsSVGElement element) => SVGSVGElement -> Maybe element -> Maybe SVGRect -> m Bool checkIntersection self element rect = liftIO (js_checkIntersection (unSVGSVGElement self) (maybe jsNull (unSVGElement . toSVGElement) element) (maybe jsNull pToJSRef rect)) foreign import javascript unsafe "($1[\"checkEnclosure\"]($2,\n$3) ? 1 : 0)" js_checkEnclosure :: JSRef SVGSVGElement -> JSRef SVGElement -> JSRef SVGRect -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.checkEnclosure Mozilla SVGSVGElement.checkEnclosure documentation> checkEnclosure :: (MonadIO m, IsSVGElement element) => SVGSVGElement -> Maybe element -> Maybe SVGRect -> m Bool checkEnclosure self element rect = liftIO (js_checkEnclosure (unSVGSVGElement self) (maybe jsNull (unSVGElement . toSVGElement) element) (maybe jsNull pToJSRef rect)) foreign import javascript unsafe "$1[\"deselectAll\"]()" js_deselectAll :: JSRef SVGSVGElement -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.deselectAll Mozilla SVGSVGElement.deselectAll documentation> deselectAll :: (MonadIO m) => SVGSVGElement -> m () deselectAll self = liftIO (js_deselectAll (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"createSVGNumber\"]()" js_createSVGNumber :: JSRef SVGSVGElement -> IO (JSRef SVGNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGNumber Mozilla SVGSVGElement.createSVGNumber documentation> createSVGNumber :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGNumber) createSVGNumber self = liftIO ((js_createSVGNumber (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"createSVGLength\"]()" js_createSVGLength :: JSRef SVGSVGElement -> IO (JSRef SVGLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGLength Mozilla SVGSVGElement.createSVGLength documentation> createSVGLength :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGLength) createSVGLength self = liftIO ((js_createSVGLength (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"createSVGAngle\"]()" js_createSVGAngle :: JSRef SVGSVGElement -> IO (JSRef SVGAngle) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGAngle Mozilla SVGSVGElement.createSVGAngle documentation> createSVGAngle :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGAngle) createSVGAngle self = liftIO ((js_createSVGAngle (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"createSVGPoint\"]()" js_createSVGPoint :: JSRef SVGSVGElement -> IO (JSRef SVGPoint) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGPoint Mozilla SVGSVGElement.createSVGPoint documentation> createSVGPoint :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGPoint) createSVGPoint self = liftIO ((js_createSVGPoint (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"createSVGMatrix\"]()" js_createSVGMatrix :: JSRef SVGSVGElement -> IO (JSRef SVGMatrix) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGMatrix Mozilla SVGSVGElement.createSVGMatrix documentation> createSVGMatrix :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGMatrix) createSVGMatrix self = liftIO ((js_createSVGMatrix (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"createSVGRect\"]()" js_createSVGRect :: JSRef SVGSVGElement -> IO (JSRef SVGRect) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGRect Mozilla SVGSVGElement.createSVGRect documentation> createSVGRect :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGRect) createSVGRect self = liftIO ((js_createSVGRect (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"createSVGTransform\"]()" js_createSVGTransform :: JSRef SVGSVGElement -> IO (JSRef SVGTransform) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGTransform Mozilla SVGSVGElement.createSVGTransform documentation> createSVGTransform :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGTransform) createSVGTransform self = liftIO ((js_createSVGTransform (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"createSVGTransformFromMatrix\"]($2)" js_createSVGTransformFromMatrix :: JSRef SVGSVGElement -> JSRef SVGMatrix -> IO (JSRef SVGTransform) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.createSVGTransformFromMatrix Mozilla SVGSVGElement.createSVGTransformFromMatrix documentation> createSVGTransformFromMatrix :: (MonadIO m) => SVGSVGElement -> Maybe SVGMatrix -> m (Maybe SVGTransform) createSVGTransformFromMatrix self matrix = liftIO ((js_createSVGTransformFromMatrix (unSVGSVGElement self) (maybe jsNull pToJSRef matrix)) >>= fromJSRef) foreign import javascript unsafe "$1[\"getElementById\"]($2)" js_getElementById :: JSRef SVGSVGElement -> JSString -> IO (JSRef Element) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.getElementById Mozilla SVGSVGElement.getElementById documentation> getElementById :: (MonadIO m, ToJSString elementId) => SVGSVGElement -> elementId -> m (Maybe Element) getElementById self elementId = liftIO ((js_getElementById (unSVGSVGElement self) (toJSString elementId)) >>= fromJSRef) foreign import javascript unsafe "$1[\"x\"]" js_getX :: JSRef SVGSVGElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.x Mozilla SVGSVGElement.x documentation> getX :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGAnimatedLength) getX self = liftIO ((js_getX (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"y\"]" js_getY :: JSRef SVGSVGElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.y Mozilla SVGSVGElement.y documentation> getY :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGAnimatedLength) getY self = liftIO ((js_getY (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: JSRef SVGSVGElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.width Mozilla SVGSVGElement.width documentation> getWidth :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGAnimatedLength) getWidth self = liftIO ((js_getWidth (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: JSRef SVGSVGElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.height Mozilla SVGSVGElement.height documentation> getHeight :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGAnimatedLength) getHeight self = liftIO ((js_getHeight (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"contentScriptType\"] = $2;" js_setContentScriptType :: JSRef SVGSVGElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.contentScriptType Mozilla SVGSVGElement.contentScriptType documentation> setContentScriptType :: (MonadIO m, ToJSString val) => SVGSVGElement -> val -> m () setContentScriptType self val = liftIO (js_setContentScriptType (unSVGSVGElement self) (toJSString val)) foreign import javascript unsafe "$1[\"contentScriptType\"]" js_getContentScriptType :: JSRef SVGSVGElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.contentScriptType Mozilla SVGSVGElement.contentScriptType documentation> getContentScriptType :: (MonadIO m, FromJSString result) => SVGSVGElement -> m result getContentScriptType self = liftIO (fromJSString <$> (js_getContentScriptType (unSVGSVGElement self))) foreign import javascript unsafe "$1[\"contentStyleType\"] = $2;" js_setContentStyleType :: JSRef SVGSVGElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.contentStyleType Mozilla SVGSVGElement.contentStyleType documentation> setContentStyleType :: (MonadIO m, ToJSString val) => SVGSVGElement -> val -> m () setContentStyleType self val = liftIO (js_setContentStyleType (unSVGSVGElement self) (toJSString val)) foreign import javascript unsafe "$1[\"contentStyleType\"]" js_getContentStyleType :: JSRef SVGSVGElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.contentStyleType Mozilla SVGSVGElement.contentStyleType documentation> getContentStyleType :: (MonadIO m, FromJSString result) => SVGSVGElement -> m result getContentStyleType self = liftIO (fromJSString <$> (js_getContentStyleType (unSVGSVGElement self))) foreign import javascript unsafe "$1[\"viewport\"]" js_getViewport :: JSRef SVGSVGElement -> IO (JSRef SVGRect) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.viewport Mozilla SVGSVGElement.viewport documentation> getViewport :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGRect) getViewport self = liftIO ((js_getViewport (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"pixelUnitToMillimeterX\"]" js_getPixelUnitToMillimeterX :: JSRef SVGSVGElement -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.pixelUnitToMillimeterX Mozilla SVGSVGElement.pixelUnitToMillimeterX documentation> getPixelUnitToMillimeterX :: (MonadIO m) => SVGSVGElement -> m Float getPixelUnitToMillimeterX self = liftIO (js_getPixelUnitToMillimeterX (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"pixelUnitToMillimeterY\"]" js_getPixelUnitToMillimeterY :: JSRef SVGSVGElement -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.pixelUnitToMillimeterY Mozilla SVGSVGElement.pixelUnitToMillimeterY documentation> getPixelUnitToMillimeterY :: (MonadIO m) => SVGSVGElement -> m Float getPixelUnitToMillimeterY self = liftIO (js_getPixelUnitToMillimeterY (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"screenPixelToMillimeterX\"]" js_getScreenPixelToMillimeterX :: JSRef SVGSVGElement -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.screenPixelToMillimeterX Mozilla SVGSVGElement.screenPixelToMillimeterX documentation> getScreenPixelToMillimeterX :: (MonadIO m) => SVGSVGElement -> m Float getScreenPixelToMillimeterX self = liftIO (js_getScreenPixelToMillimeterX (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"screenPixelToMillimeterY\"]" js_getScreenPixelToMillimeterY :: JSRef SVGSVGElement -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.screenPixelToMillimeterY Mozilla SVGSVGElement.screenPixelToMillimeterY documentation> getScreenPixelToMillimeterY :: (MonadIO m) => SVGSVGElement -> m Float getScreenPixelToMillimeterY self = liftIO (js_getScreenPixelToMillimeterY (unSVGSVGElement self)) foreign import javascript unsafe "($1[\"useCurrentView\"] ? 1 : 0)" js_getUseCurrentView :: JSRef SVGSVGElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.useCurrentView Mozilla SVGSVGElement.useCurrentView documentation> getUseCurrentView :: (MonadIO m) => SVGSVGElement -> m Bool getUseCurrentView self = liftIO (js_getUseCurrentView (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"currentView\"]" js_getCurrentView :: JSRef SVGSVGElement -> IO (JSRef SVGViewSpec) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.currentView Mozilla SVGSVGElement.currentView documentation> getCurrentView :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGViewSpec) getCurrentView self = liftIO ((js_getCurrentView (unSVGSVGElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"currentScale\"] = $2;" js_setCurrentScale :: JSRef SVGSVGElement -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.currentScale Mozilla SVGSVGElement.currentScale documentation> setCurrentScale :: (MonadIO m) => SVGSVGElement -> Float -> m () setCurrentScale self val = liftIO (js_setCurrentScale (unSVGSVGElement self) val) foreign import javascript unsafe "$1[\"currentScale\"]" js_getCurrentScale :: JSRef SVGSVGElement -> IO Float -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.currentScale Mozilla SVGSVGElement.currentScale documentation> getCurrentScale :: (MonadIO m) => SVGSVGElement -> m Float getCurrentScale self = liftIO (js_getCurrentScale (unSVGSVGElement self)) foreign import javascript unsafe "$1[\"currentTranslate\"]" js_getCurrentTranslate :: JSRef SVGSVGElement -> IO (JSRef SVGPoint) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement.currentTranslate Mozilla SVGSVGElement.currentTranslate documentation> getCurrentTranslate :: (MonadIO m) => SVGSVGElement -> m (Maybe SVGPoint) getCurrentTranslate self = liftIO ((js_getCurrentTranslate (unSVGSVGElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGSVGElement.hs
mit
22,329
278
13
3,587
4,172
2,207
1,965
319
1
import Test.Hspec -- Problem 7 -- Flatten a nested list structure. -- Transform a list, possibly holding lists as elements into a -- `flat' list by replacing each list with its elements (recursively). data NestedList a = Elem a | List [NestedList a] flatten :: NestedList a -> [a] flatten ls = flatten' ls [] where flatten' (Elem x) acc = x:acc flatten' (List []) acc = acc flatten' (List (x:xs)) acc = flatten' x $ flatten' (List xs) acc main :: IO() main = hspec $ describe "99-exercises.7 = Flatten a nested list structure" $ it "should return the number of elemnents of a list" $ do flatten (Elem 5) `shouldBe` [5] flatten (List ([] :: [NestedList Int])) `shouldBe` [] flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5, List[]]]) `shouldBe` [1,2,3,4,5]
baldore/haskell-99-exercises
7.hs
mit
834
0
17
198
313
163
150
14
3
{- ************************************************************** * Filename : Complete.hs * * Author : Markus Forsberg * * [email protected] * * Last Modified : 6 July, 2001 * * Lines : 29 * ************************************************************** -} module FST.Complete ( complete -- Makes a automaton complete (transition on every symbol at every state) ) where import FST.Automaton import Data.List ( (\\) ) complete :: Eq a => Automaton a -> Automaton a complete auto = let sink = lastState auto + 1 sinkTr = (sink,map (\a -> (a,sink)) (alphabet auto)) newTrans = sinkTr:completeStates auto sink (states auto) [] in construct (firstState auto,sink) newTrans (alphabet auto) (initials auto) (finals auto) completeStates :: Eq a => Automaton a -> State -> [State] -> [(State,Transitions a)] -> [(State,Transitions a)] completeStates _ _ [] trans = trans completeStates auto sink (s:sts) trans = let tr = transitionList auto s nTr = map (\a -> (a,sink)) ((alphabet auto) \\ (map fst tr)) in completeStates auto sink sts ((s,tr++nTr):trans)
SAdams601/ParRegexSearch
test/fst-0.9.0.1/FST/Complete.hs
mit
1,366
0
13
467
360
191
169
14
1
{-# LANGUAGE ScopedTypeVariables #-} module Util.Monad( liftExceptions , whenM , unlessM , whenMaybe , whenMaybeM ) where import Control.Exception import Control.Monad.Trans (liftIO) import Control.Monad.Trans.Either import Control.Monad import Data.Text (Text) import TextShow -- | Catches all synchronous exceptions all transforms them into EitherT Text -- | monad transformer. liftExceptions :: forall a . IO a -> EitherT Text IO a liftExceptions action = do res <- liftIO (try action :: IO (Either SomeException a)) eitherT (left.showt) right $ hoistEither res -- | Monadic condition version of @when@ whenM :: Monad m => m Bool -> m () -> m () whenM cond f = do v <- cond when v f -- | Monadic condition version of @unless@ unlessM :: Monad m => m Bool -> m () -> m () unlessM cond f = do v <- cond unless v f -- | If given value is just then pass it to handler whenMaybe :: Monad m => Maybe a -> (a -> m ()) -> m () whenMaybe Nothing _ = return () whenMaybe (Just a) f = f a whenMaybeM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () whenMaybeM cond f = do v <- cond whenMaybe v f
NCrashed/sinister
src/shared/Util/Monad.hs
mit
1,138
0
12
258
413
206
207
32
1
{-# OPTIONS -Wall #-} import Data.Functor (($>)) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import Helpers.Graph (Graph, (!)) import qualified Helpers.Graph as Graph import Helpers.Parse import Text.Parsec data Cave = Start | End | Big String | Small String deriving (Eq, Ord, Show) main :: IO () main = do connectionList <- parseLinesIO parser let connections = Graph.undirectedGraph connectionList let answer = countPaths connections print answer countPaths :: Graph Cave -> Int countPaths connections = countPaths' Set.empty Start where countPaths' :: Set Cave -> Cave -> Int countPaths' _ End = 1 countPaths' forbidden current = let newForbidden = case current of Big _ -> forbidden cave -> Set.insert cave forbidden next = Set.toList (Set.difference (connections ! current) forbidden) counts = map (countPaths' newForbidden) next in sum counts parser :: Parsec Text () (Cave, Cave) parser = do caveA <- cave _ <- string "-" caveB <- cave return (caveA, caveB) where cave = choice $ map try [ string "start" $> Start, string "end" $> End, Big <$> many1 upper, Small <$> many1 lower ]
SamirTalwar/advent-of-code
2021/AOC_12_1.hs
mit
1,304
0
15
360
432
224
208
42
3
module Wf.Kvs.Redis ( module Wf.Control.Eff.Kvs , module Wf.Control.Eff.Run.Kvs.Redis ) where import Wf.Control.Eff.Kvs import Wf.Control.Eff.Run.Kvs.Redis
bigsleep/Wf
wf-kvs-redis/src/Wf/Kvs/Redis.hs
mit
157
0
5
15
43
32
11
5
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} ---------------------------------------------------------------------- -- | -- Module: Web.Slack.Api -- Description: -- -- -- ---------------------------------------------------------------------- module Web.Slack.Api ( TestReq(..) , mkTestReq , TestRsp(..) ) where -- aeson import Data.Aeson.TH -- base import GHC.Generics (Generic) -- deepseq import Control.DeepSeq (NFData) -- http-api-data import Web.FormUrlEncoded -- slack-web import Web.Slack.Util -- text import Data.Text (Text) -- | -- -- data TestReq = TestReq { testReqError :: Maybe Text , testReqFoo :: Maybe Text } deriving (Eq, Generic, Show) instance NFData TestReq -- | -- -- $(deriveJSON (jsonOpts "testReq") ''TestReq) -- | -- -- instance ToForm TestReq where toForm = genericToForm (formOpts "testReq") -- | -- -- mkTestReq :: TestReq mkTestReq = TestReq { testReqError = Nothing , testReqFoo = Nothing } -- | -- -- data TestRsp = TestRsp { testRspArgs :: Maybe TestReq } deriving (Eq, Generic, Show) instance NFData TestRsp -- | -- -- $(deriveFromJSON (jsonOpts "testRsp") ''TestRsp)
jpvillaisaza/slack-web
src/Web/Slack/Api.hs
mit
1,239
0
9
241
283
173
110
34
1
module MarketTransaction where import qualified Data.Edison.Assoc.StandardMap as E import MarketTypes -- Given a list of things to withdraw and the current market state, returns -- the new market state without the withdrawn goods, plus a map of quantities -- of goods that could actually be bought. withdraw :: MarketQuantityMap -> MarketQuantityMap -> (MarketQuantityMap, MarketQuantityMap) withdraw shoppinglist market = E.foldrWithKey' go (market, E.empty) shoppinglist where go name q (accm, accb) = let curr = E.lookupWithDefault 0 name accm transq = min curr q in (E.insertWith subtract name transq accm, E.insertWith (+) name transq accb) -- Given a list of things to add to the market and the current market state, -- adds the things to the market and returns the updated market. deposit :: MarketQuantityMap -> MarketQuantityMap -> MarketQuantityMap deposit list market = E.foldrWithKey' go market list where go name q accm = E.insertWith (+) name q accm consume :: MarketQuantityMap -> MarketQuantityMap -> MarketQuantityMap consume s m = fst $ withdraw s m
anttisalonen/economics
src/MarketTransaction.hs
mit
1,148
0
12
243
239
130
109
13
1
repeated :: (a -> a) -> Int -> a -> a repeated _ 0 x = x repeated f n x = f (repeated f (n - 1) x)
fmi-lab/fp-elective-2017
exercises/11/repeated.hs
mit
99
0
9
29
69
35
34
3
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Foundation where import qualified Data.Set as S import Database.Persist.Sql (ConnectionPool, runSqlPool) import Import.NoFoundation import LambdaCms.Core -- import LambdaCmsOrg.Tutorial import LambdaCmsOrg.Page import qualified Network.Wai as W import Roles import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) -- import Text.Julius (juliusFile) import Yesod.Auth.BrowserId (authBrowserId) import Yesod.Core.Types (Logger) import Yesod.Default.Util (addStaticContentExternal) -- | The foundation datatype for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger , getLambdaCms :: CoreAdmin , getTutorialAdmin :: TutorialAdmin , getPageAdmin :: PageAdmin } instance HasHttpManager App where getHttpManager = appHttpManager -- Set up i18n messages. See the message folder. mkMessage "App" "messages" "en" -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the linked documentation for an -- explanation for this split. mkYesodData "App" $(parseRoutesFile "config/routes") -- | A convenient synonym for creating forms. type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot approot = ApprootMaster $ appRoot . appSettings -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 120 -- timeout in minutes "/tmp/client_session_key.aes" defaultLayout widget = do mmsg <- getMessage can <- getCan mcr <- getCurrentRoute -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do $(combineStylesheets 'StaticR [ css_main_css ]) $(combineScripts 'StaticR [ js_jquery_js -- , js_bootstrap_js , js_hoh_js ]) $(widgetFile "highlighting") $(widgetFile "default-layout") addStylesheetRemote "http://fonts.googleapis.com/css?family=Oswald" addStylesheetRemote "http://fonts.googleapis.com/css?family=Quattrocento" withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR isAuthorized theRoute _ = case theRoute of (StaticR _) -> return Authorized (CoreAdminR (AdminStaticR _)) -> return Authorized _ -> do method <- waiRequest >>= return . W.requestMethod y <- getYesod murs <- maybeAuthId >>= mapM getUserRoles return $ isAuthorizedTo y murs $ actionAllowedFor theRoute method -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = CoreAdminR AdminHomeR -- Where to send a user after logout logoutDest _ = AuthR LoginR -- Override the above two destinations when a Referer: header is present redirectToReferer _ = True authenticate = authenticateByLambdaCms maybeAuthId = lambdaCmsMaybeAuthId -- You can add other plugins like BrowserID, email or OAuth here authPlugins _ = [authBrowserId def] authHttpManager = getHttpManager authLayout = adminAuthLayout instance LambdaCmsAdmin App where type Roles App = RoleName actionAllowedFor (FaviconR) "GET" = AllowAll actionAllowedFor (RobotsR) "GET" = AllowAll actionAllowedFor (HomeR) "GET" = AllowAll actionAllowedFor (AuthR _) _ = AllowAll actionAllowedFor (CoreAdminR (AdminStaticR _)) "GET" = AllowAll actionAllowedFor (CoreAdminR (UserAdminActivateR _ _)) _ = AllowAll actionAllowedFor (CommunityR) "GET" = AllowAll actionAllowedFor (LicenseR) "GET" = AllowAll actionAllowedFor (DocumentationR _) "GET" = AllowAll actionAllowedFor _ _ = AllowRoles $ S.fromList [Admin] coreR = CoreAdminR authR = AuthR masterHomeR = HomeR getUserRoles userId = cachedBy cacheKey . fmap toRoleSet . runDB $ selectList [UserRoleUserId ==. userId] [] where cacheKey = encodeUtf8 $ toPathPiece userId toRoleSet = S.fromList . map (userRoleRoleName . entityVal) setUserRoles userId rs = runDB $ do deleteWhere [UserRoleUserId ==. userId] mapM_ (insert_ . UserRole userId) $ S.toList rs adminMenu = (defaultCoreAdminMenu CoreAdminR) ++ (defaultPageAdminMenu PageAdminR) ++ (defaultTutorialAdminMenu TutorialAdminR) renderLanguages _ = ["en"] mayAssignRoles = do authId <- requireAuthId roles <- getUserRoles authId return $ isAdmin roles lambdaCmsSendMail = lift . renderSendMail instance LambdaCmsOrgTutorial App where tutorialR = TutorialAdminR instance LambdaCmsOrgPage App where pageR = PageAdminR instance YesodAuthPersist App -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- Note: Some functionality previously present in the scaffolding has been -- moved to documentation in the Wiki. Following are some hopefully helpful -- links: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email -- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain -- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding isAdmin :: S.Set RoleName -> Bool isAdmin = S.member Admin githubSocial :: Text -> Maybe Text -> Text -> Widget githubSocial user repo kind = do let githubSocialTitle = case kind of "watch" -> MsgGithubStar "fork" -> MsgGithubFork "follow" -> MsgGithubFollow x -> error . unpack $ "Type " <> x <> " is not supported." url = "http://ghbtns.com/github-btn.html?v=2&size=large&user=" <> user <> "&type=" <> kind <> "&count=true" <> (maybe "" ("&repo=" <>) repo) $(widgetFile "github-social")
lambdacms/lambdacms.org
lambdacmsorg-base/Foundation.hs
mit
9,245
0
16
2,551
1,468
771
697
-1
-1
module Unused.CLI.ProgressIndicator ( I.ProgressIndicator , createProgressBar , createSpinner , progressWithIndicator ) where import qualified Control.Concurrent.ParallelIO as PIO import qualified Unused.CLI.ProgressIndicator.Internal as I import qualified Unused.CLI.ProgressIndicator.Types as I import Unused.CLI.Util (Color(..), installChildInterruptHandler) createProgressBar :: I.ProgressIndicator createProgressBar = I.ProgressBar Nothing Nothing createSpinner :: I.ProgressIndicator createSpinner = I.Spinner snapshots (length snapshots) 75000 colors Nothing where snapshots = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"] colors = cycle [Black, Red, Yellow, Green, Blue, Cyan, Magenta] progressWithIndicator :: Monoid b => (a -> IO b) -> I.ProgressIndicator -> [a] -> IO b progressWithIndicator f i terms = do I.printPrefix i (tid, indicator) <- I.start i $ length terms installChildInterruptHandler tid mconcat <$> PIO.parallel (ioOps indicator) <* I.stop indicator where ioOps i' = map (\t -> f t <* I.increment i') terms
joshuaclayton/unused
src/Unused/CLI/ProgressIndicator.hs
mit
1,113
0
12
197
335
187
148
23
1
{-| Description: Simple abstractions to ease working with reactive-banana. Copyright: (c) Guilherme Azzi, 2014 License: MIT Maintainer: [email protected] Stability: experimental A thin layer on top of reactive-banana to help creating 'Event's and 'Behavior's. Provides two new types: 'EventSource' (mostly a renaming of 'AddHandler') and 'BehaviorSource' (simply an 'EventSource' whose event gets wrapped in a 'stepper'). Also provides convenient functions for creating the sources, obtaining their 'Event's or 'Behavior's and firing/updating them. -} {-# LANGUAGE TupleSections #-} module Reactive.Banana.Sources ( -- * Event Sources EventSource , newEvent , fromEventSource , fire -- * Behavior Sources , BehaviorSource , newBehavior , fromBehaviorSource , update ) where import Reactive.Banana import Reactive.Banana.Frameworks hiding (newEvent) -- | A source for a reactive-banana 'Event'. Contains the information -- required by reactive-banana to create the corresponding 'Event', -- and also an action used to fire it. newtype EventSource a = ES { unES :: (AddHandler a, a -> IO ()) } -- | Create the source for a new event. newEvent :: IO (EventSource a) newEvent = ES `fmap` newAddHandler {-# INLINE newEvent #-} -- | Obtain the event that corresponds to the given source. fromEventSource :: (Frameworks t) => EventSource a -> Moment t (Event t a) fromEventSource = fromAddHandler . fst . unES {-# INLINE fromEventSource #-} -- | Fire the event that corresponds to the given source, with the given value. fire :: EventSource a -> a -> IO () fire = snd . unES {-# INLINE fire #-} -- | A source for a reactive-banana 'Behavior'. Contains the information -- required by reactive-banana to create the corresponding 'Behavior', -- and also an action used to update it. newtype BehaviorSource a = BS { unBS :: (EventSource a, a) } -- | Create the source for a new behavior, given its initial value newBehavior :: a -> IO (BehaviorSource a) newBehavior x = (BS . (,x)) `fmap` newEvent {-# INLINE newBehavior #-} -- | Obtain the behavior that corresponds to the given source. fromBehaviorSource :: (Frameworks t) => BehaviorSource a -> Moment t (Behavior t a) fromBehaviorSource (BS (es, x)) = stepper x `fmap` fromEventSource es {-# INLINE fromBehaviorSource #-} -- | Update the value of the given behavior. update :: BehaviorSource a -> a -> IO () update = fire . fst . unBS {-# INLINE update #-}
ggazzi/hzen
src/Reactive/Banana/Sources.hs
mit
2,495
0
10
478
372
217
155
32
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE OverlappingInstances, UndecidableInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} module Database.MongoDB.Structured.Types ( Parser , runParser , SerializedValue(..) , SerializedEntity(..) , Entity(..) , (.:) , (=:) , module Types ) where import Data.Bson as Types (Value(..)) import Control.Applicative ((<$>)) import qualified Data.Bson as Bson import qualified Database.MongoDB as MongoDB import Data.Int (Int32, Int64) import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Time.Clock (UTCTime) import Data.Time.Clock.POSIX (POSIXTime) type Parser rec = Either String rec runParser :: Parser rec -> Either String rec runParser = id class SerializedValue a where toBSON :: a -> Bson.Value fromBSON :: Bson.Value -> Parser a bsonVal :: Bson.Val a => a -> Bson.Value bsonVal = Bson.val bsonCast :: Bson.Val a => String -> Bson.Value -> Parser a bsonCast typeName value = maybe (fail $ "Invalid " <> typeName <> " BSON value: \"" <> show value <> "\"") return $ Bson.cast' value instance SerializedValue Bool where { toBSON = bsonVal ; fromBSON = bsonCast "Bool" } instance SerializedValue Int where { toBSON = bsonVal ; fromBSON = bsonCast "Int" } instance SerializedValue Int32 where { toBSON = bsonVal ; fromBSON = bsonCast "Int32" } instance SerializedValue Int64 where { toBSON = bsonVal ; fromBSON = bsonCast "Int64" } instance SerializedValue Integer where { toBSON = bsonVal ; fromBSON = bsonCast "Integer" } instance SerializedValue Double where { toBSON = bsonVal ; fromBSON = bsonCast "Double" } instance SerializedValue Float where { toBSON = bsonVal ; fromBSON = bsonCast "Float" } instance SerializedValue Char where { toBSON = bsonVal ; fromBSON = bsonCast "Char" } instance SerializedValue String where { toBSON = bsonVal ; fromBSON = bsonCast "String" } instance SerializedValue Text where { toBSON = bsonVal ; fromBSON = bsonCast "Text" } instance SerializedValue POSIXTime where { toBSON = bsonVal ; fromBSON = bsonCast "POSIX time" } instance SerializedValue UTCTime where { toBSON = bsonVal ; fromBSON = bsonCast "UTC time" } instance SerializedValue Bson.ObjectId where { toBSON = bsonVal ; fromBSON = bsonCast "Object ID" } instance SerializedValue a => SerializedValue [a] where toBSON = Bson.Array . map toBSON fromBSON (Bson.Array arr) = mapM fromBSON arr fromBSON x = fail $ "Expected array, got: " ++ show x instance SerializedValue a => SerializedValue (Maybe a) where toBSON = maybe Bson.Null toBSON fromBSON Bson.Null = return Nothing fromBSON x = Just <$> fromBSON x class (SerializedValue (Key rec), Eq (Key rec), Ord (Key rec), Show (Key rec)) => SerializedEntity rec where type Key rec data EntityField rec :: * -> * idField :: EntityField rec (Key rec) collectionName :: rec -> MongoDB.Collection fieldName :: forall typ. EntityField rec typ -> Bson.Label toBSONDoc :: rec -> Bson.Document fromBSONDoc :: Bson.Document -> Parser rec data Entity rec = SerializedEntity rec => Entity { entityKey :: Key rec , entityVal :: rec } deriving instance (SerializedEntity rec, Eq (Key rec), Eq rec) => Eq (Entity rec) deriving instance (SerializedEntity rec, Ord (Key rec), Ord rec) => Ord (Entity rec) deriving instance (SerializedEntity rec, Show (Key rec), Show rec) => Show (Entity rec) deriving instance (SerializedEntity rec, Read (Key rec), Read rec) => Read (Entity rec) infix 5 =:, .: (.:) :: SerializedValue a => Bson.Document -> Bson.Label -> Parser a doc .: name = maybe (fail $ "Field " ++ T.unpack name ++ " was not found") return (Bson.look name doc) >>= fromBSON (=:) :: (SerializedValue a) => Bson.Label -> a -> Bson.Field name =: value = name Bson.:= toBSON value
maximkulkin/hs-mongodb
Database/MongoDB/Structured/Types.hs
mit
4,047
0
12
734
1,261
696
565
77
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html module Stratosphere.Resources.EC2Volume where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.Tag -- | Full data type definition for EC2Volume. See 'ec2Volume' for a more -- convenient constructor. data EC2Volume = EC2Volume { _eC2VolumeAutoEnableIO :: Maybe (Val Bool) , _eC2VolumeAvailabilityZone :: Val Text , _eC2VolumeEncrypted :: Maybe (Val Bool) , _eC2VolumeIops :: Maybe (Val Integer) , _eC2VolumeKmsKeyId :: Maybe (Val Text) , _eC2VolumeSize :: Maybe (Val Integer) , _eC2VolumeSnapshotId :: Maybe (Val Text) , _eC2VolumeTags :: Maybe [Tag] , _eC2VolumeVolumeType :: Maybe (Val Text) } deriving (Show, Eq) instance ToResourceProperties EC2Volume where toResourceProperties EC2Volume{..} = ResourceProperties { resourcePropertiesType = "AWS::EC2::Volume" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ fmap (("AutoEnableIO",) . toJSON) _eC2VolumeAutoEnableIO , (Just . ("AvailabilityZone",) . toJSON) _eC2VolumeAvailabilityZone , fmap (("Encrypted",) . toJSON) _eC2VolumeEncrypted , fmap (("Iops",) . toJSON) _eC2VolumeIops , fmap (("KmsKeyId",) . toJSON) _eC2VolumeKmsKeyId , fmap (("Size",) . toJSON) _eC2VolumeSize , fmap (("SnapshotId",) . toJSON) _eC2VolumeSnapshotId , fmap (("Tags",) . toJSON) _eC2VolumeTags , fmap (("VolumeType",) . toJSON) _eC2VolumeVolumeType ] } -- | Constructor for 'EC2Volume' containing required fields as arguments. ec2Volume :: Val Text -- ^ 'ecvAvailabilityZone' -> EC2Volume ec2Volume availabilityZonearg = EC2Volume { _eC2VolumeAutoEnableIO = Nothing , _eC2VolumeAvailabilityZone = availabilityZonearg , _eC2VolumeEncrypted = Nothing , _eC2VolumeIops = Nothing , _eC2VolumeKmsKeyId = Nothing , _eC2VolumeSize = Nothing , _eC2VolumeSnapshotId = Nothing , _eC2VolumeTags = Nothing , _eC2VolumeVolumeType = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-autoenableio ecvAutoEnableIO :: Lens' EC2Volume (Maybe (Val Bool)) ecvAutoEnableIO = lens _eC2VolumeAutoEnableIO (\s a -> s { _eC2VolumeAutoEnableIO = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-availabilityzone ecvAvailabilityZone :: Lens' EC2Volume (Val Text) ecvAvailabilityZone = lens _eC2VolumeAvailabilityZone (\s a -> s { _eC2VolumeAvailabilityZone = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-encrypted ecvEncrypted :: Lens' EC2Volume (Maybe (Val Bool)) ecvEncrypted = lens _eC2VolumeEncrypted (\s a -> s { _eC2VolumeEncrypted = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-iops ecvIops :: Lens' EC2Volume (Maybe (Val Integer)) ecvIops = lens _eC2VolumeIops (\s a -> s { _eC2VolumeIops = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-kmskeyid ecvKmsKeyId :: Lens' EC2Volume (Maybe (Val Text)) ecvKmsKeyId = lens _eC2VolumeKmsKeyId (\s a -> s { _eC2VolumeKmsKeyId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-size ecvSize :: Lens' EC2Volume (Maybe (Val Integer)) ecvSize = lens _eC2VolumeSize (\s a -> s { _eC2VolumeSize = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-snapshotid ecvSnapshotId :: Lens' EC2Volume (Maybe (Val Text)) ecvSnapshotId = lens _eC2VolumeSnapshotId (\s a -> s { _eC2VolumeSnapshotId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-tags ecvTags :: Lens' EC2Volume (Maybe [Tag]) ecvTags = lens _eC2VolumeTags (\s a -> s { _eC2VolumeTags = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-volumetype ecvVolumeType :: Lens' EC2Volume (Maybe (Val Text)) ecvVolumeType = lens _eC2VolumeVolumeType (\s a -> s { _eC2VolumeVolumeType = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/EC2Volume.hs
mit
4,530
0
15
611
915
518
397
66
1
-- | -- Module: Utils.Currency -- Copyright: (c) Johan Astborg, Andreas Bock -- License: BSD-3 -- Maintainer: Andreas Bock <[email protected]> -- Stability: experimental -- Portability: portable -- -- Types and functions for HQLs Cash type module Utils.Currency where import Prelude hiding (sum) -- Some common currencies data Currency = USD | EUR | GBP | CHF | JPY | DKK | SEK | KRW deriving (Show,Eq) -- redesign, see discounting data Cash = Cash Double Currency -- Format cash using currency symbol -- TODO: Format with ***##.## decimals etc instance Show Cash where show (Cash v USD) = '$' : show v show (Cash v EUR) = '€' : show v show (Cash v GBP) = '£' : show v show (Cash v JPY) = '¥' : show v show (Cash v CHF) = show v ++ " CHF" show (Cash v DKK) = show v ++ " kr" show (Cash v SEK) = show v ++ " kr" instance Num Cash where (Cash v USD) + (Cash w USD) = Cash (v + w) USD (Cash v EUR) + (Cash w EUR) = Cash (v + w) EUR (Cash v GBP) + (Cash w GBP) = Cash (v + w) GBP (Cash v CHF) + (Cash w CHF) = Cash (v + w) CHF (Cash v JPY) + (Cash w JPY) = Cash (v + w) JPY (Cash v DKK) + (Cash w DKK) = Cash (v + w) DKK (Cash v SEK) + (Cash w SEK) = Cash (v + w) SEK _ + _ = error "Currency mismatch!" (Cash v USD) - (Cash w USD) = Cash (v - w) USD (Cash v EUR) - (Cash w EUR) = Cash (v - w) EUR (Cash v GBP) - (Cash w GBP) = Cash (v - w) GBP (Cash v CHF) - (Cash w CHF) = Cash (v - w) CHF (Cash v JPY) - (Cash w JPY) = Cash (v - w) JPY (Cash v DKK) - (Cash w DKK) = Cash (v - w) DKK (Cash v SEK) - (Cash w SEK) = Cash (v - w) SEK _ - _ = error "Currency mismatch!" (Cash v USD) * (Cash w USD) = Cash (v * w) USD (Cash v EUR) * (Cash w EUR) = Cash (v * w) EUR (Cash v GBP) * (Cash w GBP) = Cash (v * w) GBP (Cash v CHF) * (Cash w CHF) = Cash (v * w) CHF (Cash v JPY) * (Cash w JPY) = Cash (v * w) JPY (Cash v DKK) * (Cash w DKK) = Cash (v * w) DKK (Cash v SEK) * (Cash w SEK) = Cash (v * w) SEK _ * _ = error "Currency mismatch!" -- TODOs: Ajust for negative cash? fromInteger = undefined abs c = c signum c = c instance Fractional Cash where (Cash v USD) / (Cash w USD) = Cash (v / w) USD (Cash v EUR) / (Cash w EUR) = Cash (v / w) EUR (Cash v GBP) / (Cash w GBP) = Cash (v / w) GBP (Cash v CHF) / (Cash w CHF) = Cash (v / w) CHF (Cash v JPY) / (Cash w JPY) = Cash (v / w) JPY (Cash v DKK) / (Cash w DKK) = Cash (v / w) DKK (Cash v SEK) / (Cash w SEK) = Cash (v / w) SEK _ / _ = error "Currency mismatch!" fromRational = undefined instance Eq Cash where (Cash v c) == (Cash v' c') = v == v' && c == c' instance Ord Cash where (Cash v c) < (Cash v' c') | c /= c' = error "Currency mismatch!" | otherwise = v < v' expC, add, scale :: Double -> Cash -> Cash expC d (Cash v c) = Cash (v**d) c scale d (Cash v c) = Cash (d*v) c add d (Cash v c) = Cash (d+v) c sum :: [Cash] -> Cash sum (c:[]) = c sum (c:cs) = c + sum cs amount :: Cash -> Double amount (Cash a _) = a currency :: Cash -> Currency currency (Cash _ c) = c unCurrency :: Cash -> Double unCurrency (Cash v _) = v unCurrencies :: [Cash] -> [Double] unCurrencies = map unCurrency --- Support for currency conversion data CurrencyPair = CurrencyPair Currency Currency data ExchangeRate = ExchangeRate Double CurrencyPair instance Show CurrencyPair where show (CurrencyPair b q) = show b ++ "/" ++ show q -- TODO: Bid/Ask instance Show ExchangeRate where show (ExchangeRate mid pair) = show pair ++ " " ++ show mid {- Sample usage: For example, use the Cash data > Cash 115.2 USD $115.2 > Cash 89.0 SEK 89.0 kr Define a currecy pair > CurrencyPair EUR USD EUR/USD Specify an exchange rate for EUR/USD > ExchangeRate 1.32 (CurrencyPair EUR USD) EUR/USD 1.21 **** TODOs Support conversion of currencies, like this: Cash 1000.00 USD `to` EUR -- Will use implicits and infix operator -- Idea: use the exchange rate as an implicit (ImplicitParams) -- See: http://www.haskell.org/haskellwiki/Implicit_parameters -}
andreasbock/hql
src/Utils/Currency.hs
gpl-2.0
4,093
0
9
1,073
1,903
950
953
77
1
module Tema_14a_PilaConTipoDeDatoAlgebraico_Spec (main, spec) where import Tema_14.PilaConTipoDeDatoAlgebraico import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "PilaConTipoDeDatoAlgebraico" $ do it "e1" $ escribePila (apila 1 (apila 2 (apila 3 vacia))) `shouldBe` "1|2|3|-" it "e2" $ show (apila 1 (apila 2 (apila 3 vacia))) `shouldBe` "1|2|3|-" it "e3" $ show (vacia :: Pila Int) `shouldBe` "-" it "e4" $ show (apila 4 (apila 1 (apila 2 (apila 3 vacia)))) `shouldBe` "4|1|2|3|-" it "e5" $ cima (apila 1 (apila 2 (apila 3 vacia))) `shouldBe` 1 it "e6" $ show (desapila (apila 1 (apila 2 (apila 3 vacia)))) `shouldBe` "2|3|-" it "e7" $ esVacia (apila 1 (apila 2 (apila 3 vacia))) `shouldBe` False it "e8" $ esVacia vacia `shouldBe` True
jaalonso/I1M-Cod-Temas
test/Tema_14a_PilaConTipoDeDatoAlgebraico_Spec.hs
gpl-2.0
858
0
20
214
379
189
190
24
1
module Main where import Control.Monad.State import System.IO import Text.Read (readMaybe) import Reversi main :: IO () main = do loop start displayStrLn "Game Over!" -- | Run Reversi game loop until game is over. loop :: Reversi -> IO () loop r = do displayBoard (board r) when (isActive r) $ do let p = getPlayerInTurn r displayPlayerInTurn p if hasValidMove r p then do m <- getMove r p loop $ endTurn r m else loop $ endTurn r Skip -- | Proceed to next state. endTurn :: Reversi -> Move -> Reversi endTurn r m = execState (move m) r -- | Get next move for current player. getMove :: Reversi -> Piece -> IO Move getMove r p = do coord <- getCoord let m = Move p coord if isMoveValid r m then return m else do displayStrLn "Invalid move" getMove r p -- | Get move coordinates from user. getCoord :: IO Coord getCoord = do displayPrompt maybeCoord <- fmap readMaybe getLine :: IO (Maybe Coord) case maybeCoord of Nothing -> do displayStrLn "Expected board coordinates, for example: f4" getCoord Just x -> return x displayPrompt :: IO () displayPrompt = displayStr "> " displayBoard :: Board -> IO () displayBoard b = displayStr $ toPrettyStr b displayPlayerInTurn :: Piece -> IO () displayPlayerInTurn p = displayStrLn $ "Current player: " ++ show p displayStr :: String -> IO() displayStr s = do putStr $ '\n' : s hFlush stdout displayStrLn :: String -> IO() displayStrLn s = do putStrLn $ '\n' : s hFlush stdout
mharrys/reversi
cli/Main.hs
gpl-2.0
1,655
0
14
501
522
247
275
54
2
-- module Output (playCsound, playCsounds, lilypond) where module Output (playCsound, writeCsound) where -- import Music (Note3, AbstractNote(..), AbstractPitch3(..), AbstractInt3(..), AbstractDur3(..), absolute, AbstractPhrase(..)) import CsoundExp -- import Csound (testFreqs, playCsound, playCsounds) -- import Lilypond
ejlilley/AbstractMusic
Output.hs
gpl-3.0
330
0
4
40
19
14
5
2
0
{-#LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} module Carnap.Languages.PurePropositional.Logic.Tomassi (parseTomassiPL, parseTomassiPLProof, tomassiPLCalc, TomassiPL) where import Data.Map as M (lookup, Map) import Text.Parsec import Control.Lens (view) import Carnap.Core.Data.Types (Form) import Carnap.Core.Data.Classes (lhs) import Carnap.Languages.PurePropositional.Syntax import Carnap.Languages.PurePropositional.Parser import Carnap.Calculi.NaturalDeduction.Syntax import Carnap.Calculi.NaturalDeduction.Parser import Carnap.Calculi.NaturalDeduction.Checker import Carnap.Languages.ClassicalSequent.Syntax import Carnap.Languages.ClassicalSequent.Parser import Carnap.Languages.PurePropositional.Logic.Rules {-| A system for propositional logic resembling the proof system PL from Tomassi's Logic book -} data TomassiPL = AndI | AndE1 | AndE2 | MP | MT | DNI | DNE | BCI | BCE | ORI1 | ORI2 | ORE | As | CP | RAA1 | RAA2 | Pr (Maybe [(ClassicalSequentOver PurePropLexicon (Sequent (Form Bool)))]) deriving (Eq) instance Show TomassiPL where show AndI = "&I" show AndE1 = "&E" show AndE2 = "&E" show MP = "MP" show MT = "MT" show DNI = "DNI" show DNE = "DNE" show BCI = "↔I" show BCE = "↔E" show ORI1 = "∨I" show ORI2 = "∨I" show ORE = "∨E" show As = "As" show CP = "CP" show RAA1 = "RAA" show RAA2 = "RAA" show (Pr _) = "Pr" instance Inference TomassiPL PurePropLexicon (Form Bool) where ruleOf AndI = adjunction ruleOf AndE1 = simplificationVariations !! 0 ruleOf AndE2 = simplificationVariations !! 1 ruleOf MP = modusPonens ruleOf MT = modusTollens ruleOf DNI = doubleNegationIntroduction ruleOf DNE = doubleNegationElimination ruleOf BCI = conditionalToBiconditional ruleOf BCE = biconditionalToTwoConditional ruleOf ORI1 = additionVariations !! 0 ruleOf ORI2 = additionVariations !! 1 ruleOf ORE = explicitSeparationOfCases 2 ruleOf As = axiom ruleOf (Pr _) = axiom ruleOf CP = explicitConditionalProofVariations !! 0 ruleOf RAA1 = explictConstructiveConjunctionReductioVariations !! 0 ruleOf RAA2 = explictConstructiveConjunctionReductioVariations !! 2 restriction (Pr prems) = Just (premConstraint prems) restriction _ = Nothing globalRestriction (Left ded) n CP = Just (dischargeConstraint n ded (view lhs $ conclusionOf CP)) globalRestriction (Left ded) n RAA1 = Just (dischargeConstraint n ded (view lhs $ conclusionOf RAA1)) globalRestriction (Left ded) n RAA2 = Just (dischargeConstraint n ded (view lhs $ conclusionOf RAA2)) globalRestriction (Left ded) n ORE = Just (dischargeConstraint n ded (view lhs $ conclusionOf ORE)) globalRestriction _ _ _ = Nothing indirectInference CP = Just $ TypedProof (ProofType 1 1) indirectInference RAA1 = Just $ TypedProof (ProofType 1 1) indirectInference RAA2 = Just $ TypedProof (ProofType 1 1) indirectInference ORE = Just $ PolyTypedProof 2 (ProofType 1 1) indirectInference _ = Nothing isAssumption As = True isAssumption (Pr _) = True isAssumption _ = False parseTomassiPL rtc n _ = do r <- choice (map (try . string) [ "&I", "&E", "MP", "MT", "~I", "DNI", "~E", "DNE", "↔I", "<->I", "↔E", "<->E" , "∨I", "vI", "\\/I", "∨E", "vE", "\\/E", "As", "CP", "RAA", "Pr"]) return $ case r of r | r == "As" -> [As] | r == "Pr" -> [Pr (problemPremises rtc)] | r == "&I" -> [AndI] | r == "&E" -> [AndE1, AndE2] | r == "MP" -> [MP] | r == "MT" -> [MT] | r `elem` ["~I","DNI"] -> [DNI] | r `elem` ["~E","DNE"] -> [DNE] | r `elem` ["↔I","<->I"] -> [BCI] | r `elem` ["↔E","<->E"] -> [BCE] | r `elem` ["∨I", "vI", "\\/I"] -> [ORI1, ORI2] | r `elem` ["∨E", "vE", "\\/E"] -> [ORE] | r == "RAA" -> [RAA1, RAA2] | r == "CP" -> [CP] parseTomassiPLProof :: RuntimeNaturalDeductionConfig PurePropLexicon (Form Bool) -> String -> [DeductionLine TomassiPL PurePropLexicon (Form Bool)] parseTomassiPLProof rtc = toDeductionLemmonTomassi (parseTomassiPL rtc) (purePropFormulaParser standardLetters) tomassiPLNotation :: String -> String tomassiPLNotation = map replace where replace '∧' = '&' replace '¬' = '~' replace c = c tomassiPLCalc = mkNDCalc { ndRenderer = LemmonStyle TomassiStyle , ndParseProof = parseTomassiPLProof , ndProcessLine = hoProcessLineLemmon , ndProcessLineMemo = Just hoProcessLineLemmonMemo , ndNotation = tomassiPLNotation }
opentower/carnap
Carnap/src/Carnap/Languages/PurePropositional/Logic/Tomassi.hs
gpl-3.0
5,454
0
15
1,815
1,485
799
686
106
3
-- A Pythagorean triplet is a set of three natural numbers, a < b < c, for which -- a**2 + b**2 = c**2 -- For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2. -- There exists exactly one Pythagorean triplet for which a + b + c = 1000. -- Find the product abc. getmn :: [(Integer, Integer)] getmn = [(m, n) | n <- [3..999], m <- [n + 1..1000], m `mod` 2 == 1, m * n + (m^2 - n^2) `quot` 2 + (m^2 + n^2) `quot` 2 == 1000] triplet :: (Integer, Integer) -> [Integer] triplet (m, n) = [a, b, c] where a = m * n b = quot (m^2 - n^2) 2 c = quot (m^2 + n^2) 2 main :: IO () main = do putStrLn . show $ product $ triplet $ head getmn
ignuki/projecteuler
9/problem9.hs
gpl-3.0
672
0
15
201
279
156
123
13
1
module HFlint.Test.FMPZ.Integer where import Control.Arrow ( (***) ) import Data.Composition ( (.:) ) import Math.Structure.Tasty import Test.Tasty ( testGroup, TestTree ) import Test.Tasty.HUnit ( testCase, (@?=), (@=?) ) import qualified Math.Structure as M import HFlint.FMPZ import HFlint.Test.Utility.DivisionByZero -- Integer is a reference implementation for FMPZ referenceIngeger :: TestTree referenceIngeger = testGroup "Compare with Integer" [ -- Show instance testPropertyQSC "Show" $ intertwiningMorphisms (fromInteger :: Integer -> FMPZ) show show -- Eq instance , testPropertyQSC "Eq" $ intertwiningInnerPairing (fromInteger :: Integer -> FMPZ) (==) (==) -- Ord instance , testPropertyQSC "Ord" $ intertwiningInnerPairing (fromInteger :: Integer -> FMPZ) compare compare -- Enum instance , testPropertyQSC "toEnum" $ intertwiningMorphisms (toEnum :: Int -> FMPZ) (fromIntegral :: Int -> Integer) toInteger , testPropertyQSC "fromEnum" $ intertwiningMorphisms (fromInteger :: Integer -> FMPZ) fromEnum fromEnum -- Num instance , testPropertyQSC "toInteger . fromInteger" $ intertwiningMorphisms (fromInteger :: Integer -> FMPZ) id toInteger , testPropertyQSC "add" $ intertwiningBinaryOperators (fromInteger :: Integer -> FMPZ) (+) (+) , testPropertyQSC "sub" $ intertwiningBinaryOperators (fromInteger :: Integer -> FMPZ) (-) (-) , testPropertyQSC "mul" $ intertwiningBinaryOperators (fromInteger :: Integer -> FMPZ) (*) (*) , testPropertyQSC "negate" $ intertwiningEndomorphisms (fromInteger :: Integer -> FMPZ) negate negate , testPropertyQSC "abs" $ intertwiningEndomorphisms (fromInteger :: Integer -> FMPZ) abs abs , testPropertyQSC "signum" $ intertwiningEndomorphisms (fromInteger :: Integer -> FMPZ) signum signum -- Real instance -- Integral instance , testPropertyQSC "quot" $ intertwiningBinaryOperators (fmap fromInteger :: Maybe Integer -> Maybe FMPZ) (wrapDivideByZero2 quot) (wrapDivideByZero2 quot) , testPropertyQSC "quotRem" $ intertwiningInnerPairing (fmap fromInteger :: Maybe Integer -> Maybe FMPZ) (fmap (fromInteger *** fromInteger) .: wrapDivideByZero2 quotRem) (wrapDivideByZero2 quotRem) , testPropertyQSC "div" $ intertwiningBinaryOperators (fmap fromInteger :: Maybe Integer -> Maybe FMPZ) (wrapDivideByZero2 div) (wrapDivideByZero2 div) , testPropertyQSC "divMod" $ intertwiningInnerPairing (fmap fromInteger :: Maybe Integer -> Maybe FMPZ) (fmap (fromInteger *** fromInteger) .: wrapDivideByZero2 divMod) (wrapDivideByZero2 divMod) ] zeroOneUnitTests :: TestTree zeroOneUnitTests = testGroup "Zero & One Unit Tests" [ testCase "zero" $ fromInteger (M.zero :: Integer) @=? (M.zero :: FMPZ) , testCase "one" $ fromInteger (M.one :: Integer) @=? (M.one :: FMPZ) ]
martinra/hflint
test/HFlint/Test/FMPZ/Integer.hs
gpl-3.0
3,005
0
13
640
766
419
347
68
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.Analytics -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Views and manages your Google Analytics data. -- -- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> module Network.Google.Analytics ( -- * Service Configuration analyticsService -- * OAuth Scopes , analyticsManageUsersScope , analyticsProvisionScope , analyticsManageUsersReadOnlyScope , analyticsScope , analyticsReadOnlyScope , analyticsUserDeletionScope , analyticsEditScope -- * API Declaration , AnalyticsAPI -- * Resources -- ** analytics.data.ga.get , module Network.Google.Resource.Analytics.Data.Ga.Get -- ** analytics.data.mcf.get , module Network.Google.Resource.Analytics.Data.Mcf.Get -- ** analytics.data.realtime.get , module Network.Google.Resource.Analytics.Data.Realtime.Get -- ** analytics.management.accountSummaries.list , module Network.Google.Resource.Analytics.Management.AccountSummaries.List -- ** analytics.management.accountUserLinks.delete , module Network.Google.Resource.Analytics.Management.AccountUserLinks.Delete -- ** analytics.management.accountUserLinks.insert , module Network.Google.Resource.Analytics.Management.AccountUserLinks.Insert -- ** analytics.management.accountUserLinks.list , module Network.Google.Resource.Analytics.Management.AccountUserLinks.List -- ** analytics.management.accountUserLinks.update , module Network.Google.Resource.Analytics.Management.AccountUserLinks.Update -- ** analytics.management.accounts.list , module Network.Google.Resource.Analytics.Management.Accounts.List -- ** analytics.management.clientId.hashClientId , module Network.Google.Resource.Analytics.Management.ClientId.HashClientId -- ** analytics.management.customDataSources.list , module Network.Google.Resource.Analytics.Management.CustomDataSources.List -- ** analytics.management.customDimensions.get , module Network.Google.Resource.Analytics.Management.CustomDimensions.Get -- ** analytics.management.customDimensions.insert , module Network.Google.Resource.Analytics.Management.CustomDimensions.Insert -- ** analytics.management.customDimensions.list , module Network.Google.Resource.Analytics.Management.CustomDimensions.List -- ** analytics.management.customDimensions.patch , module Network.Google.Resource.Analytics.Management.CustomDimensions.Patch -- ** analytics.management.customDimensions.update , module Network.Google.Resource.Analytics.Management.CustomDimensions.Update -- ** analytics.management.customMetrics.get , module Network.Google.Resource.Analytics.Management.CustomMetrics.Get -- ** analytics.management.customMetrics.insert , module Network.Google.Resource.Analytics.Management.CustomMetrics.Insert -- ** analytics.management.customMetrics.list , module Network.Google.Resource.Analytics.Management.CustomMetrics.List -- ** analytics.management.customMetrics.patch , module Network.Google.Resource.Analytics.Management.CustomMetrics.Patch -- ** analytics.management.customMetrics.update , module Network.Google.Resource.Analytics.Management.CustomMetrics.Update -- ** analytics.management.experiments.delete , module Network.Google.Resource.Analytics.Management.Experiments.Delete -- ** analytics.management.experiments.get , module Network.Google.Resource.Analytics.Management.Experiments.Get -- ** analytics.management.experiments.insert , module Network.Google.Resource.Analytics.Management.Experiments.Insert -- ** analytics.management.experiments.list , module Network.Google.Resource.Analytics.Management.Experiments.List -- ** analytics.management.experiments.patch , module Network.Google.Resource.Analytics.Management.Experiments.Patch -- ** analytics.management.experiments.update , module Network.Google.Resource.Analytics.Management.Experiments.Update -- ** analytics.management.filters.delete , module Network.Google.Resource.Analytics.Management.Filters.Delete -- ** analytics.management.filters.get , module Network.Google.Resource.Analytics.Management.Filters.Get -- ** analytics.management.filters.insert , module Network.Google.Resource.Analytics.Management.Filters.Insert -- ** analytics.management.filters.list , module Network.Google.Resource.Analytics.Management.Filters.List -- ** analytics.management.filters.patch , module Network.Google.Resource.Analytics.Management.Filters.Patch -- ** analytics.management.filters.update , module Network.Google.Resource.Analytics.Management.Filters.Update -- ** analytics.management.goals.get , module Network.Google.Resource.Analytics.Management.Goals.Get -- ** analytics.management.goals.insert , module Network.Google.Resource.Analytics.Management.Goals.Insert -- ** analytics.management.goals.list , module Network.Google.Resource.Analytics.Management.Goals.List -- ** analytics.management.goals.patch , module Network.Google.Resource.Analytics.Management.Goals.Patch -- ** analytics.management.goals.update , module Network.Google.Resource.Analytics.Management.Goals.Update -- ** analytics.management.profileFilterLinks.delete , module Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Delete -- ** analytics.management.profileFilterLinks.get , module Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Get -- ** analytics.management.profileFilterLinks.insert , module Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Insert -- ** analytics.management.profileFilterLinks.list , module Network.Google.Resource.Analytics.Management.ProFileFilterLinks.List -- ** analytics.management.profileFilterLinks.patch , module Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Patch -- ** analytics.management.profileFilterLinks.update , module Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Update -- ** analytics.management.profileUserLinks.delete , module Network.Google.Resource.Analytics.Management.ProFileUserLinks.Delete -- ** analytics.management.profileUserLinks.insert , module Network.Google.Resource.Analytics.Management.ProFileUserLinks.Insert -- ** analytics.management.profileUserLinks.list , module Network.Google.Resource.Analytics.Management.ProFileUserLinks.List -- ** analytics.management.profileUserLinks.update , module Network.Google.Resource.Analytics.Management.ProFileUserLinks.Update -- ** analytics.management.profiles.delete , module Network.Google.Resource.Analytics.Management.ProFiles.Delete -- ** analytics.management.profiles.get , module Network.Google.Resource.Analytics.Management.ProFiles.Get -- ** analytics.management.profiles.insert , module Network.Google.Resource.Analytics.Management.ProFiles.Insert -- ** analytics.management.profiles.list , module Network.Google.Resource.Analytics.Management.ProFiles.List -- ** analytics.management.profiles.patch , module Network.Google.Resource.Analytics.Management.ProFiles.Patch -- ** analytics.management.profiles.update , module Network.Google.Resource.Analytics.Management.ProFiles.Update -- ** analytics.management.remarketingAudience.delete , module Network.Google.Resource.Analytics.Management.RemarketingAudience.Delete -- ** analytics.management.remarketingAudience.get , module Network.Google.Resource.Analytics.Management.RemarketingAudience.Get -- ** analytics.management.remarketingAudience.insert , module Network.Google.Resource.Analytics.Management.RemarketingAudience.Insert -- ** analytics.management.remarketingAudience.list , module Network.Google.Resource.Analytics.Management.RemarketingAudience.List -- ** analytics.management.remarketingAudience.patch , module Network.Google.Resource.Analytics.Management.RemarketingAudience.Patch -- ** analytics.management.remarketingAudience.update , module Network.Google.Resource.Analytics.Management.RemarketingAudience.Update -- ** analytics.management.segments.list , module Network.Google.Resource.Analytics.Management.Segments.List -- ** analytics.management.unsampledReports.delete , module Network.Google.Resource.Analytics.Management.UnSampledReports.Delete -- ** analytics.management.unsampledReports.get , module Network.Google.Resource.Analytics.Management.UnSampledReports.Get -- ** analytics.management.unsampledReports.insert , module Network.Google.Resource.Analytics.Management.UnSampledReports.Insert -- ** analytics.management.unsampledReports.list , module Network.Google.Resource.Analytics.Management.UnSampledReports.List -- ** analytics.management.uploads.deleteUploadData , module Network.Google.Resource.Analytics.Management.Uploads.DeleteUploadData -- ** analytics.management.uploads.get , module Network.Google.Resource.Analytics.Management.Uploads.Get -- ** analytics.management.uploads.list , module Network.Google.Resource.Analytics.Management.Uploads.List -- ** analytics.management.uploads.uploadData , module Network.Google.Resource.Analytics.Management.Uploads.UploadData -- ** analytics.management.webPropertyAdWordsLinks.delete , module Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Delete -- ** analytics.management.webPropertyAdWordsLinks.get , module Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Get -- ** analytics.management.webPropertyAdWordsLinks.insert , module Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Insert -- ** analytics.management.webPropertyAdWordsLinks.list , module Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.List -- ** analytics.management.webPropertyAdWordsLinks.patch , module Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Patch -- ** analytics.management.webPropertyAdWordsLinks.update , module Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Update -- ** analytics.management.webproperties.get , module Network.Google.Resource.Analytics.Management.WebProperties.Get -- ** analytics.management.webproperties.insert , module Network.Google.Resource.Analytics.Management.WebProperties.Insert -- ** analytics.management.webproperties.list , module Network.Google.Resource.Analytics.Management.WebProperties.List -- ** analytics.management.webproperties.patch , module Network.Google.Resource.Analytics.Management.WebProperties.Patch -- ** analytics.management.webproperties.update , module Network.Google.Resource.Analytics.Management.WebProperties.Update -- ** analytics.management.webpropertyUserLinks.delete , module Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.Delete -- ** analytics.management.webpropertyUserLinks.insert , module Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.Insert -- ** analytics.management.webpropertyUserLinks.list , module Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.List -- ** analytics.management.webpropertyUserLinks.update , module Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.Update -- ** analytics.metadata.columns.list , module Network.Google.Resource.Analytics.Metadata.Columns.List -- ** analytics.provisioning.createAccountTicket , module Network.Google.Resource.Analytics.Provisioning.CreateAccountTicket -- ** analytics.provisioning.createAccountTree , module Network.Google.Resource.Analytics.Provisioning.CreateAccountTree -- ** analytics.userDeletion.userDeletionRequest.upsert , module Network.Google.Resource.Analytics.UserDeletion.UserDeletionRequest.Upsert -- * Types -- ** UserDeletionRequest , UserDeletionRequest , userDeletionRequest , udrWebPropertyId , udrKind , udrPropertyId , udrId , udrFirebaseProjectId , udrDeletionRequestTime -- ** UnSampledReports , UnSampledReports , unSampledReports , usrNextLink , usrItemsPerPage , usrKind , usrUsername , usrItems , usrTotalResults , usrStartIndex , usrPreviousLink -- ** GoalURLDestinationDetailsStepsItem , GoalURLDestinationDetailsStepsItem , goalURLDestinationDetailsStepsItem , guddsiURL , guddsiName , guddsiNumber -- ** GaDataQuery , GaDataQuery , gaDataQuery , gdqMetrics , gdqSamplingLevel , gdqFilters , gdqIds , gdqEndDate , gdqSort , gdqDimensions , gdqStartIndex , gdqMaxResults , gdqSegment , gdqStartDate -- ** RemarketingAudiences , RemarketingAudiences , remarketingAudiences , raNextLink , raItemsPerPage , raKind , raUsername , raItems , raTotalResults , raStartIndex , raPreviousLink -- ** GaDataDataTableRowsItem , GaDataDataTableRowsItem , gaDataDataTableRowsItem , gddtriC -- ** UnSampledReport , UnSampledReport , unSampledReport , uDownloadType , uStatus , uMetrics , uDriveDownloadDetails , uWebPropertyId , uKind , uCreated , uFilters , uProFileId , uEndDate , uSelfLink , uAccountId , uId , uUpdated , uTitle , uDimensions , uSegment , uCloudStorageDownloadDetails , uStartDate -- ** McfDataColumnHeadersItem , McfDataColumnHeadersItem , mcfDataColumnHeadersItem , mdchiColumnType , mdchiName , mdchiDataType -- ** GaDataTotalsForAllResults , GaDataTotalsForAllResults , gaDataTotalsForAllResults , gdtfarAddtional -- ** ProFileParentLink , ProFileParentLink , proFileParentLink , pfplHref , pfplType -- ** RemarketingAudience , RemarketingAudience , remarketingAudience , rWebPropertyId , rKind , rCreated , rLinkedAdAccounts , rAudienceDefinition , rAudienceType , rAccountId , rName , rStateBasedAudienceDefinition , rLinkedViews , rInternalWebPropertyId , rId , rUpdated , rDescription -- ** GaDataDataTableRowsItemCItem , GaDataDataTableRowsItemCItem , gaDataDataTableRowsItemCItem , gddtriciV -- ** EntityUserLinkPermissions , EntityUserLinkPermissions , entityUserLinkPermissions , eulpLocal , eulpEffective -- ** RealtimeDataProFileInfo , RealtimeDataProFileInfo , realtimeDataProFileInfo , rdpfiWebPropertyId , rdpfiProFileId , rdpfiProFileName , rdpfiAccountId , rdpfiInternalWebPropertyId , rdpfiTableId -- ** McfDataRowsItemItemConversionPathValueItem , McfDataRowsItemItemConversionPathValueItem , mcfDataRowsItemItemConversionPathValueItem , mdriicpviInteractionType , mdriicpviNodeValue -- ** FilterExpression , FilterExpression , filterExpression , feFieldIndex , feField , feKind , feMatchType , feCaseSensitive , feExpressionValue -- ** ProFileRef , ProFileRef , proFileRef , pfrWebPropertyId , pfrKind , pfrHref , pfrAccountId , pfrName , pfrInternalWebPropertyId , pfrId -- ** Accounts , Accounts , accounts , aNextLink , aItemsPerPage , aKind , aUsername , aItems , aTotalResults , aStartIndex , aPreviousLink -- ** Experiments , Experiments , experiments , eNextLink , eItemsPerPage , eKind , eUsername , eItems , eTotalResults , eStartIndex , ePreviousLink -- ** ExperimentParentLink , ExperimentParentLink , experimentParentLink , eplHref , eplType -- ** UnSampledReportDriveDownloadDetails , UnSampledReportDriveDownloadDetails , unSampledReportDriveDownloadDetails , usrdddDocumentId -- ** McfDataProFileInfo , McfDataProFileInfo , mcfDataProFileInfo , mdpfiWebPropertyId , mdpfiProFileId , mdpfiProFileName , mdpfiAccountId , mdpfiInternalWebPropertyId , mdpfiTableId -- ** CustomDataSources , CustomDataSources , customDataSources , cdsNextLink , cdsItemsPerPage , cdsKind , cdsUsername , cdsItems , cdsTotalResults , cdsStartIndex , cdsPreviousLink -- ** WebPropertyChildLink , WebPropertyChildLink , webPropertyChildLink , wpclHref , wpclType -- ** DataGaGetSamplingLevel , DataGaGetSamplingLevel (..) -- ** HashClientIdResponse , HashClientIdResponse , hashClientIdResponse , hcirClientId , hcirWebPropertyId , hcirKind , hcirHashedClientId -- ** McfData , McfData , mcfData , mdNextLink , mdSampleSpace , mdItemsPerPage , mdProFileInfo , mdKind , mdSampleSize , mdRows , mdSelfLink , mdQuery , mdColumnHeaders , mdId , mdTotalResults , mdContainsSampledData , mdTotalsForAllResults , mdPreviousLink -- ** UserRef , UserRef , userRef , urEmail , urKind , urId -- ** GoalVisitNumPagesDetails , GoalVisitNumPagesDetails , goalVisitNumPagesDetails , gvnpdComparisonValue , gvnpdComparisonType -- ** RealtimeDataColumnHeadersItem , RealtimeDataColumnHeadersItem , realtimeDataColumnHeadersItem , rdchiColumnType , rdchiName , rdchiDataType -- ** AccountRef , AccountRef , accountRef , arKind , arHref , arName , arId -- ** EntityAdWordsLinks , EntityAdWordsLinks , entityAdWordsLinks , eawlNextLink , eawlItemsPerPage , eawlKind , eawlItems , eawlTotalResults , eawlStartIndex , eawlPreviousLink -- ** ProFiles , ProFiles , proFiles , pfNextLink , pfItemsPerPage , pfKind , pfUsername , pfItems , pfTotalResults , pfStartIndex , pfPreviousLink -- ** AnalyticsDataimportDeleteUploadDataRequest , AnalyticsDataimportDeleteUploadDataRequest , analyticsDataimportDeleteUploadDataRequest , addudrCustomDataImportUids -- ** EntityAdWordsLink , EntityAdWordsLink , entityAdWordsLink , entAdWordsAccounts , entProFileIds , entKind , entSelfLink , entName , entId , entEntity -- ** FilterSearchAndReplaceDetails , FilterSearchAndReplaceDetails , filterSearchAndReplaceDetails , fsardFieldIndex , fsardField , fsardSearchString , fsardReplaceString , fsardCaseSensitive -- ** ProFilePermissions , ProFilePermissions , proFilePermissions , pfpEffective -- ** ProFile , ProFile , proFile , pParentLink , pECommerceTracking , pSiteSearchCategoryParameters , pWebPropertyId , pChildLink , pSiteSearchQueryParameters , pKind , pDefaultPage , pCreated , pSelfLink , pAccountId , pBotFilteringEnabled , pName , pCurrency , pStarred , pInternalWebPropertyId , pId , pUpdated , pPermissions , pWebsiteURL , pType , pStripSiteSearchCategoryParameters , pTimezone , pExcludeQueryParameters , pEnhancedECommerceTracking , pStripSiteSearchQueryParameters -- ** AccountSummaries , AccountSummaries , accountSummaries , asNextLink , asItemsPerPage , asKind , asUsername , asItems , asTotalResults , asStartIndex , asPreviousLink -- ** GoalEventDetails , GoalEventDetails , goalEventDetails , gedUseEventValue , gedEventConditions -- ** WebPropertySummary , WebPropertySummary , webPropertySummary , wpsKind , wpsProFiles , wpsName , wpsStarred , wpsInternalWebPropertyId , wpsId , wpsWebsiteURL , wpsLevel -- ** Filters , Filters , filters , fNextLink , fItemsPerPage , fKind , fUsername , fItems , fTotalResults , fStartIndex , fPreviousLink -- ** GaData , GaData , gaData , gdNextLink , gdSampleSpace , gdItemsPerPage , gdProFileInfo , gdKind , gdSampleSize , gdRows , gdSelfLink , gdQuery , gdColumnHeaders , gdId , gdTotalResults , gdDataLastRefreshed , gdDataTable , gdContainsSampledData , gdTotalsForAllResults , gdPreviousLink -- ** RealtimeDataTotalsForAllResults , RealtimeDataTotalsForAllResults , realtimeDataTotalsForAllResults , rdtfarAddtional -- ** CustomDataSource , CustomDataSource , customDataSource , cParentLink , cWebPropertyId , cChildLink , cKind , cCreated , cUploadType , cSchema , cImportBehavior , cSelfLink , cAccountId , cName , cId , cUpdated , cType , cDescription , cProFilesLinked -- ** AccountTreeRequest , AccountTreeRequest , accountTreeRequest , atrWebPropertyName , atrKind , atrAccountName , atrProFileName , atrWebsiteURL , atrTimezone -- ** WebPropertyRef , WebPropertyRef , webPropertyRef , wprKind , wprHref , wprAccountId , wprName , wprInternalWebPropertyId , wprId -- ** LinkedForeignAccount , LinkedForeignAccount , linkedForeignAccount , lfaStatus , lfaWebPropertyId , lfaKind , lfaEligibleForSearch , lfaAccountId , lfaRemarketingAudienceId , lfaLinkedAccountId , lfaInternalWebPropertyId , lfaId , lfaType -- ** Goals , Goals , goals , gNextLink , gItemsPerPage , gKind , gUsername , gItems , gTotalResults , gStartIndex , gPreviousLink -- ** McfDataRowsItemItem , McfDataRowsItemItem , mcfDataRowsItemItem , mdriiPrimitiveValue , mdriiConversionPathValue -- ** AccountPermissions , AccountPermissions , accountPermissions , apEffective -- ** EntityUserLinkEntity , EntityUserLinkEntity , entityUserLinkEntity , euleProFileRef , euleAccountRef , euleWebPropertyRef -- ** Account , Account , account , accChildLink , accKind , accCreated , accSelfLink , accName , accStarred , accId , accUpdated , accPermissions -- ** Experiment , Experiment , experiment , expParentLink , expEqualWeighting , expStatus , expWebPropertyId , expStartTime , expSnippet , expKind , expCreated , expReasonExperimentEnded , expTrafficCoverage , expEditableInGaUi , expMinimumExperimentLengthInDays , expProFileId , expOptimizationType , expSelfLink , expAccountId , expName , expWinnerFound , expEndTime , expVariations , expInternalWebPropertyId , expId , expUpdated , expRewriteVariationURLsAsOriginal , expObjectiveMetric , expWinnerConfidenceLevel , expServingFramework , expDescription -- ** EntityUserLinks , EntityUserLinks , entityUserLinks , eulNextLink , eulItemsPerPage , eulKind , eulItems , eulTotalResults , eulStartIndex , eulPreviousLink -- ** AdWordsAccount , AdWordsAccount , adWordsAccount , awaAutoTaggingEnabled , awaKind , awaCustomerId -- ** FilterRef , FilterRef , filterRef , frKind , frHref , frAccountId , frName , frId -- ** GoalVisitTimeOnSiteDetails , GoalVisitTimeOnSiteDetails , goalVisitTimeOnSiteDetails , gvtosdComparisonValue , gvtosdComparisonType -- ** WebProperties , WebProperties , webProperties , wpNextLink , wpItemsPerPage , wpKind , wpUsername , wpItems , wpTotalResults , wpStartIndex , wpPreviousLink -- ** CustomMetrics , CustomMetrics , customMetrics , cmNextLink , cmItemsPerPage , cmKind , cmUsername , cmItems , cmTotalResults , cmStartIndex , cmPreviousLink -- ** FilterAdvancedDetails , FilterAdvancedDetails , filterAdvancedDetails , fadExtractA , fadFieldARequired , fadFieldA , fadFieldBIndex , fadOutputToField , fadOutputConstructor , fadExtractB , fadFieldAIndex , fadCaseSensitive , fadOutputToFieldIndex , fadFieldB , fadFieldBRequired , fadOverrideOutputField -- ** AccountTreeResponse , AccountTreeResponse , accountTreeResponse , atrtKind , atrtProFile , atrtAccount , atrtWebProperty -- ** FilterUppercaseDetails , FilterUppercaseDetails , filterUppercaseDetails , fudFieldIndex , fudField -- ** CustomDataSourceChildLink , CustomDataSourceChildLink , customDataSourceChildLink , cdsclHref , cdsclType -- ** IncludeConditions , IncludeConditions , includeConditions , icKind , icDaysToLookBack , icMembershipDurationDays , icSegment , icIsSmartList -- ** FilterParentLink , FilterParentLink , filterParentLink , fplHref , fplType -- ** DataGaGetOutput , DataGaGetOutput (..) -- ** HashClientIdRequest , HashClientIdRequest , hashClientIdRequest , hClientId , hWebPropertyId , hKind -- ** RealtimeData , RealtimeData , realtimeData , rdProFileInfo , rdKind , rdRows , rdSelfLink , rdQuery , rdColumnHeaders , rdId , rdTotalResults , rdTotalsForAllResults -- ** CustomMetric , CustomMetric , customMetric , cusParentLink , cusWebPropertyId , cusKind , cusMaxValue , cusCreated , cusMinValue , cusActive , cusSelfLink , cusAccountId , cusName , cusScope , cusId , cusUpdated , cusType , cusIndex -- ** ProFileSummary , ProFileSummary , proFileSummary , pfsKind , pfsName , pfsStarred , pfsId , pfsType -- ** CustomDimensionParentLink , CustomDimensionParentLink , customDimensionParentLink , cdplHref , cdplType -- ** WebProperty , WebProperty , webProperty , wParentLink , wChildLink , wDefaultProFileId , wKind , wCreated , wDataRetentionTtl , wDataRetentionResetOnNewActivity , wSelfLink , wAccountId , wName , wStarred , wInternalWebPropertyId , wId , wUpdated , wProFileCount , wPermissions , wWebsiteURL , wIndustryVertical , wLevel -- ** WebPropertyPermissions , WebPropertyPermissions , webPropertyPermissions , wppEffective -- ** EntityUserLink , EntityUserLink , entityUserLink , euluKind , euluUserRef , euluSelfLink , euluId , euluPermissions , euluEntity -- ** CustomDataSourceParentLink , CustomDataSourceParentLink , customDataSourceParentLink , cdsplHref , cdsplType -- ** GoalEventDetailsEventConditionsItem , GoalEventDetailsEventConditionsItem , goalEventDetailsEventConditionsItem , gedeciMatchType , gedeciExpression , gedeciComparisonValue , gedeciType , gedeciComparisonType -- ** McfDataQuery , McfDataQuery , mcfDataQuery , mdqMetrics , mdqSamplingLevel , mdqFilters , mdqIds , mdqEndDate , mdqSort , mdqDimensions , mdqStartIndex , mdqMaxResults , mdqSegment , mdqStartDate -- ** Goal , Goal , goal , goaParentLink , goaWebPropertyId , goaKind , goaCreated , goaValue , goaProFileId , goaEventDetails , goaActive , goaSelfLink , goaVisitTimeOnSiteDetails , goaAccountId , goaName , goaInternalWebPropertyId , goaId , goaURLDestinationDetails , goaVisitNumPagesDetails , goaUpdated , goaType -- ** AccountTicket , AccountTicket , accountTicket , atRedirectURI , atKind , atProFile , atAccount , atWebProperty , atId -- ** AccountSummary , AccountSummary , accountSummary , assKind , assWebProperties , assName , assStarred , assId -- ** RealtimeDataQuery , RealtimeDataQuery , realtimeDataQuery , rdqMetrics , rdqFilters , rdqIds , rdqSort , rdqDimensions , rdqMaxResults -- ** Columns , Columns , columns , colEtag , colKind , colItems , colTotalResults , colAttributeNames -- ** FilterLowercaseDetails , FilterLowercaseDetails , filterLowercaseDetails , fldFieldIndex , fldField -- ** Filter , Filter , filter' , filParentLink , filAdvancedDetails , filUppercaseDetails , filLowercaseDetails , filKind , filCreated , filIncludeDetails , filExcludeDetails , filSelfLink , filAccountId , filName , filId , filUpdated , filType , filSearchAndReplaceDetails -- ** Uploads , Uploads , uploads , uplNextLink , uplItemsPerPage , uplKind , uplItems , uplTotalResults , uplStartIndex , uplPreviousLink -- ** CustomDimensions , CustomDimensions , customDimensions , cdNextLink , cdItemsPerPage , cdKind , cdUsername , cdItems , cdTotalResults , cdStartIndex , cdPreviousLink -- ** Segments , Segments , segments , sNextLink , sItemsPerPage , sKind , sUsername , sItems , sTotalResults , sStartIndex , sPreviousLink -- ** GaDataDataTable , GaDataDataTable , gaDataDataTable , gddtCols , gddtRows -- ** EntityAdWordsLinkEntity , EntityAdWordsLinkEntity , entityAdWordsLinkEntity , eawleWebPropertyRef -- ** RemarketingAudienceStateBasedAudienceDefinition , RemarketingAudienceStateBasedAudienceDefinition , remarketingAudienceStateBasedAudienceDefinition , rasbadExcludeConditions , rasbadIncludeConditions -- ** GoalURLDestinationDetails , GoalURLDestinationDetails , goalURLDestinationDetails , guddURL , guddMatchType , guddSteps , guddCaseSensitive , guddFirstStepRequired -- ** ProFileFilterLinks , ProFileFilterLinks , proFileFilterLinks , pfflNextLink , pfflItemsPerPage , pfflKind , pfflUsername , pfflItems , pfflTotalResults , pfflStartIndex , pfflPreviousLink -- ** WebPropertyParentLink , WebPropertyParentLink , webPropertyParentLink , wpplHref , wpplType -- ** GaDataProFileInfo , GaDataProFileInfo , gaDataProFileInfo , gdpfiWebPropertyId , gdpfiProFileId , gdpfiProFileName , gdpfiAccountId , gdpfiInternalWebPropertyId , gdpfiTableId -- ** Upload , Upload , upload , uuStatus , uuKind , uuCustomDataSourceId , uuUploadTime , uuAccountId , uuId , uuErrors -- ** DataMcfGetSamplingLevel , DataMcfGetSamplingLevel (..) -- ** CustomDimension , CustomDimension , customDimension , cddParentLink , cddWebPropertyId , cddKind , cddCreated , cddActive , cddSelfLink , cddAccountId , cddName , cddScope , cddId , cddUpdated , cddIndex -- ** Segment , Segment , segment , segDefinition , segKind , segCreated , segSelfLink , segName , segId , segUpdated , segType , segSegmentId -- ** AccountChildLink , AccountChildLink , accountChildLink , aclHref , aclType -- ** ProFileFilterLink , ProFileFilterLink , proFileFilterLink , proProFileRef , proKind , proFilterRef , proSelfLink , proId , proRank -- ** CustomMetricParentLink , CustomMetricParentLink , customMetricParentLink , cmplHref , cmplType -- ** Column , Column , column , ccKind , ccAttributes , ccId -- ** RemarketingAudienceAudienceDefinition , RemarketingAudienceAudienceDefinition , remarketingAudienceAudienceDefinition , raadIncludeConditions -- ** GaDataDataTableColsItem , GaDataDataTableColsItem , gaDataDataTableColsItem , gddtciId , gddtciType , gddtciLabel -- ** ExperimentVariationsItem , ExperimentVariationsItem , experimentVariationsItem , eviStatus , eviWeight , eviURL , eviWon , eviName -- ** RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions , RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions , remarketingAudienceStateBasedAudienceDefinitionExcludeConditions , rasbadecExclusionDuration , rasbadecSegment -- ** McfDataTotalsForAllResults , McfDataTotalsForAllResults , mcfDataTotalsForAllResults , mdtfarAddtional -- ** UserDeletionRequestId , UserDeletionRequestId , userDeletionRequestId , udriUserId , udriType -- ** UnSampledReportCloudStorageDownloadDetails , UnSampledReportCloudStorageDownloadDetails , unSampledReportCloudStorageDownloadDetails , usrcsddObjectId , usrcsddBucketId -- ** ProFileChildLink , ProFileChildLink , proFileChildLink , pfclHref , pfclType -- ** GaDataColumnHeadersItem , GaDataColumnHeadersItem , gaDataColumnHeadersItem , gdchiColumnType , gdchiName , gdchiDataType -- ** GoalParentLink , GoalParentLink , goalParentLink , gplHref , gplType -- ** ColumnAttributes , ColumnAttributes , columnAttributes , caAddtional ) where import Network.Google.Prelude import Network.Google.Analytics.Types import Network.Google.Resource.Analytics.Data.Ga.Get import Network.Google.Resource.Analytics.Data.Mcf.Get import Network.Google.Resource.Analytics.Data.Realtime.Get import Network.Google.Resource.Analytics.Management.AccountSummaries.List import Network.Google.Resource.Analytics.Management.AccountUserLinks.Delete import Network.Google.Resource.Analytics.Management.AccountUserLinks.Insert import Network.Google.Resource.Analytics.Management.AccountUserLinks.List import Network.Google.Resource.Analytics.Management.AccountUserLinks.Update import Network.Google.Resource.Analytics.Management.Accounts.List import Network.Google.Resource.Analytics.Management.ClientId.HashClientId import Network.Google.Resource.Analytics.Management.CustomDataSources.List import Network.Google.Resource.Analytics.Management.CustomDimensions.Get import Network.Google.Resource.Analytics.Management.CustomDimensions.Insert import Network.Google.Resource.Analytics.Management.CustomDimensions.List import Network.Google.Resource.Analytics.Management.CustomDimensions.Patch import Network.Google.Resource.Analytics.Management.CustomDimensions.Update import Network.Google.Resource.Analytics.Management.CustomMetrics.Get import Network.Google.Resource.Analytics.Management.CustomMetrics.Insert import Network.Google.Resource.Analytics.Management.CustomMetrics.List import Network.Google.Resource.Analytics.Management.CustomMetrics.Patch import Network.Google.Resource.Analytics.Management.CustomMetrics.Update import Network.Google.Resource.Analytics.Management.Experiments.Delete import Network.Google.Resource.Analytics.Management.Experiments.Get import Network.Google.Resource.Analytics.Management.Experiments.Insert import Network.Google.Resource.Analytics.Management.Experiments.List import Network.Google.Resource.Analytics.Management.Experiments.Patch import Network.Google.Resource.Analytics.Management.Experiments.Update import Network.Google.Resource.Analytics.Management.Filters.Delete import Network.Google.Resource.Analytics.Management.Filters.Get import Network.Google.Resource.Analytics.Management.Filters.Insert import Network.Google.Resource.Analytics.Management.Filters.List import Network.Google.Resource.Analytics.Management.Filters.Patch import Network.Google.Resource.Analytics.Management.Filters.Update import Network.Google.Resource.Analytics.Management.Goals.Get import Network.Google.Resource.Analytics.Management.Goals.Insert import Network.Google.Resource.Analytics.Management.Goals.List import Network.Google.Resource.Analytics.Management.Goals.Patch import Network.Google.Resource.Analytics.Management.Goals.Update import Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Delete import Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Get import Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Insert import Network.Google.Resource.Analytics.Management.ProFileFilterLinks.List import Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Patch import Network.Google.Resource.Analytics.Management.ProFileFilterLinks.Update import Network.Google.Resource.Analytics.Management.ProFileUserLinks.Delete import Network.Google.Resource.Analytics.Management.ProFileUserLinks.Insert import Network.Google.Resource.Analytics.Management.ProFileUserLinks.List import Network.Google.Resource.Analytics.Management.ProFileUserLinks.Update import Network.Google.Resource.Analytics.Management.ProFiles.Delete import Network.Google.Resource.Analytics.Management.ProFiles.Get import Network.Google.Resource.Analytics.Management.ProFiles.Insert import Network.Google.Resource.Analytics.Management.ProFiles.List import Network.Google.Resource.Analytics.Management.ProFiles.Patch import Network.Google.Resource.Analytics.Management.ProFiles.Update import Network.Google.Resource.Analytics.Management.RemarketingAudience.Delete import Network.Google.Resource.Analytics.Management.RemarketingAudience.Get import Network.Google.Resource.Analytics.Management.RemarketingAudience.Insert import Network.Google.Resource.Analytics.Management.RemarketingAudience.List import Network.Google.Resource.Analytics.Management.RemarketingAudience.Patch import Network.Google.Resource.Analytics.Management.RemarketingAudience.Update import Network.Google.Resource.Analytics.Management.Segments.List import Network.Google.Resource.Analytics.Management.UnSampledReports.Delete import Network.Google.Resource.Analytics.Management.UnSampledReports.Get import Network.Google.Resource.Analytics.Management.UnSampledReports.Insert import Network.Google.Resource.Analytics.Management.UnSampledReports.List import Network.Google.Resource.Analytics.Management.Uploads.DeleteUploadData import Network.Google.Resource.Analytics.Management.Uploads.Get import Network.Google.Resource.Analytics.Management.Uploads.List import Network.Google.Resource.Analytics.Management.Uploads.UploadData import Network.Google.Resource.Analytics.Management.WebProperties.Get import Network.Google.Resource.Analytics.Management.WebProperties.Insert import Network.Google.Resource.Analytics.Management.WebProperties.List import Network.Google.Resource.Analytics.Management.WebProperties.Patch import Network.Google.Resource.Analytics.Management.WebProperties.Update import Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Delete import Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Get import Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Insert import Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.List import Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Patch import Network.Google.Resource.Analytics.Management.WebPropertyAdWordsLinks.Update import Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.Delete import Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.Insert import Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.List import Network.Google.Resource.Analytics.Management.WebPropertyUserLinks.Update import Network.Google.Resource.Analytics.Metadata.Columns.List import Network.Google.Resource.Analytics.Provisioning.CreateAccountTicket import Network.Google.Resource.Analytics.Provisioning.CreateAccountTree import Network.Google.Resource.Analytics.UserDeletion.UserDeletionRequest.Upsert {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Google Analytics API service. type AnalyticsAPI = UserDeletionUserDeletionRequestUpsertResource :<|> DataMcfGetResource :<|> DataGaGetResource :<|> DataRealtimeGetResource :<|> ManagementClientIdHashClientIdResource :<|> ManagementWebPropertyAdWordsLinksInsertResource :<|> ManagementWebPropertyAdWordsLinksListResource :<|> ManagementWebPropertyAdWordsLinksPatchResource :<|> ManagementWebPropertyAdWordsLinksGetResource :<|> ManagementWebPropertyAdWordsLinksDeleteResource :<|> ManagementWebPropertyAdWordsLinksUpdateResource :<|> ManagementUnSampledReportsInsertResource :<|> ManagementUnSampledReportsListResource :<|> ManagementUnSampledReportsGetResource :<|> ManagementUnSampledReportsDeleteResource :<|> ManagementRemarketingAudienceInsertResource :<|> ManagementRemarketingAudienceListResource :<|> ManagementRemarketingAudiencePatchResource :<|> ManagementRemarketingAudienceGetResource :<|> ManagementRemarketingAudienceDeleteResource :<|> ManagementRemarketingAudienceUpdateResource :<|> ManagementAccountsListResource :<|> ManagementExperimentsInsertResource :<|> ManagementExperimentsListResource :<|> ManagementExperimentsPatchResource :<|> ManagementExperimentsGetResource :<|> ManagementExperimentsDeleteResource :<|> ManagementExperimentsUpdateResource :<|> ManagementCustomDataSourcesListResource :<|> ManagementWebPropertyUserLinksInsertResource :<|> ManagementWebPropertyUserLinksListResource :<|> ManagementWebPropertyUserLinksDeleteResource :<|> ManagementWebPropertyUserLinksUpdateResource :<|> ManagementProFilesInsertResource :<|> ManagementProFilesListResource :<|> ManagementProFilesPatchResource :<|> ManagementProFilesGetResource :<|> ManagementProFilesDeleteResource :<|> ManagementProFilesUpdateResource :<|> ManagementFiltersInsertResource :<|> ManagementFiltersListResource :<|> ManagementFiltersPatchResource :<|> ManagementFiltersGetResource :<|> ManagementFiltersDeleteResource :<|> ManagementFiltersUpdateResource :<|> ManagementAccountSummariesListResource :<|> ManagementGoalsInsertResource :<|> ManagementGoalsListResource :<|> ManagementGoalsPatchResource :<|> ManagementGoalsGetResource :<|> ManagementGoalsUpdateResource :<|> ManagementWebPropertiesInsertResource :<|> ManagementWebPropertiesListResource :<|> ManagementWebPropertiesPatchResource :<|> ManagementWebPropertiesGetResource :<|> ManagementWebPropertiesUpdateResource :<|> ManagementCustomMetricsInsertResource :<|> ManagementCustomMetricsListResource :<|> ManagementCustomMetricsPatchResource :<|> ManagementCustomMetricsGetResource :<|> ManagementCustomMetricsUpdateResource :<|> ManagementUploadsListResource :<|> ManagementUploadsDeleteUploadDataResource :<|> ManagementUploadsGetResource :<|> ManagementUploadsUploadDataResource :<|> ManagementSegmentsListResource :<|> ManagementProFileFilterLinksInsertResource :<|> ManagementProFileFilterLinksListResource :<|> ManagementProFileFilterLinksPatchResource :<|> ManagementProFileFilterLinksGetResource :<|> ManagementProFileFilterLinksDeleteResource :<|> ManagementProFileFilterLinksUpdateResource :<|> ManagementCustomDimensionsInsertResource :<|> ManagementCustomDimensionsListResource :<|> ManagementCustomDimensionsPatchResource :<|> ManagementCustomDimensionsGetResource :<|> ManagementCustomDimensionsUpdateResource :<|> ManagementAccountUserLinksInsertResource :<|> ManagementAccountUserLinksListResource :<|> ManagementAccountUserLinksDeleteResource :<|> ManagementAccountUserLinksUpdateResource :<|> ManagementProFileUserLinksInsertResource :<|> ManagementProFileUserLinksListResource :<|> ManagementProFileUserLinksDeleteResource :<|> ManagementProFileUserLinksUpdateResource :<|> ProvisioningCreateAccountTreeResource :<|> ProvisioningCreateAccountTicketResource :<|> MetadataColumnsListResource
brendanhay/gogol
gogol-analytics/gen/Network/Google/Analytics.hs
mpl-2.0
45,148
0
91
8,780
5,151
3,715
1,436
1,172
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Logging.Organizations.Sinks.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a sink. -- -- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.organizations.sinks.get@. module Network.Google.Resource.Logging.Organizations.Sinks.Get ( -- * REST Resource OrganizationsSinksGetResource -- * Creating a Request , organizationsSinksGet , OrganizationsSinksGet -- * Request Lenses , osgXgafv , osgUploadProtocol , osgAccessToken , osgUploadType , osgSinkName , osgCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.organizations.sinks.get@ method which the -- 'OrganizationsSinksGet' request conforms to. type OrganizationsSinksGetResource = "v2" :> Capture "sinkName" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] LogSink -- | Gets a sink. -- -- /See:/ 'organizationsSinksGet' smart constructor. data OrganizationsSinksGet = OrganizationsSinksGet' { _osgXgafv :: !(Maybe Xgafv) , _osgUploadProtocol :: !(Maybe Text) , _osgAccessToken :: !(Maybe Text) , _osgUploadType :: !(Maybe Text) , _osgSinkName :: !Text , _osgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrganizationsSinksGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'osgXgafv' -- -- * 'osgUploadProtocol' -- -- * 'osgAccessToken' -- -- * 'osgUploadType' -- -- * 'osgSinkName' -- -- * 'osgCallback' organizationsSinksGet :: Text -- ^ 'osgSinkName' -> OrganizationsSinksGet organizationsSinksGet pOsgSinkName_ = OrganizationsSinksGet' { _osgXgafv = Nothing , _osgUploadProtocol = Nothing , _osgAccessToken = Nothing , _osgUploadType = Nothing , _osgSinkName = pOsgSinkName_ , _osgCallback = Nothing } -- | V1 error format. osgXgafv :: Lens' OrganizationsSinksGet (Maybe Xgafv) osgXgafv = lens _osgXgafv (\ s a -> s{_osgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). osgUploadProtocol :: Lens' OrganizationsSinksGet (Maybe Text) osgUploadProtocol = lens _osgUploadProtocol (\ s a -> s{_osgUploadProtocol = a}) -- | OAuth access token. osgAccessToken :: Lens' OrganizationsSinksGet (Maybe Text) osgAccessToken = lens _osgAccessToken (\ s a -> s{_osgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). osgUploadType :: Lens' OrganizationsSinksGet (Maybe Text) osgUploadType = lens _osgUploadType (\ s a -> s{_osgUploadType = a}) -- | Required. The resource name of the sink: -- \"projects\/[PROJECT_ID]\/sinks\/[SINK_ID]\" -- \"organizations\/[ORGANIZATION_ID]\/sinks\/[SINK_ID]\" -- \"billingAccounts\/[BILLING_ACCOUNT_ID]\/sinks\/[SINK_ID]\" -- \"folders\/[FOLDER_ID]\/sinks\/[SINK_ID]\" Example: -- \"projects\/my-project-id\/sinks\/my-sink-id\". osgSinkName :: Lens' OrganizationsSinksGet Text osgSinkName = lens _osgSinkName (\ s a -> s{_osgSinkName = a}) -- | JSONP osgCallback :: Lens' OrganizationsSinksGet (Maybe Text) osgCallback = lens _osgCallback (\ s a -> s{_osgCallback = a}) instance GoogleRequest OrganizationsSinksGet where type Rs OrganizationsSinksGet = LogSink type Scopes OrganizationsSinksGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/logging.admin", "https://www.googleapis.com/auth/logging.read"] requestClient OrganizationsSinksGet'{..} = go _osgSinkName _osgXgafv _osgUploadProtocol _osgAccessToken _osgUploadType _osgCallback (Just AltJSON) loggingService where go = buildClient (Proxy :: Proxy OrganizationsSinksGetResource) mempty
brendanhay/gogol
gogol-logging/gen/Network/Google/Resource/Logging/Organizations/Sinks/Get.hs
mpl-2.0
5,001
0
15
1,080
709
417
292
104
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} -- Module : Gen.Types.Id -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : provisional -- Portability : non-portable (GHC extensions) module Gen.Types.Id ( -- * Properties Prefix (..) , Suffix (..) -- * Unique Identifiers , Global , Local , global , local , commasep , abbreviate , globalise , localise , gid , lid , reference -- FIXME: move these , extractPath , orderParams -- * Naming , aname , mname , dname , dname' , dstr , cname , bname , fname , fstr , lname , pname ) where import Control.Applicative import Control.Monad import Data.Aeson hiding (Bool, String) import qualified Data.Attoparsec.Text as A import qualified Data.CaseInsensitive as CI import Data.Foldable (foldl') import Data.Function (on) import Data.Hashable import Data.List (elemIndex, intersperse, nub, sortOn) import Data.String import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy.Builder as Build import Data.Text.Manipulate import Formatting import Gen.Text import GHC.Generics (Generic) import Language.Haskell.Exts.Build import Language.Haskell.Exts.Syntax (Exp, Name (..)) aname :: Text -> Name () aname = name . Text.unpack . (<> "API") . upperHead . Text.replace "." "" mname :: Text -> Suffix -> Global -> (Name (), Global, Text) mname abrv (Suffix suf) (Global g) = ( name . Text.unpack $ mconcat n <> suf -- Action service type alias. , Global n -- Action data type. , Text.intercalate "." ns -- Action namespace. ) where n = drop 1 ns ns | CI.mk e == CI.mk x = e:xs | otherwise = x:xs where e = Text.replace "." "" abrv x:xs = map (upperAcronym . toPascal) g dname' :: Global -> Name () dname' g = case dname g of Ident () s -> Ident () (s <> "'") Symbol () s -> Symbol () (s <> "'") dname :: Global -> Name () dname = name . Text.unpack . renameReserved . upperHead . Text.dropWhile separator . global cname :: Global -> Name () cname = name . Text.unpack . renameReserved . lowerHead . Text.dropWhile separator . lowerFirstAcronym . global bname :: Prefix -> Text -> Name () bname (Prefix p) = name . Text.unpack . mappend (Text.toUpper p) . renameBranch fname, lname, pname :: Prefix -> Local -> Name () fname = pre (Text.cons '_' . renameField) lname = pre renameField pname = pre (flip Text.snoc '_' . Text.cons 'p' . upperHead . renameField) dstr :: Global -> Exp () dstr = strE . Text.unpack . toPascal . global fstr :: Local -> Exp () fstr = strE . Text.unpack . local pre :: (Text -> Text) -> Prefix -> Local -> Name () pre f (Prefix p) = name . Text.unpack . f . mappend p . upperHead . local newtype Suffix = Suffix Text deriving (Show, IsString) newtype Prefix = Prefix Text deriving (Show, Monoid) instance Semigroup Prefix where Prefix a <> Prefix b = Prefix (a <> b) newtype Global = Global { unsafeGlobal :: [Text] } deriving (Ord, Show, Generic) instance Eq Global where Global xs == Global ys = on (==) f xs ys where f = CI.mk . mconcat instance Hashable Global where hashWithSalt salt (Global g) = foldl' hashWithSalt salt (map CI.mk g) instance IsString Global where fromString = mkGlobal . fromString instance FromJSON Global where parseJSON = withText "global" (pure . mkGlobal) instance FromJSONKey Global where fromJSONKey = FromJSONKeyText mkGlobal instance ToJSON Global where toJSON = toJSON . global gid :: Format a (Global -> a) gid = later (Build.fromText . global) newtype Local = Local { local :: Text } deriving ( Eq , Ord , Show , Generic , Hashable , FromJSON , ToJSON , FromJSONKey , ToJSONKey , IsString ) lid :: Format a (Local -> a) lid = later (Build.fromText . local) mkGlobal :: Text -> Global mkGlobal = Global . Text.split (== '.') global :: Global -> Text global (Global g) = foldMap (upperAcronym . upperHead) g commasep :: Global -> Text commasep = mconcat . intersperse "." . unsafeGlobal reference :: Global -> Local -> Global reference (Global g) (Local l) = Global . mappend g . filter (not . Text.null) $ Text.split (== '.') l abbreviate :: Global -> Global abbreviate (Global g) | length g > 2 = Global (drop 1 g) | otherwise = Global g localise :: Global -> Local localise = Local . global globalise :: Local -> Global globalise = Global . (:[]) . local extractPath :: Text -> [Either Text (Local, Maybe Text)] extractPath x = either (error . err) id $ A.parseOnly path x where err e = "Error parsing \"" <> Text.unpack x <> "\", " <> e path = A.many1 (seg <|> rep <|> var') <* A.endOfInput seg = fmap Left $ optional (A.char '/') *> A.takeWhile1 (A.notInClass "/{+*}") rep = fmap Right $ do void $ A.string "{/" (,Nothing) <$> fmap Local (A.takeWhile1 (/= '*')) <* A.string "*}" var' = fmap Right $ do void $ optional (A.char '/') *> A.char '{' *> optional (A.char '+') (,) <$> fmap Local (A.takeWhile1 (A.notInClass "/{+*}:")) <* A.char '}' <*> optional (A.char ':' *> A.takeWhile1 (A.notInClass "/{+*}:")) orderParams :: (a -> Local) -> [a] -> [Local] -> [a] orderParams f xs ys = orderBy f zs (del zs [] ++ reserve) where zs = orderBy f (sortOn f xs) (nub (ys ++ map f xs)) del _ [] = [] del [] rs = reverse rs del (r:qs) rs | f r `elem` reserve = del qs rs | otherwise = del qs (f r:rs) reserve = [ "quotaUser" , "prettyPrint" , "userIp" , "fields" , "alt" ] orderBy :: Eq b => (a -> b) -> [a] -> [b] -> [a] orderBy g xs ys = sortOn (flip elemIndex ys . g) xs
brendanhay/gogol
gen/src/Gen/Types/Id.hs
mpl-2.0
6,687
0
18
2,106
2,247
1,191
1,056
187
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DataKinds #-} -- |A number of mathematical or physical constants. module UnitTyped.SI.Constants where import UnitTyped import UnitTyped.SI import UnitTyped.SI.Meta import UnitTyped.SI.Derived -- |π as the floating point value it has in the "Prelude". pi' :: (Fractional f, Floating f) => Value '[] '[] f pi' = mkVal Prelude.pi -- |π as a rational value. Which it isn't. But we can pretend it is. pi :: (Fractional f) => Value '[] '[] f pi = mkVal 3.1415926535897932384626433832795028841971 -- |The speed of light c :: (Fractional f) => Value Speed '[ '(Second, NOne), '(Meter, POne)] f c = mkVal 299792458 -- |Planck constant h :: Fractional f => Value '[ '(Time, ('Neg 'One)), '(Mass, ('Pos 'One)), '(Length, ('Pos ('Suc 'One))) ] '[ '(Joule, ('Pos 'One)), '(Second, ('Pos 'One)) ] f h = mkVal 6.6260695729e-34 -- |Reduced Planck constant hbar :: Fractional f => Value '[ '(Time, NOne), '(Length, PTwo), '(Mass, POne)] '[ '(Second, POne), '(Joule, POne) ] f hbar = coerce (h |/| (2 *| UnitTyped.SI.Constants.pi)) (joule |*| second) -- |Boltzmann's constant kB :: Fractional f => Value '[ '(Temperature, NOne), '(Time, NTwo), '(Mass, POne), '(Length, PTwo) ] '[ '(Kelvin, NOne), '(Joule, POne) ] f kB = mkVal 1.3806488e-23 -- |Atomic unit of charge (elementary charge) e :: (Fractional f) => f :| Coulomb e = mkVal 1.6021765314e-19 -- |Atomic unit of mass (electron mass) m_e :: (Fractional f) => f :| Kilo Gram m_e = mkVal 9.109382616e-31 -- |Atomic unit of mass (proton mass) m_p :: (Fractional f) => f :| Kilo Gram m_p = mkVal 1.672621778e-27 -- |Atomic unit of length a_0 :: (Fractional f) => f :| Meter a_0 = mkVal 0.529177210818e-10 -- |Atomic unit of energy -- e_h :: (Fractional f) => Value Energy (U Joule) f e_h :: (Fractional f) => f :| Joule e_h = mkVal 4.3597441775e-18 -- |Gas constant. r :: (Fractional f) => Value '[ '(Temperature, NOne), '(Length, PTwo), '(Mass, POne), '(Time, NTwo) ] '[ '(Mole, NOne), '(Kelvin, NOne), '(Joule, POne) ] f r = mkVal 8.314462175 -- |Gravitational constant g :: (Fractional f) => Value '[ '(Time, NTwo), '(Length, PThree), '(Mass, NOne) ] '[ '(Second, NTwo), '(Meter, PThree), '((Kilo Gram), NOne) ] f g = mkVal 6.6738480e-11 -- | Generic Gravitational constant g' :: (Fractional f, Convertible' '[ '(Time, NTwo), '(Length, PThree), '(Mass, NOne) ] b ) => Value '[ '(Time, NTwo), '(Length, PThree), '(Mass, NOne) ] b f g' = let ret = coerce g ret in ret ---- |Planck mass --m_P :: (Fractional f, Floating f) => Value f MassDimension (U (Kilo Gram)) --m_P = mkVal (sqrt (val $ hbar |*| c |/| g)) ---- |Reduced Planck mass --m_P' :: (Fractional f, Floating f) => Value f MassDimension (U (Kilo Gram)) --m_P' = mkVal (sqrt (val $ hbar |*| c |/| ((Prelude.pi * 8) *| g)))
nushio3/unittyped
src/UnitTyped/SI/Constants.hs
lgpl-2.1
3,153
0
15
564
1,021
595
426
47
1
-------------------------------------------------------------------------------- -- | -- Module : Sound.TagLib -- Copyright : (c) Brandon Bickford 2008 -- License : LGPL v3 -- Maintainer: Brandon Bickford <[email protected]> -- Stability : experimental -- Portability : only tested with GHC -- -- High level interface to read and write ID3 tag fields (album, artist, -- comment, genre, title, track number, year) and get audio properties (length, -- bit rate, sample rate, channels) -- -------------------------------------------------------------------------------- module Sound.TagLib ( -- * Data Types AudioProperties, Tag, TagFile, -- * TagFile operations open, save, -- * Tag Operations tag, album, artist, comment, genre, setAlbum, setArtist, setComment, setGenre, setTitle, setTrack, setYear, title, track, year, -- * AudioProperties Operations audioProperties, bitRate, channels, duration, sampleRate -- * Example -- $example ) where import Foreign import Foreign.C import Foreign.Ptr import Foreign.ForeignPtr import System.IO import System.IO.Unsafe import qualified Codec.Binary.UTF8.String as UTF8 import Control.Monad import qualified Data.ByteString as B import Foreign.Marshal.Array (withArray) type Void = Word8 type TagFile = ForeignPtr Void type TagFileRef = Ptr Void data AudioProperties = AudioProperties TagFile AudioPropertiesRef type AudioPropertiesRef = Ptr Void type TagRef = Ptr Void data Tag = Tag TagFile TagRef type UTF8String = Ptr Word8 foreign import ccall unsafe "taglib/tag_c.h taglib_file_new" taglib_file_new :: UTF8String -> IO TagFileRef foreign import ccall unsafe "taglib/tag_c.h &taglib_file_free" taglib_file_free :: FunPtr (TagFileRef -> IO ()) foreign import ccall unsafe "taglib/tag_c.h taglib_file_tag" taglib_file_tag :: TagFileRef -> IO TagRef {- Tag Getters -} foreign import ccall unsafe "taglib/tag_c.h taglib_tag_artist" taglib_tag_artist :: TagRef -> IO UTF8String foreign import ccall unsafe "taglib/tag_c.h taglib_tag_album" taglib_tag_album :: TagRef -> IO UTF8String foreign import ccall unsafe "taglib/tag_c.h taglib_tag_title" taglib_tag_title :: TagRef -> IO UTF8String foreign import ccall unsafe "taglib/tag_c.h taglib_tag_comment" taglib_tag_comment :: TagRef -> IO UTF8String foreign import ccall unsafe "taglib/tag_c.h taglib_tag_genre" taglib_tag_genre :: TagRef -> IO UTF8String foreign import ccall unsafe "taglib/tag_c.h taglib_tag_year" taglib_tag_year :: TagRef -> IO CUInt foreign import ccall unsafe "taglib/tag_c.h taglib_tag_track" taglib_tag_track :: TagRef -> IO CUInt -- We manage our strings, so we don't need this guy --foreign import ccall unsafe "taglib/tag_c.h taglib_tag_free_strings" taglib_tag_free_strings :: IO () foreign import ccall unsafe "taglib/tag_c.h taglib_file_save" taglib_file_save :: TagFileRef -> IO CInt foreign import ccall unsafe "taglib/tag_c.h taglib_set_string_management_enabled" taglib_set_string_management_enabled :: CInt -> IO () {- Audio properties -} foreign import ccall unsafe "taglib/tag_c.h taglib_file_audioproperties" taglib_file_audioproperties :: TagFileRef -> IO AudioPropertiesRef foreign import ccall unsafe "taglib/tac_c.h taglib_audioproperties_length" taglib_audioproperties_length :: AudioPropertiesRef -> IO CInt foreign import ccall unsafe "taglib/tac_c.h taglib_audioproperties_bitrate" taglib_audioproperties_bitrate :: AudioPropertiesRef -> IO CInt foreign import ccall unsafe "taglib/tac_c.h taglib_audioproperties_samplerate" taglib_audioproperties_samplerate :: AudioPropertiesRef -> IO CInt foreign import ccall unsafe "taglib/tac_c.h taglib_audioproperties_channels" taglib_audioproperties_channels :: AudioPropertiesRef -> IO CInt {- Tag Setters -} foreign import ccall unsafe "taglib/tac_c.h taglib_tag_set_track" taglib_tag_set_track :: TagRef -> CUInt -> IO () foreign import ccall unsafe "taglib/tac_c.h taglib_tag_set_year" taglib_tag_set_year :: TagRef -> CUInt -> IO () foreign import ccall unsafe "taglib/tac_c.h taglib_tag_set_genre" taglib_tag_set_genre :: TagRef -> UTF8String -> IO () foreign import ccall unsafe "taglib/tac_c.h taglib_tag_set_comment" taglib_tag_set_comment :: TagRef -> UTF8String -> IO () foreign import ccall unsafe "taglib/tac_c.h taglib_tag_set_album" taglib_tag_set_album :: TagRef -> UTF8String -> IO () foreign import ccall unsafe "taglib/tac_c.h taglib_tag_set_title" taglib_tag_set_title :: TagRef -> UTF8String -> IO () foreign import ccall unsafe "taglib/tac_c.h taglib_tag_set_artist" taglib_tag_set_artist :: TagRef -> UTF8String -> IO () foreign import ccall unsafe "taglib/tac_c.h taglib_id3v2_set_default_text_encoding" taglib_id3v2_set_default_text_encoding :: CUInt -> IO () withUTF8String :: String -> (UTF8String -> IO a) -> IO a withUTF8String s f = do let s' = (UTF8.encode s) ++ [nullByte] withArray s' f nullByte :: Word8 nullByte = 0 peekUTF8String :: UTF8String -> IO String peekUTF8String utf = do bytes <- peekArray0 nullByte utf return $ UTF8.decode bytes no = 0 yes = 1 -- |Open a filename and possibly get a TagFile open :: String -> IO (Maybe TagFile) open filename = do taglib_set_string_management_enabled no ptr <- withUTF8String filename taglib_file_new if ptr == nullPtr then return Nothing else do tagFile <- newForeignPtr taglib_file_free ptr return $ Just tagFile -- |Save changes to a tag save :: TagFile -> IO Integer save tagFile = liftM fromIntegral $ withForeignPtr tagFile taglib_file_save -- |Get a Tag from a TagFile, if it has one tag :: TagFile -> IO (Maybe Tag) tag tagFile = do tagPtr <- withForeignPtr tagFile taglib_file_tag return (if tagPtr == nullPtr then Nothing else Just (Tag tagFile tagPtr)) -- |Get an artist string from a Tag artist :: Tag -> IO String artist = extractTagString taglib_tag_artist -- |Get an album string from a Tag album :: Tag -> IO String album = extractTagString taglib_tag_album -- |Get a title string from a Tag title :: Tag -> IO String title = extractTagString taglib_tag_title -- |Get the comment string from a Tag comment :: Tag -> IO String comment = extractTagString taglib_tag_comment -- |Get the comment string from a Tag genre :: Tag -> IO String genre = extractTagString taglib_tag_genre extractTagString :: (Ptr Void -> IO UTF8String) -> Tag -> IO String extractTagString taglib_cfunc (Tag tagFile tagPtr) = do cs <- taglib_cfunc tagPtr s <- peekUTF8String cs free cs return s -- |Get the year from a Tag. Empty values will be 0 year :: Tag -> IO Integer year (Tag tagFile tagPtr) = liftM fromIntegral (taglib_tag_year tagPtr) -- |Get the track number from a Tag. Empty values will be 0 track :: Tag -> IO Integer track (Tag tagFile tagPtr) = liftM fromIntegral (taglib_tag_track $ tagPtr) {- Tag Setters -} setTagString taglib_cfunc (Tag _ tagPtr) val = withUTF8String val $ taglib_cfunc tagPtr {- Tag Setters -} setTagInt :: (TagRef -> CUInt -> IO ()) -> Tag -> Integer -> IO () setTagInt taglib_cfunc (Tag _ tagRef) val = taglib_cfunc tagRef (fromIntegral val) -- |Set the title of a tag setTitle :: Tag -> String -> IO () setTitle = setTagString taglib_tag_set_title -- |Set the album of a tag setAlbum :: Tag -> String -> IO () setAlbum = setTagString taglib_tag_set_album -- |Set the artist of a tag setArtist :: Tag -> String -> IO () setArtist = setTagString taglib_tag_set_artist -- |Set the comment of a tag setComment :: Tag -> String -> IO () setComment = setTagString taglib_tag_set_comment -- |Set the genre of a tag setGenre :: Tag -> String -> IO () setGenre = setTagString taglib_tag_set_genre -- |Set the year of a tag setYear :: Tag -> Integer -> IO () setYear = setTagInt taglib_tag_set_year -- |Set the track of a tag setTrack :: Tag -> Integer -> IO () setTrack = setTagInt taglib_tag_set_track -- |Get the AudioProperties from a TagFile audioProperties :: TagFile -> IO (Maybe AudioProperties) audioProperties tagFile = do ap <- withForeignPtr tagFile taglib_file_audioproperties return $ (if ap == nullPtr then Nothing else Just $ AudioProperties tagFile ap) {- | Get the duration (in seconds) from AudioProperties In TagLib, this is named length. This is renamed so that it doesn't conflict with the Prelude length -} duration :: AudioProperties -> IO Integer duration (AudioProperties _ prop) = liftM fromIntegral $ taglib_audioproperties_length prop -- |Get the bitRate from AudioProperties bitRate :: AudioProperties -> IO Integer bitRate (AudioProperties _ prop) = liftM fromIntegral $ taglib_audioproperties_bitrate prop -- |Get the number of channels from AudioProperties channels :: AudioProperties -> IO Integer channels (AudioProperties _ prop) = liftM fromIntegral $ taglib_audioproperties_channels prop -- |Get the sampleRate from AudioProperties sampleRate :: AudioProperties -> IO Integer sampleRate (AudioProperties _ prop) = liftM fromIntegral $ taglib_audioproperties_samplerate prop ----------- -- $example -- -- > module Main where -- > -- > import qualified Sound.TagLib as TagLib -- > import Data.Maybe -- > import Control.Monad -- > import System -- > -- > main = do -- > args <- getArgs -- > mapM showFile args -- > -- > withMaybe :: (Maybe j) -> (j -> IO ()) -> IO () -- > withMaybe mebbe action = do -- > case mebbe of -- > Just x -> do action x -- > return () -- > Nothing -> return () -- > -- > showFile filename = do -- > t <- TagLib.open filename -- > withMaybe t showTagFile -- > -- > showTagFile :: TagLib.TagFile -> IO () -- > showTagFile tagFile = do -- > t <- TagLib.tag tagFile -- > withMaybe t showTag -- > p <- TagLib.audioProperties tagFile -- > withMaybe p showAudioProperties -- > -- > showTag :: TagLib.Tag -> IO () -- > showTag tag = do -- > artist <- TagLib.artist tag -- > album <- TagLib.album tag -- > title <- TagLib.title tag -- > comment <- TagLib.comment tag -- > year <- TagLib.year tag -- > track <- TagLib.track tag -- > print (artist, album, title, year, track) -- > -- > showAudioProperties :: TagLib.AudioProperties -> IO () -- > showAudioProperties props = do -- > bitrate <- TagLib.bitRate props -- > length <- TagLib.duration props -- > samplerate <- TagLib.sampleRate props -- > channels <- TagLib.channels props -- > print (bitrate, length, channels, samplerate) -- >
bickfordb/haskell-taglib
src/Sound/TagLib.hs
lgpl-3.0
10,645
0
13
1,984
1,975
1,060
915
149
2
module Main where import Types.Cards import Types.Lists import Types.Trees import Types.User main :: IO () main = putStrLn "CombinedTests compiled" {- Combined tests are a way of testing that diffrent commands can be run on a file in one session -} {- Test Purpose: Testing fucntion with several lines Expected Scope [ s :: String, i :: Int, s2 :: String ] Expected Return Type [ Return Type :: String ] -} test0 :: User -> String test0 (Student s i s2) = {- In Scope [ s :: String, i :: Int, s2 :: String, Return Type :: String ] -} "" test0 (Admin s i) = "" {-Exected Type :: User -> String || User -> [Char] -} test1 :: User -> [Char] test1 (Student s i ss) = s ++ ss test1 (Admin s i) = s ++ (show i) {-Exected Type :: User -> [String] -} test2 :: User -> [String] test2 (Student s i ss) = s : [ss] test2 (Admin s i) = s : [(show i)] {- Testing List - From internal type db Expected [ [] & (x:xs) ] -} test3 :: [Int] -> Int test3 [] = 0 test3 (xs : xs1) = 0 {- Testing Either - From internal type db Expected [ Left ? & Right ? ] -} test4 :: Either Int Int -> Int test4 (Left l) = 0 test4 (Right r) = 0 {- Sometimes compiler warnings are sent over STDERR We don't care so this tests that they are ignored when testing if a file loaded -} testCompilerWarningIgnoring a = a testCompilerWarningIgnoring [] = []
DarrenMowat/blackbox
tests/results/CombinedTests.hs
unlicense
1,380
0
8
338
318
171
147
24
1
import Control.Monad.Trans.State fizzBuzz :: Integer -> String fizzBuzz n | n `mod` 15 == 0 = "FizzBuzz" | n `mod` 5 == 0 = "Fizz" | n `mod` 3 == 0 = "Buzz" | otherwise = show n fizzBuzzList :: [Integer] -> [String] fizzBuzzList list = execState (mapM_ addResult list) [] addResult :: Integer -> State [String] () addResult n = do xs <- get let result = fizzBuzz n put (result : xs) fizzbuzzFromTo :: Integer -> Integer -> [String] fizzbuzzFromTo x y | x == y = fizzBuzzList [x] | x < y && y - x == 1 = fizzBuzzList [y,x] | x < y = fizzBuzzList [y, y - 1 .. x] | otherwise = fizzbuzzFromTo y x main :: IO () main = mapM_ putStrLn $ fizzbuzzFromTo 1 100
dmvianna/haskellbook
src/Ch23-FizzBuzz.hs
unlicense
725
0
11
206
334
167
167
22
1
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE OverloadedStrings #-} module HttpRequestParser where import Text.ParserCombinators.Parsec import qualified Data.IntSet as S data HttpRequest = HttpRequest { request :: HttpRequestLine, headers :: [Header], body :: Maybe String -- todo } deriving Show data HttpRequestLine = RequestLine { method :: String, url :: String, version :: Int } deriving (Show) data Header = Header { name :: String, value :: [String] } deriving (Eq, Ord, Show) parseRequest :: String -> HttpRequest parseRequest input = case run of Left e -> error $ show e ++ " => " ++ input Right req -> req where run = parse parseHttpRequest "request" input parseHttpRequest :: Parser HttpRequest parseHttpRequest = do hl <- headLine headers <- many requestHeader crlf return $! HttpRequest hl headers Nothing requestHeader :: Parser Header requestHeader = do header <- many token' char ':' >> skipMany whiteSpace body <- manyTill anyChar crlf conts <- many $ (many1 whiteSpace) >> manyTill anyChar crlf return $ Header header (body:conts) headLine :: Parser HttpRequestLine headLine = do m <- methods whiteSpace u <- many1 (satisfy $ not . isWhiteSpace) whiteSpace v <- string "HTTP/1." >> versions crlf return $ RequestLine m u v isWhiteSpace c = ' ' == c || '\t' == c whiteSpace = satisfy isWhiteSpace versions :: Parser Int versions = try (char '0' >> return 0) <|> (char '1' >> return 1) methods :: Parser String methods = try (string "GET") <|> try (string "POST") <|> try (string "DELETE") <|> try (string "HEAD") <|> fail "unknown http method" endOfLine = try (crlf >> return ()) <|> (char '\n' >> return ()) crlf = string "\r\n" token' = satisfy $ \c -> S.notMember (fromEnum c) set where set = S.fromList . map fromEnum $ ['\0'..'\31'] ++ "()<>@,;:\\\"/[]?={} \t" ++ ['\128'..'\255']
songpp/halo
src/HttpRequestParser.hs
apache-2.0
2,020
0
11
514
666
336
330
61
2
----------------------------------------------------------------------------- -- | -- Module : Finance.Hqfl.Instrument -- Copyright : (C) 2018 Mika'il Khan -- License : (see the file LICENSE) -- Maintainer : Mika'il Khan <[email protected]> -- Stability : stable -- Portability : portable -- ---------------------------------------------------------------------------- module Finance.Hqfl.Instrument ( module Finance.Hqfl.Instrument.Equity , module Finance.Hqfl.Instrument.Bond , module Finance.Hqfl.Instrument.BarrierOption , module Finance.Hqfl.Instrument.Option , module Finance.Hqfl.Instrument.Cap , module Finance.Hqfl.Instrument.Commodity , module Finance.Hqfl.Instrument.Credit , module Finance.Hqfl.Instrument.Energy , module Finance.Hqfl.Instrument.Forward , module Finance.Hqfl.Instrument.Future , module Finance.Hqfl.Instrument.StockIndex , module Finance.Hqfl.Instrument.Insurance , module Finance.Hqfl.Instrument.Swap , module Finance.Hqfl.Instrument.Weather , module Finance.Hqfl.Instrument.Type ) where import Finance.Hqfl.Instrument.BarrierOption import Finance.Hqfl.Instrument.Equity import Finance.Hqfl.Instrument.Bond import Finance.Hqfl.Instrument.Option import Finance.Hqfl.Instrument.Cap import Finance.Hqfl.Instrument.Commodity import Finance.Hqfl.Instrument.Credit import Finance.Hqfl.Instrument.Energy import Finance.Hqfl.Instrument.Forward import Finance.Hqfl.Instrument.Future import Finance.Hqfl.Instrument.StockIndex import Finance.Hqfl.Instrument.Insurance import Finance.Hqfl.Instrument.Swap import Finance.Hqfl.Instrument.Weather import Finance.Hqfl.Instrument.Type
cokleisli/hqfl
src/Finance/Hqfl/Instrument.hs
apache-2.0
1,748
0
5
262
244
181
63
32
0
-- Convention used below: -- when 'name' and 'nameCT' both appear, 'name' is the Haskell function and -- 'nameCT' is the "Code Template" that 'name' builds. module Drasil.GlassBR.ModuleDefs (allMods, implVars, interpY, interpZ) where import Language.Drasil import Language.Drasil.ShortHands import Language.Drasil.Code (($:=), Func, FuncStmt(..), Mod, asVC, funcDef, fdec, ffor, funcData, quantvar, multiLine, packmod, repeated, singleLine) allMods :: [Mod] allMods = [readTableMod, interpMod] -- It's a bit odd that this has to be explicitly built here... implVars :: [QuantityDict] implVars = [v, x_z_1, y_z_1, x_z_2, y_z_2, mat, col, i, j, k, z, zVector, yMatrix, xMatrix, y, arr, filename, y_2, y_1, x_2, x_1, x] --from TSD.txt: readTableMod :: Mod readTableMod = packmod "ReadTable" "Provides a function for reading glass ASTM data" [] [readTable] readTable :: Func readTable = funcData "read_table" "Reads glass ASTM data from a file with the given file name" [ singleLine (repeated [quantvar zVector]) ',', multiLine (repeated (map quantvar [xMatrix, yMatrix])) ',' ] ----- one, two :: Symbol one = Integ 1 two = Integ 2 var :: String -> String -> Symbol -> Space -> QuantityDict var nam np = implVar nam (nounPhraseSP np) y_2, y_1, x_2, x_1, x :: QuantityDict y_1 = var "y1" "lower y-coordinate" (sub lY one) Real y_2 = var "y2" "upper y-coordinate" (sub lY two) Real x_1 = var "x1" "lower x-coordinate" (sub lX one) Real x_2 = var "x2" "upper x-coordinate" (sub lX two) Real x = var "x" "x-coordinate to interpolate at" lX Real -- = params.wtnt from mainFun.py v, x_z_1, y_z_1, x_z_2, y_z_2, mat, col, i, j, k, z, zVector, yMatrix, xMatrix, y, arr, filename :: QuantityDict i = var "i" "index" lI Natural j = var "j" "index" lJ Natural k = var "k" "index" (sub lK two) Natural v = var "v" "value whose index will be found" lV Real y = var "y" "y-coordinate to interpolate at" lY Real z = var "z" "z-coordinate to interpolate at" lZ Real zVector = var "zVector" "list of z values" (sub lZ (Label "vector")) (Vect Real) yMatrix = var "yMatrix" "lists of y values at different z values" (sub lY (Label "matrix")) (Vect $ Vect Real) xMatrix = var "xMatrix" "lists of x values at different z values" (sub lX (Label "matrix")) (Vect $ Vect Real) arr = var "arr" "array in which value should be found" (Label "arr") (Vect Real) --FIXME: temporary variable for findCT? x_z_1 = var "x_z_1" "list of x values at a specific z value" (sub lX (sub lZ one)) (Vect Real) y_z_1 = var "y_z_1" "list of y values at a specific z value" (sub lY (sub lZ one)) (Vect Real) x_z_2 = var "x_z_2" "list of x values at a specific z value" (sub lX (sub lZ two)) (Vect Real) y_z_2 = var "y_z_2" "list of y values at a specific z value" (sub lY (sub lZ two)) (Vect Real) mat = var "mat" "matrix from which column will be extracted" (Label "mat") (Vect $ Vect Real) col = var "col" "extracted column" (Label "col") (Vect Real) filename = var "filename" "name of file with x y and z data" (Label "filename") String ------------------------------------------------------------------------------------------ -- -- Some semantic functions -- Given two points (x1,y1) and (x2,y2), return the slope of the line going through them slope :: (Fractional a) => (a, a) -> (a, a) -> a slope (x1,y1) (x2,y2) = (y2 - y1) / (x2 - x1) -- Given two points (x1,y1) and (x2,y2), and an x ordinate, return -- extrapoled y on the straight line in between onLine :: (Fractional a) => (a, a) -> (a, a) -> a -> a onLine p1@(x1,y1) p2 x_ = let m = slope p1 p2 in m * (x_ - x1) + y1 ------------------------------------------------------------------------------------------ -- Code Template helper functions vLook :: (HasSymbol a, HasSymbol i, HasUID a, HasUID i) => a -> i -> Expr -> Expr vLook a i_ p = idx (sy a) (sy i_ + p) aLook :: (HasSymbol a, HasSymbol i, HasSymbol j, HasUID a, HasUID i, HasUID j) => a -> i -> j -> Expr aLook a i_ j_ = idx (idx (sy a) (sy i_)) (sy j_) getCol :: (HasSymbol a, HasSymbol i, HasUID a, HasUID i) => a -> i -> Expr -> Expr getCol a_ i_ p = apply (asVC extractColumnCT) [sy a_, sy i_ + p] call :: Func -> [QuantityDict] -> FuncStmt call f l = FVal $ apply (asVC f) $ map sy l find :: (HasUID zv, HasUID z, HasSymbol zv, HasSymbol z) => zv -> z -> Expr find zv z_ = apply (asVC findCT) [sy zv, sy z_] linInterp :: [Expr] -> Expr linInterp = apply (asVC linInterpCT) interpOver :: (HasUID ptx, HasUID pty, HasUID ind, HasUID vv, HasSymbol ptx, HasSymbol pty, HasSymbol ind, HasSymbol vv) => ptx -> pty -> ind -> vv -> [Expr] interpOver ptx pty ind vv = [ vLook ptx ind 0, vLook pty ind 0 , vLook ptx ind 1, vLook pty ind 1 , sy vv ] ------------------------------------------------------------------------------------------ -- Code Templates -- Note how this one uses a semantic function in its body -- But it is also 'wrong' in the sense that it assumes x_1 <= x <= x_2 linInterpCT :: Func linInterpCT = funcDef "lin_interp" "Performs linear interpolation" [x_1, y_1, x_2, y_2, x] Real (Just "y value interpolated at given x value") [ FRet $ onLine (sy x_1, sy y_1) (sy x_2, sy y_2) (sy x) ] findCT :: Func findCT = funcDef "find" "Finds the array index for a value closest to the given value" [arr, v] Natural (Just "index of given value in given array") [ ffor i (sy i $< (dim (sy arr) - 1)) [ FCond ((vLook arr i 0 $<= sy v) $&& (sy v $<= vLook arr i 1)) [ FRet $ sy i ] [] ], FThrow "Bound error" ] extractColumnCT :: Func extractColumnCT = funcDef "extractColumn" "Extracts a column from a 2D matrix" [mat, j] (Vect Real) (Just "column of the given matrix at the given index") [ fdec col, -- ffor i (sy i $< dim (sy mat)) [ FAppend (sy col) (aLook mat i j) ], FRet (sy col) ] interpY :: Func interpY = funcDef "interpY" "Linearly interpolates a y value at given x and z values" [filename, x, z] Real (Just "y value interpolated at given x and z values") [ -- hack fdec xMatrix, fdec yMatrix, fdec zVector, -- call readTable [filename, zVector, xMatrix, yMatrix], -- endhack i $:= find zVector z, x_z_1 $:= getCol xMatrix i 0, y_z_1 $:= getCol yMatrix i 0, x_z_2 $:= getCol xMatrix i 1, y_z_2 $:= getCol yMatrix i 1, FTry [ j $:= find x_z_1 x, k $:= find x_z_2 x ] [ FThrow "Interpolation of y failed" ], y_1 $:= linInterp (interpOver x_z_1 y_z_1 j x), y_2 $:= linInterp (interpOver x_z_2 y_z_2 k x), FRet $ linInterp [ vLook zVector i 0, sy y_1, vLook zVector i 1, sy y_2, sy z ] ] interpZ :: Func interpZ = funcDef "interpZ" "Linearly interpolates a z value at given x and y values" [filename, x, y] Real (Just "z value interpolated at given x and y values") [ -- hack fdec xMatrix, fdec yMatrix, fdec zVector, -- call readTable [filename, zVector, xMatrix, yMatrix], -- endhack ffor i (sy i $< (dim (sy zVector) - 1)) [ x_z_1 $:= getCol xMatrix i 0, y_z_1 $:= getCol yMatrix i 0, x_z_2 $:= getCol xMatrix i 1, y_z_2 $:= getCol yMatrix i 1, FTry [ j $:= find x_z_1 x, k $:= find x_z_2 x ] [ FContinue ], y_1 $:= linInterp (interpOver x_z_1 y_z_1 j x), y_2 $:= linInterp (interpOver x_z_2 y_z_2 k x), FCond ((sy y_1 $<= sy y) $&& (sy y $<= sy y_2)) [ FRet $ linInterp [ sy y_1, vLook zVector i 0, sy y_2, vLook zVector i 1, sy y ] ] [] ], FThrow "Interpolation of z failed" ] interpMod :: Mod interpMod = packmod "Interpolation" "Provides functions for linear interpolation on three-dimensional data" [] [linInterpCT, findCT, extractColumnCT, interpY, interpZ]
JacquesCarette/literate-scientific-software
code/drasil-example/Drasil/GlassBR/ModuleDefs.hs
bsd-2-clause
8,040
0
14
2,026
2,668
1,433
1,235
158
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE DeriveGeneric #-} module Nero.Payload ( -- * Payload Payload , payloadText , defaultPayload , defaultPayloadForm , Encoding , utf8Encoding , HasPayload(..) -- * Body , Body , HasBody(..) -- * Form , form ) where import GHC.Generics (Generic) import Nero.Binary import Nero.Prelude import Nero.Param -- * Payload -- | Contains the 'Body' and any metadata associated with it. data Payload = PayloadText Encoding Body | PayloadBinary Body | PayloadForm Body deriving (Show,Eq,Generic) -- | Indicates a 'Text' encoding. data Encoding = Utf8 | CustomEncoding String deriving (Show,Eq,Generic) defaultPayload :: Payload defaultPayload = PayloadBinary mempty -- | A 'Payload' with an empty 'Form'. defaultPayloadForm :: Payload defaultPayloadForm = PayloadForm mempty -- Creates a '/text/plain/' 'Payload' with the given 'Encoding' and a 'Body' payloadText :: Encoding -> Body -> Payload payloadText = PayloadText utf8Encoding :: Encoding utf8Encoding = Utf8 -- | A 'Lens'' for types with a 'Payload'. class HasPayload a where payload :: Lens' a Payload -- * Body -- | It's the main data associated with the 'Payload' of 'Request' or a -- 'Response'. type Body = ByteString -- | Get the 'Body' for types with one. class HasBody a where body :: Lens' a Body instance HasBody Payload where body f (PayloadText e b) = PayloadText e <$> f b body f (PayloadBinary b) = PayloadBinary <$> f b body f (PayloadForm b) = PayloadForm <$> f b -- * Form -- | A 'Prism'' to obtain a 'Form' from a 'Payload' and make 'Payload' from -- a 'Form'. form :: Prism' Payload MultiMap form = prism' (PayloadForm . review binary) $ \case PayloadForm b -> b ^? binary _ -> Nothing instance Params Payload where params = form
plutonbrb/nero
src/Nero/Payload.hs
bsd-3-clause
1,906
0
9
458
398
223
175
48
2
module Language.MicroKanren (module MK) where import Language.MicroKanren.Core as MK import Language.MicroKanren.Extended as MK import Language.MicroKanren.Reify as MK
joneshf/MicroKanren
src/Language/MicroKanren.hs
bsd-3-clause
176
0
4
25
36
26
10
4
0
module Main where import Numeric.LinearAlgebra import Common import Forward import BackProp import AutoEncoder import ActivFunc import Other main :: IO () main = do regression classification regression :: IO () regression = do ws <- genWeights [2, 4, 8, 1] let x = matrix 4 [0, 0, 1, 1, 0, 1, 0, 1] let y = matrix 4 [0, 1, 1, 0] let i = matrix 4 [0, 0, 1, 1, 0, 1, 0, 1] -- example -- let nws = last . take 500 $ iterate (backPropRegression sigmoids (x, y)) ws nws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropRegression 0.1 sigmoids) ws let pws = preTrains 0.1 500 sigmoids x ws npws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropRegression 0.1 sigmoids) pws putStrLn "training inputs" print x putStrLn "training outputs" print y putStrLn "inputs" print i putStrLn "not trained outputs" print $ forwardRegression sigmoidC ws i putStrLn "trainined outputs" print $ forwardRegression sigmoidC nws i putStrLn "pretrainined outputs" print $ forwardRegression sigmoidC npws i classification :: IO () classification = do ws <- genWeights [2, 4, 8, 3] let x = matrix 4 [0, 0, 1, 1, 0, 1, 0, 1] let y = matrix 4 [1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1] let i = matrix 4 [0, 0, 1, 1, 0, 1, 0, 1] -- example -- let nws = last . take 500 $ iterate (backPropClassification sigmoids (x, y)) ws nws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropClassification 0.1 sigmoids) ws let pws = preTrains 0.1 500 sigmoids x ws npws <- last . take 500 $ iterateM (sgdMethod 2 (x, y) $ backPropClassification 0.1 sigmoids) pws putStrLn "training inputs" print x putStrLn "training outputs" print y putStrLn "inputs" print i putStrLn "not trained outputs" print $ forwardClassification sigmoidC ws i putStrLn "trainined outputs" print $ forwardClassification sigmoidC nws i putStrLn "pretrainined outputs" print $ forwardClassification sigmoidC npws i
pupuu/deep-neuralnet
app/Main.hs
bsd-3-clause
2,075
0
13
544
770
382
388
60
1
module Codegen.TigerCodegen where -- Tiger compiler bindings import Tiger.TigerLanguage import Codegen.TigerSymbolTable import Codegen.TigerEnvironment -- LLVM bindings import qualified LLVM.General.AST as AST import qualified LLVM.General.AST.Type as Type import qualified LLVM.General.AST.Global as Global import qualified LLVM.General.AST.Constant as Constant import qualified LLVM.General.AST.Linkage as Linkage -- states and monads import Control.Applicative -- Utilities import Control.Lens import Data.Map.Lens import Data.Maybe import qualified Data.Map as Map import qualified Data.Sequence as Seq import Control.Monad import Control.Monad.State.Strict import Data.Foldable (toList) import qualified Data.List as List (sortBy) import Data.Function (on) import Data.Char (ord) uniqueName :: Symbol -> Names -> (Symbol, Names) uniqueName nm ns = case ns^.at nm of Nothing -> (nm, Map.insert nm 1 ns) Just idx -> (nm ++ show idx, Map.insert nm (idx+1) ns) runLLVM :: AST.Module -> LLVM a -> AST.Module runLLVM = flip (execState . unLLVM) emptyModule :: Symbol -> AST.Module emptyModule label = AST.defaultModule { AST.moduleName = label } execCodegen :: CodegenState -> Codegen a -> CodegenState execCodegen cgs mcg = execState (runCodegen mcg) cgs nextCount :: Codegen Word nextCount = count += 1 >> use count -- Returns the reference to the generated instruction emitInst :: AST.Instruction -> Codegen AST.Operand emitInst i = do n <- nextCount let ref = (AST.UnName n) let newInst = ref AST.:= i emitNamedInst newInst return $ local ref terminator :: NamedTerminator -> Codegen (NamedTerminator) terminator trm = emitTerm trm >> return trm insertInstruction :: NamedInstruction -> Codegen () insertInstruction inst = undefined -- References -- variables, they are all 32 bits. local :: AST.Name -> AST.Operand local = AST.LocalReference Type.i32 currentBB :: Codegen BB currentBB = do c <- use curBlkName blks <- use bbs case blks^.at c of Just x -> return x Nothing -> error $ "No such block: " ++ show c -- Symbol Table enterDefScope :: Codegen () enterDefScope = do st <- use symtab symtab .= [Map.empty] ++ st tt <- use tytab tytab .= [Map.empty] ++ tt ft <- use functab functab .= [Map.empty] ++ ft exitDefScope :: Codegen () exitDefScope = do st <- use symtab symtab .= tail st tt <- use tytab tytab .= tail tt ft <- use functab functab .= tail ft -- record types in type table registerNewType :: Symbol -> Ty -> Codegen () registerNewType nm (NameTy tyname) = do ty <- lookupTypeTable tyname insertTypeTable nm ty -- TODO: for aggregated types, we should add to global definition. registerNewType nm (RecordTy _) = error "registerNewType for RecordTy not implemented." registerNewType nm (ArrayTy ty) = do elemty <- getType ty -- create array type let aty = Type.ArrayType 0 elemty insertTypeTable nm aty -- utility functiosn for type tables lookupTypeTable :: Symbol -> Codegen Type.Type lookupTypeTable sym = do tt <- use tytab lookupTableHelper sym tt lookupFuncTable :: Symbol -> Codegen Type.Type lookupFuncTable sym = do ft <- use functab lookupTableHelper sym ft lookupTableHelper :: Symbol -> [Map.Map Symbol a] -> Codegen a lookupTableHelper sym tt = do when (null tt) $ do error $ "lookupTypeTable: cannot find symbol: " ++ show sym let t = (head tt)^.at sym if isNothing t then lookupTableHelper sym (tail tt) else return (fromJust t) insertTypeTable :: Symbol -> Type.Type -> Codegen () insertTypeTable sym ty = do tt <- use tytab when (null tt) $ error "insertTypeTable: encounter empty TypeTable list." tytab .= [Map.insert sym ty (head tt)] ++ tail tt getType :: Ty -> Codegen Type.Type getType (NameTy tysym) = lookupTypeTable tysym getType _ = error $ "undefined function: getType" -- find the first occurrence from the stack. getvar :: Symbol -> Codegen AST.Operand getvar var = do st <- use symtab let result = lookupST st var when (isFunction result) $ error $ "var " ++ show var ++ " is shadowed by a function." return result -- Blocks addBB :: Symbol -> Codegen AST.Name addBB bn = do bls <- use bbs ix <- use blockCount nms <- use names let (qname, supply) = uniqueName bn nms newName = AST.Name qname new = emptyBlock ix newName blockCount += 1 names .= supply modify' $ \s -> s { _bbs = Map.insert newName new bls } return newName setBB :: AST.Name -> Codegen AST.Name setBB name = do curBlkName .= name return name emitNamedInst :: NamedInstruction -> Codegen () emitNamedInst inst = do b <- currentBB bn <- use curBlkName let b' = over instrs (\x -> x |> inst) b modify' $ bbs . at bn ?~ b' emitTerm :: NamedTerminator -> Codegen () emitTerm t = do b <- currentBB bn <- use curBlkName modify' $ bbs . at bn ?~ set term (Just t) b -- definitions type FunctionBody = [Global.BasicBlock] createFuncDef :: Type.Type -> Symbol -> Arguments -> FunctionBody -> AST.Definition createFuncDef rt fn args body = AST.GlobalDefinition $ AST.functionDefaults { Global.name = AST.Name fn, Global.parameters = ([AST.Parameter ty nm [] | (ty, nm) <- args], False), Global.returnType = rt, Global.basicBlocks = body } addDefinition :: AST.Definition -> LLVM () addDefinition def = do definitions <- gets AST.moduleDefinitions modify' $ \s -> s { AST.moduleDefinitions = [def] ++ definitions } createExternFuncDef :: Type.Type -> Symbol -> [AST.Parameter] -> AST.Definition createExternFuncDef rt fn args = AST.GlobalDefinition $ AST.functionDefaults { Global.name = AST.Name fn, Global.parameters = (args, False), Global.returnType = rt, Global.basicBlocks = [] } createVarExternFuncDef :: Type.Type -> Symbol -> [AST.Parameter] -> AST.Definition createVarExternFuncDef rt fn args = AST.GlobalDefinition $ AST.functionDefaults { Global.name = AST.Name fn, Global.parameters = (args, True), Global.returnType = rt, Global.basicBlocks = [] } createStringDef :: Symbol -> String -> AST.Definition createStringDef name val = AST.GlobalDefinition $ AST.globalVariableDefaults { Global.name = AST.Name name, Global.linkage = Linkage.Private, Global.isConstant = True, Global.type' = Type.ArrayType (fromIntegral $ length val) Type.i8, Global.initializer = Just (Constant.Array Type.i8 (fmap (\c -> Constant.Int 8 (fromIntegral $ ord c)) val)) } -- we need a way to identify isFunction :: AST.Operand -> Bool isFunction (AST.ConstantOperand (Constant.GlobalReference (Type.FunctionType _ _ _) _)) = True isFunction _ = False -- Types embeddedTypes = Map.fromList [("int", Type.i32)] lookupType :: SymbolTable -> Symbol -> Type.Type lookupType st nm = case embeddedTypes^.at nm of Just x -> x Nothing -> error $ "Custom types are not yet implemented: " ++ show nm isSimpleType :: Type.Type -> Bool isSimpleType i32 = True isSimpleType _ = False -- Basic block toBasicBlock :: (AST.Name, BasicBlock) -> AST.BasicBlock toBasicBlock (_, BasicBlock idx insts term name) = AST.BasicBlock name (toList insts) (getTerm term) where getTerm t = case t of Just x -> x Nothing -> error $ "basic block has no terminator: " ++ show idx sortBlocks :: [(AST.Name, BasicBlock)] -> [(AST.Name, BasicBlock)] sortBlocks = List.sortBy (compare `on` (_idx . snd)) createBlocks :: CodegenState -> [AST.BasicBlock] createBlocks cgs = map toBasicBlock (sortBlocks $ Map.toList $ cgs^.bbs)
lialan/TigerCompiler
app/Codegen/TigerCodegen.hs
bsd-3-clause
7,535
0
18
1,463
2,585
1,318
1,267
-1
-1
-- | Module definining the 6502 architecture. module Arch6502 where import Data.Bits import Data.Word -- |All supported 6502 Mnemonics data Mnemonic = ADC -- ^ Add with carry | AND -- ^ And (with accumulator) | ASL -- ^ Arithmetic shift left | BCC -- ^ Branch on carry clear | BCS -- ^ Branch on carry set | BEQ -- ^ Branch on equal | BIT -- ^ Bit test | BMI -- ^ Branch on minus | BNE -- ^ Branch on not equal | BPL -- ^ Branch on plus | BRK -- ^ Interrupt | BVC -- ^ Branch on overflow clear | BVS -- ^ Branch on overflow set | CLC -- ^ Clear carry | CLD -- ^ Clear decimal | CLI -- ^ Clear interrupt disable | CLV -- ^ Clear overflow | CMP -- ^ Compare (with accumulator) | CPX -- ^ Compare with X | CPY -- ^ Compare with Y | DEC -- ^ Decrement | DEX -- ^ Decrement X | DEY -- ^ Decrement Y | EOR -- ^ Exclusive or (with accumulator) | INC -- ^ Increment | INX -- ^ Increment X | INY -- ^ Increment Y | JMP -- ^ Jump | JSR -- ^ Jump subroutine | LDA -- ^ Load accumulator | LDX -- ^ Load X | LDY -- ^ Load Y | LSR -- ^ Logical shift right | NOP -- ^ No operation | ORA -- ^ Or with accumulator | PHA -- ^ Push accumulator | PHP -- ^ Push processor status | PLA -- ^ Pull accumulator | PLP -- ^ Pull processor status | ROL -- ^ Rotate left | ROR -- ^ Rotate right | RTI -- ^ Return from interrupt | RTS -- ^ Return from subroutine | SBC -- ^ Subtract with carry | SEC -- ^ Set carry | SED -- ^ Set decimal | SEI -- ^ Set interrupt disable | STA -- ^ Store accumulator | STX -- ^ Store X | STY -- ^ Store Y | TAX -- ^ Transfer accumulator to X | TAY -- ^ Transfer accumulator to Y | TSX -- ^ Transfer stack pointer to X | TXA -- ^ Transfer X to accumulator | TXS -- ^ Transfer X to stack pointer | TYA -- ^ Transfer Y to accumulator deriving (Eq,Enum,Bounded,Show,Read) -- |List of all 6502 Mnemonics allMnemonics :: [Mnemonic] allMnemonics = [minBound..maxBound] -- |Predicate to filter relative branch instructions isBranch :: Mnemonic -> Bool isBranch m = opCode m Relative /= Nothing -- |Predicate to filter rotate and shift instructions isShiftRotate :: Mnemonic -> Bool isShiftRotate m = opCode m Accumulator /= Nothing -- |6502 Addressing Modes data AddressingMode = Absolute -- ^ Absolute addressing: $A5B6 | AbsoluteX -- ^ Absolute Indexed with X: $A5B6,X | AbsoluteY -- ^ Absolute Indexed with X: $A5B6,Y | Accumulator -- ^ Accumulator: A | Immediate -- ^ Immediate: #$A5 | Implied -- ^ No operand is specified | IndexedIndirect -- ^ Indexed Indirect: ($A5,X) | Indirect -- ^ Indirect ($A5) | IndirectIndexed -- ^ Indirect Indexed: ($A5),Y | Relative -- ^ Specified operand must be converted into a relative offset (used for branches) | ZeroPage -- ^ Zero Page: $A5 | ZeroPageX -- ^ Zero Page Indexed with X: $A5,X | ZeroPageY -- ^ Zero Page Indexed with Y: $A5,Y deriving (Eq,Enum,Show) -- |Encode a mnemonic with an operand of a specific addressing mode into a sequence of bytes encodeInstruction :: Int -> Mnemonic -> AddressingMode -> Int -> Maybe [Word8] encodeInstruction addr mnemonic mode value = -- encoding is the instruction opcode followed by a stream of bytes for the operand case opCode mnemonic mode of Just code -> Just $ code : encodeOperand (operandLength mode) value' _ -> Nothing where -- convert target address into relative distance for branches value' = if mode == Relative then value - addr - 2 else value -- |Encode an integer value into a little endian sequence of bytes encodeOperand :: Int -> Int -> [Word8] encodeOperand 0 _ = [] encodeOperand n v = (fromIntegral $ v .&. 255) : encodeOperand (n-1) (v `shift` (-8)) -- |Returns the number of bytes needed to encode an addressing mode operandLength :: AddressingMode -> Int operandLength mode = case mode of Accumulator -> 0 Implied -> 0 Absolute -> 2 AbsoluteX -> 2 AbsoluteY -> 2 _ -> 1 -- |Returns the opcode for a combination of instruction mnemonic and addressing mode opCode :: Mnemonic -> AddressingMode -> Maybe Word8 opCode mnemonic mode = opcode mode mnemonic where opcode m = case m of Absolute -> opcodeAbsolute AbsoluteX -> opcodeAbsoluteX AbsoluteY -> opcodeAbsoluteY Accumulator -> opcodeAccumulator Immediate -> opcodeImmediate Implied -> opcodeImplied IndexedIndirect -> opcodeIndexedIndirect Indirect -> opcodeIndirect IndirectIndexed -> opcodeIndirectIndexed Relative -> opcodeRelative ZeroPage -> opcodeZeroPage ZeroPageX -> opcodeZeroPageX ZeroPageY -> opcodeZeroPageY opcodeAbsolute m = case m of ADC -> Just 0x6d AND -> Just 0x2d ASL -> Just 0x0e BIT -> Just 0x2c CMP -> Just 0xcd CPX -> Just 0xec CPY -> Just 0xcc DEC -> Just 0xce EOR -> Just 0x4d INC -> Just 0xee JMP -> Just 0x4c JSR -> Just 0x20 LDA -> Just 0xad LDX -> Just 0xae LDY -> Just 0xac LSR -> Just 0x4e ORA -> Just 0x0d ROL -> Just 0x2e ROR -> Just 0x6e SBC -> Just 0xed STA -> Just 0x8d STX -> Just 0x8e STY -> Just 0x8c _ -> Nothing opcodeAbsoluteX m = case m of ADC -> Just 0x7d AND -> Just 0x3d ASL -> Just 0x1e CMP -> Just 0xdd DEC -> Just 0xde EOR -> Just 0x5d INC -> Just 0xfe LDA -> Just 0xbd LDY -> Just 0xbc LSR -> Just 0x5e ORA -> Just 0x1d ROL -> Just 0x3e ROR -> Just 0x7e SBC -> Just 0xfd STA -> Just 0x9d _ -> Nothing opcodeAbsoluteY m = case m of ADC -> Just 0x79 AND -> Just 0x39 CMP -> Just 0xd9 EOR -> Just 0x59 LDA -> Just 0xb9 LDX -> Just 0xbe ORA -> Just 0x19 SBC -> Just 0xf9 STA -> Just 0x99 _ -> Nothing opcodeAccumulator m = case m of ASL -> Just 0x0a LSR -> Just 0x4a ROL -> Just 0x2a ROR -> Just 0x6a _ -> Nothing opcodeImmediate m = case m of ADC -> Just 0x69 AND -> Just 0x29 CMP -> Just 0xc9 CPX -> Just 0xe0 CPY -> Just 0xc0 EOR -> Just 0x49 LDA -> Just 0xa9 LDX -> Just 0xa2 LDY -> Just 0xa0 ORA -> Just 0x09 SBC -> Just 0xe9 _ -> Nothing opcodeImplied m = case m of BRK -> Just 0x00 CLC -> Just 0x18 CLD -> Just 0xd8 CLI -> Just 0x58 CLV -> Just 0xb8 DEX -> Just 0xca DEY -> Just 0x88 INX -> Just 0xe8 INY -> Just 0xc8 NOP -> Just 0xea PHA -> Just 0x48 PHP -> Just 0x08 PLA -> Just 0x68 PLP -> Just 0x28 RTI -> Just 0x40 RTS -> Just 0x60 SEC -> Just 0x38 SED -> Just 0xf8 SEI -> Just 0x78 TAX -> Just 0xaa TAY -> Just 0xa8 TSX -> Just 0xba TXA -> Just 0x8a TXS -> Just 0x9a TYA -> Just 0x98 _ -> Nothing opcodeIndexedIndirect m = case m of ADC -> Just 0x61 AND -> Just 0x21 CMP -> Just 0xc1 EOR -> Just 0x41 LDA -> Just 0xa1 ORA -> Just 0x01 SBC -> Just 0xe1 STA -> Just 0x81 _ -> Nothing opcodeIndirect m = case m of JMP -> Just 0x6c _ -> Nothing opcodeIndirectIndexed m = case m of ADC -> Just 0x71 AND -> Just 0x31 CMP -> Just 0xd1 EOR -> Just 0x51 LDA -> Just 0xb1 ORA -> Just 0x11 SBC -> Just 0xf1 STA -> Just 0x91 _ -> Nothing opcodeRelative m = case m of BCC -> Just 0x90 BCS -> Just 0xb0 BEQ -> Just 0xf0 BMI -> Just 0x30 BNE -> Just 0xd0 BPL -> Just 0x10 BVC -> Just 0x50 BVS -> Just 0x70 _ -> Nothing opcodeZeroPage m = case m of ADC -> Just 0x65 AND -> Just 0x25 ASL -> Just 0x06 BIT -> Just 0x24 CMP -> Just 0xc5 CPX -> Just 0xe4 CPY -> Just 0xc4 DEC -> Just 0xc6 EOR -> Just 0x45 INC -> Just 0xe6 LDA -> Just 0xa5 LDX -> Just 0xa6 LDY -> Just 0xa4 LSR -> Just 0x46 ORA -> Just 0x05 ROL -> Just 0x26 ROR -> Just 0x66 SBC -> Just 0xe5 STA -> Just 0x85 STX -> Just 0x86 STY -> Just 0x84 _ -> Nothing opcodeZeroPageX m = case m of ADC -> Just 0x75 AND -> Just 0x35 ASL -> Just 0x16 CMP -> Just 0xd5 DEC -> Just 0xd6 EOR -> Just 0x55 INC -> Just 0xf6 LDA -> Just 0xb5 LDY -> Just 0xb4 LSR -> Just 0x56 ORA -> Just 0x15 ROL -> Just 0x36 ROR -> Just 0x76 SBC -> Just 0xf5 STA -> Just 0x95 STY -> Just 0x94 _ -> Nothing opcodeZeroPageY m = case m of LDX -> Just 0xb6 STX -> Just 0x96 _ -> Nothing -- |Check whether a combination of mnemonic and addressing mode is illegal isIllegalInstruction :: Mnemonic -> AddressingMode -> Bool isIllegalInstruction = ((Nothing ==) . ) . opCode
m-schmidt/Asm6502
src/Arch6502.hs
bsd-3-clause
10,263
0
11
4,129
2,412
1,218
1,194
292
164
-- http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_9_C -- Card Game -- input: -- 3 -- cat dog -- fish fish -- lion tiger -- output: -- 1 7 import Control.Applicative ((<$>)) import qualified Control.Monad as Monad (replicateM) type Hands = [String] type Points = [Int] main = do n <- read <$> getLine hs <- map words <$> Monad.replicateM n getLine putStrLn . unwords $ show <$> cardGame hs cardGame :: [Hands] -> Points cardGame hs = foldr1 (\x acc -> zipWith (+) x acc) $ map oneGame hs oneGame :: Hands -> Points oneGame [a,b] | result == LT = [0,3] | result == EQ = [1,1] | result == GT = [3,0] where result = a `compare` b
ku00/aoj-haskell
src/ITP1_9_C.hs
bsd-3-clause
676
0
10
150
249
139
110
16
1
-- | -- Module : Simulation.Aivika.Experiment.Chart.Utils -- Copyright : Copyright (c) 2012-2017, David Sorokin <[email protected]> -- License : BSD3 -- Maintainer : David Sorokin <[email protected]> -- Stability : experimental -- Tested with: GHC 8.0.1 -- -- The module defines some utilities used in the charting. -- module Simulation.Aivika.Experiment.Chart.Utils (colourisePlotLines, colourisePlotFillBetween, colourisePlotBars) where import Control.Lens import Data.Colour import Data.Colour.Names import Graphics.Rendering.Chart -- | Colourise the plot lines. colourisePlotLines :: [PlotLines x y -> PlotLines x y] colourisePlotLines = map mkstyle $ cycle defaultColorSeq where mkstyle c = plot_lines_style . line_color .~ c -- | Colourise the filling areas. colourisePlotFillBetween :: [PlotFillBetween x y -> PlotFillBetween x y] colourisePlotFillBetween = map mkstyle $ cycle defaultColorSeq where mkstyle c = plot_fillbetween_style .~ solidFillStyle (dissolve 0.4 c) -- | Colourise the plot bars. colourisePlotBars :: PlotBars x y -> PlotBars x y colourisePlotBars = plot_bars_item_styles .~ map mkstyle (cycle defaultColorSeq) where mkstyle c = (solidFillStyle c, Just $ solidLine 1.0 $ opaque black)
dsorokin/aivika-experiment-chart
Simulation/Aivika/Experiment/Chart/Utils.hs
bsd-3-clause
1,275
0
10
209
244
133
111
-1
-1
{- Test/Main.hs The units Package Copyright (c) 2014 Richard Eisenberg [email protected] This is the main testing file for the units package. -} {-# LANGUAGE ImplicitParams #-} module Tests.Main where import qualified Tests.Compile.CGS () import qualified Tests.Compile.EvalType () import qualified Tests.Compile.Lcsu () import qualified Tests.Compile.MetrologySynonyms () import qualified Tests.Compile.NoVector () import qualified Tests.Compile.Physics () import qualified Tests.Compile.Quantity () import qualified Tests.Compile.Readme () import qualified Tests.Compile.Simulator () import qualified Tests.Compile.TH () import qualified Tests.Compile.UnitParser () import qualified Tests.Compile.Units () import qualified Tests.Compile.T23 () import qualified Tests.Imperial import qualified Tests.LennardJones import qualified Tests.Linearity import qualified Tests.OffSystemAdd import qualified Tests.OffSystemCSU import qualified Tests.Parser import qualified Tests.PhysicalConstants import qualified Tests.Show import qualified Tests.Travel import qualified Tests.Vector import Test.Tasty main :: IO () main = defaultMain tests tests :: TestTree tests = let ?epsilon = 0.0000001 in testGroup "Tests" [ Tests.Imperial.tests , Tests.LennardJones.tests , Tests.Linearity.tests , Tests.OffSystemAdd.tests , Tests.OffSystemCSU.tests , Tests.Parser.tests , Tests.PhysicalConstants.tests , Tests.Show.tests , Tests.Travel.tests , Tests.Vector.tests ]
hesiod/units
Tests/Main.hs
bsd-3-clause
1,638
0
9
341
307
202
105
42
1
-- | More HUnit practice -- -- tutoralial located at: <https://leiffrenzel.de/papers/getting-started-with-hunit.html> module FindIdentifier (findIdentifier) where import Data.List( sort ) import Data.Maybe import Data.Generics import Language.Haskell.Parser import Language.Haskell.Syntax findIdentifier :: String -> (Int, Int) -> Maybe String findIdentifier [] _ = Nothing findIdentifier content pos = if pos < (1, 1) then error "Bad cursor position" else do hsModule <- fromParseResult $ parseModule content getIdentifierForPos hsModule pos -- helper functions fromParseResult(ParseOk hm) = Just hm fromParseResult _ = Nothing getIdentifierForPos :: HsModule -> (Int, Int) -> Maybe String getIdentifierForPos hsModule pos = do let occs = sort $ colloectOccurences hsModule occ <- find occs pos fromOcc occ pos collectOccurrences :: HsModule -> [(SrcLoc, String)] collectOccurrences = everthing (++) ([], `mkQ` getOcc) where getOcc (HsIdent loc str) = [(loc, str)] find :: [(SrcLoc, String)] -> (Int, Int) -> Maybe (SrcLoc, String) find [] _ = Nothing find locs pos = getLast$ locsBefore locs pos where getLast [] = Nothing getLast locs = Just $ last locs locsBefore locs pos = filter (before pos) locs where before :: (Int, Int) -> (SrcLoc, String) -> Bool before (posL, posC) ( (SrcLoc _ line col), _ ) = line < posL || ( line == posL && col <= posC ) -- we have the first identifier before the specified position, but still the -- end of the identifier must be after the specified position (else the cursor -- would in fact be after the identifier that we have found) fromOcc :: (SrcLoc, String) -> (Int, Int) -> Maybe String fromOcc ((SrcLoc _ line col), ident) (posL, posC) = do if line /= posL || ( col + length ident ) < posC then Nothing else Just ident
emaphis/Haskell-Practice
testing-project/src/FindIdentifier.hs
bsd-3-clause
1,834
0
12
354
592
320
272
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans -fno-warn-missing-methods #-} module PeerTrader.AutoFilter.AutoFilter ( AutoFilter (..) , autoFilter , AutoFilterConstructor (..) ) where import Control.Monad (guard, mzero, unless) import Control.Monad.Trans (lift) import Control.Monad.Trans.Maybe import Data.Aeson import GHC.Generics import Database.Groundhog () import Database.Groundhog.TH import NoteScript as N import Prosper hiding (Money) import PeerTrader.AutoFilter.Range -- | TODO Needs to be abstracted to multiple backends or something data AutoFilter = AutoFilter { -- Filters ratings :: ![Rating] , categories :: ![Category] , ficoRange :: !(Maybe (Range Int)) , bankcardUtilizationRange :: !(Maybe (Range Double)) , -- | Nothing represents No filter. -- Just True is Only homeowners. Just False is only non-homeowners. isHomeownerFilter :: !(Maybe Bool) , yieldRange :: !(Maybe (Range Double)) , effectiveYieldRange :: !(Maybe (Range Double)) , rateRange :: !(Maybe (Range Double)) , aprRange :: !(Maybe (Range Double)) , -- | Similar to how isHomeownerFilter works. -- Just True means that you only want 3 year terms -- Just False is for only 5 year terms -- Nothing is for both termInMonthsFilter :: !(Maybe Bool) , incomeRangeRange :: !(Maybe (Range Money)) , statedMonthlyIncomeRange :: !(Maybe (Range Money)) , debtToIncomeRange :: !(Maybe (Range Double)) , amountDelinquentRange :: !(Maybe (Range Money)) , openCreditLinesRange :: !(Maybe (Range Int)) , totOpenRevolvingAcctsRange :: !(Maybe (Range Int)) , revolvingBalanceRange :: !(Maybe (Range Money)) , revolvingAvailableCreditRange :: !(Maybe (Range Int)) -- ^ Percent , nowDelinquentDerogRange :: !(Maybe (Range Int)) , wasDelinquentDerogRange :: !(Maybe (Range Int)) } deriving (Show, Eq, Generic) mkPersist defaultCodegenConfig [groundhog| definitions: - primitive: Rating - primitive: Category |] mkPersist defaultCodegenConfig [groundhog| entity: AutoFilter |] instance ToJSON AutoFilter where instance FromJSON AutoFilter where -- | Check if a value is inside of a range, inclusively inclInRange :: Ord a => a -> Range a -> Bool inclInRange x (Range l h) = x >= l && x <= h -- | Check if a value from a Listing is inside of a range, if not, then do not -- continue with the investment in the 'autoFilter' function. This can be thought -- of as a guard on a range. guardInRange :: Ord a => (Listing -> a) -- ^ Accessor function for the value in the listing -> Maybe (Range a) -- ^ Range considered -> MaybeT ProsperScript () guardInRange _ Nothing = return () guardInRange x (Just range) = do x' <- lift $ get x guard (inclInRange x' range) -- | If the field is not included in the listing, then fall through, else do -- a normal check. -- -- TODO This should probably check if the range is well defined. Perhaps a -- Maybe (Range a) makes sense. Nothing would mean that we just pass-through -- and ignore the condition. Just (Range) means that the field in the listing -- must be defined and that it must be in the appropriate range. guardMaybeInRange :: Ord a => (Listing -> Maybe a) -> Maybe (Range a) -> MaybeT ProsperScript () guardMaybeInRange _ Nothing = return () guardMaybeInRange x (Just range) = do x' <- lift $ get x case x' of Nothing -> return () Just x'' -> guard (inclInRange x'' range) -- | This guard handles boolean values from listings with the option of handling -- both cases. The encoding is: -- Nothing means accept both -- Just True means that the listing property must have a value of True -- Just False means that the listing property must be False guardMaybeBool :: (Listing -> Bool) -> Maybe Bool -> MaybeT ProsperScript () guardMaybeBool _ Nothing = return () guardMaybeBool x (Just y) = do x' <- lift $ get x unless (x' == y) mzero -- | A guard for 'incomeRange'. If both ends of the income range are in the -- given range for the strategy, then pass-through, else 'mzero'. guardIncomeRange :: Maybe (Range Money) -> MaybeT ProsperScript () guardIncomeRange Nothing = return () guardIncomeRange (Just range) = do x <- lift $ get (incomeRange . credit) case x of -- TODO Might have to add another filter for employment -- Check if the investor is willing to invest in unemployed Nothing -> return () -- If they're unemployed, then just continue Just (x', y') -> unless (inclInRange x' range && inclInRange y' range) mzero -- | Convert a 'AutoFilter' into a 'NoteScript' -- Invest if all of the guards pass autoFilter :: AutoFilter -> ProsperScript Bool autoFilter AutoFilter{..} = fmap maybeToBool . runMaybeT $ do r <- lift $ get rating guard (null ratings || r `elem` ratings) -- If the ratings are [], then ignore. c <- lift $ get category guard (null categories || c `elem` categories) guardInRange (yield . offer) yieldRange guardInRange (effectiveYield . offer) effectiveYieldRange guardInRange (apr . offer) aprRange guardInRange (rate . offer) rateRange guardMaybeBool ((== 36) . termInMonths . offer) termInMonthsFilter guardInRange (fico . credit) ficoRange guardInRange (bankcardUtilization . credit) bankcardUtilizationRange guardMaybeBool (isHomeowner . credit) isHomeownerFilter guardInRange (debtToIncome . credit) debtToIncomeRange guardIncomeRange incomeRangeRange guardMaybeInRange (statedMonthlyIncome . credit) statedMonthlyIncomeRange guardMaybeInRange (amountDelinquent . credit) amountDelinquentRange guardMaybeInRange (openCreditLines . credit) openCreditLinesRange guardMaybeInRange (totOpenRevolvingAccts . credit) totOpenRevolvingAcctsRange guardMaybeInRange (revolvingBalance . credit) revolvingBalanceRange guardMaybeInRange (revolvingAvailableCredit . credit) revolvingAvailableCreditRange guardMaybeInRange (nowDelinquentDerog . credit) nowDelinquentDerogRange guardMaybeInRange (wasDelinquentDerog . credit) wasDelinquentDerogRange where maybeToBool :: Maybe () -> Bool maybeToBool (Just _) = True maybeToBool Nothing = False
WraithM/peertrader-backend
src/PeerTrader/AutoFilter/AutoFilter.hs
bsd-3-clause
6,909
0
13
1,706
1,480
769
711
149
2
{-# LANGUAGE TypeFamilies #-} ---------------------------------------------------------------------- -- | -- Module : Data.Functor.Representable.Trie.Bool -- Copyright : (c) Edward Kmett 2011 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- ---------------------------------------------------------------------- module Data.Functor.Representable.Trie.Bool ( BoolTrie (..) ) where import Control.Applicative import Data.Distributive import Data.Functor.Representable import Data.Functor.Bind import Data.Foldable import Data.Traversable import Data.Semigroup import Data.Semigroup.Foldable import Data.Semigroup.Traversable import Data.Key import Prelude hiding (lookup) -- (Bool, -) -| BoolTrie data BoolTrie a = BoolTrie a a deriving (Eq,Ord,Show,Read) false :: BoolTrie a -> a false (BoolTrie a _) = a true :: BoolTrie a -> a true (BoolTrie _ b) = b type instance Key BoolTrie = Bool instance Functor BoolTrie where fmap f (BoolTrie a b) = BoolTrie (f a) (f b) b <$ _ = pure b instance Apply BoolTrie where BoolTrie a b <.> BoolTrie c d = BoolTrie (a c) (b d) a <. _ = a _ .> b = b instance Applicative BoolTrie where pure a = BoolTrie a a (<*>) = (<.>) a <* _ = a _ *> b = b instance Bind BoolTrie where BoolTrie a b >>- f = BoolTrie (false (f a)) (true (f b)) instance Monad BoolTrie where return = pure BoolTrie a b >>= f = BoolTrie (false (f a)) (true (f b)) _ >> a = a instance Keyed BoolTrie where mapWithKey f (BoolTrie a b) = BoolTrie (f False a) (f True b) instance Zip BoolTrie where zipWith f (BoolTrie a b) (BoolTrie c d) = BoolTrie (f a c) (f b d) instance ZipWithKey BoolTrie where zipWithKey f (BoolTrie a b) (BoolTrie c d) = BoolTrie (f False a c) (f True b d) instance Foldable BoolTrie where foldMap f (BoolTrie a b) = f a `mappend` f b instance Foldable1 BoolTrie where foldMap1 f (BoolTrie a b) = f a <> f b instance Traversable BoolTrie where traverse f (BoolTrie a b) = BoolTrie <$> f a <*> f b instance Traversable1 BoolTrie where traverse1 f (BoolTrie a b) = BoolTrie <$> f a <.> f b instance FoldableWithKey BoolTrie where foldMapWithKey f (BoolTrie a b) = f False a `mappend` f True b instance FoldableWithKey1 BoolTrie where foldMapWithKey1 f (BoolTrie a b) = f False a <> f True b instance TraversableWithKey BoolTrie where traverseWithKey f (BoolTrie a b) = BoolTrie <$> f False a <*> f True b instance TraversableWithKey1 BoolTrie where traverseWithKey1 f (BoolTrie a b) = BoolTrie <$> f False a <.> f True b instance Distributive BoolTrie where distribute = distributeRep instance Indexable BoolTrie where index (BoolTrie a _) False = a index (BoolTrie _ b) True = b instance Adjustable BoolTrie where adjust f False (BoolTrie a b) = BoolTrie (f a) b adjust f True (BoolTrie a b) = BoolTrie a (f b) instance Lookup BoolTrie where lookup = lookupDefault instance Representable BoolTrie where tabulate f = BoolTrie (f False) (f True)
ekmett/representable-tries
src/Data/Functor/Representable/Trie/Bool.hs
bsd-3-clause
3,013
0
10
598
1,151
582
569
71
1
module Main where import PBKDF2 import Control.Monad import Control.DeepSeq import System.CPUTime import Text.Printf main :: IO () main = do putStrLn "start" test 1 test 10 test 100 test 1000 putStrLn "end" test :: Int -> IO () test n = do start <- getCPUTime ((iterate sha1 msg) !! n) `deepseq` return () end <- getCPUTime let diff = (fromIntegral (end - start)) / (10^12) printf "iter %d, time %0.6f sec\n" (n :: Int) (diff :: Double)
markus-git/PBKDF2
src/Main.hs
bsd-3-clause
490
0
14
130
198
98
100
21
1