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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- !!! Re-exporting a module whose contents is partially hidden.
module ShouldCompile ( module Data.List ) where
import Data.List hiding ( sort )
| siddhanathan/ghc | testsuite/tests/rename/should_compile/rn025.hs | bsd-3-clause | 148 | 0 | 5 | 25 | 24 | 16 | 8 | 2 | 0 |
module Main where
import Common
import GridCoord
import Data.List
import qualified Data.Set as Set
import Text.Megaparsec
import Text.Megaparsec.Char
-- | Vectors used for incremental steps
data Vec = Vec !Int !Int
deriving (Eq, Ord, Show, Read)
data Command = Command !Char !Int
parser :: Parser [Command]
parser = (Command <$> oneOf "LDRU" <*> number) `sepBy` string ", "
main :: IO ()
main =
do cmds <- parseOrDie parser <$> readInputFile 1
let path = computePath cmds
print (part1 path)
print (part2 path)
-- | Given a list of steps determine the ultimate Manhattan-distance from
-- the starting position.
part1 :: [Coord] -> Int
part1 = manhattanDistance origin . last
part2 :: [Coord] -> Maybe Int
part2 = fmap (manhattanDistance origin) . duplicate
computePath :: [Command] -> [Coord]
computePath = toCoords origin . toSteps north
where
north = Vec 0 (-1)
-- | Find the first duplicate element in a list
duplicate :: Ord a => [a] -> Maybe a
duplicate = aux Set.empty
where
aux _ [] = Nothing
aux seen (x:xs)
| Set.member x seen = Just x
| otherwise = aux (Set.insert x seen) xs
-- | Compute steps taken by following a list of commands
toSteps ::
Vec {- ^ initial direction -} ->
[Command] {- ^ commands -} ->
[Vec] {- ^ list of directions -}
toSteps dir0 cmds = concat (snd (mapAccumL aux dir0 cmds))
where
aux dir (Command lr steps) =
let dir' = turn lr dir
in (dir', replicate steps dir')
toCoords ::
Coord {- ^ origin -} ->
[Vec] {- ^ steps -} ->
[Coord] {- ^ path -}
toCoords = scanl step
turn :: Char -> Vec -> Vec
turn 'L' (Vec dx dy) = Vec (-dy) dx
turn 'R' (Vec dx dy) = Vec dy (-dx)
turn c _ = error ("Bad instruction: " ++ [c])
step :: Coord -> Vec -> Coord
step (Coord x y) (Vec dx dy) = Coord (x + dx) (y + dy)
| glguy/advent2016 | Day01.hs | isc | 1,923 | 0 | 11 | 522 | 676 | 351 | 325 | 58 | 2 |
t = [5,"kkk"]
| mortum5/programming | haskell/ITMO-Course/test.hs | mit | 14 | 1 | 5 | 3 | 15 | 7 | 8 | 1 | 1 |
module Main where
import qualified Data.ByteString.Lazy as BS
import qualified Codec.Picture.Types as PicTypes
import qualified Codec.Picture.Png as Png
import Data.IDX
import Data.List.Split
import qualified Data.Vector.Unboxed as DU
import System.Random.Mersenne.Pure64
import Data.Maybe -- FIXME: for fromJust, which can throw an error
import Data.Word (Word64)
import Control.Monad
import System.Random
import Data.List
import Data.Ord
-- FIXME: using psuedo-random numbers for test
-- thx http://stackoverflow.com/a/8777494
randomStream :: DU.Unbox a => (PureMT -> (a, PureMT)) -> PureMT -> DU.Vector a
randomStream rndstep = DU.unfoldr (Just . rndstep)
toStream :: Word64 -> [Double]
toStream seed = DU.toList (randomStream randomDouble $ pureMT seed)
genFooImage x y = PicTypes.PixelRGB8 (fromIntegral x) (fromIntegral y) 128
fooImage = PicTypes.generateImage genFooImage 250 300
matrixToPNG :: Int -> Int -> [Int] -> PicTypes.Image PicTypes.PixelRGB8
matrixToPNG w h matrix = PicTypes.generateImage rasterize w h where
gray b = PicTypes.PixelRGB8 b b b
rasterize x y = gray (fromIntegral (matrix !! (y * w + x)))
idxToPng :: IDXData -> [PicTypes.Image PicTypes.PixelRGB8]
idxToPng idxData = map (matrixToPNG width height) imageMatrices where
[numImages, width, height] = DU.toList (idxDimensions idxData)
imageData = idxIntContent idxData
imageMatrices = chunksOf (width * height) (DU.toList imageData)
data ImageMatrix = ImageMatrix {
width :: Int,
height :: Int,
pixels :: [Int]
}
-- Agh how do monads actually work!?
imagesFromIDXFile :: String -> IO [ImageMatrix]
imagesFromIDXFile path = do
idxData <- decodeIDXFile path
let [imageCount, width, height] = DU.toList (idxDimensions $ fromJust idxData)
let imageData = idxIntContent $ fromJust idxData
let imageMatrices = chunksOf (width * height) (DU.toList imageData)
let images = map (\pixels -> ImageMatrix { width = width, height = height, pixels = pixels }) imageMatrices
return images
-- FIXME: handle case where IDX data has wrong dimensions for labels
labelsFromIDXFile :: String -> IO [Label]
labelsFromIDXFile path = do
idxData <- decodeIDXFile path
let labels = DU.toList (idxIntContent $ fromJust idxData)
return (map toInteger labels)
getPixel :: Int -> Int -> ImageMatrix -> Int
getPixel x y image = fromIntegral (pixels image !! (y * w + x)) where
w = width image
type Label = Integer
randomClassifier :: ImageMatrix -> Label
randomClassifier image = 10 * floor (head $ toStream 42)
-- given some images return a classifier
-- or nothing if the number of images does not match the number of labels
trainClassifier :: [ImageMatrix] -> [Label] -> Maybe (ImageMatrix -> Label)
trainClassifier images labels = if length images == length labels then
Just randomClassifier
else
Nothing
-- BEGIN things stolen from https://crypto.stanford.edu/~blynn/haskell/brain.html
gauss :: Float -> IO Float
gauss stdev = do
x1 <- randomIO
x2 <- randomIO
return $ stdev * sqrt (-2 * log x1) * cos (2 * pi * x2)
-- f is activation function
-- ws is weights
-- b is bias
-- as is inputs
output f ws b as = f (sum (zipWith (*) ws as) + b)
-- rectifier: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
relu = max 0
relu' x | x < 0 = 0
| otherwise = 1
dCost a y | y == 1 && a >= y = 0
| otherwise = a - y
newBrain :: [Int] -> IO [([Float], [[Float]])]
newBrain szs@(_:ts) = zip (flip replicate 1 <$> ts) <$>
zipWithM (\m n -> replicateM n $ replicateM m $ gauss 0.01) szs ts
zLayer :: [Float] -> ([Float], [[Float]]) -> [Float]
zLayer as (bs, wvs) = zipWith (+) bs $ sum . zipWith (*) as <$> wvs
feed :: [Float] -> [([Float], [[Float]])] -> [Float]
feed = foldl (((relu <$>) . ) . zLayer)
-- xv: vector of inputs
-- Returns a list of (weighted inputs, activations) of each layer,
-- from last layer to first.
revaz :: [Float] -> [([Float], [[Float]])] -> ([[Float]], [[Float]])
revaz xv = foldl (\(avs@(av:_), zs) (bs, wms) -> let
zs' = zLayer av (bs, wms) in (((relu <$> zs'):avs), (zs':zs))) ([xv], [])
-- xv: vector of inputs
-- yv: vector of desired outputs
-- Returns list of (activations, deltas) of each layer in order.
deltas :: [Float] -> [Float] -> [([Float], [[Float]])] -> ([[Float]], [[Float]])
deltas xv yv layers = let
(avs@(av:_), zv:zvs) = revaz xv layers
delta0 = zipWith (*) (zipWith dCost av yv) (relu' <$> zv)
in (reverse avs, f (transpose . snd <$> reverse layers) zvs [delta0]) where
f _ [] dvs = dvs
f (wm:wms) (zv:zvs) dvs@(dv:_) = f wms zvs $ (:dvs) $
zipWith (*) [(sum $ zipWith (*) row dv) | row <- wm] (relu' <$> zv)
eta = 0.002
descend av dv = zipWith (-) av ((eta *) <$> dv)
learn :: [Float] -> [Float] -> [([Float], [[Float]])] -> [([Float], [[Float]])]
learn xv yv layers = let (avs, dvs) = deltas xv yv layers
in zip (zipWith descend (fst <$> layers) dvs) $
zipWith3 (\wvs av dv -> zipWith (\wv d -> descend wv ((d*) <$> av)) wvs dv)
(snd <$> layers) avs dvs
getImage s n = pixels $ s !! n
getX s n = (/ 256) . fromIntegral <$> getImage s n
getLabel s n = s !! n
getY s n = fromIntegral . fromEnum . (getLabel s n ==) <$> [0..9]
-- END stolen things
{-
data Neuron = Neuron {
inputs :: [Neuron],
weights :: [Double],
activation :: Double -> Double
}
e = exp 1
sigmoidActivation :: Double -> Double
sigmoidActivation v = 1 / (1 + e ** (- v))
-- Get the output value of a neuron
output :: Neuron -> Double
output neuron = activation neuron $ sum inputValues where
inputValues = map output (inputs neuron)
testNet = Neuron { inputs = [], weights = [], activation = const 0 }
-}
main :: IO ()
main = do
trainingImages <- imagesFromIDXFile "./data/t10k-images-idx3-ubyte"
trainingLabels <- labelsFromIDXFile "./data/t10k-labels-idx1-ubyte"
testImages <- imagesFromIDXFile "./data/train-images-idx3-ubyte"
testLabels <- labelsFromIDXFile "./data/train-labels-idx1-ubyte"
b <- newBrain [784, 30, 10]
n <- (`mod` (10000 :: Int)) <$> randomIO
let
example = getX testImages n
bs = scanl (foldl' (\b n -> learn (getX trainingImages n) (getY trainingLabels n) b)) b [
[ 0.. 999],
[1000..2999],
[3000..5999],
[6000..9999]]
smart = last bs
cute d score = show d ++ ": " ++ replicate (round $ 70 * min 1 score) '+'
bestOf = fst . maximumBy (comparing snd) . zip [0..]
forM_ bs $ putStrLn . unlines . zipWith cute [0..9] . feed example
putStrLn $ "best guess: " ++ show (bestOf $ feed example smart)
let answers = getLabel testLabels <$> [0..9999]
--putStrLn $ show (sum $ fromEnum <$> zipWith (==) guesses answers) ++
-- " / 10000"
--let classifier = fromJust $ trainClassifier trainingImages trainingLabels
let guesses = bestOf . (\n -> feed (getX testImages n) smart) <$> [0..9999]
let numberOfCorrectGuesses = length (filter (uncurry (==)) (zip answers guesses))
let ratioCorrect = realToFrac numberOfCorrectGuesses / realToFrac (length answers)
let outputMessage = show (100.0 * ratioCorrect) ++ "% of labels on test images guessed correctly"
in putStrLn outputMessage
| jmptable/mnist-classifier | src/Main.hs | mit | 7,114 | 0 | 17 | 1,398 | 2,563 | 1,368 | 1,195 | 122 | 2 |
{-|
Programming Languages
Fall 2015
Implementation in Haskell of the concepts covered in Chapter 1 of
Nielson & Nielson, Semantics with Applications
Author: Haritz Puerto-San-Roman
-}
module Exercises01 where
import While
import Test.HUnit hiding (State)
import Data.List
-- |----------------------------------------------------------------------
-- | Exercise 1
-- |----------------------------------------------------------------------
-- | Given the algebraic data type 'Bin' for the binary numerals:
data Bit = O
| I
deriving Show
data Bin = MSB Bit
| B Bin Bit
-- | and the following values of type 'Bin':
zero :: Bin
zero = MSB O
one :: Bin
one = MSB I
three :: Bin
three = B (B (MSB O) I) I
six :: Bin
six = B (B (MSB I) I) O
-- | define a semantic function 'binVal' that associates
-- | a binary number (Bin) to a decimal number.
binVal :: Bin -> Z
binVal (MSB O) = 0
binVal (MSB I) = 1
binVal (B b O) = 2*(binVal b)
binVal (B b I) = 2*(binVal b) + 1
-- | Test your function with HUnit.
testBinVal :: Test
testBinVal = test ["value of zero" ~: 0 ~=? binVal zero,
"value of one" ~: 1 ~=? binVal one,
"value of three" ~: 3 ~=? binVal three,
"value of six" ~: 6 ~=? binVal six]
-- | If you dare, define a function 'foldBin' to fold a value of type 'Bin'
foldBin :: (Bit -> Z -> Z) -> Z -> Bin -> Z
foldBin f base x = solve x
where
solve (MSB z) = z `f` base
solve (B x z) = z `f` (solve x)
fbin :: Bit -> Z -> Z
fbin O x = 2 * x
fbin I x = 1 + 2 * x
-- | and use 'foldBin' to define a function 'binVal'' equivalent to 'binVal'
binVal' :: Bin -> Integer
binVal' b = foldBin fbin 0 b
-- | Test your function with HUnit.
testBinVal' :: Test
testBinVal' = test ["value of zero" ~: 0 ~=? binVal' zero,
"value of one" ~: 1 ~=? binVal one,
"value of three" ~: 3 ~=? binVal three,
"value of six" ~: 6 ~=? binVal six]
-- |----------------------------------------------------------------------
-- | Exercise 2
-- |----------------------------------------------------------------------
-- | Define the function 'fvAexp' that computes the set of free variables
-- | occurring in an arithmetic expression. Ensure that each free variable
-- | occurs once in the resulting list.
fvAexp :: Aexp -> [Var]
fvAexp (N x) = []
fvAexp (V x) = [x]
fvAexp (Add x y) = nub $ (fvAexp x) ++ (fvAexp y)
fvAexp (Mult x y) = nub $ (fvAexp x) ++ (fvAexp y)
fvAexp (Sub x y) = nub $ (fvAexp x) ++ (fvAexp y)
-- nub is available at Data.List It removes repeated elements
removeRepeatedElems :: Eq a => [a] -> [a]
removeRepeatedElems [] = []
removeRepeatedElems (x:xs)
| elem x xs = xs
| otherwise = x:xs
-- | Test your function with HUnit.
testfvAexp :: Test
testfvAexp = test ["FV(x)" ~: ["x"] ~=? fvAexp (V "x"),
"FV(5)" ~: [] ~=? fvAexp (N 5),
"FV(x + 3)" ~: ["x"] ~=? fvAexp (Add (V "x") (N 3)),
"FV(x * 3)" ~: ["x"] ~=? fvAexp (Mult (V "x") (N 3)),
"FV(x - y)" ~: ["x", "y"] ~=? fvAexp (Add (V "x") (V "y"))]
-- | Define the function 'fvBexp' that computes the set of free variables
-- | occurring in a Boolean expression.
fvBexp :: Bexp -> [Var]
fvBexp TRUE = []
fvBexp FALSE = []
fvBexp (Eq x y) = nub $ (fvAexp x) ++ (fvAexp y)
fvBexp (Le x y) = nub $ (fvAexp x) ++ (fvAexp y)
fvBexp (Neg b) = nub $ (fvBexp b)
fvBexp (And b bb) = nub $ (fvBexp b) ++ (fvBexp bb)
-- | Test your function with HUnit.
testfvBexp :: Test
testfvBexp = test ["FV(TRUE)" ~: ["x"] ~=? fvBexp TRUE,
"FV(FALSE)" ~: [] ~=? fvBexp FALSE,
"FV((Eq (V x) (V y) ))" ~: ["x", "y"] ~=? fvBexp (Eq (V "x") (V "y") ),
"FV((Le (V x) (V y) ))" ~: ["x", "y"] ~=? fvBexp ((Le (V "x") (V "y") )),
"FV((Neg (Eq (V x) (V y) )))" ~: ["x", "y"] ~=? fvBexp (Neg (Eq (V "x") (V "y") )),
"FV((And (Eq (V x) (V y) ) (Eq (V x) (V y) ) ))" ~: ["x", "y"] ~=? fvBexp (And (Eq (V "x") (V "y") ) (Eq (V "x") (V "y") )) ]
-- |----------------------------------------------------------------------
-- | Exercise 3
-- |----------------------------------------------------------------------
-- | Given the algebraic data type 'Subst' for representing substitutions:
data Subst = Var :->: Aexp
-- | define a function 'substAexp' that takes an arithmetic expression
-- | 'a' and a substitution 'y:->:a0' and returns the substitution a [y:->:a0];
-- | i.e., replaces every occurrence of 'y' in 'a' by 'a0'.
substAexp :: Aexp -> Subst -> Aexp
substAexp (N x) _ = (N x)
substAexp (V x) (y:->:a0)
| x == y = a0
| otherwise = (V x)
substAexp (Add a1 a2) s = Add (substAexp a1 s) (substAexp a2 s)
substAexp (Mult a1 a2) s = Mult (substAexp a1 s) (substAexp a2 s)
substAexp (Sub a1 a2) s = Sub (substAexp a1 s) (substAexp a2 s)
testSubstAexp :: Test
testSubstAexp = test ["5 [y:->:x]" ~: (N 5) ~=? substAexp (N 5) ("y":->: (V "x")),
"y [y:->:x]" ~: (V "x") ~=? substAexp (V "y") ("y":->: (V "x")),
"y [z:->:x]" ~: (V "y") ~=? substAexp (V "y") ("z":->: (V "x")),
"(Add (N 5) (V y)) [y:->:x]" ~: (Add (N 5) (V "x")) ~=? substAexp (Add (N 5) (V "y")) ("y":->: (V "x")),
"(Mult (N 5) (V y)) [y:->:x]" ~: (Mult (N 5) (V "x")) ~=? substAexp (Mult (N 5) (V "y")) ("y":->: (V "x")),
"(Sub (N 5) (V y)) [y:->:x]" ~: (Sub (N 5) (V "x")) ~=? substAexp (Sub (N 5) (V "y")) ("y":->: (V "x"))]
-- | Define a function 'substBexp' that implements substitution for
-- | Boolean expressions.
substBexp :: Bexp -> Subst -> Bexp
substBexp TRUE _ = TRUE
substBexp FALSE _ = FALSE
substBexp (Eq x y) subs = (Eq (substAexp x subs) (substAexp y subs))
substBexp (Le x y) subs = (Le (substAexp x subs) (substAexp y subs))
substBexp (Neg b) subs = (Neg (substBexp b subs))
substBexp (And b bb) subs = (And (substBexp b subs) (substBexp bb subs))
-- | Test your function with HUnit.
testsubstBexp :: Test
testsubstBexp = test ["sInit [y:->:x]" ~: TRUE ~=? substBexp TRUE ("y":->: (V "x")),
"FALSE [y:->:x]" ~: FALSE ~=? substBexp FALSE ("y":->: (V "x")),
"(a1 == a2) [y:->:x]" ~: (Eq (V "x") (N 5) ) ~=? substBexp (Eq (V "y") (N 5) ) ("y":->: (V "x")),
"(a1 < a2) [y:->:x]" ~: (Le (V "x") (N 5) ) ~=? substBexp (Le (V "y") (N 5) ) ("y":->: (V "x")),
"(! (a1 == a2) ) [y:->:x]" ~: (Neg (Eq (V "x") (N 5) )) ~=? substBexp (Eq (V "y") (N 5) ) ("y":->: (V "x")),
"(AND TRUE (V y)) [y:->:x]" ~: (And (Eq (V "z") (N 5) ) (Le (V "x") (N 5) )) ~=? substBexp (And (Eq (V "z") (N 5) ) (Le (V "y") (N 5) )) ("y":->: (V "x"))]
-- |----------------------------------------------------------------------
-- | Exercise 4
-- |----------------------------------------------------------------------
-- | Given the algebraic data type 'Update' for state updates:
data Update = Var :=>: Z
-- | define a function 'update' that takes a state 's' and an update 'x :=>: v'
-- | and returns the updated state 's [x :=> y]'
update :: State -> Update -> State
update s (x :=>: v) y
| x == y = v
| otherwise = s y
testUpdate :: Test
testUpdate = test ["sInit [x:=>:5]" ~: 5 ~=? (update sInit ("x":=>: 5)) "x",
"sInit [y:=>:5]" ~: 3 ~=? (update sInit ("y":=>: 5)) "x"]
-- | Define a function 'updates' that takes a state 's' and a list of updates
-- | 'us' and returns the updated states resulting from applying the updates
-- | in 'us' from head to tail. For example:
-- |
-- | updates s ["x" :=> 1, "y" :=> 2, "x" :=> 3]
-- |
-- | returns a state that binds "x" to 3 (the most recent update for "x").
updates :: State -> [Update] -> State
updates s [] = s
updates s (x:xs) = updates (update s x) xs
-- |----------------------------------------------------------------------
-- | Exercise 5
-- |----------------------------------------------------------------------
-- | Define a function 'foldAexp' to fold an arithmetic expression
foldAexp :: (Integer -> a) ->
(Var -> a) ->
(a -> a -> a) ->
(a -> a -> a) ->
(a -> a -> a) ->
Aexp ->
a
foldAexp n v a m s exp = resolver exp
where
resolver (N const) = n const
resolver (V x) = v x
resolver (Add e1 e2) = a (resolver e1) (resolver e2)
resolver (Mult e1 e2) = m (resolver e1) (resolver e2)
resolver (Sub e1 e2) = s (resolver e1) (resolver e2)
-- | Use 'foldAexp' to fefine the functions 'aVal'', 'fvAexp'', and 'substAexp''
-- | and test your definitions with HUnit.
aVal' :: Aexp -> State -> Z
aVal' e s = foldAexp (\n -> n) (\x -> s x) (\x1 x2 -> x1 + x2) (\x1 x2 -> x1 * x2) (\x1 x2 -> x1 - x2) e
fvAexp' :: Aexp -> [Var]
fvAexp' = foldAexp (\x -> []) (\x -> [x]) (\x1 x2 -> nub $ x1 ++ x2) (\x1 x2 -> nub $ x1 ++ x2) (\x1 x2 -> nub $ x1 ++ x2)
substAexp' :: Aexp -> Subst -> Aexp
substAexp' e s = foldAexp (\x -> (N x)) (subsVar s) (\x1 x2 -> (Add x1 x2)) (\x1 x2 -> (Mult x1 x2)) (\x1 x2 -> (Sub x1 x2)) e
subsVar :: Subst -> Var -> Aexp
subsVar (y:->:a0) x
| x == y = a0
| otherwise = (V x)
-- | Define a function 'foldBexp' to fold a Boolean expression and use it
-- | to define the functions 'bVal'', 'fvBexp'', and 'substAexp''. Test
-- | your definitions with HUnit.
foldBexp :: a -> a ->
(Aexp -> Aexp -> a) ->
(Aexp -> Aexp -> a) ->
(a-> a) ->
(a-> a-> a) ->
Bexp ->
a
foldBexp t f eq le n a b = resolver b
where
resolver TRUE = t
resolver FALSE = f
resolver (Eq e1 e2) = eq e1 e2
resolver (Le e1 e2) = le e1 e2
resolver (Neg e) = n (resolver e)
resolver (And e1 e2) = a (resolver e1) (resolver e2)
bVal' :: Bexp -> State -> Bool
bVal' b s = foldBexp True False (\x1 x2 -> aVal' x1 s == aVal' x2 s) (\x1 x2 -> aVal' x1 s < aVal' x2 s) (\x -> not x) (\x1 x2 -> x1 && x2) b
fvBexp' :: Bexp -> [Var]
fvBexp' = foldBexp [] [] (\x1 x2 -> nub $ fvAexp' x1 ++ fvAexp' x2) (\x1 x2 -> nub $ fvAexp' x1 ++ fvAexp' x2) (\x1 -> x1) (\x1 x2 -> nub $ x1 ++ x2)
substBexp' :: Bexp -> Subst -> Bexp
substBexp' e s = foldBexp TRUE FALSE (\x1 x2 -> (Eq (substAexp' x1 s) (substAexp' x2 s) ) ) (\x1 x2 -> (Le (substAexp' x1 s) (substAexp' x2 s) )) (\x -> (Neg x) ) (\x1 x2 -> (And x1 x2) ) e
| HaritzPuerto/SemanticsforWhileLanguage | While/Exercises01.hs | mit | 10,032 | 66 | 14 | 2,334 | 3,967 | 2,065 | 1,902 | 156 | 6 |
import Control.Applicative
import Control.Arrow
import Data.List.Split
(|>) :: a -> (a -> b) -> b
(|>) x y = y x
infixl 0 |>
main :: IO ()
main = do
_ <- getLine
widths <- readInts <$> getLine
interact $ lines >>> map (readInts >>> solve widths >>> show) >>> unlines
readInts :: String -> [Int]
readInts = splitOn " " >>> map read
solve :: [Int] -> [Int] -> Int
solve widths [i, j] = sublist i (j + 1) widths |> minimum
solve _ _ = error "wrong number of inputs, 2 expected"
-- right open interval
sublist :: Int -> Int -> [a] -> [a]
sublist start end = drop start >>> take (end - start) | Dobiasd/HackerRank-solutions | Algorithms/Warmup/Service_Lane/Main.hs | mit | 604 | 1 | 13 | 136 | 275 | 142 | 133 | 18 | 1 |
module Players.SinglePlayer where
import Players.Player
import TicTacToe as T hiding (win)
import Util
data SinglePlayer = SinglePlayer String Token
deriving Show
instance Player SinglePlayer where
iToken (SinglePlayer _ t) = t
iName (SinglePlayer n _) = n
iMove = move
iChooseSize = chooseSize
iWin = win
iLose = lose
iReceiveSize = receiveSize
move :: SinglePlayer -> TicTacToe -> IO (Int, Int)
move __ = playerMove
playerMove :: TicTacToe -> IO (Int, Int)
playerMove state = do
mv <- getMove
case mv of
Left _ -> rc
Right oMove ->
if T.isLegal state oMove && T.isBlank state oMove
then return oMove
else rc
where
rc = do
putStrLn "Illegal move, please try again!"
playerMove state
receiveSize :: SinglePlayer -> Int -> IO ()
receiveSize _ sz = putStrLn $ "Opponent chose size " ++ show sz ++ "."
chooseSize :: SinglePlayer -> IO Int
chooseSize p = do
putStrLn "Please choose the size of the board: "
n <- getInt
if n <= 0
then do
putStrLn "Illegal number, must be greater than 0"
chooseSize p
else
return n
win :: SinglePlayer -> TicTacToe -> IO ()
win (SinglePlayer n _) _ = putStrLn $ n ++ " wins!"
lose :: SinglePlayer -> TicTacToe -> IO ()
lose (SinglePlayer n _) _ = putStrLn $ n ++ " lost!"
generatePlayer :: Token -> IO SinglePlayer
generatePlayer t = do
putStr $ "Enter the name of player " ++ show t ++ ": "
n <- getLine
return (SinglePlayer n t)
| davidarnarsson/tictactoe | Players/SinglePlayer.hs | mit | 1,626 | 0 | 13 | 516 | 493 | 246 | 247 | 48 | 3 |
module STree ( STree
, snil
, sisNil
, sisNode
, sleftSub
, srightSub
, streeVal
, sinsTree
, sdelete
, sminTree
, sindexT
, successor
, ancientor
, closest ) where
data STree a = SNil | SNode a Int (STree a) (STree a) deriving (Eq, Show)
snil :: STree a
snil = SNil
sisNil :: STree a -> Bool
sisNil SNil = True
sisNil SNode {} = False
sisNode :: STree a -> Bool
sisNode = not . sisNil
sleftSub :: STree a -> STree a
sleftSub SNil = SNil
sleftSub (SNode _ _ lft _) = lft
srightSub :: STree a -> STree a
srightSub SNil = SNil
srightSub (SNode _ _ _ rht) = rht
streeVal :: STree a -> a
streeVal SNil = error "empty tree"
streeVal (SNode val _ _ _) = val
sinsTree :: Ord a => a -> STree a -> STree a
sinsTree val SNil = SNode val 1 SNil SNil
sinsTree v (SNode val sz tl tr)
| v == val = SNode val sz tl tr
| val > v = SNode val (sz + 1) (sinsTree v tl) tr
| otherwise = SNode val (sz + 1) tl (sinsTree v tr)
sdelete :: Ord a => a -> STree a -> STree a
sdelete _ SNil = SNil
sdelete targ (SNode val sz tl tr)
| targ < val = SNode val sz (sdelete targ tl) tr
| targ > val = SNode val sz tl (sdelete targ tr)
| sisNil tl = tr
| sisNil tr = tl
| otherwise = sjoin tl tr
where sjoin :: Ord a => STree a -> STree a -> STree a
sjoin lt rt = SNode sminr (ssize lt + ssize rt) lt (sdelete sminr rt)
where (Just sminr) = sminTree rt
sminTree :: Ord a => STree a -> Maybe a
sminTree tree
| sisNil tree = Nothing
| sisNil (sleftSub tree) = Just (streeVal tree)
| otherwise = (sminTree . sleftSub) tree
ssize :: STree a -> Int
ssize SNil = 0
ssize (SNode _ n _ _) = n
sindexT :: Int -> STree a -> a
sindexT n tr
| sisNil tr = error "index error fail to fetch"
| n == ssize tr = streeVal tr
| n < ssize (sleftSub tr) = sindexT n (sleftSub tr)
| otherwise = sindexT (n - 1 - (ssize . sleftSub) tr) (srightSub tr)
successor :: Ord a => a -> STree a -> Maybe a
successor _ SNil = Nothing
successor v (SNode val _ SNil SNil)
| v <= val = Just val
| otherwise = Nothing
successor fdtg (SNode val _ tl tr)
| fdtg >= val = successor fdtg tr
| otherwise = successor fdtg (sinsTree val tl)
ancientor :: Ord a => a -> STree a -> Maybe a
ancientor _ SNil = Nothing
ancientor v (SNode val _ SNil SNil)
| v <= val = Nothing
| otherwise = Just val
ancientor v (SNode val _ tl tr)
| v < val = ancientor v tl
| otherwise = ancientor v (sinsTree val tr)
closest :: Int -> STree Int -> Int
closest val tr
| Nothing == suc = maybe (error "fuck you") id anc
| Nothing == anc = maybe (error "fuck you") id suc
| otherwise = clos anc suc val
where suc = successor val tr
anc = ancientor val tr
clos :: Maybe Int -> Maybe Int -> Int -> Int
clos (Just vl) (Just vr) _val = if _val - vl > vr - _val
then vr
else vl
| tonyfloatersu/solution-haskell-craft-of-FP | STree.hs | mit | 3,564 | 0 | 11 | 1,494 | 1,396 | 670 | 726 | 89 | 2 |
import Data.List
import Data.Function
main :: IO ()
main = interact (run . map read . words)
run :: [Int] -> String
run (n:xs) = out (solve (pairs xs)) where
-- show result
out :: [Int] -> String
out ys = unlines [show (length ys), unwords (map show ys)]
-- form input
pairs :: [Int] -> [(Int, Int)]
pairs [] = []
pairs (x:y:zs) = (x, y) : pairs zs
-- solution
solve :: [(Int, Int)] -> [Int]
solve ps = solve' (sortBy (compare `on` snd) ps) [] where
solve' [] acc = acc
solve' ((_, s):us) acc = solve' (filter (\u -> fst u > s || snd u < s) us) (s:acc)
| da-eto-ya/trash | haskell/algos/segments-points/Main.hs | mit | 598 | 1 | 17 | 159 | 347 | 183 | 164 | 15 | 3 |
module Urbit.Vere.Ames.LaneCache (cache) where
import Urbit.Prelude
import Urbit.Noun.Time
expiry :: Gap
expiry = (2 * 60) ^. from secs
cache :: forall a b m n
. (Ord a, MonadIO m, MonadIO n)
=> (a -> m b)
-> n (a -> m b)
cache act = do
cas <- newTVarIO (mempty :: Map a (Wen, b))
let fun x = lookup x <$> readTVarIO cas >>= \case
Nothing -> thru
Just (t, v) -> do
t' <- io now
if gap t' t > expiry
then thru
else pure v
where
thru :: m b
thru = do
t <- io now
v <- act x
atomically $ modifyTVar' cas (insertMap x (t, v))
pure v
pure fun
| urbit/urbit | pkg/hs/urbit-king/lib/Urbit/Vere/Ames/LaneCache.hs | mit | 705 | 0 | 18 | 286 | 299 | 151 | 148 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Betfair.APING.Types.PersistenceType
( PersistenceType(..)
) where
import Data.Aeson.TH (Options (omitNothingFields),
defaultOptions, deriveJSON)
import Protolude
import Text.PrettyPrint.GenericPretty
data PersistenceType
= LAPSE
| PERSIST
| MARKET_ON_CLOSE
deriving (Eq, Show, Generic, Pretty)
$(deriveJSON defaultOptions {omitNothingFields = True} ''PersistenceType)
| joe9/betfair-api | src/Betfair/APING/Types/PersistenceType.hs | mit | 663 | 0 | 9 | 145 | 107 | 67 | 40 | 18 | 0 |
module SemiGroupAssociativeLaw (
semigroupAssoc
) where
import Data.Semigroup
semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c)
| NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter15.hsproj/SemiGroupAssociativeLaw.hs | mit | 208 | 0 | 9 | 49 | 90 | 50 | 40 | 5 | 1 |
module Jan22MoreRec where
-- import Data.Char
-- : set expandtab ts=4 ruler number spell
import Test.QuickCheck
{- Most everything in Haskell is a function. If it isn't data.
Church of Recursion
Recursion gets you everything you would want just as well as a Turing Machine
a recursive definition of a list
it's either null as in []
or
constructed as in x:xs
with head x an element and tail xs as a list
that we can then apply head to get x until
the xs = empty
FIRST IS CLEAR AND UNDERSTANDABLE
THEN AND ONLY THEN SHOULD IT BE FASTER
Conditionals are required if wet want to do interesting stuff.
More Conditionals means, each branch requires testing in itself.
operator properties that matter:
associativity If a binary operation is associative, repeated application of the operation produces the same result regardless how valid pairs of parenthesis are inserted in the expression
identity In algebra, an identity or identity element of a set S with a binary operation is an element e that, when combined with any element x of S, produces that same x.
commutativity In mathematics, a binary operation is commutative if changing the order of the operands does not change the result.
distributivity
zero
idempotence is the property of certain operations in mathematics and computer science, that can be applied multiple times without changing the result beyond the initial application.
-}
prop_sum :: Integral a => a -> Property
prop_sum n = n >= 0 ==> sum [1..n] == n * (n + 1) `div` 2
{- *Jan22MoreRec> quickCheck prop_sum
Loading package array-0.4.0.1 ... linking ... done.
Loading package deepseq-1.3.0.1 ... linking ... done.
Loading package bytestring-0.10.0.2 ... linking ... done.
Loading package Win32-2.3.0.0 ... linking ... done.
Loading package old-locale-1.0.0.5 ... linking ... done.
Loading package time-1.4.0.1 ... linking ... done.
Loading package random-1.0.1.1 ... linking ... done.
Loading package containers-0.5.0.0 ... linking ... done.
Loading package pretty-1.1.1.0 ... linking ... done.
Loading package template-haskell ... linking ... done.
Loading package QuickCheck-2.6 ... linking ... done.
-}
-- Associativity Left vs Right
-- (x*x)*x) vs (x*(x*x)
--
-- SEQUENTIAL takes 7 steps which mean m lists it takes m - 1 steps
-- xs1 + (xs2 + (xs3 + (xs4 + (xs5 + (xs6 + (xs7 + xs8))))))
--
-- PARALLEL takes 3 steps
-- ((xs1 + xs2) + (xs3 + xs4)) + ((xs5 + xs6) + (xs7 + xs8))
--
-- if we have m lists it takes log2m steps
-- when m = 1000 sequential takes a hundred times longer than parallel
--}
en5nFromTo m n | m > n = []
| m <= n = m : en5nFromTo (m+1) n
{- the recursion call moves toward the smaller, reducing the distance between start point and end point.
en5nFromTo 1 3
=
1: en5nFromTo 2 3
=
1 : (2 : en5nFromTo 3 3)
=
1: (2 : (3 : en5nFromTo 4 3)
=
1 : (2 : (3 []))
=
[1,2,3]
-}
factorial n = product [1..]
factorialRec n = fact 1 n
where
-- :fact :: Int -> Int -> Int
fact m n | m > n = 1
| m <= n = m * fact (m+1) n
-- prop_fac n = factorial n == factorialRec n
-- Counting
-- enumFrom 0 == [0..]
en5mFrom m = m : enumFrom (m+1)
z3p [] _ = []
z3p _ [] = []
z3p (x:xs) (y:ys) = (x,y) : z3p xs ys
--
| HaskellForCats/HaskellForCats | 30MinHaskell/z_notes/3_ab_quickCheck.hs | mit | 3,406 | 0 | 11 | 851 | 310 | 167 | 143 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.HTMLMeterElement
(setValue, getValue, setMin, getMin, setMax, getMax, setLow,
getLow, setHigh, getHigh, setOptimum, getOptimum, getLabels,
HTMLMeterElement(..), gTypeHTMLMeterElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.value Mozilla HTMLMeterElement.value documentation>
setValue :: (MonadDOM m) => HTMLMeterElement -> Double -> m ()
setValue self val = liftDOM (self ^. jss "value" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.value Mozilla HTMLMeterElement.value documentation>
getValue :: (MonadDOM m) => HTMLMeterElement -> m Double
getValue self = liftDOM ((self ^. js "value") >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.min Mozilla HTMLMeterElement.min documentation>
setMin :: (MonadDOM m) => HTMLMeterElement -> Double -> m ()
setMin self val = liftDOM (self ^. jss "min" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.min Mozilla HTMLMeterElement.min documentation>
getMin :: (MonadDOM m) => HTMLMeterElement -> m Double
getMin self = liftDOM ((self ^. js "min") >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.max Mozilla HTMLMeterElement.max documentation>
setMax :: (MonadDOM m) => HTMLMeterElement -> Double -> m ()
setMax self val = liftDOM (self ^. jss "max" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.max Mozilla HTMLMeterElement.max documentation>
getMax :: (MonadDOM m) => HTMLMeterElement -> m Double
getMax self = liftDOM ((self ^. js "max") >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.low Mozilla HTMLMeterElement.low documentation>
setLow :: (MonadDOM m) => HTMLMeterElement -> Double -> m ()
setLow self val = liftDOM (self ^. jss "low" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.low Mozilla HTMLMeterElement.low documentation>
getLow :: (MonadDOM m) => HTMLMeterElement -> m Double
getLow self = liftDOM ((self ^. js "low") >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.high Mozilla HTMLMeterElement.high documentation>
setHigh :: (MonadDOM m) => HTMLMeterElement -> Double -> m ()
setHigh self val = liftDOM (self ^. jss "high" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.high Mozilla HTMLMeterElement.high documentation>
getHigh :: (MonadDOM m) => HTMLMeterElement -> m Double
getHigh self = liftDOM ((self ^. js "high") >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.optimum Mozilla HTMLMeterElement.optimum documentation>
setOptimum :: (MonadDOM m) => HTMLMeterElement -> Double -> m ()
setOptimum self val = liftDOM (self ^. jss "optimum" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.optimum Mozilla HTMLMeterElement.optimum documentation>
getOptimum :: (MonadDOM m) => HTMLMeterElement -> m Double
getOptimum self = liftDOM ((self ^. js "optimum") >>= valToNumber)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement.labels Mozilla HTMLMeterElement.labels documentation>
getLabels :: (MonadDOM m) => HTMLMeterElement -> m NodeList
getLabels self
= liftDOM ((self ^. js "labels") >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/HTMLMeterElement.hs | mit | 4,363 | 0 | 10 | 515 | 1,035 | 584 | 451 | 47 | 1 |
{-# LANGUAGE PackageImports #-}
import "lambda-arduino" Application (develMain)
import Prelude (IO)
main :: IO ()
main = develMain
| aufheben/lambda-arduino | app/devel.hs | mit | 132 | 1 | 6 | 19 | 37 | 20 | 17 | 5 | 1 |
{-# LANGUAGE OverloadedStrings, FlexibleInstances, TemplateHaskell#-}
module Dom where
import Data.Maybe (maybe)
import Data.Monoid ((<>))
import Data.Foldable
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import Data.HashSet
import Control.Lens
data NTree a = NTree { _root :: a, _children :: [NTree a] }
deriving (Show,Eq)
makeLenses ''NTree
instance Functor NTree where
fmap f (NTree n ns) = NTree (f n) $ fmap (fmap f) ns
instance Foldable NTree where
foldMap f (NTree n []) = f n
foldMap f (NTree n ns) = f n <> foldMap (foldMap f) ns
-- data specific to each node type
data NodeType = Text T.Text
| Element ElementData
deriving (Show,Eq)
type Node = NTree NodeType
type AttrMap = HM.HashMap T.Text T.Text
data ElementData = ElementData T.Text AttrMap
deriving (Show,Eq)
text :: T.Text -> Node
text = flip NTree [] . Text
elem :: T.Text -> AttrMap -> [Node] -> Node
elem name atts = NTree (Element (ElementData name atts))
findAttr :: ElementData -> T.Text -> Maybe T.Text
findAttr (ElementData _ m) k = HM.lookup k m
findID :: ElementData -> Maybe T.Text
findID = flip findAttr "id"
classes :: ElementData -> HashSet T.Text
classes = maybe empty (fromList . T.split (==' ')) . flip findAttr "class" | Hrothen/Hubert | src/Dom.hs | mit | 1,285 | 0 | 10 | 255 | 495 | 263 | 232 | 34 | 1 |
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Data.Either.Compat"
-- from a globally unique namespace.
module Data.Either.Compat.Repl.Batteries (
module Data.Either.Compat
) where
import "this" Data.Either.Compat
| haskell-compat/base-compat | base-compat-batteries/src/Data/Either/Compat/Repl/Batteries.hs | mit | 286 | 0 | 5 | 31 | 29 | 22 | 7 | 5 | 0 |
module ProjectEuler.Problem020Spec (main, spec) where
import Test.Hspec
import ProjectEuler.Problem020
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $
describe "solve" $
it "finds the sum of the digits in the number 100!" $
solve 100 `shouldBe` 648
| hachibu/project-euler | test/ProjectEuler/Problem020Spec.hs | mit | 279 | 0 | 9 | 58 | 79 | 43 | 36 | 10 | 1 |
module Lisley.Types
( module Lisley.Types
, module Control.Monad.Error
) where
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IORef
import Control.Monad.Error
import Control.Applicative ((<$>))
import Text.ParserCombinators.Parsec (ParseError)
type SimpleFn = [Expr] -> Action Expr
type Fn = Env -> SimpleFn
data Expr = Symbol String
| List [Expr]
| Vector [Expr]
| HashMap (Map Expr Expr)
| Nil
| Number Int
| Keyword String
| String String
| Bool Bool
| PrimitiveFunction String Fn
| Function { fName :: String, params :: [String], vararg :: Maybe String, body :: Expr, closure :: Env }
data LispError = ArityError Int Bool [Expr]
| ArgumentError String [Expr]
| TypeMismatch String Expr
| NotFunction String String
| BadSpecialForm String Expr
| UnboundSymbol String
| Parser ParseError
type Action = ErrorT LispError IO
type Env = IORef [(String, IORef Expr)]
instance Ord Expr where
(Symbol a) `compare` (Symbol b) = a `compare` b
(List a) `compare` (List b) = a `compare` b
(Vector a) `compare` (Vector b) = a `compare` b
(HashMap a) `compare` (HashMap b) = a `compare` b
(Number a) `compare` (Number b) = a `compare` b
(Keyword a) `compare` (Keyword b) = a `compare` b
(String a) `compare` (String b) = a `compare` b
(Bool a) `compare` (Bool b) = a `compare` b
other1 `compare` other2 = GT
instance Eq Expr where
(Symbol a) == (Symbol b) = a == b
(List a) == (List b) = a == b
(Vector a) == (Vector b) = a == b
(HashMap a) == (HashMap b) = a == b
(Number a) == (Number b) = a == b
(Keyword a) == (Keyword b) = a == b
(String a) == (String b) = a == b
(Bool a) == (Bool b) = a == b
other1 == other2 = False
showExpr :: Expr -> String
showExpr (Symbol a) = a
showExpr (Number n) = show n
showExpr (Keyword k) = ":" ++ k
showExpr (String s) = show s
showExpr (Bool b) = if b then "true" else "false"
showExpr Nil = "nil"
showExpr (List xs) = "(" ++ unwordsCol xs ++ ")"
showExpr (Vector xs) = "[" ++ unwordsCol xs ++ "]"
showExpr (HashMap m) = "{" ++ unwordsCol (Map.foldlWithKey (\acc key v -> acc ++ [key,v]) [] m) ++ "}"
showExpr (PrimitiveFunction name f) =
"#<primitive-fn:" ++ name ++ ">"
showExpr (Function name params vararg body _) =
"(fn " ++ (if name == "noname" then "" else name ++ " ") ++ "[" ++ unwords params ++ (if isJust vararg then " & " ++ fromJust vararg else "") ++ "] ...)"
showError :: LispError -> String
showError (ArityError exp var fnd) =
"Expected " ++ show exp ++ (if var then "+" else "") ++ " args, found " ++ show (length fnd) ++ " args: " ++ "(" ++ unwordsCol fnd ++ ")"
showError (ArgumentError msg exprs) = msg ++ ": " ++ unwordsCol exprs
showError (TypeMismatch exp fnd) = "Invalid type: expected " ++ exp ++ ", found " ++ show fnd
showError (NotFunction msg fn) = msg ++ ": " ++ show fn
showError (BadSpecialForm msg f) = msg ++ ": " ++ show f
showError (UnboundSymbol sym) = "Unable to resolve symbol: " ++ sym
showError (Parser parseError) = "Parse error at " ++ show parseError
instance Show Expr where show = showExpr
instance Show LispError where show = showError
instance Error LispError
runAction :: Action String -> IO String
runAction a = extractValue <$> runErrorT (trapError a)
emptyEnv :: IO Env
emptyEnv = newIORef []
unwordsCol :: [Expr] -> String
unwordsCol = unwords . map showExpr
isList :: Expr -> Bool
isList (List _) = True
isList notList = False
isVector :: Expr -> Bool
isVector (Vector _) = True
isVector notVector = False
isHashMap :: Expr -> Bool
isHashMap (HashMap _) = True
isHashMap notHashmap = False
isCol :: Expr -> Bool
isCol x = isList x || isVector x || isHashMap x
isFn :: Expr -> Bool
isFn (PrimitiveFunction _ _) = True
isFn (Function _ _ _ _ _) = True
isFn notFunction = False
trapError action = catchError action (return . show)
extractValue :: Either a b -> b
extractValue (Right val) = val
| goshakkk/lisley | src/Lisley/Types.hs | mit | 4,172 | 0 | 13 | 1,069 | 1,708 | 896 | 812 | 102 | 4 |
-- GenI surface realiser
-- Copyright (C) 2009 Eric Kow
-- Copyright (C) 2005 Carlos Areces
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE TemplateHaskell #-}
-- | GenI values (variables, constants)
module NLP.GenI.GeniVal
( -- * GeniVal
GeniVal, gLabel, gConstraints
, mkGConst, mkGConstNone, mkGVar, mkGVarNone, mkGAnon
-- ** queries and manipulation
, isAnon, singletonVal
-- ** fancy disjunction
, SchemaVal(..), crushOne
-- * Unification and subsumption
--
-- ** Finalisation
--
-- Before you do any unification/subsumption, you should finalise all
-- the variables in all the objects (a one time alpha-conversion type
-- thing)
, finaliseVars, finaliseVarsById, anonymiseSingletons
-- ** Unification
, MonadUnify, unify, UnificationResult(..), Subst, appendSubst
-- ** subsumption
, subsumeOne, allSubsume
-- * Traversing GeniVal containers
, DescendGeniVal(..), Collectable(..), Idable(..)
, replace, replaceList
) where
import NLP.GenI.GeniVal.Internal
| kowey/GenI | src/NLP/GenI/GeniVal.hs | gpl-2.0 | 1,849 | 0 | 5 | 362 | 152 | 115 | 37 | 16 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-------------------------------------------------------------------------------
-- |
-- Module : OpenSandbox.Protocol.Handle.Status
-- Copyright : (c) 2016 Michael Carpenter
-- License : GPL3
-- Maintainer : Michael Carpenter <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module OpenSandbox.Protocol.Handle.Status
( handleStatus
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.State.Lazy
import Data.Conduit
import qualified Data.Text as T
import OpenSandbox.Config
import OpenSandbox.Logger
import OpenSandbox.Protocol.Packet (CBStatus(..),SBStatus(..))
import OpenSandbox.Protocol.Types (ProtocolState(..))
import OpenSandbox.Version
logMsg :: Logger -> Lvl -> String -> IO ()
logMsg logger lvl msg = logIO logger "OpenSandbox.Protocol.Handle.Status" lvl (T.pack msg)
handleStatus :: Config -> Logger -> Conduit SBStatus (StateT ProtocolState IO) CBStatus
handleStatus config logger = awaitForever $ \status ->
case status of
SBRequest -> sendAndLog $
CBResponse
snapshotVersion
(toEnum protocolVersion)
0
(toEnum . fromEnum . srvMaxPlayers $ config)
(srvMotd config)
SBPing payload -> sendAndLog $ CBPong payload
where
sendAndLog :: MonadIO m => CBStatus -> Conduit SBStatus m CBStatus
sendAndLog packet = do
liftIO $ logMsg logger LvlDebug $ "Sending: " ++ show packet
yield packet
| oldmanmike/opensandbox | src/OpenSandbox/Protocol/Handle/Status.hs | gpl-3.0 | 1,599 | 0 | 15 | 308 | 332 | 184 | 148 | 29 | 2 |
module Main where
import HomMad.Goban (initGame)
import HomMad.AI (move)
import Data.Time.Clock
main :: IO ()
main = do
start <- getCurrentTime
putStrLn $ show $ move 0 initGame
end <- getCurrentTime
putStrLn $ "running move for init Game took " ++ show (diffUTCTime end start)
| h-hirai/hommad | bench/bench-move.hs | gpl-3.0 | 288 | 0 | 10 | 55 | 97 | 50 | 47 | 10 | 1 |
{-| Module : LexerMessage
License : GPL
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module Database.Design.Ampersand.Input.ADL1.LexerMessage
( LexerError(..)
, LexerErrorInfo(..)
, LexerWarning(..)
, LexerWarningInfo(..)
, keepOneTabWarning
, isLooksLikeFloatWarningInfo
, showLexerErrorInfo
, showLexerWarningInfo
, showLexerWarnings
) where
import Data.List (intercalate)
import Database.Design.Ampersand.Input.ADL1.FilePos(FilePos)
import qualified Database.Design.Ampersand.Input.ADL1.LexerTexts as Texts
--TODO: Delete the code commented out
{-
instance HasMessage LexerError where
getRanges (LexerError _ (StillOpenAtEOF brackets)) =
reverse (map (sourcePosToRange . fst) brackets)
getRanges (LexerError pos (UnexpectedClose _ pos2 _)) =
map sourcePosToRange [pos, pos2]
getRanges (LexerError pos _) =
[ sourcePosToRange pos ]
getMessage (LexerError _ info) =
let (line:rest) = showLexerErrorInfo info
in MessageOneLiner (MessageString line) :
[ MessageHints Texts.hint [ MessageString s | s <- rest ] ]
sourcePosToRange :: FilePos -> Range
sourcePosToRange pos =
let name = sourceName pos; line = sourceLine pos; col = sourceColumn pos
position = Position_Position name line col
in Range_Range position position
-}
data LexerError = LexerError FilePos LexerErrorInfo
deriving(Show)
data LexerErrorInfo
= UnterminatedComment
| UnterminatedPurpose
| UnterminatedAtom
| UnexpectedChar Char
| NonTerminatedString String
| TooManyClose Char
-- In UnexpectedClose, first char is the closing bracket we see,
-- second char is the closing bracket we would like to see first
-- e.g. [(1,3] => UnexpectedClose ']' ... ')'
| UnexpectedClose Char FilePos Char
| StillOpenAtEOF [(FilePos, Char)]
deriving(Show)
showLexerErrorInfo :: LexerErrorInfo -> [String]
showLexerErrorInfo info =
case info of
UnterminatedComment -> [ Texts.lexerUnterminatedComment ]
UnterminatedPurpose -> [ Texts.lexerUnterminatedPurpose ]
UnterminatedAtom -> [ Texts.lexerUnterminatedAtom ]
UnexpectedChar c -> [ Texts.lexerUnexpectedChar c ]
NonTerminatedString _ -> [ Texts.lexerNonTerminatedString, correctStrings ]
TooManyClose c -> [ Texts.lexerTooManyClose c ]
UnexpectedClose c1 _ c2 -> Texts.lexerUnexpectedClose c1 c2
StillOpenAtEOF [b] -> [ Texts.lexerStillOpenAtEOF [ show (snd b) ] ]
StillOpenAtEOF bs -> [ Texts.lexerStillOpenAtEOF (reverse (map (show.snd) bs)) ]
-- 'reverse' because positions will be sorted and brackets are
-- reported in reversed order
correctStrings :: String
correctStrings = Texts.lexerCorrectStrings
{-
instance HasMessage LexerWarning where
getRanges (LexerWarning pos (NestedComment pos2)) =
map sourcePosToRange [ pos, pos2 ]
getRanges (LexerWarning pos _) =
[ sourcePosToRange pos ]
getMessage (LexerWarning _ info) =
let (line:rest) = showLexerWarningInfo info
in MessageOneLiner (MessageString (Texts.warning ++ ": " ++ line)) :
[ MessageHints Texts.hint [ MessageString s | s <- rest ] ]
-}
data LexerWarning =
LexerWarning FilePos LexerWarningInfo
data LexerWarningInfo
= TabCharacter
| LooksLikeFloatNoFraction String
| LooksLikeFloatNoDigits String
| NestedComment FilePos
| UtfChar
| CommentOperator
showLexerWarnings :: [LexerWarning] -> String
showLexerWarnings ws = intercalate "\n-----------\n" $ map showWarning ws
where showWarning (LexerWarning pos info) = "Warning: " ++
intercalate "\n" (showLexerWarningInfo info) ++ " " ++ show pos
showLexerWarningInfo :: LexerWarningInfo -> [String]
showLexerWarningInfo info =
case info of
TabCharacter -> Texts.lexerTabCharacter
LooksLikeFloatNoFraction digits -> Texts.lexerLooksLikeFloatNoFraction digits
LooksLikeFloatNoDigits fraction -> Texts.lexerLooksLikeFloatNoDigits fraction
NestedComment _ -> Texts.lexerNestedComment
UtfChar -> Texts.lexerUtfChar
CommentOperator -> Texts.lexerCommentOperator
-- TODO: This is only valid for haskell.. Probably more of the warnings too!
keepOneTabWarning :: [LexerWarning] -> [LexerWarning]
keepOneTabWarning = keepOneTab True
where
keepOneTab isFirst (warning@(LexerWarning _ TabCharacter):rest)
| isFirst = warning : keepOneTab False rest
| otherwise = keepOneTab isFirst rest
keepOneTab isFirst (warning:rest) =
warning : keepOneTab isFirst rest
keepOneTab _ [] = []
isLooksLikeFloatWarningInfo :: LexerWarningInfo -> Bool
isLooksLikeFloatWarningInfo warningInfo =
case warningInfo of
LooksLikeFloatNoFraction _ -> True
LooksLikeFloatNoDigits _ -> True
_ -> False | DanielSchiavini/ampersand | src/Database/Design/Ampersand/Input/ADL1/LexerMessage.hs | gpl-3.0 | 5,250 | 0 | 15 | 1,378 | 754 | 411 | 343 | 75 | 9 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module Lamdu.GUI.ExpressionEdit.GetFieldEdit
( make
) where
import Prelude.Compat
import Control.Lens.Operators
import Control.MonadA (MonadA)
import qualified Graphics.UI.Bottle.EventMap as E
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Lamdu.Config as Config
import qualified Lamdu.GUI.ExpressionEdit.TagEdit as TagEdit
import Lamdu.GUI.ExpressionGui (ExpressionGui)
import qualified Lamdu.GUI.ExpressionGui as ExpressionGui
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT
import Lamdu.Sugar.Names.Types (Name(..))
import qualified Lamdu.Sugar.Types as Sugar
import qualified Lamdu.GUI.WidgetIds as WidgetIds
make ::
MonadA m =>
Sugar.GetField (Name m) m (ExprGuiT.SugarExpr m) ->
Sugar.Payload m ExprGuiT.Payload ->
ExprGuiM m (ExpressionGui m)
make (Sugar.GetField recExpr tagG mDelField) pl =
ExpressionGui.stdWrapParentExpr pl $ \myId ->
do
recExprEdit <- ExprGuiM.makeSubexpression 11 recExpr
dotLabel <- ExpressionGui.makeLabel "." (Widget.toAnimId myId)
config <- ExprGuiM.readConfig
let delEventMap =
mDelField
<&> fmap WidgetIds.fromEntityId
& maybe mempty
(Widget.keysEventMapMovesCursor (Config.delKeys config) delDoc)
tagEdit <-
TagEdit.makeRecordTag
(pl ^. Sugar.plData . ExprGuiT.plNearestHoles) tagG
<&> ExpressionGui.egWidget %~ Widget.weakerEvents delEventMap
return $ ExpressionGui.hbox [recExprEdit, dotLabel, tagEdit]
& ExprGuiM.assignCursor myId tagId
where
tagId = WidgetIds.fromEntityId (tagG ^. Sugar.tagInstance)
delDoc = E.Doc ["Edit", "Delete GetField"]
| rvion/lamdu | Lamdu/GUI/ExpressionEdit/GetFieldEdit.hs | gpl-3.0 | 1,947 | 0 | 19 | 437 | 461 | 262 | 199 | -1 | -1 |
-- CSE 240H Lab 1 - Word Count & Histogram
import Data.Char
import Data.List
import qualified Data.Map as Map
import Text.Regex
import System.Environment
normalize :: String -> String
normalize word = map toLower (strip_cruft word) where
strip_cruft word' = subRegex (mkRegex "[^a-zA-Z]*(.*[a-zA-Z])[^a-zA-Z]*") word' "\\1"
isWord :: String -> Bool
isWord = any isAlpha
countWords :: Ord a => [a] -> Map.Map a Int
countWords ws = foldl addOccurance Map.empty ws where
addOccurance m word = Map.insert word (count + 1) m where
count | Map.member word m = m Map.! word
| otherwise = 0
histogramLine :: Int -> Int -> (String, Int) -> String
histogramLine max_key_length max_count (key, count) = key ++ nchars " " ' ' (max_key_length - length key) ++
nchars "" '#' ((80 - max_key_length - 1) *
count `div` max_count) where
nchars str c n | n <= 0 = str -- Append n of c to str
| otherwise = nchars (c:str) c (n - 1)
histogramPairs text = reverse $ sortBy compareCounts $ Map.toList $ countWords ws where
ws = filter isWord $ map normalize (words text)
compareCounts (_, count1) (_, count2) = compare count1 count2
main = do args <- getArgs
text <- if length args > 0 then readFile $ head args
else getContents
-- Process pairs into [(word, count)]
let pairs = histogramPairs text
let max_key_length = maximum $ map (length . fst) pairs
let max_count = maximum $ map snd pairs
-- And output results
mapM_ (putStrLn . histogramLine max_key_length max_count) pairs
| alevy/cs240h-lab1 | hist.hs | gpl-3.0 | 1,707 | 1 | 13 | 502 | 557 | 279 | 278 | 31 | 2 |
module Hadolint.Rule.DL4003 (rule) where
import Hadolint.Rule
import Language.Docker.Syntax (Instruction (..))
data HasCmd = HasCmd | NoCmd
rule :: Rule args
rule = customRule check (emptyState NoCmd)
where
code = "DL4003"
severity = DLWarningC
message =
"Multiple `CMD` instructions found. If you list more than one `CMD` then only the last \
\`CMD` will take effect"
-- Reset the state each time we find a FROM
check _ st From {} = st |> replaceWith NoCmd
-- Remember we found a CMD, fail if we found a CMD before
check _ st@(State _ NoCmd) Cmd {} = st |> replaceWith HasCmd
-- If we already saw a CMD, add an error for the line
check line st@(State _ HasCmd) Cmd {} = st |> addFail (CheckFailure {..})
-- otherwise return the accumulator
check _ st _ = st
{-# INLINEABLE rule #-}
| lukasmartinelli/hadolint | src/Hadolint/Rule/DL4003.hs | gpl-3.0 | 845 | 0 | 10 | 203 | 199 | 110 | 89 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
-- Module : Keiretsu.Config
-- 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)
module Keiretsu.Config
( dependencies
, proctypes
, environment
) where
import Control.Applicative
import Control.Arrow
import Control.Exception (bracket)
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Function
import qualified Data.HashSet as Set
import Data.List
import Data.Monoid
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Yaml
import Keiretsu.Log
import Keiretsu.Types
import Network.Socket
import System.Directory
import System.FilePath
dependencies :: FilePath -> IO [Dep]
dependencies = fmap (reverse . nub) . go mempty <=< canonicalizePath
where
go memo dir = do
let path = dir </> "Intfile"
if not (path `Set.member` memo)
then do
logDebug $ "Loading " ++ dir ++ " ..."
p <- doesFileExist path
with dir $
load memo path p
else do
logDebug $ "Already loaded " ++ dir ++ ", skipping."
return []
with path f =
bracket getCurrentDirectory setCurrentDirectory
(const $ setCurrentDirectory path >> f)
load _ _ False = return []
load memo path True = do
logDebug $ "Reading " ++ path ++ " ..."
xs <- decodeYAML path >>= mapM canonicalise
ys <- concat <$> mapM (go (Set.insert path memo) . depPath) xs
return $! xs ++ ys
canonicalise d = (\p -> d { depPath = p }) <$> canonicalizePath (depPath d)
proctypes :: Int -> Dep -> IO [Proc]
proctypes n d@Dep{..} = do
logDebug $ "Reading " ++ path ++ " ..."
fs <- decodeYAML path
ws <- alloc (length fs)
return $! reverse $ zipWith proc' fs ws
where
path = depPath </> "Procfile"
alloc m = do
!ss <- replicateM m . sequence $ replicate n sock
forM ss . mapM $ \s -> fromIntegral <$> socketPort s <* close s
sock = do
s <- socket AF_INET Stream defaultProtocol
a <- inet_addr "127.0.0.1"
setSocketOption s NoDelay 0
bind s $ SockAddrInet aNY_PORT a
return s
proc' (($ d) -> p@Proc{..}) ws = p
{ procPorts = zipWith ports portRange ws
}
where
ports i w
| i == bound = Port local remote w
| otherwise =
let s = Text.pack (show i)
in Port (local <> s) (remote <> s) w
bound = head portRange
remote = Text.toUpper $ Text.intercalate "_" [depName, procName, local]
local = "PORT"
environment :: [Proc] -> [FilePath] -> IO Env
environment ps fs = do
es <- filterM doesFileExist $ getEnvFiles ps
env <- mapM read' $ es ++ fs
return $! merge (parse env) ps
where
read' path = logDebug ("Reading " ++ path ++ " ...") >> Text.readFile path
merge env = nubBy ((==) `on` fst)
. (++ env)
. getRemoteEnv
parse = map (second Text.tail . Text.break (== '='))
. Text.lines
. Text.concat
decodeYAML :: FromJSON a => FilePath -> IO a
decodeYAML = either error return . decodeEither <=< BS.readFile
| bnordbo/keiretsu | src/Keiretsu/Config.hs | mpl-2.0 | 3,903 | 0 | 17 | 1,283 | 1,097 | 559 | 538 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DLP.Projects.Locations.InspectTemplates.Delete
-- 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)
--
-- Deletes an InspectTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.projects.locations.inspectTemplates.delete@.
module Network.Google.Resource.DLP.Projects.Locations.InspectTemplates.Delete
(
-- * REST Resource
ProjectsLocationsInspectTemplatesDeleteResource
-- * Creating a Request
, projectsLocationsInspectTemplatesDelete
, ProjectsLocationsInspectTemplatesDelete
-- * Request Lenses
, plitdXgafv
, plitdUploadProtocol
, plitdAccessToken
, plitdUploadType
, plitdName
, plitdCallback
) where
import Network.Google.DLP.Types
import Network.Google.Prelude
-- | A resource alias for @dlp.projects.locations.inspectTemplates.delete@ method which the
-- 'ProjectsLocationsInspectTemplatesDelete' request conforms to.
type ProjectsLocationsInspectTemplatesDeleteResource
=
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] GoogleProtobufEmpty
-- | Deletes an InspectTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ 'projectsLocationsInspectTemplatesDelete' smart constructor.
data ProjectsLocationsInspectTemplatesDelete =
ProjectsLocationsInspectTemplatesDelete'
{ _plitdXgafv :: !(Maybe Xgafv)
, _plitdUploadProtocol :: !(Maybe Text)
, _plitdAccessToken :: !(Maybe Text)
, _plitdUploadType :: !(Maybe Text)
, _plitdName :: !Text
, _plitdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsInspectTemplatesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plitdXgafv'
--
-- * 'plitdUploadProtocol'
--
-- * 'plitdAccessToken'
--
-- * 'plitdUploadType'
--
-- * 'plitdName'
--
-- * 'plitdCallback'
projectsLocationsInspectTemplatesDelete
:: Text -- ^ 'plitdName'
-> ProjectsLocationsInspectTemplatesDelete
projectsLocationsInspectTemplatesDelete pPlitdName_ =
ProjectsLocationsInspectTemplatesDelete'
{ _plitdXgafv = Nothing
, _plitdUploadProtocol = Nothing
, _plitdAccessToken = Nothing
, _plitdUploadType = Nothing
, _plitdName = pPlitdName_
, _plitdCallback = Nothing
}
-- | V1 error format.
plitdXgafv :: Lens' ProjectsLocationsInspectTemplatesDelete (Maybe Xgafv)
plitdXgafv
= lens _plitdXgafv (\ s a -> s{_plitdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plitdUploadProtocol :: Lens' ProjectsLocationsInspectTemplatesDelete (Maybe Text)
plitdUploadProtocol
= lens _plitdUploadProtocol
(\ s a -> s{_plitdUploadProtocol = a})
-- | OAuth access token.
plitdAccessToken :: Lens' ProjectsLocationsInspectTemplatesDelete (Maybe Text)
plitdAccessToken
= lens _plitdAccessToken
(\ s a -> s{_plitdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plitdUploadType :: Lens' ProjectsLocationsInspectTemplatesDelete (Maybe Text)
plitdUploadType
= lens _plitdUploadType
(\ s a -> s{_plitdUploadType = a})
-- | Required. Resource name of the organization and inspectTemplate to be
-- deleted, for example
-- \`organizations\/433245324\/inspectTemplates\/432452342\` or
-- projects\/project-id\/inspectTemplates\/432452342.
plitdName :: Lens' ProjectsLocationsInspectTemplatesDelete Text
plitdName
= lens _plitdName (\ s a -> s{_plitdName = a})
-- | JSONP
plitdCallback :: Lens' ProjectsLocationsInspectTemplatesDelete (Maybe Text)
plitdCallback
= lens _plitdCallback
(\ s a -> s{_plitdCallback = a})
instance GoogleRequest
ProjectsLocationsInspectTemplatesDelete
where
type Rs ProjectsLocationsInspectTemplatesDelete =
GoogleProtobufEmpty
type Scopes ProjectsLocationsInspectTemplatesDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsInspectTemplatesDelete'{..}
= go _plitdName _plitdXgafv _plitdUploadProtocol
_plitdAccessToken
_plitdUploadType
_plitdCallback
(Just AltJSON)
dLPService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsInspectTemplatesDeleteResource)
mempty
| brendanhay/gogol | gogol-dlp/gen/Network/Google/Resource/DLP/Projects/Locations/InspectTemplates/Delete.hs | mpl-2.0 | 5,602 | 0 | 15 | 1,177 | 701 | 412 | 289 | 109 | 1 |
module Handler.Partials
( _userInfo'
, ConsoleType(..)
, _console'
, _chart'
) where
import Import
import Yesod.Auth
_userInfo' :: Entity User -> Widget
_userInfo' (Entity uid user) = $(widgetFile "partials/_userInfo")
data ConsoleType = ModuleConsole | SynthaxConsole
_console' :: ConsoleType -> Maybe Text -> Widget
_console' consoleType code = do
addScriptRemote "/static/js/ace-min/ace.js"
$(widgetFile "partials/_console")
_chart' :: Widget
_chart' = $(widgetFile "partials/_chart")
| burz/sonada | Handler/Partials.hs | apache-2.0 | 502 | 0 | 9 | 73 | 136 | 72 | 64 | -1 | -1 |
module Network.Eureka.SemVer (
addSemVer
) where
import Data.Version (Version, showVersion)
import Network.Eureka (InstanceConfig (..), addMetadata)
addSemVer
:: Version
-> InstanceConfig
-> InstanceConfig
addSemVer semver = addMetadata ("semver", showVersion semver)
| taphu/haskell-eureka-semver | src/Network/Eureka/SemVer.hs | apache-2.0 | 304 | 0 | 7 | 65 | 75 | 44 | 31 | 9 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
module CI.CurrentTime where
import Control.Monad.Eff
import Control.Monad.Eff.Lift
import Data.Time
data CurrentTime x where
CurrentTime :: CurrentTime LocalTime
currentTime :: Member CurrentTime r => Eff r LocalTime
currentTime = send CurrentTime
printCurrentTime :: Member CurrentTime r => String -> Eff r String
printCurrentTime fmt = printTime fmt <$> currentTime
currentLocalTime :: IO LocalTime
currentLocalTime = utcToLocalTime <$> getCurrentTimeZone <*> getCurrentTime
printTime :: String -> LocalTime -> String
printTime = formatTime defaultTimeLocale
-- nb no initial "+"
ymDHMS :: String
ymDHMS = "%Y%m%d%H%M%S"
runCurrentTime :: MemberU2 Lift (Lift IO) r => Eff (CurrentTime ': r) a -> Eff r a
runCurrentTime = handleRelay return (\CurrentTime k -> lift currentLocalTime >>= k)
runTestCurrentTime :: LocalTime -> Eff (CurrentTime ': r) a -> Eff r a
runTestCurrentTime lt = handleRelay return (\CurrentTime k -> k lt)
| lancelet/bored-robot | src/CI/CurrentTime.hs | apache-2.0 | 1,077 | 0 | 9 | 181 | 289 | 153 | 136 | 24 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-
Copyright 2019 The CodeWorld Authors. 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 CodeWorld.Color where
import Control.DeepSeq
import GHC.Generics (Generic)
data Color
= RGBA
!Double
!Double
!Double
!Double
deriving (Generic, Show, Eq)
instance NFData Color
type Colour = Color
pattern RGB :: Double -> Double -> Double -> Color
pattern RGB r g b = RGBA r g b 1
pattern HSL :: Double -> Double -> Double -> Color
pattern HSL h s l <-
(toHSL -> Just (h, s, l))
where
HSL h s l = fromHSL h s l
-- Utility functions for pattern synonyms.
fence :: Double -> Double
fence = max 0 . min 1
wrapNum :: Double -> Double -> Double
wrapNum lim x = x - fromInteger (floor (x / lim)) * lim
fenceColor :: Color -> Color
fenceColor (RGBA r g b a) = RGBA (fence r) (fence g) (fence b) (fence a)
-- Based on the algorithm from the CSS3 specification.
fromHSL :: Double -> Double -> Double -> Color
fromHSL (wrapNum (2 * pi) -> h) (fence -> s) (fence -> l) = RGBA r g b 1
where
m1 = l * 2 - m2
m2
| l <= 0.5 = l * (s + 1)
| otherwise = l + s - l * s
r = convert m1 m2 (h / 2 / pi + 1 / 3)
g = convert m1 m2 (h / 2 / pi)
b = convert m1 m2 (h / 2 / pi - 1 / 3)
convert m1 m2 h
| h < 0 = convert m1 m2 (h + 1)
| h > 1 = convert m1 m2 (h - 1)
| h * 6 < 1 = m1 + (m2 - m1) * h * 6
| h * 2 < 1 = m2
| h * 3 < 2 = m1 + (m2 - m1) * (2 / 3 - h) * 6
| otherwise = m1
toHSL :: Color -> Maybe (Double, Double, Double)
toHSL c@(RGBA _ _ _ 1) = Just (hue c, saturation c, luminosity c)
toHSL _ = Nothing
mixed :: [Color] -> Color
mixed colors = go 0 0 0 0 0 colors
where
go rr gg bb aa n ((fenceColor -> RGBA r g b a) : cs) =
go (rr + r * r * a) (gg + g * g * a) (bb + b * b * a) (aa + a) (n + 1) cs
go rr gg bb aa n []
| aa == 0 = RGBA 0 0 0 0
| otherwise = RGBA (sqrt (rr / aa)) (sqrt (gg / aa)) (sqrt (bb / aa)) (aa / n)
-- Helper function that sets the alpha of the second color to that
-- of the first
sameAlpha :: Color -> Color -> Color
sameAlpha (fenceColor -> RGBA _ _ _ a1) (fenceColor -> RGBA r2 g2 b2 _) =
RGBA r2 g2 b2 a1
lighter :: Double -> Color -> Color
lighter d c =
sameAlpha c $ HSL (hue c) (saturation c) (fence (luminosity c + d))
light :: Color -> Color
light = lighter 0.15
darker :: Double -> Color -> Color
darker d = lighter (- d)
dark :: Color -> Color
dark = darker 0.15
brighter :: Double -> Color -> Color
brighter d c =
sameAlpha c $ HSL (hue c) (fence (saturation c + d)) (luminosity c)
bright :: Color -> Color
bright = brighter 0.25
duller :: Double -> Color -> Color
duller d = brighter (- d)
dull :: Color -> Color
dull = duller 0.25
translucent :: Color -> Color
translucent (fenceColor -> RGBA r g b a) = RGBA r g b (a / 2)
-- | An infinite list of colors.
assortedColors :: [Color]
assortedColors = [HSL (adjusted h) 0.75 0.5 | h <- [0, 2 * pi / phi ..]]
where
phi = (1 + sqrt 5) / 2
adjusted x =
x + a0
+ a1 * sin (1 * x)
+ b1 * cos (1 * x)
+ a2 * sin (2 * x)
+ b2 * cos (2 * x)
+ a3 * sin (3 * x)
+ b3 * cos (3 * x)
+ a4 * sin (4 * x)
+ b4 * cos (4 * x)
a0 = -8.6870353473225553e-02
a1 = 8.6485747604766350e-02
b1 = -9.6564816819163041e-02
a2 = -3.0072759267059756e-03
b2 = 1.5048456422494966e-01
a3 = 9.3179137558373148e-02
b3 = 2.9002513227535595e-03
a4 = -6.6275768228887290e-03
b4 = -1.0451841243520298e-02
hue :: Color -> Double
hue (fenceColor -> RGBA r g b _)
| hi - lo < epsilon = 0
| r == hi && g >= b = (g - b) / (hi - lo) * pi / 3
| r == hi = (g - b) / (hi - lo) * pi / 3 + 2 * pi
| g == hi = (b - r) / (hi - lo) * pi / 3 + 2 / 3 * pi
| otherwise = (r - g) / (hi - lo) * pi / 3 + 4 / 3 * pi
where
hi = max r (max g b)
lo = min r (min g b)
epsilon = 0.000001
saturation :: Color -> Double
saturation (fenceColor -> RGBA r g b _)
| hi - lo < epsilon = 0
| otherwise = (hi - lo) / (1 - abs (hi + lo - 1))
where
hi = max r (max g b)
lo = min r (min g b)
epsilon = 0.000001
luminosity :: Color -> Double
luminosity (fenceColor -> RGBA r g b _) = (lo + hi) / 2
where
hi = max r (max g b)
lo = min r (min g b)
alpha :: Color -> Double
alpha (RGBA _ _ _ a) = fence a
-- Old-style colors
white, black, red, green, blue, cyan, magenta, yellow :: Color
orange, rose, chartreuse, aquamarine, violet, azure :: Color
gray, grey, brown, purple, pink :: Color
white = HSL 0.00 0.00 1.00
black = HSL 0.00 0.00 0.00
gray = HSL 0.00 0.00 0.50
grey = HSL 0.00 0.00 0.50
red = HSL 0.00 0.75 0.50
orange = HSL 0.61 0.75 0.50
yellow = HSL 0.98 0.75 0.50
green = HSL 2.09 0.75 0.50
blue = HSL 3.84 0.75 0.50
purple = HSL 4.80 0.75 0.50
pink = HSL 5.76 0.75 0.75
brown = HSL 0.52 0.60 0.40
cyan = HSL (3 / 3 * pi) 0.75 0.5
magenta = HSL (5 / 3 * pi) 0.75 0.5
chartreuse = HSL (3 / 6 * pi) 0.75 0.5
aquamarine = HSL (5 / 6 * pi) 0.75 0.5
azure = HSL (7 / 6 * pi) 0.75 0.5
violet = HSL (9 / 6 * pi) 0.75 0.5
rose = HSL (11 / 6 * pi) 0.75 0.5
{-# WARNING
magenta
[ "Please use HSL(5 * pi / 3, 0.75, 0.5) instead of magenta.",
"The variable magenta may be removed July 2020."
]
#-}
{-# WARNING
cyan
[ "Please use HSL(pi, 0.75, 0.5) instead of cyan.",
"The variable cyan may be removed July 2020."
]
#-}
{-# WARNING
chartreuse
[ "Please use HSL(pi / 2, 0.75, 0.5) instead of chartreuse.",
"The variable chartreuse may be removed July 2020."
]
#-}
{-# WARNING
aquamarine
[ "Please use HSL(5 * pi / 6, 0.75, 0.5) instead of aquamarine.",
"The variable aquamarine may be removed July 2020."
]
#-}
{-# WARNING
azure
[ "Please use HSL(7 * pi / 6, 0.75, 0.5) instead of azure.",
"The variable azure may be removed July 2020."
]
#-}
{-# WARNING
rose
[ "Please use HSL(11 * pi / 6, 0.75, 0.5) instead of rose.",
"The variable rose may be removed July 2020."
]
#-}
{-# WARNING
violet
[ "Please use purple instead of violet.",
"The variable violet may be removed July 2020."
]
#-}
| alphalambda/codeworld | codeworld-api/src/CodeWorld/Color.hs | apache-2.0 | 6,785 | 0 | 24 | 1,889 | 2,579 | 1,342 | 1,237 | -1 | -1 |
-- | Static semantics errors
module Language.Example.MiniCore.Errors where
import Control.Monad.Except
import Language.Common.Label
import Language.Example.MiniCore.Syntax
data TypeSpine =
ForallSp
| FunctionSp
| ProductSp
| SigmaSp
deriving Show
data CoreErr =
ExpectedTypeExpr TypeSpine Expr
| ExpectedFnType Type
| ExpectedEquivTypes Type Type
| ExpectedEquivKinds Kind Kind
| UnboundVar Var
| UnboundTyVar TyVar
| UnknownFieldProj [(Label, Type)] Label
| TyVarOccursInType TyVar Type
deriving Show
raiseExpectedFn :: MonadError CoreErr m => Expr -> m a
raiseExpectedFn = throwError . ExpectedTypeExpr FunctionSp
raiseExpectedForall :: MonadError CoreErr m => Expr -> m a
raiseExpectedForall = throwError . ExpectedTypeExpr ForallSp
raiseExpectedProduct :: MonadError CoreErr m => Expr -> m a
raiseExpectedProduct = throwError . ExpectedTypeExpr ProductSp
raiseExpectedSigma :: MonadError CoreErr m => Expr -> m a
raiseExpectedSigma = throwError . ExpectedTypeExpr SigmaSp
raiseExpectedFnKind :: MonadError CoreErr m => Type -> m a
raiseExpectedFnKind = throwError . ExpectedFnType
raiseExpectedEqTy :: MonadError CoreErr m => Type -> Type -> m a
raiseExpectedEqTy τ = throwError . ExpectedEquivTypes τ
raiseExpectedEqK :: MonadError CoreErr m => Kind -> Kind -> m a
raiseExpectedEqK κ = throwError . ExpectedEquivKinds κ
raiseUnboundVar :: MonadError CoreErr m => Var -> m a
raiseUnboundVar = throwError . UnboundVar
raiseUnboundTyVar :: MonadError CoreErr m => TyVar -> m a
raiseUnboundTyVar = throwError . UnboundTyVar
raiseUnknownFieldProj :: MonadError CoreErr m => [(Label, Type)] -> Label -> m a
raiseUnknownFieldProj lτs = throwError . UnknownFieldProj lτs
raiseTyVarOccursInType :: MonadError CoreErr m => TyVar -> Type -> m a
raiseTyVarOccursInType α = throwError . TyVarOccursInType α
| lambdageek/emile | src/Language/Example/MiniCore/Errors.hs | bsd-2-clause | 1,851 | 0 | 8 | 290 | 508 | 264 | 244 | -1 | -1 |
import NLP.General
import NLP.Crubadan
import NLP.Freq
import NLP.Tools
import Control.Exception (evaluate)
import System.IO (hPutStrLn, stderr)
import Options.Applicative
import Control.Monad
import System.Directory
import System.IO.Strict
import qualified Data.List as L
import qualified Data.Map.Strict as M
percentTestData = 10
data Opts = Opts { opDir :: String
, opDB :: String
, opPr :: Bool
, opNum :: Int
, opNumTrigrams :: Int }
parser = Opts <$> pDir <*> pDB <*> pPr <*> pNum <*> pTrigrams
pTrigrams = option auto (long "num-trigrams"
<> short 't'
<> value 50
<> metavar "NUMBER"
<> showDefault
<> help h)
where h = "The number of trigrams to pull from each checked \
\language for the comparison (starting with the \
\most frequent)"
pNum = option auto (long "load-size"
<> short 'n'
<> metavar "NUMBER"
<> value 20
<> showDefault
<> help h)
where h = "The number of languages to load at one time; \
\a higher number will speed up execution but\
\will also consume more memory..."
pDir = strOption (long "source"
<> short 's'
<> metavar "DIRECTORY"
<> value "/data/crubadan"
<> showDefault
<> help h)
where h = "Root directory of files to use as the test \
\data (only necessary if \"--use-files\" is \
\used"
pPr = switch (long "use-files"
<> help h)
where h = "Use to analyze with a corpora of sample text \
\on the filesystem, ignoring the database"
pDB = strOption (long "database"
<> short 'd'
<> metavar "FILENAME"
<> value "nlp.db"
<> showDefault
<> help h)
where h = "Filename of database to analyze"
desc = fullDesc
<> progDesc "Test identifier accuracy using \
\pre-classified data"
<> header "analyze - test identifier accuracy"
opts = execParser (info (helper <*> parser) desc)
main = opts >>= (\os -> if opPr os
then fromFS (opDir os)
else fromDB os)
fromFS :: String -> IO ()
fromFS dir =
do targets <- (fmap (L.delete ".") . fmap (L.delete "..")
. getDirectoryContents) dir
texts <- sequence (fmap (bfetch . qual dir) targets)
let (ts,ps) = testprocess texts
tf :: [(String, FreqList TriGram)]
tf = fmap (\(a,b) -> (a,features b)) ts
pf :: [(String, FreqList TriGram)]
pf = fmap (\(a,b) -> (a,features b)) ps
res :: [(String, String)]
res = fmap (\(n,f) -> (n, choosebest pf f)) tf
sequence_ (fmap print res)
putStrLn (stats res)
type Results = M.Map String [(Double, String)]
type Lang = (String, FreqList TriGram)
fromDB :: Opts -> IO ()
fromDB os =
do db <- connectDB (opDB os)
langs <- (fmap fst . M.toList)
<$> fetchAllLengths db "dataAll"
let sets = divie' " " (opNum os) langs
st <- fetchSt db (opNum os)
let crawl1' = crawl1 st os sets
results <- foldM crawl1' M.empty sets
let winners = fmap (snd . maximum) results
mistakes = filter (\(a,b) -> a /= b) . M.toList $ winners
ml = maxlen mistakes
putStrLn (":: Database analysis on \"" ++ opDB os ++ "\" ::")
putStrLn ""
putStrLn ("(Using the " ++ show (opNumTrigrams os)
++ " most frequent TriGrams from each list)")
putStrLn ""
(putStrLn . stats . M.toList) winners
putStrLn ""
putStrLn "The following mistakes occured:"
putStrLn ""
(sequence_ . fmap (putStrLn . idAs ml)) mistakes
putStrLn ""
putStrLn ""
putStrLn "Mistake Details:"
putStrLn ""
(sequence_ . fmap (Main.prettyprint ml results)) mistakes
idAs m (a,b) = show a ++ replicate (m - length a + 2) ' ' ++ "identified as " ++ show b
prettyprint :: Int -> M.Map String [(Double,String)] -> (String,String) -> IO ()
prettyprint ml res mis =
let vals = fmap (\(a,b) -> (b,a))
. takeWhilePlus (\(v,l) -> l /= (fst mis))
. L.sortBy (\(v1,_) (v2,_) -> compare v2 v1)
$ (res M.! (fst mis))
in do putStrLn "-----------------------------"
putStrLn ""
putStrLn (idAs ml mis)
putStrLn ""
sequence_ (fmap (line (fst mis)) vals)
putStrLn ""
maxlen ((a,b):cs) = max (length a) . max (length b) $ maxlen cs
maxlen _ = 0
line c (l,v) = putStrLn (if c == l
then " --> " ++ show (l,v)
else " X " ++ show (l,v))
takeWhilePlus b (a:as) = if b a
then a : takeWhilePlus b as
else a : []
takeWhilePlus _ _ = []
crawl1 :: Statement -> Opts -> [[String]] -> Results -> [String] -> IO Results
crawl1 st os sets results f1 =
do trs <- fetch st "dataA" (opNumTrigrams os) f1
foldM (crawl2 st os trs) results sets
crawl2 :: Statement -> Opts -> M.Map String (FreqList TriGram) -> Results -> [String] -> IO Results
crawl2 st os dataA results f2 =
do trs <- fetch st "dataB" (opNumTrigrams os) f2
hPutStrLn stderr ("\nNow crunching\n" ++ (show $ M.keys dataA) ++ "\nand\n" ++ (show f2))
evaluate (L.foldl' (check os (M.toList trs)) results (M.toList dataA))
check :: Opts -> [(String, FreqList TriGram)] -> Results -> (String, FreqList TriGram) -> Results
check os dataB results a =
L.foldl' (compTwo os a) results dataB
compTwo :: Opts -> Lang -> Results -> Lang -> Results
compTwo os (la,fa) r (lb,fb) = mupd la lb (cosine fa fb) r
mupd :: String -> String -> Double -> Results -> Results
mupd tn cn v r = case M.lookup tn r of
Just vs -> M.insert tn ((v,cn) : vs) r
Nothing -> M.insert tn ((v,cn) : []) r
-- combineRs :: [String] -> [Results] -> Results
-- combineRs ls rs =
-- foldr (\k -> M.insert k (mid k rs)) M.empty ls
--
-- mid :: String -> [Results] -> [(Double,String)]
-- mid k rs = foldr cc [] (fmap (M.lookup k) rs)
--
-- cc :: Maybe [a] -> [a] -> [a]
-- cc (Just as) bs = as ++ bs
-- cc _ bs = bs
divie :: Int -> [a] -> [[a]]
divie 0 _ = [[]] -- possibly surprising?
divie _ [] = []
divie n xs = let (as,bs) = splitAt n xs
in as : divie n bs
divie' :: a -> Int -> [a] -> [[a]]
divie' _ 0 _ = [[]]
divie' _ _ [] = []
divie' p n xs = let (as,bs) = splitAt n xs
l = length as
in (as ++ replicate (n - l) p) : divie' p n bs
-- analyze :: Database -> [String] -> [String] -> IO Results
-- analyze db langs cands =
-- do cs <- manyData db fetchBData cands
-- ts <- manyData db fetchAData langs
--
-- return (foldr (compAll ts) M.empty cs)
--
-- compAll :: [Lang] -> Lang -> Results -> Results
-- compAll ts (cn,cd) r =
-- foldr (\(tn,td) -> mupd tn cn (cosine td cd)) r ts
--
-- mupd :: String -> String -> Double -> Results -> Results
-- mupd tn cn v r = case M.lookup tn r of
-- Just vs -> M.insert tn ((v,cn) : vs) r
-- Nothing -> M.insert tn ((v,cn) : []) r
--
-- manyData db f ns = sequence (fmap (f db) ns)
--
stats :: [(String,String)] -> String
stats ss = let total = length ss
correct = length (filter (\(a,b) -> a == b) ss)
percent = correct * 100 `div` total
in "Accuracy: "
++ (show correct)
++ " / "
++ (show total)
++ " ("
++ (show percent)
++ ("%)")
qual r s = (s, r ++ "/" ++ s ++ "/SAMPSENTS")
bfetch (n,p) = do t <- System.IO.Strict.readFile p
return (n,t)
testprocess :: [(String,String)] -> ([(String, String)], [(String, String)])
testprocess = (\ts -> (fmap fst ts, fmap snd ts)) . fmap d
d (id,text) = let ls = parseSampSents text
num = length ls
(t,p) = L.splitAt
(num * percentTestData `div` 100) ls
in ((id, concat t), (id, concat p))
parseSampSents :: String -> [String]
parseSampSents = lines
| RoboNickBot/nlp-tools | src/Analyze.hs | bsd-2-clause | 8,429 | 7 | 17 | 2,872 | 2,822 | 1,445 | 1,377 | 174 | 2 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes #-}
module Main where
import Prelude hiding (lookup)
import Blaze.ByteString.Builder.ByteString (fromLazyByteString)
import Control.Monad.Trans.Resource (withIO)
import Data.Aeson (encode)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Database.MongoDB
( Document, Query (sort), Value (Doc)
, (=:), findOne, select )
import Network.HTTP.Types (status200)
import Network.Wai.Handler.Warp (run)
import Network.Wai
( Application, Response (ResponseBuilder), Request (pathInfo) )
import Network.Wai.Application.Static (staticApp, defaultWebAppSettings)
import Text.Blaze (Html, preEscapedLazyText, preEscapedText)
import Text.Blaze.Renderer.Utf8 (renderHtmlBuilder)
import Text.Hamlet (shamletFile)
import Data.Bson.Aeson ()
import Web.WheresMikeCraig.Config
getPoint :: Config -> IO Document
getPoint cfg = do
Right (Just doc) <- cfgAccess cfg $ findOne
(select [] $ cfgPointsColl cfg) { sort = ["date_ts" =: (-1 :: Int)] }
return doc
html :: Config -> Html -> Html
html cfg geoloqiPoint =
let dataUrl = preEscapedText $ cfgDataUrl cfg
in $(shamletFile "server/index.hamlet")
index :: Config -> Application
index cfg _ = do
(_, pt) <- withIO (getPoint cfg) $ const (return ())
return $ ResponseBuilder status200 [] $ renderHtmlBuilder $ html cfg $
preEscapedLazyText $ decodeUtf8 $ encode $ Doc pt
point :: Config -> Application
point cfg _ = do
(_, pt) <- withIO (getPoint cfg) $ const (return ())
return $ ResponseBuilder status200 [] $
fromLazyByteString $ encode $ Doc pt
static :: Application
static = staticApp defaultWebAppSettings
switch :: Config -> Application
switch cfg req
| pathInfo req == [] = index cfg req
| pathInfo req == ["point.json"] = point cfg req
| otherwise = static req
main :: IO ()
main = do
cfg <- getConfig
run (cfgServerPort cfg) $ switch cfg
| mkscrg/wheresmikecraig | server/main.hs | bsd-2-clause | 1,894 | 0 | 15 | 310 | 662 | 355 | 307 | 50 | 1 |
module TelnetHandler where
import System.IO
import Network.Socket
import Control.Monad
import Paths_harlson (version)
import Data.Version (showVersion)
import Data.Char
handleTelnet :: (String -> IO String) -> SockAddr -> Handle -> IO ()
handleTelnet runCmd sa h = do
hPutStrLn h "\n"
hPutStrLn h ("harlson " ++ showVersion version)
handleTelnet' runCmd sa h
handleTelnet' :: (String -> IO String) -> SockAddr -> Handle -> IO ()
handleTelnet' runCmd sa h = do
hPutStrLn h "Ctrl-D to quit"
hPutStr h "> "
hFlush h
c <- hLookAhead h
unless (c == chr 4) $
do
cmd <- fmap strip $ hGetLine h
unless (cmd == ":q" || cmd == [chr 4]) $
do
out <- runCmd cmd
hPutStrLn h out
hPutStrLn h ""
handleTelnet' runCmd sa h
strip :: String -> String
strip = lstrip . rstrip where
lstrip = dropWhile (`elem` " \t\r\n")
rstrip = reverse . lstrip . reverse
| EchoTeam/harlson | TelnetHandler.hs | bsd-2-clause | 1,014 | 0 | 15 | 325 | 349 | 169 | 180 | 31 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
-- | A bare transaction; that is, one without any serial numbers.
--
-- Contrast a 'Penny.Core.Transaction', which has serial numbers.
module Penny.Transaction where
import Penny.Ents
import Penny.Tranche
import qualified Control.Lens as Lens
-- | A bare transaction; that is, one without any serial numbers. In
-- contrast, 'Penny.Core.Transaction' includes serial numbers for
-- both the top line and the postings.
data Transaction a = Transaction
{ _topLine :: TopLine a
, _postings :: Balanced (Postline a)
} deriving (Show, Functor, Foldable, Traversable)
Lens.makeLenses ''Transaction
| massysett/penny | penny/lib/Penny/Transaction.hs | bsd-3-clause | 731 | 0 | 11 | 112 | 96 | 58 | 38 | 12 | 0 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | See "Control.Monad.Ether.State.Lazy".
module Control.Monad.Ether.Implicit.State.Lazy
(
-- * MonadState class
MonadState
, get
, put
, state
, modify
, gets
-- * The State monad
, State
, runState
, evalState
, execState
-- * The StateT monad transformer
, StateT
, stateT
, runStateT
, evalStateT
, execStateT
) where
import Data.Proxy
import qualified Control.Monad.Ether.State.Lazy as Explicit
-- | See 'Control.Monad.Ether.State.Lazy.StateT'.
type StateT s = Explicit.StateT s s
-- | See 'Control.Monad.Ether.State.Lazy.State'.
type State s = Explicit.State s s
-- | See 'Control.Monad.Ether.State.Lazy.stateT'.
stateT :: (s -> m (a, s)) -> StateT s m a
stateT = Explicit.stateT Proxy
-- | See 'Control.Monad.Ether.State.Lazy.runStateT'.
runStateT :: StateT s m a -> s -> m (a, s)
runStateT = Explicit.runStateT Proxy
-- | See 'Control.Monad.Ether.State.Lazy.runState'.
runState :: State s a -> s -> (a, s)
runState = Explicit.runState Proxy
-- | See 'Control.Monad.Ether.State.Lazy.evalStateT'.
evalStateT :: Monad m => StateT s m a -> s -> m a
evalStateT = Explicit.evalStateT Proxy
-- | See 'Control.Monad.Ether.State.Lazy.evalState'.
evalState :: State s a -> s -> a
evalState = Explicit.evalState Proxy
-- | See 'Control.Monad.Ether.State.Lazy.execStateT'.
execStateT :: Monad m => StateT s m a -> s -> m s
execStateT = Explicit.execStateT Proxy
-- | See 'Control.Monad.Ether.State.Lazy.execState'.
execState :: State s a -> s -> s
execState = Explicit.execState Proxy
-- | See 'Control.Monad.Ether.State.Lazy.MonadState'.
type MonadState s = Explicit.MonadState s s
-- | See 'Control.Monad.Ether.State.Lazy.get'.
get :: forall m s . MonadState s m => m s
get = Explicit.get (Proxy :: Proxy s)
-- | See 'Control.Monad.Ether.State.Lazy.gets'.
gets :: forall m s a . MonadState s m => (s -> a) -> m a
gets = Explicit.gets (Proxy :: Proxy s)
-- | See 'Control.Monad.Ether.State.Lazy.put'.
put :: forall m s . MonadState s m => s -> m ()
put = Explicit.put (Proxy :: Proxy s)
-- | See 'Control.Monad.Ether.State.Lazy.state'.
state :: forall m s a . MonadState s m => (s -> (a, s)) -> m a
state = Explicit.state (Proxy :: Proxy s)
-- | See 'Control.Monad.Ether.State.Lazy.modify'.
modify :: forall m s . MonadState s m => (s -> s) -> m ()
modify = Explicit.modify (Proxy :: Proxy s)
| bitemyapp/ether | src/Control/Monad/Ether/Implicit/State/Lazy.hs | bsd-3-clause | 2,463 | 0 | 10 | 471 | 646 | 360 | 286 | 48 | 1 |
module Lexer where
import Prelude hiding (lex)
import Data.Char (isSpace)
import Control.Applicative
import qualified Text.Parsec as P
import qualified Text.Parsec.Token as PT
data Token
= LParen
| RParen
| LBracket
| RBracket
| Period
| Pipe
| Bind
| Name String
| Keyword String
| Arg String
| Symbol String
| StringLiteral String
| CharLiteral Char
| Number Int
deriving (Show, Eq)
ppToken :: Token -> String
ppToken LParen = "("
ppToken RParen = ")"
ppToken LBracket = "["
ppToken RBracket = "]"
ppToken Period = "."
ppToken Pipe = "|"
ppToken Bind = ":="
ppToken (Keyword s) = s ++ ":"
ppToken (Name s) = s
ppToken (Arg s) = ":" ++ s
ppToken (Symbol s) = s
ppToken (StringLiteral s) = "'" ++ s ++ "'"
ppToken (CharLiteral c) = "$" ++ [c]
ppToken (Number n) = show n
data PositionedToken = PositionedToken
{ ptSourcePos :: P.SourcePos
, ptToken :: Token
} deriving (Eq)
instance Show PositionedToken where
show = ppToken . ptToken
lex :: FilePath -> String -> Either P.ParseError [PositionedToken]
lex filePath input = P.parse parseTokens filePath input
parseTokens :: P.Parsec String u [PositionedToken]
parseTokens = whitespace *> P.many parsePositionedToken <* P.eof
whitespace :: P.Parsec String u ()
whitespace = P.skipMany (P.satisfy isSpace)
parsePositionedToken :: P.Parsec String u PositionedToken
parsePositionedToken = P.try $ do
pos <- P.getPosition
tok <- parseToken
return $ PositionedToken pos tok
parseToken :: P.Parsec String u Token
parseToken = P.choice
[ P.try $ Bind <$ P.string ":="
, LParen <$ P.char '('
, RParen <$ P.char ')'
, LBracket <$ P.char '['
, RBracket <$ P.char ']'
, Period <$ P.char '.'
, Pipe <$ P.char '|'
, P.try $ Keyword <$> parseName <* P.char ':'
, Name <$> parseName
, Arg <$> (P.char ':' *> parseName)
, Symbol <$> (P.many1 $ P.oneOf "+-*/")
, StringLiteral <$> (P.char '\'' *> P.many (P.noneOf "'") <* P.char '\'')
, CharLiteral <$> (P.char '$' *> P.anyChar)
, Number . read <$> P.many1 P.digit
] <* whitespace
where
parseName = (:) <$> nameStart <*> P.many nameLetter
nameStart = P.letter <|> P.char '_'
nameLetter = nameStart <|> P.digit
type TokenParser a = P.Parsec [PositionedToken] () a
token :: (Token -> Maybe a) -> TokenParser a
token f = P.token (ppToken . ptToken) ptSourcePos (f . ptToken)
match :: Token -> TokenParser ()
match tok = token (\tok' -> if tok == tok' then Just () else Nothing) P.<?> ppToken tok
parens :: TokenParser a -> TokenParser a
parens p = match LParen *> p <* match RParen
brackets :: TokenParser a -> TokenParser a
brackets p = match LBracket *> p <* match RBracket
charLiteral :: TokenParser Char
charLiteral = token go P.<?> "char literal"
where go (CharLiteral c) = Just c
go _ = Nothing
stringLiteral :: TokenParser String
stringLiteral = token go P.<?> "string literal"
where go (StringLiteral s) = Just s
go _ = Nothing
number :: TokenParser Int
number = token go P.<?> "number"
where go (Number n) = Just n
go _ = Nothing
identifier :: TokenParser String
identifier = token go P.<?> "identifier"
where go (Name s) = Just s
go _ = Nothing
keyword :: TokenParser String
keyword = token go P.<?> "keyword"
where go (Keyword s) = Just s
go _ = Nothing
arg :: TokenParser String
arg = token go P.<?> "arg"
where go (Arg s) = Just s
go _ = Nothing
symbol :: TokenParser String
symbol = token go P.<?> "symbol"
where go (Symbol s) = Just s
go _ = Nothing | rjeli/luatalk | src/Lexer.hs | bsd-3-clause | 3,734 | 0 | 15 | 977 | 1,384 | 710 | 674 | 111 | 2 |
import Data.Sound
import Data.Sound.Draw
main :: IO ()
main = renderFileSound "sine2.pdf" $ sine 1 1 1 0 <|> sine 1 1 1 (pi/2) | Daniel-Diaz/Wavy-Draw | examples/sine2.hs | bsd-3-clause | 128 | 1 | 8 | 25 | 66 | 32 | 34 | 4 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.CompactMap.Types where
import Control.Monad
import Foreign
import Foreign.Storable
import Data.IORef
import GHC.Exts
import GHC.IO hiding (Buffer)
data Buffer = Buffer
{ bufferData :: {-# UNPACK #-} !(IORef (ForeignPtr ()))
, bufferOld :: {-# UNPACK #-} !(IORef [ForeignPtr ()])
, bufferPos :: {-# UNPACK #-} !FastMutInt
, bufferSize :: {-# UNPACK #-} !FastMutInt
}
-- Strict, unboxed IORef
data FastMutInt = FastMutInt (MutableByteArray# RealWorld)
newFastMutInt (I# i) = IO $ \s -> case newByteArray# size s of
(# s, arr #) -> case writeIntArray# arr 0# i s of
s -> (# s, FastMutInt arr #)
where !(I# size) = sizeOf (0::Int)
readFastMutInt (FastMutInt arr) = IO $ \s ->
case readIntArray# arr 0# s of { (# s, i #) ->
(# s, I# i #) }
writeFastMutInt (FastMutInt arr) (I# i) = IO $ \s ->
case writeIntArray# arr 0# i s of { s ->
(# s, () #) }
data KeyCursor
data DataCursor
data Index = Index { indexStart :: {-# UNPACK #-} !(Ptr IndexItem)
, indexBuffer :: {-# UNPACK #-} !Buffer }
data IndexItem = IndexItem {-# UNPACK #-} !(Ptr IndexItem)
{-# UNPACK #-} !(Ptr ())
{-# UNPACK #-} !(Ptr KeyCursor)
{-# UNPACK #-} !(Ptr IndexItem)
{-# UNPACK #-} !(Ptr IndexItem) -- Top, size, elem idx, left, right
type IdxInt = Ptr IndexItem
{-# INLINE extractField #-}
-- Get field 'f' out of the n'th IndexItem.
extractField :: Int -> (Ptr IndexItem) -> IO (Ptr IndexItem)
extractField !f !ptr = do v <- peekByteOff ptr ((sizeOf (undefined::IdxInt) * f))
return (v::IdxInt)
{-# INLINE putField #-}
-- Put field 'f' in the n'th IndexItem
putField :: Int -> (Ptr IndexItem) -> Ptr IndexItem -> IO ()
putField !f !ptr !v = pokeByteOff ptr ((sizeOf (undefined::IdxInt) * f)) (v :: IdxInt)
instance Storable IndexItem where
sizeOf _ = sizeOf (undefined :: IdxInt) * 5
alignment _ = alignment (undefined :: IdxInt)
{-# INLINE peek #-}
peek ptr = let ptr' = castPtr ptr
get n = (peekElemOff ptr' n :: IO (Ptr a))
in liftM5 IndexItem (get 0) (get 1) (get 2) (get 3) (get 4)
{-# INLINE poke #-}
poke ptr' (IndexItem a b c d e)
= let ptr = castPtr ptr'
put n v = pokeElemOff ptr n v
in put 0 a >> put 1 b >> put 2 c >> put 3 d >> put 4 e
| dmjio/CompactMap | src/Data/CompactMap/Types.hs | bsd-3-clause | 2,772 | 0 | 14 | 902 | 847 | 443 | 404 | -1 | -1 |
{-|
Module : Idris.PartialEval
Description : Implementation of a partial evaluator.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.PartialEval(
partial_eval, getSpecApps, specType
, mkPE_TyDecl, mkPE_TermDecl, PEArgType(..)
, pe_app, pe_def, pe_clauses, pe_simple
) where
import Idris.AbsSyntax
import Idris.Delaborate
import Idris.Core.TT
import Idris.Core.CaseTree
import Idris.Core.Evaluate
import Control.Monad.State
import Control.Applicative
import Data.Maybe
import Debug.Trace
-- | Data type representing binding-time annotations for partial evaluation of arguments
data PEArgType = ImplicitS -- ^ Implicit static argument
| ImplicitD -- ^ Implicit dynamic argument
| ExplicitS -- ^ Explicit static argument
| ExplicitD -- ^ Explicit dynamic argument
| UnifiedD -- ^ Erasable dynamic argument (found under unification)
deriving (Eq, Show)
-- | A partially evaluated function. pe_app captures the lhs of the
-- new definition, pe_def captures the rhs, and pe_clauses is the
-- specialised implementation.
--
-- pe_simple is set if the result is always reducible, because in such
-- a case we'll also need to reduce the static argument
data PEDecl = PEDecl { pe_app :: PTerm, -- new application
pe_def :: PTerm, -- old application
pe_clauses :: [(PTerm, PTerm)], -- clauses of new application
pe_simple :: Bool -- if just one reducible clause
}
-- | Partially evaluates given terms under the given context.
-- It is an error if partial evaluation fails to make any progress.
-- Making progress is defined as: all of the names given with explicit
-- reduction limits (in practice, the function being specialised)
-- must have reduced at least once.
-- If we don't do this, we might end up making an infinite function after
-- applying the transformation.
partial_eval :: Context
-> [(Name, Maybe Int)]
-> [Either Term (Term, Term)]
-> Maybe [Either Term (Term, Term)]
partial_eval ctxt ns_in tms = mapM peClause tms where
ns = squash ns_in
squash ((n, Just x) : ns)
| Just (Just y) <- lookup n ns
= squash ((n, Just (x + y)) : drop n ns)
| otherwise = (n, Just x) : squash ns
squash (n : ns) = n : squash ns
squash [] = []
drop n ((m, _) : ns) | n == m = ns
drop n (x : ns) = x : drop n ns
drop n [] = []
-- If the term is not a clause, it is simply kept as is
peClause (Left t) = Just $ Left t
-- If the term is a clause, specialise the right hand side
peClause (Right (lhs, rhs))
= let (rhs', reductions) = specialise ctxt [] (map toLimit ns) rhs in
do when (length tms == 1) $ checkProgress ns reductions
return (Right (lhs, rhs'))
-- TMP HACK until I do PE by WHNF rather than using main evaluator
toLimit (n, Nothing) | isTCDict n ctxt = (n, 2)
toLimit (n, Nothing) = (n, 65536) -- somewhat arbitrary reduction limit
toLimit (n, Just l) = (n, l)
checkProgress ns [] = return ()
checkProgress ns ((n, r) : rs)
| Just (Just start) <- lookup n ns
= if start <= 1 || r < start then checkProgress ns rs else Nothing
| otherwise = checkProgress ns rs
-- | Specialises the type of a partially evaluated TT function returning
-- a pair of the specialised type and the types of expected arguments.
specType :: [(PEArgType, Term)] -> Type -> (Type, [(PEArgType, Term)])
specType args ty = let (t, args') = runState (unifyEq args ty) [] in
(st (map fst args') t, map fst args')
where
-- Specialise static argument in type by let-binding provided value instead
-- of expecting it as a function argument
st ((ExplicitS, v) : xs) (Bind n (Pi _ t _) sc)
= Bind n (Let t v) (st xs sc)
st ((ImplicitS, v) : xs) (Bind n (Pi _ t _) sc)
= Bind n (Let t v) (st xs sc)
-- Erase argument from function type
st ((UnifiedD, _) : xs) (Bind n (Pi _ t _) sc)
= st xs sc
-- Keep types as is
st (_ : xs) (Bind n (Pi i t k) sc)
= Bind n (Pi i t k) (st xs sc)
st _ t = t
-- Erase implicit dynamic argument if existing argument shares it value,
-- by substituting the value of previous argument
unifyEq (imp@(ImplicitD, v) : xs) (Bind n (Pi i t k) sc)
= do amap <- get
case lookup imp amap of
Just n' ->
do put (amap ++ [((UnifiedD, Erased), n)])
sc' <- unifyEq xs (subst n (P Bound n' Erased) sc)
return (Bind n (Pi i t k) sc') -- erase later
_ -> do put (amap ++ [(imp, n)])
sc' <- unifyEq xs sc
return (Bind n (Pi i t k) sc')
unifyEq (x : xs) (Bind n (Pi i t k) sc)
= do args <- get
put (args ++ [(x, n)])
sc' <- unifyEq xs sc
return (Bind n (Pi i t k) sc')
unifyEq xs t = do args <- get
put (args ++ (zip xs (repeat (sUN "_"))))
return t
-- | Creates an Idris type declaration given current state and a
-- specialised TT function application type.
-- Can be used in combination with the output of 'specType'.
--
-- This should: specialise any static argument position, then generalise
-- over any function applications in the result.
mkPE_TyDecl :: IState -> [(PEArgType, Term)] -> Type -> PTerm
mkPE_TyDecl ist args ty = mkty args ty
where
mkty ((ExplicitD, v) : xs) (Bind n (Pi _ t k) sc)
= PPi expl n NoFC (delab ist (generaliseIn t)) (mkty xs sc)
mkty ((ImplicitD, v) : xs) (Bind n (Pi _ t k) sc)
| concreteInterface ist t = mkty xs sc
| interfaceConstraint ist t
= PPi constraint n NoFC (delab ist (generaliseIn t)) (mkty xs sc)
| otherwise = PPi impl n NoFC (delab ist (generaliseIn t)) (mkty xs sc)
mkty (_ : xs) t
= mkty xs t
mkty [] t = delab ist t
generaliseIn tm = evalState (gen tm) 0
gen tm | (P _ fn _, args) <- unApply tm,
isFnName fn (tt_ctxt ist)
= do nm <- get
put (nm + 1)
return (P Bound (sMN nm "spec") Erased)
gen (App s f a) = App s <$> gen f <*> gen a
gen tm = return tm
-- | Checks if a given argument is an interface constraint argument
interfaceConstraint :: Idris.AbsSyntax.IState -> TT Name -> Bool
interfaceConstraint ist v
| (P _ c _, args) <- unApply v = case lookupCtxt c (idris_interfaces ist) of
[_] -> True
_ -> False
| otherwise = False
-- | Checks if the given arguments of an interface constraint are all either constants
-- or references (i.e. that it doesn't contain any complex terms).
concreteInterface :: IState -> TT Name -> Bool
concreteInterface ist v
| not (interfaceConstraint ist v) = False
| (P _ c _, args) <- unApply v = all concrete args
| otherwise = False
where concrete (Constant _) = True
concrete tm | (P _ n _, args) <- unApply tm
= case lookupTy n (tt_ctxt ist) of
[_] -> all concrete args
_ -> False
| otherwise = False
mkNewPats :: IState
-> [(Term, Term)] -- ^ definition to specialise
-> [(PEArgType, Term)] -- ^ arguments to specialise with
-> Name -- ^ New name
-> Name -- ^ Specialised function name
-> PTerm -- ^ Default lhs
-> PTerm -- ^ Default rhs
-> PEDecl
-- If all of the dynamic positions on the lhs are variables (rather than
-- patterns or constants) then we can just make a simple definition
-- directly applying the specialised function, since we know the
-- definition isn't going to block on any of the dynamic arguments
-- in this case
mkNewPats ist d ns newname sname lhs rhs | all dynVar (map fst d)
= PEDecl lhs rhs [(lhs, rhs)] True
where dynVar ap = case unApply ap of
(_, args) -> dynArgs ns args
dynArgs _ [] = True -- can definitely reduce from here
-- if Static, doesn't matter what the argument is
dynArgs ((ImplicitS, _) : ns) (a : as) = dynArgs ns as
dynArgs ((ExplicitS, _) : ns) (a : as) = dynArgs ns as
-- if Dynamic, it had better be a variable or we'll need to
-- do some more work
dynArgs (_ : ns) (V _ : as) = dynArgs ns as
dynArgs (_ : ns) (P _ _ _ : as) = dynArgs ns as
dynArgs _ _ = False -- and now we'll get stuck
mkNewPats ist d ns newname sname lhs rhs =
PEDecl lhs rhs (map mkClause d) False
where
mkClause :: (Term, Term) -> (PTerm, PTerm)
mkClause (oldlhs, oldrhs)
= let (_, as) = unApply oldlhs
lhsargs = mkLHSargs [] ns as
lhs = PApp emptyFC (PRef emptyFC [] newname) lhsargs
rhs = PApp emptyFC (PRef emptyFC [] sname)
(mkRHSargs ns lhsargs) in
(lhs, rhs)
mkLHSargs _ [] _ = []
-- dynamics don't appear if they're implicit
mkLHSargs sub ((ExplicitD, t) : ns) (a : as)
= pexp (delab ist (substNames sub a)) : mkLHSargs sub ns as
mkLHSargs sub ((ImplicitD, _) : ns) (a : as)
= mkLHSargs sub ns as
mkLHSargs sub ((UnifiedD, _) : ns) (a : as)
= mkLHSargs sub ns as
-- statics get dropped in any case
mkLHSargs sub ((ImplicitS, t) : ns) (a : as)
= mkLHSargs (extend a t sub) ns as
mkLHSargs sub ((ExplicitS, t) : ns) (a : as)
= mkLHSargs (extend a t sub) ns as
mkLHSargs sub _ [] = [] -- no more LHS
extend (P _ n _) t sub = (n, t) : sub
extend _ _ sub = sub
mkRHSargs ((ExplicitS, t) : ns) as = pexp (delab ist t) : mkRHSargs ns as
mkRHSargs ((ExplicitD, t) : ns) (a : as) = a : mkRHSargs ns as
mkRHSargs (_ : ns) as = mkRHSargs ns as
mkRHSargs _ _ = []
mkSubst :: (Term, Term) -> Maybe (Name, Term)
mkSubst (P _ n _, t) = Just (n, t)
mkSubst _ = Nothing
-- | Creates a new declaration for a specialised function application.
-- Simple version at the moment: just create a version which is a direct
-- application of the function to be specialised.
-- More complex version to do: specialise the definition clause by clause
mkPE_TermDecl :: IState
-> Name
-> Name
-> [(PEArgType, Term)]
-> PEDecl
mkPE_TermDecl ist newname sname ns
= let lhs = PApp emptyFC (PRef emptyFC [] newname) (map pexp (mkp ns))
rhs = eraseImps $ delab ist (mkApp (P Ref sname Erased) (map snd ns))
patdef = lookupCtxtExact sname (idris_patdefs ist)
newpats = case patdef of
Nothing -> PEDecl lhs rhs [(lhs, rhs)] True
Just d -> mkNewPats ist (getPats d) ns
newname sname lhs rhs in
newpats where
getPats (ps, _) = map (\(_, lhs, rhs) -> (lhs, rhs)) ps
mkp [] = []
mkp ((ExplicitD, tm) : tms) = delab ist tm : mkp tms
mkp (_ : tms) = mkp tms
eraseImps tm = mapPT deImp tm
deImp (PApp fc t as) = PApp fc t (map deImpArg as)
deImp t = t
deImpArg a@(PImp _ _ _ _ _) = a { getTm = Placeholder }
deImpArg a = a
-- | Get specialised applications for a given function
getSpecApps :: IState
-> [Name]
-> Term
-> [(Name, [(PEArgType, Term)])]
getSpecApps ist env tm = ga env (explicitNames tm) where
-- staticArg env True _ tm@(P _ n _) _ | n `elem` env = Just (True, tm)
-- staticArg env True _ tm@(App f a) _ | (P _ n _, args) <- unApply tm,
-- n `elem` env = Just (True, tm)
staticArg env x imp tm n
| x && imparg imp = (ImplicitS, tm)
| x = (ExplicitS, tm)
| imparg imp = (ImplicitD, tm)
| otherwise = (ExplicitD, (P Ref (sUN (show n ++ "arg")) Erased))
imparg (PExp _ _ _ _) = False
imparg _ = True
buildApp env [] [] _ _ = []
buildApp env (s:ss) (i:is) (a:as) (n:ns)
= let s' = staticArg env s i a n
ss' = buildApp env ss is as ns in
(s' : ss')
-- if we have a *defined* function that has static arguments,
-- it will become a specialised application
ga env tm@(App _ f a) | (P _ n _, args) <- unApply tm,
n `notElem` map fst (idris_metavars ist) =
ga env f ++ ga env a ++
case (lookupCtxtExact n (idris_statics ist),
lookupCtxtExact n (idris_implicits ist)) of
(Just statics, Just imps) ->
if (length statics == length args && or statics
&& specialisable (tt_ctxt ist) n) then
case buildApp env statics imps args [0..] of
args -> [(n, args)]
-- _ -> []
else []
_ -> []
ga env (Bind n (Let t v) sc) = ga env v ++ ga (n : env) sc
ga env (Bind n t sc) = ga (n : env) sc
ga env t = []
-- A function is only specialisable if there are no overlapping
-- cases in the case tree (otherwise the partial evaluation could
-- easily get stuck)
specialisable :: Context -> Name -> Bool
specialisable ctxt n = case lookupDefExact n ctxt of
Just (CaseOp _ _ _ _ _ cds) ->
noOverlap (snd (cases_compiletime cds))
_ -> False
noOverlap :: SC -> Bool
noOverlap (Case _ _ [DefaultCase sc]) = noOverlap sc
noOverlap (Case _ _ alts) = noOverlapAlts alts
noOverlap _ = True
-- There's an overlap if the case tree has a default case along with
-- some other cases. It's fine if there's a default case on its own.
noOverlapAlts (ConCase _ _ _ sc : rest)
= noOverlapAlts rest && noOverlap sc
noOverlapAlts (FnCase _ _ sc : rest) = noOverlapAlts rest
noOverlapAlts (ConstCase _ sc : rest)
= noOverlapAlts rest && noOverlap sc
noOverlapAlts (SucCase _ sc : rest)
= noOverlapAlts rest && noOverlap sc
noOverlapAlts (DefaultCase _ : _) = False
noOverlapAlts _ = True
| enolan/Idris-dev | src/Idris/PartialEval.hs | bsd-3-clause | 14,546 | 1 | 20 | 4,845 | 4,614 | 2,393 | 2,221 | 241 | 17 |
-- Pipes-based UDP-to-reliable-protocol adapter
module Network.Punch.Peer.Reliable (
module Network.Punch.Peer.Reliable.Types,
newRcb,
newRcbFromPeer,
gracefullyShutdownRcb,
sendRcb,
recvRcb,
-- XXX: The functions below have unstable signatures
sendMailbox,
recvMailbox,
toMailbox,
fromMailbox
) where
import Control.Arrow (second)
import Control.Concurrent.Async (async)
import Control.Exception (try, SomeException)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Either (left, EitherT, runEitherT)
import Control.Monad.IO.Class (liftIO)
import Control.Monad (forM, replicateM, when)
import Control.Applicative ((<$>), (<*>))
import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar
import Control.Concurrent.STM
( STM
, atomically
, newTVarIO
, readTVar
, writeTVar
, modifyTVar'
, retry
, orElse
)
import Data.Time
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Serialize as S
import Pipes (each, runEffect, (>->), Consumer, Producer)
import qualified Pipes.Concurrent as P
import qualified Data.ByteString as B
import Text.Printf (printf)
import Network.Punch.Peer.Types
import Network.Punch.Peer.Reliable.Types
import Network.Punch.Util (cutBs, mapPipe)
instance Peer RcbRef where
sendPeer peer = atomically . sendRcb peer
recvPeer = atomically . recvRcb
closePeer = gracefullyShutdownRcb
newRcb :: ConnOption -> IO RcbRef
newRcb opt@(ConnOption {..}) = do
stateRef <- newTVarIO RcbOpen
seqGenRef <- newTVarIO 0
finSeqRef <- newTVarIO (-1)
lastDeliverySeqRef <- newTVarIO 0
outputQRef <- newTVarIO M.empty
deliveryQRef <- newTVarIO M.empty
resendQRef <- newTVarIO M.empty
extraFinalizersRef <- newTVarIO []
-- Used for circular initialization
rcbRef <- newEmptyMVar
-- Bounded buffers for inter-thread communications
fromApp <- P.spawn' (P.bounded optTxBufferSize)
-- This is unbounded: NIC's tx is controlled by the unacked packet count
toNic <- P.spawn' P.unbounded
fromNic <- P.spawn' (P.bounded optRxBufferSize)
toApp <- P.spawn' (P.bounded optRxBufferSize)
tResend <- async $ runResend rcbRef
tRecv <- async $ runRecv rcbRef
tSend <- async $ runSend rcbRef
tKeepAlive <- async $ runKeepAlive rcbRef
-- ^ Those will kill themselves when the connection is closed
let
rcb = Rcb
{ rcbConnOpt = opt
, rcbFromNic = Mailbox fromNic
, rcbToNic = Mailbox toNic
, rcbFromApp = Mailbox fromApp
, rcbToApp = Mailbox toApp
, rcbState = stateRef
, rcbSeqGen = seqGenRef
, rcbFinSeq = finSeqRef
, rcbLastDeliverySeq = lastDeliverySeqRef
, rcbOutputQ = outputQRef
, rcbDeliveryQ = deliveryQRef
, rcbResendQ = resendQRef
, rcbExtraFinalizers = extraFinalizersRef
}
putMVar rcbRef rcb
return rcb
newRcbFromPeer :: Peer p => ConnOption -> p -> IO RcbRef
newRcbFromPeer rcbOpt peer = do
rcb@(Rcb {..}) <- newRcb rcbOpt
let (bsFromRcb, bsToRcb) = transportsForRcb rcb
async $ runEffect $ fromPeer peer >-> bsToRcb
async $ runEffect $ bsFromRcb >-> toPeer peer
atomically $ modifyTVar' rcbExtraFinalizers (closePeer peer :)
return rcb
gracefullyShutdownRcb :: RcbRef -> IO ()
gracefullyShutdownRcb rcb@(Rcb {..}) = do
now <- getCurrentTime
atomically $ do
seqGen <- readTVar rcbSeqGen
let
finPkt = mkFinPkt $ seqGen + 1
mut' <- sendDataOrFinPkt rcb finPkt now
writeTVar rcbState RcbFinSent
sendRcb :: RcbRef -> B.ByteString -> STM Bool
sendRcb rcb@(Rcb {..}) bs = do
seqGen <- readTVar rcbSeqGen
let
bss = cutBs (optMaxPayloadSize rcbConnOpt) bs
newSeqGen = seqGen + length bss
writeTVar rcbSeqGen newSeqGen
-- Blocks when fromApp buffer is full.
sendsMailbox rcbFromApp $ zip [seqGen + 1..] bss
recvRcb :: RcbRef -> STM (Maybe B.ByteString)
-- Blocks when toApp buffer is empty
recvRcb rcb@(Rcb {..}) = recvMailbox rcbToApp
transportsForRcb
:: RcbRef
-> (Producer B.ByteString IO (), Consumer B.ByteString IO ())
transportsForRcb (Rcb {..}) = (producer, consumer)
where
producer = do
let Mailbox (_, toNic, _) = rcbToNic
P.fromInput toNic >-> mapPipe (S.runPut . putPacket)
consumer = do
let Mailbox (fromNic, _, _) = rcbFromNic
mapPipe (either reportPktErr id . S.runGet getPacket) >->
P.toOutput fromNic
reportPktErr e = error $ "[rcb.transport] Parse error: " ++ show e
----
mkDataPkt seqNo payload = Packet seqNo [DATA] payload
mkFinAckPkt seqNo = Packet seqNo [FIN, ACK] B.empty
mkFinPkt seqNo = Packet seqNo [FIN] B.empty
mkAckPkt seqNo = Packet seqNo [ACK] B.empty
mkDataAckPkt seqNo = Packet seqNo [DATA, ACK] B.empty
mkRstPkt = Packet (-1) [RST] B.empty
areFlags flags expected = L.sort flags == L.sort expected
runResend :: MVar Rcb -> IO ()
runResend rcbRef = readMVar rcbRef >>= go
where
go rcb = do
threadDelay (100 * 1000)
now <- getCurrentTime
(shallContinue, ioAction) <- atomically $ goSTM rcb now
ioAction
when shallContinue $ go rcb
goSTM rcb@(Rcb {..}) now = do
state <- readTVar rcbState
if state == RcbClosed
then return (False, return ())
else do
eiErr <- runEitherT $ resendOnce rcb now
mbErr <- case eiErr of
Left e -> return $ Just e
Right () -> do
cwd <- isCloseWaitDone rcb
if cwd
then return $ Just GracefullyShutdown
else return Nothing
case mbErr of
Nothing ->
return (True, return ())
Just err -> do
let action = printCloseReason "runResend" err
extraFinalizers <- internalResetEverything rcb
return (False, action >> extraFinalizers)
isCloseWaitDone :: Rcb -> STM Bool
isCloseWaitDone (Rcb {..}) = do
state <- readTVar rcbState
lastDeliverySeq <- readTVar rcbLastDeliverySeq
finSeq <- readTVar rcbFinSeq
outputQ <- readTVar rcbOutputQ
return $
state == RcbCloseWait &&
lastDeliverySeq + 1 == finSeq &&
-- ^ We have received all DATA packets from the other side.
M.null outputQ
-- ^ And the other side has ACKed all of our DATA packets.
-- Resend packets in the resendQ and update their last-send-time
-- Invariant: (Left CloseReason) means that the rcb is not changed
resendOnce :: Rcb -> UTCTime -> EitherT CloseReason STM ()
resendOnce (Rcb {..}) now = do
(works, rest) <- M.split (now, (-1)) <$> lift (readTVar rcbResendQ)
outputQ <- lift $ readTVar rcbOutputQ
newResends <- forM (M.toList works) $
\ ((_, dataSeq), (backOff, numRetries)) -> do
case M.lookup dataSeq outputQ of
Nothing -> do
-- Received ACK-ECHO for this packet and there is no need
-- to keep resending this packet. Clear it.
return Nothing
Just dataPkt -> if numRetries > optMaxRetries rcbConnOpt
then left TooManyRetries
else do
-- Try to resend it
ok <- lift $ sendMailbox rcbToNic dataPkt
if not ok
then
-- This mean the connection was closed.
left PeerClosed
else do
-- And set the backoff timeout for this packet
let
(nextTime, nextBackOff) = calcBackOff now backOff
return $ Just ((nextTime, dataSeq),
(nextBackOff, numRetries + 1))
let
-- Add back new backoffs
combine = maybe id (uncurry M.insert)
newResendQ = foldr combine rest newResends
lift $ writeTVar rcbResendQ newResendQ
-- We will see many `True <- sendMailbox ...` here since this is expected
-- to succeed -- the mailboxes will only be closed after we set the
-- rcbState to RcbClosed (and kill those threads).
runRecv :: MVar Rcb -> IO ()
runRecv rcbRef = readMVar rcbRef >>= go
where
go rcb = do
mbLast <- atomically $ goSTM rcb
case mbLast of
Nothing -> go rcb
Just action -> action
goSTM :: Rcb -> STM (Maybe (IO ()))
goSTM rcb@(Rcb {..}) = do
mbPkt <- recvMailbox rcbFromNic
case mbPkt of
Just pkt -> do
mbErr <- onPkt pkt rcb
return $ fmap mergeLogAndAction mbErr
Nothing -> do
currState <- readTVar rcbState
if currState /= RcbClosed
-- This mean the connection was closed.
then return $ Just $
printCloseReason "runRecv|fromNic->Nothing|Debug" PeerClosed
else return $ Just $ return ()
mergeLogAndAction (err, action) = case err of
AlreadyClosed -> action
_ -> printCloseReason "runRecv|fromNic->Just" err >> action
onPkt :: Packet -> Rcb -> STM (Maybe (CloseReason, IO ()))
onPkt pkt rcb@(Rcb {..}) = do
state <- readTVar rcbState
eiRes <- runEitherT $ onPktState state pkt rcb
return $ either Just (const $ Nothing) eiRes
onPktState :: RcbState -> Packet -> Rcb
-> EitherT (CloseReason, IO ()) STM ()
onPktState RcbClosed pkt rcb =
left (AlreadyClosed, return ())
onPktState state pkt@(Packet {..}) rcb@(Rcb {..})
| pktFlags `areFlags` [DATA] =
let
sendDataToApp = do
-- Send a DATA-ACK anytime a DATA packet is received.
let ackPkt = mkDataAckPkt pktSeqNo
True <- sendMailbox rcbToNic ackPkt
-- Check if we need to deliver this payload.
lastDeliverySeq <- readTVar rcbLastDeliverySeq
when (lastDeliverySeq < pktSeqNo) $ do
deliveryQ <- readTVar rcbDeliveryQ
let
-- And see how many payloads shall we deliver
insertedDeliveryQ = M.insert pktSeqNo pktPayload deliveryQ
(newDeliveryQ, newLastDeliverySeq, sequentialPayloads) =
mergeExtract insertedDeliveryQ lastDeliverySeq
-- This might block if toApp mailbox is full.
-- In this case, the other branch (dropThePacket)
-- will be taken.
True <- sendsMailbox rcbToApp sequentialPayloads
writeTVar rcbDeliveryQ newDeliveryQ
writeTVar rcbLastDeliverySeq newLastDeliverySeq
-- Drop the packet reply when the toApp queue is full
dropThePacket = return ()
in
lift (sendDataToApp `orElse` dropThePacket)
| pktFlags `areFlags` [DATA, ACK] =
-- And the resending thread will note this and stop rescheduling
-- this packet.
lift $ modifyTVar' rcbOutputQ $ M.delete pktSeqNo
| pktFlags `areFlags` [FIN] = lift $ do
-- Always send a reply.
let ackPkt = mkFinAckPkt pktSeqNo
True <- sendMailbox rcbToNic ackPkt
-- Shutdown App -> Nic.
sealMailbox rcbFromApp
when (state == RcbOpen) $ do
-- Only change the state and record the seq when we were open.
writeTVar rcbFinSeq pktSeqNo
writeTVar rcbState RcbCloseWait
| pktFlags `areFlags` [FIN, ACK] && state == RcbFinSent = lift $ do
-- Set the state to CloseWait if not there yet.
-- If we changed the state, record the FIN's seqNo as well.
writeTVar rcbFinSeq pktSeqNo
writeTVar rcbState RcbCloseWait
-- Also stop sending the FIN
modifyTVar' rcbOutputQ $ M.delete pktSeqNo
| pktFlags `areFlags` [RST] = do
-- This can happen before FIN-ACK is received (if we are initiating
-- the graceful shutdown)
let
reason = if state == RcbClosed then AlreadyClosed else PeerClosed
logAction = putStrLn $ "RST on " ++ show state
extraFinalizers <- lift $ internalResetEverything rcb
left (reason, logAction >> extraFinalizers)
runKeepAlive rcbRef = readMVar rcbRef >>= go
where
go rcb = do
threadDelay (1000000)
ok <- atomically $ sendRcb rcb B.empty
if ok
then go rcb
else return ()
internalResetEverything :: Rcb -> STM (IO ())
internalResetEverything rcb@(Rcb {..}) = do
-- We send an RST as well
sendMailbox rcbToNic mkRstPkt
sealMailbox rcbFromApp
sealMailbox rcbToApp
sealMailbox rcbFromNic
sealMailbox rcbToNic
writeTVar rcbState RcbClosed
-- Let the caller to stop the underlying raw peer
-- And the runner threads will stop by themselves.
extraFinalizers <- readTVar rcbExtraFinalizers
return $ sequence_ extraFinalizers
runSend :: MVar Rcb -> IO ()
runSend rcbRef = readMVar rcbRef >>= go
where
go rcb = do
now <- getCurrentTime
goOn <- atomically $ goSTM rcb now
when goOn (go rcb)
goSTM rcb@(Rcb {..}) now = do
-- Check if there are too many unacked packets. If so,
-- wait until the number decrease.
let ConnOption {..} = rcbConnOpt
tooManyUnacks <- txUnackOverflow rcb
when tooManyUnacks retry
mbBs <- recvMailbox rcbFromApp
case mbBs of
Nothing ->
-- Sealed: FIN or closed. This thread is done.
-- False to discontinue the loop
return False
Just (seqNo, payload) -> do
sendDataOrFinPkt rcb (mkDataPkt seqNo payload) now
-- True to continue the loop
return True
barf :: SomeException -> IO ()
barf e = do
putStrLn $ "[runSend] STM.retry: " ++ show e
sendDataOrFinPkt :: Rcb -> Packet -> UTCTime -> STM ()
sendDataOrFinPkt (Rcb {..}) packet@(Packet {..}) now = do
sendMailbox rcbToNic packet
let
-- Add to OutputQ and schedule a resend
(nextTime, nextBackOff) =
calcBackOff now (optDefaultBackOff rcbConnOpt)
modifyTVar' rcbOutputQ $ M.insert pktSeqNo packet
modifyTVar' rcbResendQ $ M.insert (nextTime, pktSeqNo) (nextBackOff, 0)
sendMailbox :: Mailbox a -> a -> STM Bool
sendMailbox (Mailbox (output, _, _)) a = P.send output a
sendsMailbox :: Mailbox a -> [a] -> STM Bool
sendsMailbox m@(Mailbox (output, _, _)) xs =
all id <$> mapM (sendMailbox m) xs
recvMailbox :: Mailbox a -> STM (Maybe a)
recvMailbox (Mailbox (_, input, _)) = P.recv input
fromMailbox (Mailbox (_, input, _)) = P.fromInput input
toMailbox (Mailbox (output, _, _)) = P.toOutput output
-- Closes the mailbox but still allow reading
sealMailbox :: Mailbox a -> STM ()
sealMailbox (Mailbox (_, _, seal)) = seal
calcBackOff :: UTCTime -> Int -> (UTCTime, Int)
calcBackOff now backOff = (nextTime, floor $ (fromIntegral backOff) * 1.2)
where
nextBackOffSec = fromIntegral backOff / 1000000
nextTime = addUTCTime nextBackOffSec now
mergeExtract :: M.Map Int a -> Int -> (M.Map Int a, Int, [a])
mergeExtract m begin = go m begin []
where
go src i dst =
let i' = i + 1
in case M.lookup i' src of
Nothing -> (src, i, reverse dst)
Just a -> go (M.delete i' src) i' (a:dst)
printCloseReason :: String -> CloseReason -> IO ()
printCloseReason tag err =
printf "[%s] Connection closed by `%s`.\n" tag (show err)
txUnackOverflow :: Rcb -> STM Bool
txUnackOverflow (Rcb {..}) = do
let ConnOption {..} = rcbConnOpt
unacked <- M.size <$> readTVar rcbResendQ
return $ unacked >= optMaxUnackedPackets
| overminder/punch-forward | src/Network/Punch/Peer/Reliable.hs | bsd-3-clause | 14,987 | 3 | 27 | 3,836 | 4,311 | 2,168 | 2,143 | -1 | -1 |
{-#LANGUAGE OverloadedStrings#-}
{-
Min Zhang
Oct 14, 2015
Functions on DNA sequences
v.0.1.0 (Oct 14, 2015): switch from Data.Text to Data.Text.Lazy
-}
module Dna
( copySeq
, complSeq
, revSeq
, revCompSeq
, dnaToRna
, gcPct
)
where
import qualified Data.Text.Lazy as T
import Data.List (genericLength)
--with copySeq together, clean up DNA input, remove not ATGC, turn everything into uppercase
toDna = T.toUpper
copySeq = T.map copyNt . toDna
where
copyNt nt = case nt of
'A' -> 'A'
'T' -> 'T'
'G' -> 'G'
'C' -> 'C'
_ -> 'N'
complSeq = T.map complNt . toDna
where
complNt nt = case nt of
'A' -> 'T'
'T' -> 'A'
'G' -> 'C'
'C' -> 'G'
_ -> 'N'
revSeq = copySeq . T.reverse . toDna
revCompSeq = revSeq . complSeq . toDna
dnaToRna = T.map dnaToRnaNt . toDna
where
dnaToRnaNt nt = case nt of
'T' -> 'U'
_ -> nt -- save a lot of lines
gcPct seq = lenGC seq / (realToFrac $ T.length seq)
where
lenGC = T.foldr ((+) . countGC) 0 . copySeq
countGC nt = case nt of
'G' -> 1.0
'C' -> 1.0
_ -> 0
--need a function to test if the input format is good, or put it into IO? or it's too costful for data from fastq? (because most of the format actually is good in fastq file)
| Min-/fourseq | src/lib/Dna.hs | bsd-3-clause | 1,344 | 0 | 10 | 411 | 323 | 174 | 149 | 37 | 5 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Type.Nat (
Nat (..), KnownNat (..)
) where
import Data.Proxy (Proxy (..))
data Nat = Zero | Succ Nat
class KnownNat (n :: Nat) where
natVal :: proxy n -> Integer
instance KnownNat 'Zero where
natVal _ = 0
instance KnownNat n => KnownNat ('Succ n) where
natVal _ = 1 + natVal (Proxy :: Proxy n)
| YellPika/effin | src/Data/Type/Nat.hs | bsd-3-clause | 444 | 0 | 9 | 112 | 144 | 81 | 63 | 13 | 0 |
module Main where
import Logic.Pheasant
main :: IO ()
main = do
putStrLn "hello world"
| thsutton/pheasant | src/Main.hs | bsd-3-clause | 101 | 0 | 7 | 29 | 30 | 16 | 14 | 5 | 1 |
{-# LANGUAGE RecordWildCards #-}
module System.Hardware.Z21.XBus where
import System.Hardware.Z21.Types
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString.Lazy (ByteString)
import Data.Binary.Get
import Data.Binary.Put
import Data.Binary
import Data.Bits
data XBus = XBus
{ xbusHeader :: !Word8
, xbusData :: !ByteString
} deriving (Show, Eq)
instance Binary XBus where
put XBus{..} = do
putWord8 xbusHeader
putLazyByteString xbusData
putWord8 xorByte
where xorByte = LBS.foldl1' xor $ LBS.cons xbusHeader xbusData
get = do
xheader <- getWord8
remains <- getRemainingLazyByteString
let xorByte = LBS.last remains
xdata = LBS.init remains
xorByte' = LBS.foldl1' xor $ LBS.cons xheader xdata
packet = XBus xheader xdata
if xorByte /= xorByte'
then return packet
else fail $ "Broken ckecksum at " ++ show packet
++ " should be " ++ show xorByte'
++ " but " ++ show xorByte
| akru/z21-hs | src/System/Hardware/Z21/XBus.hs | bsd-3-clause | 1,088 | 0 | 14 | 328 | 280 | 146 | 134 | 35 | 0 |
module Parser where
import Rules
import Data.Char
import Data.List.Split
import Data.List
import Data.Maybe
import Control.Applicative
parse :: FilePath -> IO (Maybe [Rule])
parse path = do
strs <- zip [1..] . map stripComments . lines <$> readFile path
x <- mapM parseRule $ filter (not . null) $ splitWhen (all isSpace . snd) strs
return $ if not (any (any isNothing) x) then Just $ concatMap catMaybes x
else Nothing
where stripComments = takeWhile (/= '#')
parseRule :: [(Int, String)] -> IO [Maybe Rule]
parseRule input = let
isVinculum = ("--" `isPrefixOf`) . dropWhile isSpace
in case split (keepDelimsL $ whenElt (isVinculum . snd)) input of
[topLine,[vinc,bottomLine]] -> let
tops = filter (any (not . isSpace))
$ concatMap (splitOn " ")
$ map snd topLine
bot = unwords . words $ snd bottomLine
nam = dropWhile (== '-') $ dropWhile isSpace $ snd vinc
in if nam == "" then do
putStrLn $ "No name given after vinculum on line " ++ show (fst vinc)
return [Nothing]
else return [Just $ Rule (unwords $ words nam) (map (unwords . words) tops) bot]
[one] -> do
putStrLn $ "No vinculum found for rule on line " ++ show (fst $ head one)
return [Nothing]
[one,_] -> do
putStrLn $ "Multiple lines found in conclusion of rule on line " ++ show (fst $ head one)
return [Nothing]
[] -> do
putStrLn "Unexpected error"
return [Nothing]
one:_:_ -> do
putStrLn $ "Multiple vinculi found for rule on line " ++ show (fst $ head one)
return [Nothing]
| liamoc/hilbert | Parser.hs | bsd-3-clause | 1,744 | 0 | 20 | 559 | 625 | 313 | 312 | 40 | 6 |
{-# LANGUAGE ConstraintKinds, DataKinds, FlexibleContexts, GADTs,
OverloadedStrings, PatternSynonyms, QuasiQuotes,
ScopedTypeVariables, TemplateHaskell, TypeOperators,
ViewPatterns #-}
-- This is a loose port of a
-- [[https://ajkl.github.io/2014/11/23/Dataframes/][dataframe tutorial]] Rosetta
-- Stone to compare traditional dataframe tools built in R, Julia,
-- Python, etc. with
-- [[https://github.com/acowley/Frames][Frames]]. Performing data
-- analysis in Haskell brings with it a few advantages:
-- - Interactive exploration is supported in GHCi
-- - GHC produces fast, memory-efficient code when you're ready to run a
-- program that might take a bit of time
-- - You get to use Haskell to write your own functions when what you
-- want isn't already defined in the library
-- - The code you write is /statically typed/ so that mismatches between
-- your code and your data data are found by the type checker
-- The example [[http://grouplens.org/datasets/movielens/][data]] file
-- used (specifically, the =u.user= file from the /MovieLens 100k/
-- data set) does not include column headers, nor does it use commas
-- to separate values, so it does not fall into the sweet spot of CSV
-- parsing that ~Frames~ is aimed at. That said, this mismatch of test
-- data and library support is a great opportunity to verify that
-- ~Frames~ are flexible enough to meet a variety of needs.
-- We begin with rather a lot of imports to support a variety of test
-- operations and parser customization. I encourage you to start with a
-- smaller test program than this!
import Control.Applicative
import qualified Control.Foldl as L
import qualified Data.Foldable as F
import Data.Proxy (Proxy(..))
import Lens.Micro
import Lens.Micro.Extras
import Frames
import Frames.CSV (readTableOpt, rowGen, RowGen(..))
import Pipes hiding (Proxy)
import qualified Pipes.Prelude as P
-- A few other imports will be used for highly customized parsing [[Better Types][later]].
import Frames.CSV (colQ)
import TutorialZipCode
-- * Data Import
-- We usually package column names with the data to keep things a bit
-- more self-documenting. In the common case where a data file has a
-- header row providing column names, and columns are separated by
-- commas, generating the types needed to import a data set is as simple
-- as,
-- -- #+BEGIN_SRC haskell
-- tableTypes "User" "data/ml-100k/u.user"
-- #+END_SRC
-- The data set /this/ example considers is rather far from the sweet
-- spot of CSV processing that ~Frames~ is aimed it: it does not include
-- column headers, nor does it use commas to separate values! However,
-- these mismatches do provide an opportunity to see that the ~Frames~
-- library is flexible enough to meet a variety of needs.
tableTypes' rowGen { rowTypeName = "User"
, columnNames = [ "user id", "age", "gender"
, "occupation", "zip code" ]
, separator = "|" }
"data/ml-100k/u.user"
-- This template haskell splice explicitly specifies the name for the
-- inferred record type, column names, a separator string, and the
-- data file from which to infer the record type (i.e. what type
-- should be used to represent each column). The result of this splice
-- is included in an [[* Splice Dump][appendix]] below so you can flip
-- between the generated code and how it is used.
-- Since this data is far from the ideal CSV file, we have to tell
-- ~Frames~ how to interpret the data so that it can decide what data
-- type to use for each column. Having the types depend upon the data in
-- the given file is a useful exercise in this domain as the actual shape
-- of the data is of paramount importance during the early import and
-- exploration phases of data analysis.
-- We can load the module into =cabal repl= to see what we have so far.
-- #+BEGIN_EXAMPLE
-- λ> :i User
-- type User =
-- Record
-- '["user id" :-> Int, "age" :-> Int, "gender" :-> Text,
-- "occupation" :-> Text, "zip code" :-> Text]
-- #+END_EXAMPLE
-- This lets us perform a quick check that the types are basically what
-- we expect them to be.
-- We now define a streaming representation of the full data set. If the
-- data set is too large to keep in memory, we can process it as it
-- streams through RAM.
movieStream :: Producer User IO ()
movieStream = readTableOpt userParser "data/ml-100k/u.user"
-- Alternately, if we want to run multiple operations against a data set
-- that /can/ fit in RAM, we can do that. Here we define an in-core (in
-- memory) array of structures (AoS) representation.
loadMovies :: IO (Frame User)
loadMovies = inCoreAoS movieStream
-- ** Streaming Cores?
-- A ~Frame~ is an in-memory representation of your data. The ~Frames~
-- library stores each column as compactly as it knows how, and lets
-- you index your data as a structure of arrays (where each field of
-- the structure is an array corresponding to a column of your data),
-- or as an array of structures, also known as a ~Frame~. These latter
-- structures correspond to rows of your data. Alternatively, rows of
-- data may be handled in a streaming fashion so that you are not
-- limited to available RAM. In the streaming paradigm, you process
-- each row individually as a single record.
-- A ~Frame~ provides ~O(1)~ indexing, as well as any other operations
-- you are familiar with based on the ~Foldable~ class. If a data set is
-- small, keeping it in RAM is usually the fastest way to perform
-- multiple analyses on that data that you can't fuse into a single
-- traversal.
-- Alternatively, a ~Producer~ of rows is a great way to whittle down a
-- large data set before moving on to whatever you want to do next.
-- The upshot is that you can work with your data as a collection of
-- rows with either a densely packed in-memory reporesentation -- a
-- ~Frame~ -- or a stream of rows provided by a ~Producer~. The choice
-- depends on if you want to perform multiple queries against your
-- data, and, if so, whether you have enough RAM to hold the data. If
-- the answer to both of those questions is,
-- @@html:<i>@@"Yes!"@@html:</i>@@, consider using a ~Frame~ as in the
-- ~loadMovies~ example. If the answer to either question is,
-- @@html:<i>@@"Nope!"@@html:</i>@@, you will be better off with a
-- ~Producer~, as in the ~movieStream~ example.
-- ** Sanity Check
-- We can compute some easy statistics to see how things look.
-- #+BEGIN_EXAMPLE
-- λ> ms <- loadMovies
-- λ> L.fold L.minimum (view age <$> ms)
-- Just 7
-- #+END_EXAMPLE
-- When there are multiple properties we would like to compute, we can
-- fuse multiple traversals into one pass using something like the [[http://hackage.haskell.org/package/foldl][foldl]]
-- package,
minMax :: Ord a => L.Fold a (Maybe a, Maybe a)
minMax = (,) <$> L.minimum <*> L.maximum
-- #+BEGIN_EXAMPLE
-- λ> L.fold (L.handles age minMax) ms
-- (Just 7,Just 73)
-- #+END_EXAMPLE
-- Here we are projecting the =age= column out of each record, and
-- computing the minimum and maximum =age= across all rows.
-- * Subsetting
-- ** Row Subset
-- Data may be inspected using either Haskell's traditional list API...
-- #+BEGIN_EXAMPLE
-- λ> mapM_ print (take 3 (F.toList ms))
-- {user id :-> 1, age :-> 24, gender :-> "M", occupation :-> "technician", zip code :-> "85711"}
-- {user id :-> 2, age :-> 53, gender :-> "F", occupation :-> "other", zip code :-> "94043"}
-- {user id :-> 3, age :-> 23, gender :-> "M", occupation :-> "writer", zip code :-> "32067"}
-- #+END_EXAMPLE
-- ... or =O(1)= indexing of individual rows. Here we take the last three
-- rows of the data set,
-- #+BEGIN_EXAMPLE
-- λ> mapM_ (print . frameRow ms) [frameLength ms - 3 .. frameLength ms - 1]
-- {user id :-> 941, age :-> 20, gender :-> "M", occupation :-> "student", zip code :-> "97229"}
-- {user id :-> 942, age :-> 48, gender :-> "F", occupation :-> "librarian", zip code :-> "78209"}
-- {user id :-> 943, age :-> 22, gender :-> "M", occupation :-> "student", zip code :-> "77841"}
-- #+END_EXAMPLE
-- This lets us view a subset of rows,
-- #+BEGIN_EXAMPLE
-- λ> mapM_ (print . frameRow ms) [50..55]
-- {user id :-> 51, age :-> 28, gender :-> "M", occupation :-> "educator", zip code :-> "16509"}
-- {user id :-> 52, age :-> 18, gender :-> "F", occupation :-> "student", zip code :-> "55105"}
-- {user id :-> 53, age :-> 26, gender :-> "M", occupation :-> "programmer", zip code :-> "55414"}
-- {user id :-> 54, age :-> 22, gender :-> "M", occupation :-> "executive", zip code :-> "66315"}
-- {user id :-> 55, age :-> 37, gender :-> "M", occupation :-> "programmer", zip code :-> "01331"}
-- {user id :-> 56, age :-> 25, gender :-> "M", occupation :-> "librarian", zip code :-> "46260"}
-- #+END_EXAMPLE
-- ** Column Subset
-- We can consider a single column.
-- #+BEGIN_EXAMPLE
-- λ> take 6 . F.toList $ view occupation <$> ms
-- ["technician","other","writer","technician","other","executive"]
-- #+END_EXAMPLE
-- Or multiple columns,
miniUser :: User -> Record '[Occupation, Gender, Age]
miniUser = rcast
-- #+BEGIN_EXAMPLE
-- λ> mapM_ print . take 6 . F.toList $ fmap miniUser ms
-- {occupation :-> "technician", gender :-> "M", age :-> 24}
-- {occupation :-> "other", gender :-> "F", age :-> 53}
-- {occupation :-> "writer", gender :-> "M", age :-> 23}
-- {occupation :-> "technician", gender :-> "M", age :-> 24}
-- {occupation :-> "other", gender :-> "F", age :-> 33}
-- {occupation :-> "executive", gender :-> "M", age :-> 42}
-- #+END_EXAMPLE
-- If you'd rather not define a function like ~miniUser~, you can fix
-- the types in-line by using the ~select~ function.
-- #+BEGIN_EXAMPLE
-- λ> :set -XDataKinds
-- λ> select (Proxy::Proxy '[Occupation,Gender,Age]) $ frameRow ms 0
-- {occupation :-> "technician", gender :-> "M", age :-> 24}
-- #+END_EXAMPLE
-- If you are frequently using this style of projection, you can also
-- take advantage of another bit of Template Haskell shorthand for
-- creating those ~Proxy~ values.
-- #+BEGIN_EXAMPLE
-- λ> :set -XDataKinds -XQuasiQuotes
-- λ> select [pr|Occupation,Gender,Age|] $ frameRow ms 0
-- {occupation :-> "technician", gender :-> "M", age :-> 24}
-- #+END_EXAMPLE
-- ** Query / Conditional Subset
-- Filtering our frame is rather nicely done using the
-- [[http://hackage.haskell.org/package/pipes][pipes]] package. Here
-- we pick out the users whose occupation is "writer".
writers :: (Occupation ∈ rs, Monad m) => Pipe (Record rs) (Record rs) m r
writers = P.filter ((== "writer") . view occupation)
-- #+BEGIN_EXAMPLE
-- λ> runEffect $ movieStream >-> writers >-> P.take 6 >-> P.print
-- {user id :-> 3, age :-> 23, gender :-> "M", occupation :-> "writer", zip code :-> "32067"}
-- {user id :-> 21, age :-> 26, gender :-> "M", occupation :-> "writer", zip code :-> "30068"}
-- {user id :-> 22, age :-> 25, gender :-> "M", occupation :-> "writer", zip code :-> "40206"}
-- {user id :-> 28, age :-> 32, gender :-> "M", occupation :-> "writer", zip code :-> "55369"}
-- {user id :-> 50, age :-> 21, gender :-> "M", occupation :-> "writer", zip code :-> "52245"}
-- {user id :-> 122, age :-> 32, gender :-> "F", occupation :-> "writer", zip code :-> "22206"}
-- #+END_EXAMPLE
-- If you're not too keen on all the ~pipes~ syntax in that example, you
-- could also write it using a helper function provided by ~Frames~,
-- #+BEGIN_EXAMPLE
-- λ> pipePreview movieStream 6 writers
-- #+END_EXAMPLE
-- This is a handy way to try out various maps and filters you may want
-- to eventually apply to a large data set.
-- ** Column Subset Update
-- We can also apply a function to a subset of columns of each row! Here,
-- we want to apply a function with type ~Int -> Int~ to two columns
-- whose values are of type ~Int~.
intFieldDoubler :: Record '[UserId, Age] -> Record '[UserId, Age]
intFieldDoubler = mapMono (* 2)
-- Let's preview the effect of this function by applying it to the
-- ~UserId~ and ~Age~ columns of the first three rows of our data set.
-- #+BEGIN_EXAMPLE
-- λ> pipePreview movieStream 3 (P.map (rsubset %~ intFieldDoubler))
-- {user id :-> 2, age :-> 48, gender :-> "M", occupation :-> "technician", zip code :-> "85711"}
-- {user id :-> 4, age :-> 106, gender :-> "F", occupation :-> "other", zip code :-> "94043"}
-- {user id :-> 6, age :-> 46, gender :-> "M", occupation :-> "writer", zip code :-> "32067"}
-- #+END_EXAMPLE
-- This is a neat way of manipulating a few columns without having to
-- worry about what other columns might exist. You might want to use this
-- for normalizing the capitalization, or truncating the length of,
-- various text fields, for example.
-- ** Mostly-Uniform Data
-- /(Warning: This section veers into types that are likely of more
-- use to library authors than end users.)/
-- Suppose we don't know much about our data, but we do know that it
-- starts with an identifying column, and then some number of numeric
-- columns. We can structurally peel off the first column, perform a
-- constrained polymorphic operation on the other columns, then glue
-- the first column back on to the result.
addTwoRest :: (AllCols Num rs, AsVinyl rs)
=> Record (s :-> a ': rs) -> Record (s :-> a ': rs)
addTwoRest (h :& t) = frameCons h (aux t)
where aux = mapMethod [pr|Num|] (\x -> x + 2)
-- #+BEGIN_EXAMPLE
-- λ> addTwoRest (select [pr|Occupation, UserId, Age|] (frameRow ms 0))
-- {occupation :-> "technician", user id :-> 3, age :-> 26}
-- #+END_EXAMPLE
-- But what if we don't want to rely entirely on ordering of our rows?
-- Here, we know there is an identifying column, ~Occupation~, and we
-- want to shuffle it around to the head of the record while mapping a
-- constrained polymorphic operation over the other columns.
addTwoOccupation :: (CanDelete Occupation rs,
rs' ~ RDelete Occupation rs,
AllCols Num rs', AsVinyl rs')
=> Record rs -> Record (Occupation ': RDelete Occupation rs)
addTwoOccupation r = frameCons (rget' occupation' r)
$ mapMethod [pr|Num|] (+ 2) (rdel [pr|Occupation|] r)
-- #+BEGIN_EXAMPLE
-- λ> addTwoOccupation (select [pr|UserId,Age,Occupation|] (frameRow ms 0))
-- {occupation :-> "technician", user id :-> 3, age :-> 26}
-- #+END_EXAMPLE
-- It is a bit clumsy to delete and then add back a particular field,
-- and the dependence on explicit structure is relying a bit more on
-- coincidence than we might like. We could choose, instead, to work
-- with row types that contain a distinguished column somewhere in
-- their midst, but regarding precisely /where/ it is, or /how many/
-- other fields there are, we care not.
addTwoOccupation' :: forall rs rs'.
(CanDelete Occupation rs,
rs' ~ RDelete Occupation rs,
AllCols Num rs', AsVinyl rs')
=> Record rs -> Record rs
addTwoOccupation' = lenses [pr|rs'|] %~ mapMethod [pr|Num|] (+ 2)
-- #+BEGIN_EXAMPLE
-- λ> addTwoOccupation' (select [pr|UserId,Age,Occupation|] (frameRow ms 0))
-- {user id :-> 3, age :-> 26, occupation :-> "technician"}
-- #+END_EXAMPLE
-- We can unpack this type a bit to understand what is happening. A
-- ~Frames~ ~Record~ is a record from the ~Vinyl~ library, except that
-- each type has phantom column information. This metadata is
-- available to the type checker, but is erased during compilation so
-- that it does not impose any runtime overhead. What we are doing
-- here is saying that we will operate on a ~Frames~ row type, ~Record
-- rs~, that has an element ~Occupation~, and that deleting this
-- element works properly (i.e. the leftover fields are a proper
-- subset of the original row type). We further state -- with the
-- ~AsVinyl~ constraint -- that we want to work on the unadorned field
-- values, temporarily discarding their header information, with the
-- ~mapMethod~ function that will treat our richly-typed row as a less
-- informative ~Vinyl~ record.
-- We then peer through a lens onto the set of all unadorned fields other
-- than ~Occupation~, apply a function with a ~Num~ constraint to each of
-- those fields, then pull back out of the lens reattaching the column
-- header information on our way. All of that manipulation and
-- bookkeeping is managed by the type checker.
-- Lest we forget we are working in a typed setting, what happens if
-- the constraint on our polymorphic operation can't be satisfied by
-- one of the columns?
-- #+BEGIN_EXAMPLE
-- λ> addTwoOccupation (select [pr|Age,Occupation,Gender|] (frameRow ms 0))
-- <interactive>:15:1-16:
-- No instance for (Num Text) arising from a use of ‘addTwoOccupation’
-- In the expression:
-- addTwoOccupation
-- (select
-- (Proxy :: Proxy '[Age, Occupation, Gender]) (frameRow ms 0))
-- In an equation for ‘it’:
-- it
-- = addTwoOccupation
-- (select
-- (Proxy :: Proxy '[Age, Occupation, Gender]) (frameRow ms 0))
-- #+END_EXAMPLE
-- This error message isn't ideal in that it doesn't tell us which
-- column failed to satisfy the constraint. Hopefully this can be
-- improved in the future!
-- * Escape Hatch
-- When you're done with ~Frames~ and want to get back to more
-- familiar monomorphic pastures, you can bundle your data up.
restInts :: (AllAre Int (UnColumn rs), AsVinyl rs)
=> Record (s :-> Text ': rs) -> (Text, [Int])
restInts (recUncons -> (h, t)) = (h, recToList t)
-- #+BEGIN_EXAMPLE
-- λ> restInts (select [pr|Occupation,UserId,Age|] (frameRow ms 0))
-- ("technician",[1,24])
-- #+END_EXAMPLE
-- * Better Types
-- A common disappointment of parsing general data sets is the
-- reliance on text for data representation even /after/ parsing. If
-- you find that the default ~Columns~ spectrum of potential column
-- types that =Frames= uses doesn't capture desired structure, you can
-- go ahead and define your own universe of column types! The =User=
-- row types we've been playing with here is rather boring: it only
-- uses =Int= and =Text= column types. But =Text= is far too vague a
-- type for a column like =zipCode=.
-- All of the zip codes in this set are five characters, and most are
-- standard numeric US zip codes. Let's go ahead and define our own
-- universe of column types.
-- -- #+begin_src haskell
-- data ZipT = ZipUS Int Int Int Int Int
-- | ZipWorld Char Char Char Char Char
-- deriving (Eq, Ord, Show, Typeable)
-- type instance VectorFor ZipT = V.Vector
-- instance Readable ZipT where
-- fromText t
-- | T.length t == 5 = let cs@[v,w,x,y,z] = T.unpack t
-- [a,b,c,d,e] = map C.digitToInt cs
-- in if all C.isDigit cs
-- then return $ ZipUS a b c d e
-- else return $ ZipWorld v w x y z
-- | otherwise = mzero
-- type MyColumns = ZipT ': CommonColumns
-- #+end_src
-- Note that these definitions must be imported from a separate module
-- to satisfy GHC's stage restrictions related to Template
-- Haskell. The full code for the custom type may be found in an [[*
-- User Types][appendix]].
-- We name this record type ~U2~, and give all the generated column types
-- and lenses a prefix, "u2", so they don't conflict with the definitions
-- we generated earlier.
tableTypes' rowGen { rowTypeName = "U2"
, columnNames = [ "user id", "age", "gender"
, "occupation", "zip code" ]
, separator = "|"
, tablePrefix = "u2"
, columnUniverse = $(colQ ''MyColumns) }
"data/ml-100k/u.user"
movieStream2 :: Producer U2 IO ()
movieStream2 = readTableOpt u2Parser "data/ml-100k/u.user"
-- This new record type, =U2=, has a more interesting =zip code=
-- column.
-- #+BEGIN_EXAMPLE
-- λ> :i U2
-- type U2 =
-- Record
-- '["user id" :-> Int, "age" :-> Int, "gender" :-> Text,
-- "occupation" :-> Text, "zip code" :-> ZipT]
-- #+END_EXAMPLE
-- Let's take the occupations of the first 10 users from New England,
-- New Jersey, and other places whose zip codes begin with a zero.
neOccupations :: (U2zipCode ∈ rs, U2occupation ∈ rs, Monad m)
=> Pipe (Record rs) Text m r
neOccupations = P.filter (isNewEngland . view u2zipCode)
>-> P.map (view u2occupation)
where isNewEngland (ZipUS 0 _ _ _ _) = True
isNewEngland _ = False
-- #+BEGIN_EXAMPLE
-- λ> runEffect $ movieStream2 >-> neOccupations >-> P.take 10 >-> P.print
-- "administrator"
-- "student"
-- "other"
-- "programmer"
-- "librarian"
-- "entertainment"
-- "marketing"
-- "programmer"
-- "educator"
-- "healthcare"
-- #+END_EXAMPLE
-- So there we go! We've done both row and column subset queries with a
-- strongly typed query (namely, ~isNewEngland~). Another situation in
-- which one might want to define a custom universe of column types is
-- when dealing with dates. This would let you both reject rows with
-- badly formatted dates, for example, and efficiently query the data set
-- with richly-typed queries.
-- Even better, did you notice the types of ~writers~ and
-- ~neOccupations~? They are polymorphic over the full row type!
-- That's what the ~(Occupation ∈ rs)~ constraint signifies: such a
-- function will work for record types with any set of fields, ~rs~, so
-- long as ~Occupation~ is an element of that set. This means that if
-- your schema changes, or you switch to a related but different data
-- set, *these functions can still be used without even touching the
-- code*. Just recompile against the new data set, and you're good to go.
-- * Appendix
-- ** User Types
-- Here are the definitions needed to define the ~MyColumns~ type with
-- its more descriptive ~ZipT~ type. We have to define these things in
-- a separate module from our main work due to GHC's stage
-- restrictions regarding Template Haskell. Specifically, ~ZipT~ and
-- its instances are used at compile time to infer the record type
-- needed to represent the data file. Notice the extension point here
-- is not too rough: you prepend new, more refined, type compatibility
-- checks to the head of ~CommonColumns~, or you can build up your own
-- list of expected types.
-- This may not be something you'd want to do for every data
-- set. However, the /ability/ to refine the structure of parsed data
-- is in keeping with the overall goal of ~Frames~: it's easy to take
-- off, and the sky's the limit.
-- -- #+begin_src haskell
-- {-# LANGUAGE DataKinds, DeriveDataTypeable, TypeFamilies, TypeOperators #-}
-- module TutorialZipCode where
-- import Control.Monad (mzero)
-- import qualified Data.Char as C
-- import Data.Readable (Readable(fromText))
-- import qualified Data.Text as T
-- import Data.Typeable
-- import qualified Data.Vector as V
-- import Frames.InCore (VectorFor)
-- import Frames
-- data ZipT = ZipUS Int Int Int Int Int
-- | ZipWorld Char Char Char Char Char
-- deriving (Eq, Ord, Show, Typeable)
-- type instance VectorFor ZipT = V.Vector
-- instance Readable ZipT where
-- fromText t
-- | T.length t == 5 = let cs@[v,w,x,y,z] = T.unpack t
-- [a,b,c,d,e] = map C.digitToInt cs
-- in if all C.isDigit cs
-- then return $ ZipUS a b c d e
-- else return $ ZipWorld v w x y z
-- | otherwise = mzero
-- type MyColumns = ZipT ': CommonColumns
-- #+end_src
-- ** Splice Dump
-- The Template Haskell splices we use produce quite a lot of
-- code. The raw dumps of these splices can be hard to read, but I
-- have included some elisp code for cleaning up that output in the
-- design notes for =Frames=. Here is what we get from the
-- @@html:<code>@@tableTypes'@@html:</code>@@ splice shown above.
-- The overall structure is this:
-- - A ~Record~ type called ~User~ with all necessary columns
-- - A ~userParser~ value that overrides parsing defaults
-- - A type synonym for each column that pairs the column name with its
-- type
-- - A lens to work with each column on any given row
-- Remember that for CSV files that include a header, the splice you
-- write in your code need not include the column names or separator
-- character.
-- -- #+begin_src haskell
-- tableTypes'
-- (rowGen
-- {rowTypeName = "User",
-- columnNames = ["user id", "age", "gender", "occupation",
-- "zip code"],
-- separator = "|"})
-- "data/ml-100k/u.user"
-- ======>
-- type User =
-- Record ["user id" :-> Int, "age" :-> Int, "gender" :-> Text, "occupation" :-> Text, "zip code" :-> Text]
-- userParser :: ParserOptions
-- userParser
-- = ParserOptions
-- (Just
-- (map
-- T.pack
-- ["user id", "age", "gender", "occupation", "zip code"]))
-- (T.pack "|")
-- type UserId = "user id" :-> Int
-- userId ::
-- forall f_adkB rs_adkC. (Functor f_adkB,
-- RElem UserId rs_adkC (RIndex UserId rs_adkC)) =>
-- (Int -> f_adkB Int) -> Record rs_adkC -> f_adkB (Record rs_adkC)
-- userId = rlens (Proxy :: Proxy UserId)
-- userId' ::
-- forall g_adkD f_adkE rs_adkF. (Functor f_adkE,
-- Functor g_adkD,
-- RElem UserId rs_adkF (RIndex UserId rs_adkF)) =>
-- (g_adkD UserId -> f_adkE (g_adkD UserId))
-- -> Rec g_adkD rs_adkF -> f_adkE (Rec g_adkD rs_adkF)
-- userId' = rlens' (Proxy :: Proxy UserId)
-- type Age = "age" :-> Int
-- age ::
-- forall f_adkG rs_adkH. (Functor f_adkG,
-- RElem Age rs_adkH (RIndex Age rs_adkH)) =>
-- (Int -> f_adkG Int) -> Record rs_adkH -> f_adkG (Record rs_adkH)
-- age = rlens (Proxy :: Proxy Age)
-- age' ::
-- forall g_adkI f_adkJ rs_adkK. (Functor f_adkJ,
-- Functor g_adkI,
-- RElem Age rs_adkK (RIndex Age rs_adkK)) =>
-- (g_adkI Age -> f_adkJ (g_adkI Age))
-- -> Rec g_adkI rs_adkK -> f_adkJ (Rec g_adkI rs_adkK)
-- age' = rlens' (Proxy :: Proxy Age)
-- type Gender = "gender" :-> Text
-- gender ::
-- forall f_adkL rs_adkM. (Functor f_adkL,
-- RElem Gender rs_adkM (RIndex Gender rs_adkM)) =>
-- (Text -> f_adkL Text) -> Record rs_adkM -> f_adkL (Record rs_adkM)
-- gender = rlens (Proxy :: Proxy Gender)
-- gender' ::
-- forall g_adkN f_adkO rs_adkP. (Functor f_adkO,
-- Functor g_adkN,
-- RElem Gender rs_adkP (RIndex Gender rs_adkP)) =>
-- (g_adkN Gender -> f_adkO (g_adkN Gender))
-- -> Rec g_adkN rs_adkP -> f_adkO (Rec g_adkN rs_adkP)
-- gender' = rlens' (Proxy :: Proxy Gender)
-- type Occupation = "occupation" :-> Text
-- occupation ::
-- forall f_adkQ rs_adkR. (Functor f_adkQ,
-- RElem Occupation rs_adkR (RIndex Occupation rs_adkR)) =>
-- (Text -> f_adkQ Text) -> Record rs_adkR -> f_adkQ (Record rs_adkR)
-- occupation = rlens (Proxy :: Proxy Occupation)
-- occupation' ::
-- forall g_adkS f_adkT rs_adkU. (Functor f_adkT,
-- Functor g_adkS,
-- RElem Occupation rs_adkU (RIndex Occupation rs_adkU)) =>
-- (g_adkS Occupation -> f_adkT (g_adkS Occupation))
-- -> Rec g_adkS rs_adkU -> f_adkT (Rec g_adkS rs_adkU)
-- occupation' = rlens' (Proxy :: Proxy Occupation)
-- type ZipCode = "zip code" :-> Text
-- zipCode ::
-- forall f_adkV rs_adkW. (Functor f_adkV,
-- RElem ZipCode rs_adkW (RIndex ZipCode rs_adkW)) =>
-- (Text -> f_adkV Text) -> Record rs_adkW -> f_adkV (Record rs_adkW)
-- zipCode = rlens (Proxy :: Proxy ZipCode)
-- zipCode' ::
-- forall g_adkX f_adkY rs_adkZ. (Functor f_adkY,
-- Functor g_adkX,
-- RElem ZipCode rs_adkZ (RIndex ZipCode rs_adkZ)) =>
-- (g_adkX ZipCode -> f_adkY (g_adkX ZipCode))
-- -> Rec g_adkX rs_adkZ -> f_adkY (Rec g_adkX rs_adkZ)
-- zipCode' = rlens' (Proxy :: Proxy ZipCode)
-- #+end_src
-- ** Thanks
-- Thanks to Greg Hale and Ben Gamari for reviewing early drafts of this document.
-- #+DATE:
-- #+TITLE: Frames Tutorial
-- #+OPTIONS: html-link-use-abs-url:nil html-postamble:nil
| codygman/Frames | demo/Tutorial.hs | bsd-3-clause | 28,603 | 0 | 11 | 6,394 | 1,478 | 1,037 | 441 | 67 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
--
-- RCC.hs --- the portion of the RCC (Reset and Clock Control) peripehral common
-- to the entire STM32 series (was prev based on F405, its possible some of
-- these are wrong for other chips! but i think i got it right.)
--
-- Copyright (C) 2013, Galois, Inc.
-- All Rights Reserved.
--
module Ivory.BSP.STM32.Peripheral.RCC
( RCC(..)
, rcc
, module Ivory.BSP.STM32.Peripheral.RCC.Regs
, module Ivory.BSP.STM32.Peripheral.RCC.RegTypes
) where
import Ivory.HW
import Ivory.BSP.STM32.MemoryMap (rcc_periph_base)
import Ivory.BSP.STM32.Peripheral.RCC.Regs
import Ivory.BSP.STM32.Peripheral.RCC.RegTypes
data RCC =
RCC
{ rcc_reg_cr :: BitDataReg RCC_CR
, rcc_reg_pllcfgr :: BitDataReg RCC_PLLCFGR
, rcc_reg_cfgr :: BitDataReg RCC_CFGR
, rcc_reg_cir :: BitDataReg RCC_CIR
, rcc_reg_apb1enr :: BitDataReg RCC_APB1ENR
}
rcc :: RCC
rcc = RCC
{ rcc_reg_cr = mkBitDataRegNamed (rcc_periph_base + 0x00) "rcc_cr"
, rcc_reg_pllcfgr = mkBitDataRegNamed (rcc_periph_base + 0x04) "rcc_pllcfgr"
, rcc_reg_cfgr = mkBitDataRegNamed (rcc_periph_base + 0x08) "rcc_cfgr"
, rcc_reg_cir = mkBitDataRegNamed (rcc_periph_base + 0x0c) "rcc_cir"
, rcc_reg_apb1enr = mkBitDataRegNamed (rcc_periph_base + 0x40) "rcc_apb1enr"
}
| GaloisInc/ivory-tower-stm32 | ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/RCC.hs | bsd-3-clause | 1,417 | 0 | 9 | 258 | 244 | 155 | 89 | 27 | 1 |
-- | This module re-export useful top-level definitions.
module Tct.Its (module M) where
import Tct.Its.Config as M (runIts, ItsConfig, itsConfig)
import Tct.Its.Data.Problem as M (Its (..), ItsStrategy, ItsDeclaration)
import Tct.Its.Strategies as M
| ComputationWithBoundedResources/tct-its | src/Tct/Its.hs | bsd-3-clause | 261 | 0 | 6 | 42 | 64 | 45 | 19 | 4 | 0 |
module Addition where
import Test.Hspec
import Test.QuickCheck
main :: IO ()
main = do
hspec $
describe "Addition" $ do
it "15 devided by 3 is 5" $ do
devideBy 15 3 `shouldBe` (5, 0)
it "22 devided by 5 is 4 remainder 2" $ do
devideBy 22 5 `shouldBe` (4, 2)
it "x + 1 is always greater than x" $ do
-- run quickcheck through hspec
property $ \x -> x + 1 > (x :: Integer)
-- run property check without hspec
quickCheck prop_additionGreater
prop_additionGreater :: Int -> Bool
prop_additionGreater x = x + 1 > x
devideBy :: Integer -> Integer -> (Integer, Integer)
devideBy num denom = go num denom 0
where go n d count
| n < d = (count, n)
| otherwise = go (n - d) d (count + 1)
trivialInt :: Gen Int
trivialInt = return 1
oneThroughThree :: Gen Int
oneThroughThree = elements [1..1000]
genBool :: Gen Bool
genBool = choose (False, True)
genBool' :: Gen Bool
genBool' = elements [False, True]
genOrdering :: Gen Ordering
genOrdering = elements [LT, EQ, GT]
genChar :: Gen Char
genChar = elements ['a'..'z']
genTupple :: (Arbitrary a, Arbitrary b) => Gen (a, b)
genTupple = do
a <- arbitrary
b <- arbitrary
return (a, b)
data Person = Person String Int deriving Show
genPerson :: Gen Person
genPerson = do
name <- arbitrary :: Gen String
age <- arbitrary :: Gen Int
return $ Person name age
genEither :: (Arbitrary a, Arbitrary b) => Gen (Either a b)
genEither = do
a <- arbitrary
b <- arbitrary
elements [Left a, Right b]
genMaybe :: Arbitrary a => Gen (Maybe a)
genMaybe = do
a <- arbitrary
elements [Nothing, Just a]
genMaybe' :: Arbitrary a => Gen (Maybe a)
genMaybe' = do
a <- arbitrary
frequency [ (1, return Nothing)
, (3, return $ Just a)]
| chengzh2008/hpffp | src/ch14-Testing/addition/Addition.hs | bsd-3-clause | 1,782 | 0 | 16 | 449 | 703 | 358 | 345 | 58 | 1 |
{- Parses the ARFF Header. -}
module ARFFParser.Header (
parseHeader
) where
import ARFFParser.Adecls (parseAdecls)
import ARFFParser.AST
import ARFFParser.BasicCombinators
import ARFFParser.Junk
import ARFFParser.Value (parseStringLit)
import Control.Applicative (liftA2)
parseHeader :: Parser Char Header
parseHeader
= declaration "relation" >> liftA2 Header parseStringLit parseAdecls
| shirazb/orpiva-k-means | src/ARFFParser/Header.hs | bsd-3-clause | 395 | 0 | 6 | 48 | 86 | 49 | 37 | 11 | 1 |
{-#LANGUAGE RecordWildCards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
module DirectoryServer where
import Network hiding (accept, sClose)
import Network.Socket hiding (send, recv, sendTo, recvFrom, Broadcast)
import Network.Socket.ByteString
import Data.ByteString.Char8 (pack, unpack)
import System.Environment
import System.IO
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import Control.Monad (forever, when, join)
import Data.List.Split
import Data.Word
import Text.Printf (printf)
import System.Directory
import Data.Map (Map) -- from the `containers` library
import Data.Time
import System.Random
import qualified Data.Map as M
type Uuid = Int
type Address = String
type Port = String
type Filename = String
type Timestamp = IO String
--Server data type allows me to pass address and port details easily
data DirectoryServer = DirectoryServer
{ address :: String
, port :: String
, filemappings :: TVar (M.Map Filename Filemapping)
, fileservers :: TVar (M.Map Uuid Fileserver)
, fileservercount :: TVar Int
}
--Constructor
newDirectoryServer :: String -> String -> IO DirectoryServer
newDirectoryServer address port = atomically $ do DirectoryServer <$> return address <*> return port <*> newTVar M.empty <*> newTVar M.empty <*> newTVar 0
addFilemapping :: DirectoryServer -> Filename -> Uuid -> Address -> Port -> Timestamp -> STM ()
addFilemapping DirectoryServer{..} filename uuid fmaddress fmport timestamp = do
fm <- newFilemapping filename uuid fmaddress fmport timestamp
modifyTVar filemappings . M.insert filename $ fm
addFileserver :: DirectoryServer -> Uuid -> Address -> Port -> STM ()
addFileserver DirectoryServer{..} uuid fsaddress fsport = do
fs <- newFileserver uuid fsaddress fsport
modifyTVar fileservers . M.insert uuid $ fs
lookupFilemapping :: DirectoryServer -> Filename -> STM (Maybe Filemapping)
lookupFilemapping DirectoryServer{..} filename = M.lookup filename <$> readTVar filemappings
lookupFileserver :: DirectoryServer -> Uuid -> STM (Maybe Fileserver)
lookupFileserver DirectoryServer{..} uuid = M.lookup uuid <$> readTVar fileservers
data Filemapping = Filemapping
{ fmfilename :: Filename
, fmuuid :: Uuid
, fmaddress :: Address
, fmport :: Port
, fmtimestamp :: Timestamp
}
newFilemapping :: Filename -> Uuid -> Address -> Port -> Timestamp -> STM Filemapping
newFilemapping fmfilename fmuuid fmaddress fmport fmtimestamp = Filemapping <$> return fmfilename <*> return fmuuid <*> return fmaddress <*> return fmport <*> return fmtimestamp
getFilemappinguuid :: Filemapping -> Uuid
getFilemappinguuid Filemapping{..} = fmuuid
getFilemappingaddress :: Filemapping -> Address
getFilemappingaddress Filemapping{..} = fmaddress
getFilemappingport :: Filemapping -> Port
getFilemappingport Filemapping{..} = fmport
getFilemappingtimestamp :: Filemapping -> Timestamp
getFilemappingtimestamp Filemapping{..} = fmtimestamp
data Fileserver = Fileserver
{ fsuuid :: Uuid
, fsaddress :: HostName
, fsport :: Port
}
newFileserver :: Uuid -> Address -> Port -> STM Fileserver
newFileserver fsuuid fsaddress fsport = Fileserver <$> return fsuuid <*> return fsaddress <*> return fsport
getFileserveraddress :: Fileserver -> HostName
getFileserveraddress Fileserver{..} = fsaddress
getFileserverport :: Fileserver -> Port
getFileserverport Fileserver{..} = fsport
--4 is easy for testing the pooling
maxnumThreads = 4
serverport :: String
serverport = "7008"
serverhost :: String
serverhost = "localhost"
dirrun:: IO ()
dirrun = withSocketsDo $ do
--Command line arguments for port and address
--args <- getArgs
server <- newDirectoryServer serverhost serverport
--sock <- listenOn (PortNumber (fromIntegral serverport))
addrinfos <- getAddrInfo
(Just (defaultHints {addrFlags = [AI_PASSIVE]}))
Nothing (Just serverport)
let serveraddr = head addrinfos
sock <- socket (addrFamily serveraddr) Stream defaultProtocol
bindSocket sock (addrAddress serveraddr)
listen sock 5
_ <- printf "Listening on port %s\n" serverport
--Listen on port from command line argument
--New Abstract FIFO Channel
chan <- newChan
--Tvars are variables Stored in memory, this way we can access the numThreads from any method
numThreads <- atomically $ newTVar 0
--Spawns a new thread to handle the clientconnectHandler method, passes socket, channel, numThreads and server
forkIO $ clientconnectHandler sock chan numThreads server
--Calls the mainHandler which will monitor the FIFO channel
mainHandler sock chan
mainHandler :: Socket -> Chan String -> IO ()
mainHandler sock chan = do
--Read current message on the FIFO channel
chanMsg <- readChan chan
--If KILL_SERVICE, stop mainHandler running, If anything else, call mainHandler again, keeping the service running
case (chanMsg) of
("KILL_SERVICE") -> putStrLn "Terminating the Service!"
_ -> mainHandler sock chan
clientconnectHandler :: Socket -> Chan String -> TVar Int -> DirectoryServer -> IO ()
clientconnectHandler sock chan numThreads server = do
--Accept the socket which returns a handle, host and port
--(handle, host, port) <- accept sock
(s,a) <- accept sock
--handle <- socketToHandle s ReadWriteMode
--Read numThreads from memory and print it on server console
count <- atomically $ readTVar numThreads
putStrLn $ "numThreads = " ++ show count
--If there are still threads remaining create new thread and increment (exception if thread is lost -> decrement), else tell user capacity has been reached
if (count < maxnumThreads) then do
forkFinally (clientHandler s chan server) (\_ -> atomically $ decrementTVar numThreads)
atomically $ incrementTVar numThreads
else do
send s (pack ("Maximum number of threads in use. try again soon"++"\n\n"))
sClose s
clientconnectHandler sock chan numThreads server
clientHandler :: Socket -> Chan String -> DirectoryServer -> IO ()
clientHandler sock chan server@DirectoryServer{..} =
forever $ do
message <- recv sock 1024
let msg = unpack message
print $ msg ++ "!ENDLINE!"
let cmd = head $ words $ head $ splitOn ":" msg
print cmd
case cmd of
("HELO") -> heloCommand sock server $ (words msg) !! 1
("KILL_SERVICE") -> killCommand chan sock
("DOWNLOAD") -> downloadCommand sock server msg
("JOIN") -> joinCommand sock server msg
_ -> do send sock (pack ("Unknown Command - " ++ msg ++ "\n\n")) ; return ()
--Function called when HELO text command recieved
heloCommand :: Socket -> DirectoryServer -> String -> IO ()
heloCommand sock DirectoryServer{..} msg = do
send sock $ pack $ "HELO " ++ msg ++ "\n" ++
"IP:" ++ "192.168.6.129" ++ "\n" ++
"Port:" ++ port ++ "\n" ++
"StudentID:12306421\n\n"
return ()
killCommand :: Chan String -> Socket -> IO ()
killCommand chan sock = do
send sock $ pack $ "Service is now terminating!"
writeChan chan "KILL_SERVICE"
downloadCommand :: Socket -> DirectoryServer ->String -> IO ()
downloadCommand sock server@DirectoryServer{..} command = do
let clines = splitOn "\\n" command
filename = (splitOn ":" $ clines !! 1) !! 1
fm <- atomically $ lookupFilemapping server $ filename
case fm of
Nothing -> send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\n" ++
"STATUS: " ++ "File not found" ++ "\n\n"
Just fm -> do downloadmsg filename (getFilemappingaddress fm) (getFilemappingport fm) sock
return ()
downloadmsg :: String -> String -> String -> Socket -> IO (Int)
downloadmsg filename host port sock = do
addrInfo <- getAddrInfo Nothing (Just host) (Just $ show port)
let serverAddr = head addrInfo
clsock <- socket (addrFamily serverAddr) Stream defaultProtocol
connect clsock (addrAddress serverAddr)
sClose clsock
send clsock $ pack $ "DOWNLOAD:FILE" ++ "\\n" ++
"FILENAME:" ++ filename ++ "\n"
resp <- recv clsock 1024
let msg = unpack resp
let clines = splitOn "\\n" msg
fdata = (splitOn ":" $ clines !! 1) !! 1
send sock $ pack $ "DOWNLOAD: " ++ filename ++ "\\n" ++
"DATA: " ++ fdata ++ "\n\n"
uploadCommand :: Socket -> DirectoryServer ->String -> IO ()
uploadCommand sock server@DirectoryServer{..} command = do
let clines = splitOn "\\n" command
filename = (splitOn ":" $ clines !! 1) !! 1
fdata = (splitOn ":" $ clines !! 2) !! 1
fm <- atomically $ lookupFilemapping server filename
case fm of
Just fm -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n" ++
"STATUS: " ++ "File Already Exists" ++ "\n\n"
Nothing -> do numfs <- atomically $ M.size <$> readTVar fileservers
rand <- randomRIO (0, numfs)
fs <- atomically $ lookupFileserver server rand
case fs of
Nothing -> send sock $ pack $ "UPLOAD: " ++ filename ++ "\n"++
"FAILED: " ++ "No valid Fileserver found to host" ++ "\n\n"
Just fs -> do uploadmsg sock filename fdata fs rand server
return ()
uploadmsg :: Socket -> String -> String -> Fileserver -> Int -> DirectoryServer -> IO (Int )
uploadmsg sock filename fdata fs rand server@DirectoryServer{..}= do
addrInfo <- getAddrInfo Nothing (Just (getFileserveraddress fs)) (Just $ show (getFileserverport fs))
let serverAddr = head addrInfo
clsock <- socket (addrFamily serverAddr) Stream defaultProtocol
connect clsock (addrAddress serverAddr)
send clsock $ pack $ "UPLOAD:FILE" ++ "\\n" ++
"FILENAME:" ++ filename ++ "\n" ++
"DATA:" ++ fdata ++ "\n"
resp <- recv clsock 1024
let msg = unpack resp
let clines = splitOn "\\n" msg
status = (splitOn ":" $ clines !! 1) !! 1
send sock $ pack $ "UPLOAD: " ++ filename ++ "\\n" ++
"STATUS: " ++ status ++ "\n\n"
fm <- atomically $ newFilemapping filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime)
atomically $ addFilemapping server filename rand (getFileserveraddress fs) (getFileserverport fs) (fmap show getZonedTime)
return (0)
joinCommand :: Socket -> DirectoryServer ->String -> IO ()
joinCommand sock server@DirectoryServer{..} command = do
let clines = splitOn "\\n" command
newaddress = (splitOn ":" $ clines !! 1) !! 1
newport = (splitOn ":" $ clines !! 2) !! 1
nodeID <- atomically $ readTVar fileservercount
fs <- atomically $ newFileserver nodeID newaddress newport
atomically $ addFileserver server nodeID newaddress newport
atomically $ incrementFileserverCount fileservercount
send sock $ pack $ "JOINED DISTRIBUTED FILE SERVICE" ++ "\n\n"
return ()
--Increment Tvar stored in memory i.e. numThreads
incrementTVar :: TVar Int -> STM ()
incrementTVar tv = modifyTVar tv ((+) 1)
--Decrement Tvar stored in memory i.e. numThreads
decrementTVar :: TVar Int -> STM ()
decrementTVar tv = modifyTVar tv (subtract 1)
incrementFileserverCount :: TVar Int -> STM ()
incrementFileserverCount tv = modifyTVar tv ((+) 1)
| Garygunn94/DFS | .stack-work/intero/intero18496rlb.hs | bsd-3-clause | 11,637 | 266 | 15 | 2,632 | 3,095 | 1,598 | 1,497 | 215 | 5 |
{-# LANGUAGE CPP, OverloadedStrings #-}
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
module Language.Hakaru.Parser.Parser where
import Prelude hiding (Real)
#if __GLASGOW_HASKELL__ < 710
import Data.Functor ((<$>), (<$))
import Control.Applicative (Applicative(..))
#endif
import qualified Control.Monad as M
import Data.Functor.Identity
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Ratio ((%))
import Data.Char (digitToInt)
import Text.Parsec hiding (Empty)
import Text.Parsec.Text () -- instances only
import Text.Parsec.Indentation
import Text.Parsec.Indentation.Char
import qualified Text.Parsec.Indentation.Token as ITok
import qualified Text.Parsec.Expr as Ex
import qualified Text.Parsec.Token as Tok
import Language.Hakaru.Parser.AST
ops, types, names :: [String]
ops = ["+","*","-","^", "**", ":",".", "<~","==", "=", "_", "<|>"]
types = ["->"]
names = ["def", "fn", "if", "else", "∞", "expect", "observe",
"return", "match", "integrate", "summate", "product",
"data", "import"]
type ParserStream = IndentStream (CharIndentStream Text)
type Parser = ParsecT ParserStream () Identity
type Operator a = Ex.Operator ParserStream () Identity a
type OperatorTable a = [[Operator a]]
style :: Tok.GenLanguageDef ParserStream st Identity
style = ITok.makeIndentLanguageDef $ Tok.LanguageDef
{ Tok.commentStart = ""
, Tok.commentEnd = ""
, Tok.nestedComments = True
, Tok.identStart = letter <|> char '_'
, Tok.identLetter = alphaNum <|> oneOf "_'"
, Tok.opStart = oneOf "!$%&*+./<=>?@\\^|-~"
, Tok.opLetter = oneOf "!$%&*+./<=>?@\\^|-~"
, Tok.caseSensitive = True
, Tok.commentLine = "#"
, Tok.reservedOpNames = ops ++ types
, Tok.reservedNames = names
}
comments :: Parser ()
comments = string "#"
*> manyTill anyChar newline
*> return ()
emptyLine :: Parser ()
emptyLine = newline *> return ()
lexer :: Tok.GenTokenParser ParserStream () Identity
lexer = ITok.makeTokenParser style
whiteSpace :: Parser ()
whiteSpace = Tok.whiteSpace lexer
decimal :: Parser Integer
decimal = Tok.decimal lexer
integer :: Parser Integer
integer = Tok.integer lexer
float :: Parser Rational
float = (decimal >>= fractExponent) <* whiteSpace
fractFloat :: Integer -> Parser (Either Integer Rational)
fractFloat n = fractExponent n >>= return . Right
fractExponent :: Integer -> Parser Rational
fractExponent n = do{ fract <- fraction
; expo <- option 1 exponent'
; return ((fromInteger n + fract)*expo)
}
<|>
do{ expo <- exponent'
; return ((fromInteger n)*expo)
}
fraction :: Parser Rational
fraction = do{ _ <- char '.'
; digits <- many1 digit <?> "fraction"
; return (foldr op 0 digits)
}
<?> "fraction"
where
op d f = (f + fromIntegral (digitToInt d))/10
exponent' :: Parser Rational
exponent' = do{ _ <- oneOf "eE"
; f <- sign
; e <- decimal <?> "exponent"
; return (power (f e))
}
<?> "exponent"
where
power e | e < 0 = 1.0/power(-e)
| otherwise = fromInteger (10^e)
sign = (char '-' >> return negate)
<|> (char '+' >> return id)
<|> return id
parens :: Parser a -> Parser a
parens = Tok.parens lexer . localIndentation Any
braces :: Parser a -> Parser a
braces = Tok.parens lexer . localIndentation Any
brackets :: Parser a -> Parser a
brackets = Tok.brackets lexer . localIndentation Any
commaSep :: Parser a -> Parser [a]
commaSep = Tok.commaSep lexer
semiSep :: Parser a -> Parser [a]
semiSep = Tok.semiSep lexer
semiSep1 :: Parser a -> Parser [a]
semiSep1 = Tok.semiSep1 lexer
identifier :: Parser Text
identifier = M.liftM Text.pack $ Tok.identifier lexer
reserved :: String -> Parser ()
reserved = Tok.reserved lexer
reservedOp :: String -> Parser ()
reservedOp = Tok.reservedOp lexer
symbol :: Text -> Parser Text
symbol = M.liftM Text.pack . Tok.symbol lexer . Text.unpack
app1 :: Text -> AST' Text -> AST' Text
app1 s x@(WithMeta _ m) = WithMeta (Var s `App` x) m
app1 s x = Var s `App` x
app2 :: Text -> AST' Text -> AST' Text -> AST' Text
app2 s x y = Var s `App` x `App` y
-- | Smart constructor for divide
divide :: AST' Text -> AST' Text -> AST' Text
divide (ULiteral x') (ULiteral y') = ULiteral (go x' y')
where go :: Literal' -> Literal' -> Literal'
go (Nat x) (Nat y) = Prob (x % y)
go x y = Real (litToRat x / litToRat y)
litToRat :: Literal' -> Rational
litToRat (Nat x) = toRational x
litToRat (Int x) = toRational x
litToRat (Prob x) = toRational x
litToRat (Real x) = toRational x
divide x y = NaryOp Prod [x, app1 "recip" y]
binop :: Text -> AST' Text -> AST' Text -> AST' Text
binop s x y
| s == "+" = NaryOp Sum [x, y]
| s == "-" = NaryOp Sum [x, app1 "negate" y]
| s == "*" = NaryOp Prod [x, y]
| s == "/" = x `divide` y
| s == "<" = app2 "less" x y
| s == ">" = app2 "less" y x
| s == "==" = app2 "equal" x y
| s == "<=" = NaryOp Or [ app2 "less" x y
, app2 "equal" x y]
| s == ">=" = NaryOp Or [ app2 "less" y x
, app2 "equal" x y]
| s == "&&" = NaryOp And [x, y]
| s == "<|>" = Msum [x, y]
| otherwise = app2 s x y
binary :: String -> Ex.Assoc -> Operator (AST' Text)
binary s = Ex.Infix (binop (Text.pack s) <$ reservedOp s)
prefix :: String -> (a -> a) -> Operator a
prefix s f = Ex.Prefix (f <$ reservedOp s)
postfix :: Parser (a -> a) -> Operator a
postfix p = Ex.Postfix . chainl1 p . return $ flip (.)
table :: OperatorTable (AST' Text)
table =
[ [ postfix array_index ]
, [ prefix "+" id ]
, [ binary "^" Ex.AssocRight
, binary "**" Ex.AssocRight]
, [ binary "*" Ex.AssocLeft
, binary "/" Ex.AssocLeft]
, [ binary "+" Ex.AssocLeft
, binary "-" Ex.AssocLeft
, prefix "-" (app1 "negate")]
-- TODO: add "/="
-- TODO: do you *really* mean AssocLeft? Shouldn't they be non-assoc?
, [ postfix ann_expr ]
, [ binary "<|>" Ex.AssocRight]
, [ binary "<" Ex.AssocLeft
, binary ">" Ex.AssocLeft
, binary "<=" Ex.AssocLeft
, binary ">=" Ex.AssocLeft
, binary "==" Ex.AssocLeft]
, [ binary "&&" Ex.AssocLeft]]
unit_ :: Parser (AST' a)
unit_ = Unit <$ symbol "()"
empty_ :: Parser (AST' a)
empty_ = Empty <$ symbol "[]"
int :: Parser (AST' a)
int = do
n <- integer
return $
if n < 0
then ULiteral $ Int n
else ULiteral $ Nat n
floating :: Parser (AST' a)
floating = do
sign <- option '+' (oneOf "+-")
n <- float
return $
case sign of
'-' -> ULiteral $ Real (negate n)
'+' -> ULiteral $ Prob n
_ -> error "floating: the impossible happened"
inf_ :: Parser (AST' Text)
inf_ = reserved "∞" *> return Infinity'
var :: Parser (AST' Text)
var = Var <$> identifier
pairs :: Parser (AST' Text)
pairs = foldr1 Pair <$> parens (commaSep expr)
type_var :: Parser TypeAST'
type_var = TypeVar <$> identifier
type_app :: Parser TypeAST'
type_app = TypeApp <$> identifier <*> parens (commaSep type_expr)
type_fun :: Parser TypeAST'
type_fun =
chainr1
( try type_app
<|> try type_var
<|> parens type_fun)
(TypeFun <$ reservedOp "->")
type_expr :: Parser TypeAST'
type_expr = try type_fun
<|> try type_app
<|> try type_var
<|> parens type_expr
ann_expr :: Parser (AST' Text -> AST' Text)
ann_expr = reservedOp "." *> (flip Ann <$> type_expr)
pdat_expr :: Parser (PDatum Text)
pdat_expr = DV <$> identifier <*> parens (commaSep pat_expr)
pat_expr :: Parser (Pattern' Text)
pat_expr = try (PData' <$> pdat_expr)
<|> (PData' <$> (DV "pair" <$> parens (commaSep pat_expr)))
<|> (PWild' <$ reservedOp "_")
<|> (PVar' <$> identifier)
-- | Blocks are indicated by colons, and must be indented.
blockOfMany :: Parser a -> Parser [a]
blockOfMany p = do
reservedOp ":"
localIndentation Gt (many $ absoluteIndentation p)
-- | Semiblocks are like blocks, but indentation is optional. Also,
-- there are only 'expr' semiblocks.
semiblockExpr :: Parser (AST' Text)
semiblockExpr = reservedOp ":" *> localIndentation Ge expr
-- | Pseudoblocks seem like semiblocks, but actually they aren't
-- indented.
--
-- TODO: do we actually want this in our grammar, or did we really
-- mean to use 'semiblockExpr' instead?
pseudoblockExpr :: Parser (AST' Text)
pseudoblockExpr = reservedOp ":" *> expr
branch_expr :: Parser (Branch' Text)
branch_expr = Branch' <$> pat_expr <*> semiblockExpr
match_expr :: Parser (AST' Text)
match_expr =
reserved "match"
*> (Case
<$> expr
<*> blockOfMany branch_expr
)
integrate_expr :: Parser (AST' Text)
integrate_expr =
reserved "integrate"
*> (Integrate
<$> identifier
<* symbol "from"
<*> expr
<* symbol "to"
<*> expr
<*> semiblockExpr
)
summate_expr :: Parser (AST' Text)
summate_expr =
reserved "summate"
*> (Summate
<$> identifier
<* symbol "from"
<*> expr
<* symbol "to"
<*> expr
<*> semiblockExpr
)
product_expr :: Parser (AST' Text)
product_expr =
reserved "product"
*> (Product
<$> identifier
<* symbol "from"
<*> expr
<* symbol "to"
<*> expr
<*> semiblockExpr
)
expect_expr :: Parser (AST' Text)
expect_expr =
reserved "expect"
*> (Expect
<$> identifier
<*> expr
<*> semiblockExpr
)
observe_expr :: Parser (AST' Text)
observe_expr =
reserved "observe"
*> (Observe
<$> expr
<*> expr
)
array_expr :: Parser (AST' Text)
array_expr =
reserved "array"
*> (Array
<$> identifier
<* symbol "of"
<*> expr
<*> semiblockExpr
)
array_index :: Parser (AST' Text -> AST' Text)
array_index = flip Index <$> brackets expr
array_literal :: Parser (AST' Text)
array_literal = checkEmpty <$> brackets (commaSep expr)
where checkEmpty [] = Empty
checkEmpty xs = ArrayLiteral xs
plate_expr :: Parser (AST' Text)
plate_expr =
reserved "plate"
*> (Plate
<$> identifier
<* symbol "of"
<*> expr
<*> semiblockExpr
)
chain_expr :: Parser (AST' Text)
chain_expr =
reserved "chain"
*> (Chain
<$> identifier
<*> expr
<*> expr
<*> semiblockExpr
)
if_expr :: Parser (AST' Text)
if_expr =
reserved "if"
*> (If
<$> localIndentation Ge expr
<*> semiblockExpr
<* reserved "else"
<*> semiblockExpr
)
lam_expr :: Parser (AST' Text)
lam_expr =
reserved "fn"
*> (Lam
<$> identifier
<*> type_expr
<*> semiblockExpr
)
bind_expr :: Parser (AST' Text)
bind_expr = Bind
<$> identifier
<* reservedOp "<~"
<*> expr
<*> expr
let_expr :: Parser (AST' Text)
let_expr = Let
<$> identifier
<* reservedOp "="
<*> expr
<*> expr
def_expr :: Parser (AST' Text)
def_expr = do
reserved "def"
name <- identifier
vars <- parens (commaSep defarg)
bodyTyp <- optionMaybe type_expr
body <- semiblockExpr
let body' = foldr (\(var', varTyp) e -> Lam var' varTyp e) body vars
typ = foldr TypeFun <$> bodyTyp <*> return (map snd vars)
Let name (maybe id (flip Ann) typ body')
<$> expr -- the \"rest\"; i.e., where the 'def' is in scope
defarg :: Parser (Text, TypeAST')
defarg = (,) <$> identifier <*> type_expr
call_expr :: Parser (AST' Text)
call_expr =
foldl App
<$> (Var <$> identifier)
<*> parens (commaSep expr)
return_expr :: Parser (AST' Text)
return_expr = do
reserved "return" <|> reserved "dirac"
Dirac <$> expr
term :: Parser (AST' Text)
term = try if_expr
<|> try return_expr
<|> try lam_expr
<|> try def_expr
<|> try match_expr
<|> try data_expr
<|> try integrate_expr
<|> try summate_expr
<|> try product_expr
<|> try expect_expr
<|> try observe_expr
<|> try array_expr
<|> try plate_expr
<|> try chain_expr
<|> try let_expr
<|> try bind_expr
<|> try call_expr
<|> try array_literal
<|> try floating
<|> try inf_
<|> try unit_
<|> try empty_
<|> try int
<|> try var
<|> try pairs
<|> parens expr
<?> "an expression"
expr :: Parser (AST' Text)
expr = withPos (Ex.buildExpressionParser table (withPos term) <?> "an expression")
indentConfig :: Text -> ParserStream
indentConfig =
mkIndentStream 0 infIndentation True Ge . mkCharIndentStream
parseHakaru :: Text -> Either ParseError (AST' Text)
parseHakaru =
runParser (skipMany (comments <|> emptyLine) *>
expr <* eof) () "<input>" . indentConfig
parseHakaruWithImports :: Text -> Either ParseError (ASTWithImport' Text)
parseHakaruWithImports =
runParser (skipMany (comments <|> emptyLine) *>
exprWithImport <* eof) () "<input>" . indentConfig . Text.strip
withPos :: Parser (AST' a) -> Parser (AST' a)
withPos x = do
s <- getPosition
x' <- x
e <- getPosition
return $ WithMeta x' (SourceSpan s e)
{-
user-defined types:
data either(a,b):
left(a)
right(a)
data maybe(a):
nothing
just(a)
-}
data_expr :: Parser (AST' Text)
data_expr = do
reserved "data"
ident <- identifier
typvars <- parens (commaSep identifier)
ts <- blockOfMany (try type_app <|> type_var)
e <- expr
return (Data ident typvars ts e)
import_expr :: Parser (Import Text)
import_expr =
reserved "import" *> (Import <$> identifier)
exprWithImport :: Parser (ASTWithImport' Text)
exprWithImport = ASTWithImport' <$> (many import_expr) <*> expr
| zaxtax/hakaru | haskell/Language/Hakaru/Parser/Parser.hs | bsd-3-clause | 14,739 | 0 | 33 | 4,526 | 4,740 | 2,400 | 2,340 | 411 | 5 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Ticket.View.Form (ticketForm
) where
import Data.Maybe
import Control.Monad
import Text.Blaze.Html
import Text.Hamlet (shamlet)
import Ticket.Types (Client (..), ProductArea, Ticket (..), formatTargetDate)
ticketForm :: [Client] -> [ProductArea] -> Maybe Ticket -> Html
ticketForm clients productAreas maybeTicket = [shamlet|
<form id="ticketForm" data-parsley-validate>
<input type="text" name="ticketId" id="ticketId" value=#{fromMaybe 0 (join (ticketId <$> maybeTicket))} hidden>
<label for="title">Title
<input type="text" name="title" id="title" value=#{fromMaybe mempty (ticketTitle <$> maybeTicket)} required>
<label for="description">Description
<textarea name="description" id="description" form="ticketForm" required>#{fromMaybe mempty (ticketDescription <$> maybeTicket)}
<label for="client">Client
<select id="client" name="client">
$forall client <- clients
$if (Just (clientName client) == ((clientName . ticketClient) <$> maybeTicket))
<option value=#{clientName client} selected>#{clientName client}
$else
<option value=#{clientName client}>#{clientName client}
<input type="text" name="clientPriority" id="clientPriority" value=#{fromMaybe 0 ((ticketClientPriority) <$> maybeTicket)} hidden>
<label for="targetDate">Target Date
<input type="text" data-date-format="MM/DD/YYYY" placeholder="MM/DD/YY" name="targetDate" id="targetDate" value=#{fromMaybe mempty ((formatTargetDate . ticketTargetDate) <$> maybeTicket)} readonly required>
<label for="url">URL
<input type="text" data-parsley-type="url" name="url" id="url" value=#{fromMaybe mempty (join (ticketURL <$> maybeTicket))}>
<label for="productArea">ProductArea
<select type="text" name="productArea" id="productArea">
$forall productArea <- productAreas
$if (Just productArea == (ticketProductArea <$> maybeTicket))
<option value=#{show productArea} selected>#{show productArea}
$else
<option value=#{show productArea}>#{show productArea}
<br>
<input type="submit" value="Submit">
|]
| ExternalReality/features | src/Ticket/View/Form.hs | bsd-3-clause | 2,258 | 0 | 8 | 413 | 109 | 68 | 41 | 10 | 1 |
module Envirius.Commands.Ls (cmd) where
import Envirius.Types.Command
import Envirius.Util (listEnvs, showEnv)
cmd :: Cmd
cmd = Cmd "ls" action desc usage help
-- main command action
action :: [String] -> IO ()
action opts = do
envs <- listEnvs
let showMetaInfo = "--no-meta" `notElem` opts
case length envs of
0 -> putStrLn "No environments found."
_ -> do
putStrLn "Available environment(s):"
mapM_ (showEnv showMetaInfo) envs
-- command short name
desc :: String
desc = "List environments"
usage :: String
usage = "env-name [--plugin=version] [--plugin=version] ..."
-- help for command
help :: [String]
help = [
"Options:",
" --no-meta Do not show meta information of the environment"
]
| ekalinin/envirius.hs | src/Envirius/Commands/Ls.hs | bsd-3-clause | 776 | 0 | 14 | 191 | 186 | 101 | 85 | 22 | 2 |
{-|
Module : Data.Algorithm.PPattern.Conflict
Structription : Encapsulate a conflict
Copyright : (c) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-2017
License : MIT
Maintainer : [email protected]
Stability : experimental
Conflict for pattern matching.
-}
module Data.Algorithm.PPattern.Search.Conflict
(
-- * The @Conflict@ type
Conflict(..)
-- * Querying
, colorPoint
, threshold
)
where
import qualified Data.Algorithm.PPattern.Geometry.ColorPoint as ColorPoint
-- Encapsulate a conflict (order or value conflict).
data Conflict = HorizontalConflict {-# UNPACK #-} !ColorPoint.ColorPoint !Int
| VerticalConflict {-# UNPACK #-} !ColorPoint.ColorPoint !Int
deriving (Show)
-- Return the color point of a conflict.
colorPoint :: Conflict -> ColorPoint.ColorPoint
colorPoint (HorizontalConflict cp _) = cp
colorPoint (VerticalConflict cp _) = cp
-- Return the threshold of a conflict
threshold :: Conflict -> Int
threshold (HorizontalConflict _ t) = t
threshold (VerticalConflict _ t) = t
| vialette/ppattern | src/Data/Algorithm/PPattern/Search/Conflict.hs | mit | 1,081 | 0 | 8 | 214 | 160 | 93 | 67 | 19 | 1 |
quasiQuicksort :: (Ord a) => [a] -> [a]
quasiQuicksort [] = []
quasiQuicksort (head:tail) = smaller ++ [pivot] ++ larger
where pivot = head
smaller = filter (< pivot) (quasiQuicksort tail)
larger = filter (> pivot) (quasiQuicksort tail) | 2015-Fall-UPT-PLDA/labs | week-02/quasi-quicksort.hs | mit | 329 | 0 | 9 | 130 | 110 | 60 | 50 | 6 | 1 |
{-
Notifaika reposts notifications
from different feeds to Gitter chats.
Copyright (C) 2015 Yuriy Syrovetskiy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Data.Aeson.X (module Data.Aeson, module Data.Aeson.X) where
import Data.Aeson
import Data.ByteString.Lazy as ByteString
import Data.Monoid
decodeFile :: FromJSON a => FilePath -> IO a
decodeFile filepath = do
bytes <- ByteString.readFile filepath
let decodeResult = eitherDecode bytes
case decodeResult of
Left decodeError ->
error ("Cannot decode file \"" <> filepath <> "\": " <> decodeError)
Right value ->
return value
| cblp/notifaika | src/Data/Aeson/X.hs | gpl-3.0 | 1,263 | 0 | 14 | 287 | 138 | 72 | 66 | 13 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Monad (forM_)
import qualified Data.ByteString as SB
import Data.Maybe (fromMaybe)
import qualified Data.Text.Lazy as L
import System.Exit (exitFailure)
import System.IO (hClose, hPutStrLn, stderr)
import Text.Printf (printf)
import Data.GraphViz
import qualified Data.GraphViz.Attributes.Colors.X11 as C
import qualified Data.GraphViz.Attributes.Complete as A
import qualified Data.GraphViz.Attributes.HTML as H
import qualified Data.GraphViz.Types.Generalised as G
import Data.GraphViz.Types.Monadic
import Config
import ER
import Parse
main :: IO ()
main = do
conf <- configIO
er' <- uncurry loadER (cin conf)
case er' of
Left err -> do
hPutStrLn stderr err
exitFailure
Right er -> let dotted = dotER er
toFile h = SB.hGetContents h >>= SB.hPut (snd $ cout conf)
fmt = fromMaybe Pdf (outfmt conf)
in graphvizWithHandle Dot dotted fmt toFile
hClose (snd $ cin conf)
hClose (snd $ cout conf)
-- | Converts an entire ER-diagram from an ER file into a GraphViz graph.
dotER :: ER -> G.DotGraph L.Text
dotER er = graph' $ do
graphAttrs (graphTitle $ title er)
graphAttrs [A.RankDir A.FromLeft]
nodeAttrs [shape PlainText] -- recommended for HTML labels
edgeAttrs [ A.Color [A.toWC $ A.toColor C.Gray50] -- easier to read labels
, A.MinLen 2 -- give some breathing room
, A.Style [A.SItem A.Dashed []] -- easier to read labels, maybe?
]
forM_ (entities er) $ \e ->
node (name e) [toLabel (htmlEntity e)]
forM_ (rels er) $ \r -> do
let opts = roptions r
let rlab = A.HtmlLabel . H.Text . htmlFont opts . L.pack . show
let (l1, l2) = (A.TailLabel $ rlab $ card1 r, A.HeadLabel $ rlab $ card2 r)
let label = A.Label $ A.HtmlLabel $ H.Text $ withLabelFmt " %s " opts []
edge (entity1 r) (entity2 r) [label, l1, l2]
-- | Converts a single entity to an HTML label.
htmlEntity :: Entity -> H.Label
htmlEntity e = H.Table H.HTable
{ H.tableFontAttrs = Just $ optionsTo optToFont $ eoptions e
, H.tableAttrs = optionsTo optToHtml (eoptions e)
, H.tableRows = rows
}
where rows = headerRow : map htmlAttr (attribs e)
headerRow = H.Cells [H.LabelCell [] $ H.Text text]
text = withLabelFmt " [%s]" (hoptions e) $ bold hname
hname = htmlFont (hoptions e) (name e)
bold s = [H.Format H.Bold s]
-- | Converts a single attribute to an HTML table row.
htmlAttr :: ER.Attribute -> H.Row
htmlAttr a = H.Cells [cell]
where cell = H.LabelCell cellAttrs (H.Text $ withLabelFmt " [%s]" opts name)
name = fkfmt $ pkfmt $ htmlFont opts (field a)
pkfmt s = if pk a then [H.Format H.Underline s] else s
fkfmt s = if fk a then [H.Format H.Italics s] else s
cellAttrs = H.Align H.HLeft : optionsTo optToHtml opts
opts = aoptions a
-- | Formats HTML text with a label. The format string given should be
-- in `Data.Text.printf` style. (Only font options are used from the options
-- given.)
withLabelFmt :: String -> Options -> H.Text -> H.Text
withLabelFmt fmt opts s =
case optionsTo optToLabel opts of
(x:_) -> s ++ htmlFont opts (L.pack $ printf fmt $ L.unpack x)
_ -> s
-- | Formats an arbitrary string with the options given (using only font
-- attributes).
htmlFont :: Options -> L.Text -> H.Text
htmlFont opts s = [H.Font (optionsTo optToFont opts) [H.Str s]]
-- | Extracts and formats a graph title from the options given.
-- The options should be title options from an ER value.
-- If a title does not exist, an empty list is returned and `graphAttrs attrs`
-- should be a no-op.
graphTitle :: Options -> [A.Attribute]
graphTitle topts =
let glabel = optionsTo optToLabel topts
in if null glabel then [] else
[ A.LabelJust A.JLeft
, A.LabelLoc A.VTop
, A.Label $ A.HtmlLabel $ H.Text $ htmlFont topts (head glabel)
]
| fgaray/erd | src/Main.hs | unlicense | 4,024 | 54 | 18 | 976 | 1,266 | 667 | 599 | 80 | 3 |
{-# LANGUAGE MultiParamTypeClasses #-}
-- the content concept of an object
-- core questions: where is this object? is it the same as that object?
-- collections of objects are objects too (consistent with feature collections being features in OGC)
-- objects have temporal state (manifested in their spatial and thematic properties and relations)
-- (c) Werner Kuhn
-- latest change: July 24, 2016
-- TO DO
-- consider boundedness by upper hierarchy level of a tesselation (AURIN does that?)
-- make FIELDS a subclass of OBJECTS
module Object where
import Location
-- the class of all object types
-- Eq captures identity (each object type has its own identity criterion)
-- all objects are bounded, but they may not have a boundary
-- object properties and relations to be defined on concrete object types (none are generic)
class Eq object => OBJECTS object where
bounds :: object -> Location -- need to differentiate object geometry from object boundary
-- object IDs (for types that use one)
newtype Id = Id Int deriving (Eq, Show)
-- points of interest
data POI = POI Id Position deriving Show
instance Eq POI where
POI i p == POI j q = i == j
instance OBJECTS POI where
bounds (POI i p) = Location p []
-- tests
poi1, poi2 :: POI
poi1 = POI (Id 1) p11
poi2 = POI (Id 2) p22
ot1 = bounds poi1
| spatial-ucsb/ConceptsOfSpatialInformation | CoreConceptsHs/Object.hs | apache-2.0 | 1,314 | 0 | 8 | 251 | 194 | 109 | 85 | 15 | 1 |
{-# LANGUAGE PArr #-}
{-# OPTIONS -fvectorise #-}
module Delaunay ( delaunay, delaunayPoints ) where
import Types
import Hull
import Sort
import Data.Array.Parallel.Prelude
import Data.Array.Parallel.Prelude.Double
import qualified Data.Array.Parallel.Prelude.Int as Int
import Data.Array.Parallel.Prelude.Int ( Int )
import qualified Prelude as P
xOf :: IPoint -> Double
xOf (_,(x,_)) = x
yOf :: IPoint -> Double
yOf (_,(_,y)) = y
iOf :: IPoint -> Int
iOf (i,_) = i
lineFromPoint :: Point -> Point
lineFromPoint (x,y) = (x/q,y/q)
where
q = sq x + sq y
sq :: Double -> Double
sq d = d*d
neighbours :: IPoint -> [:IPoint:] -> [:(Int,Int):]
neighbours (i,(x0,y0)) points = [:(i,j) | j <- hull, j Int./= i:]
where
npts = [:(j,lineFromPoint ((x-x0),(y-y0))) | (j,(x,y)) <- points:]
hull = convexHull ([:(i,(0.0,0.0)):] +:+ npts)
nestedGet :: [:IPoint:] -> [:[:Int:]:] -> [:[:IPoint:]:]
nestedGet a i = [:bpermuteP a k | k <- i:]
removeDuplicates :: [:(Int,Int):] -> [:(Int,Int):]
removeDuplicates edges
= [:e | (i,e) <- iedges, andP [: e `neq` e' | e' <- sliceP 0 i edges :] :]
where
iedges = indexedP edges
neq (i1,j1) (i2,j2) = i1 Int./= i2 || j1 Int./= j2
delaunayFromEdgelist :: [:Point:] -> [:(Int,Int):] -> [:[:(Int,Int):]:]
delaunayFromEdgelist points edges
= [:neighbours p ps | (p,ps) <- zipP ipoints (nestedGet ipoints adj_lists):]
where
edges1 = removeDuplicates [:(Int.max i j, Int.min i j) | (i,j) <- edges:]
edges2 = edges1 +:+ [:(j,i) | (i,j) <- edges1:]
adj_lists = [:js | (i,js) <- collect edges2:]
ipoints = indexedP points
{-
% Given a set of points and a set of edges (pairs of indices to the points),
this returns for each point its delaunay edges sorted clockwise.
It assumes that all Delaunay edges are included in the input edgelist
but that they don't have to appear in both directions %
FUNCTION delaunay_from_edgelist(points,edges) =
let
% orient the edges and remove duplicates %
edges = remove_duplicates({max(i,j),min(i,j): (i,j) in edges});
% put in the back edges %
edges = edges ++ {j,i : (i,j) in edges};
% create an adjacency list for each node %
adj_lists = {e : i,e in int_collect(edges)};
% tag the points with indices %
pts = zip([0:#points],points);
% for each point subselect the delaunay edges and sort clockwise %
adj_lists = {delaunay_neighbors(pt,npts):
pt in pts; npts in nested_get(pts,adj_lists)};
in adj_lists $
function slow_delaunay(pts) =
if #pts == 0 then [] (int,int)
else
let rest = drop(pts,1);
in delaunay_neighbors(pts[0],rest)++slow_delaunay(rest) $
-}
slowDelaunay :: [:IPoint:] -> [:(Int,Int):]
slowDelaunay points | lengthP points Int.== 0 = [::]
slowDelaunay points = neighbours (points !: 0) rest +:+ slowDelaunay rest
where
rest = sliceP 1 (lengthP points Int.- 1) points
delaunayDivide :: [:IPoint:] -> Int -> [:[:IPoint:]:]
delaunayDivide points prev_n
| lengthP points Int.<= 4 || lengthP points Int.== prev_n = [:points:]
delaunayDivide points prev_n
= concatP [: delaunayDivide x n | x <- [: down_points, up_points :] :]
where
n = lengthP points
(_, pts) = unzipP points
(xm,ym) = pts !: medianIndex [:y | (x,y) <- pts:]
proj = [:(x, sq (x-xm) + sq (y-ym)) | (x,y) <- pts:]
lower_hull_indices = lowerHull (indexedP proj)
hull_flags = updateP (replicateP n 0) [:(i,1) | i <- lower_hull_indices:]
down_points = [:(i,(y,x)) | ((i,(x,y)),fl) <- zipP points hull_flags, y < ym || fl Int./= 0:]
up_points = [:(i,(y,x)) | ((i,(x,y)),fl) <- zipP points hull_flags, y >= ym || fl Int./= 0:]
{-
function delaunay_divide(points,previous_n) =
if (#points <= block_size) or #points == previous_n
% terminate if either points is smaller than block_size or if no progress
was made in the previous step %
then [points]
else let
n = #points;
% flip x and y coordinates -- this makes it so that we alternate between
cutting in x and in y %
points = {i,y,x : i,x,y in points};
% find x median %
med = median({x : i,x,y in points});
(i,xm,ym) = {i,x,y in points | x == med}[0];
% project points onto a parabola around median point %
proj = {j,y,(x-xm)^2+(y-ym)^2: i,x,y in points; j in index(n)};
% find the lower hull of this parabola and mark these points %
lower_hull_indices = lower_hull(proj);
hull_flags = dist(f,n)<-{i,t: i in lower_hull_indices};
% divide points into two sets based on median and such that the hull
points belong to both sets %
down_points = {i,x,y in points; fl in hull_flags | x < med or fl};
up_points = {i,x,y in points; fl in hull_flags | x >= med or fl};
% Recurse %
in flatten({delaunay_divide(x,n) : x in [down_points,up_points]}) $
-}
delaunay' :: [:Point:] -> [:(Int,Int):]
delaunay' points = concatP (delaunayFromEdgelist points all_edges)
where
ipoints = indexedP points
point_groups = delaunayDivide ipoints (lengthP ipoints Int.+ 1)
all_edges = concatP [:slowDelaunay group | group <- point_groups:]
delaunay :: PArray Point -> PArray (Int,Int)
{-# NOINLINE delaunay #-}
delaunay ps = toPArrayP (delaunay' (fromPArrayP ps))
delaunayPoints' :: [:Point:] -> [:(Point,Point):]
delaunayPoints' points = zipP (bpermuteP points is)
(bpermuteP points js)
where
(is,js) = unzipP (delaunay' points)
delaunayPoints :: PArray Point -> PArray (Point,Point)
{-# NOINLINE delaunayPoints #-}
delaunayPoints ps = toPArrayP (delaunayPoints' (fromPArrayP ps))
{-
function delaunay(pts) =
let
% Tag the points with an index %
ipts = {i,p : i in index(#pts) ; p in pts};
% Break into components using divide and conquer until
point sets are of size block_size %
point_groups = delaunay_divide(ipts,#ipts+1);
% Now find delaunay edges within each block %
all_edges = flatten({slow_delaunay(group) : group in point_groups});
% Finally put all blocks together and remove redundant edges %
edges = delaunay_from_edgelist(pts,all_edges);
in edges $
-}
| mainland/dph | icebox/examples/delaunay/Delaunay.hs | bsd-3-clause | 6,078 | 124 | 15 | 1,276 | 1,691 | 932 | 759 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
import Control.Applicative
import Data.Aeson.Quick
import Data.ByteString.Lazy (ByteString)
import Lens.Micro
import Test.Tasty
import Test.Tasty.HUnit
main :: IO ()
main = defaultMain $ testGroup "Tests"
[ oneKey
, multipleKeys
, deepKey
, keyInArray
, complex
, optionalKey
, nonExistentKey
, asLens
, parseInvalid
, showStructure
, quotedKey
]
oneKey :: TestTree
oneKey = testGroup "oneKey"
[ testCase "get" $
val .! "{a}" @?= one
, testCase "set" $
"{a}" .% Null `jt` "{\"a\":null}"
]
where val = d "{\"a\":1}"
multipleKeys :: TestTree
multipleKeys = testGroup "multipleKeys"
[ testCase "get" $
multiple .! "{a,b}" @?= (one,two)
, testCase "set" $
build "{a,b}" multiple (two,[one,one]) `jt` "{\"a\":2,\"b\":[1,1]}"
]
where multiple = d "{\"a\":1,\"b\":2}"
deepKey :: TestTree
deepKey = testGroup "deepKey"
[ testCase "get" $
multilevel .! "{a:{b}}" @?= Just one
, testCase "set" $
build "{a:{b}}" multilevel two `jt` "{\"a\":{\"b\":2}}"
]
where multilevel = d "{\"a\":{\"b\":1}}"
keyInArray :: TestTree
keyInArray = testGroup "keyInArray"
[ testCase "get" $
many .! "[{a}]" @?= [one,two]
, testCase "set" $
build "[{a}]" many [True,False] `jt` "[{\"a\":true},{\"a\":false}]"
]
where many = d "[{\"a\":1},{\"a\":2}]"
complex :: TestTree
complex = testGroup "complex"
[ testCase "get" $
val .! "{a,b:[{a}]}" @?= (one,[[two,one]])
, testCase "set" $
build "{a,b:[{a}]}" val (two,[[one]]) `jt` "{\"a\":2,\"b\":[{\"a\":[1]}]}"
]
where val = d "{\"a\":1,\"b\":[{\"a\":[2,1]}]}"
optionalKey :: TestTree
optionalKey = testGroup "optionalKey"
[ testCase "get" $
val .! "{a?,b?}" @?= (Just one, Nothing :: Maybe Int)
]
where val = d "{\"a\":1}"
nonExistentKey :: TestTree
nonExistentKey = testGroup "nonExistentKey"
[ testCase "get" $
val .? "{b}" @?= (Nothing :: Maybe Int)
, testCase "set" $
build "{a}" (d "{}") Null `jt` "{\"a\":null}"
, testCase "setDeep" $
"{a:[{b}]}" .% Null `jt` "{\"a\":[{\"b\":null}]}"
, testCase "setDeepArray" $
"[{a}]" .% [one,two] `jt` "[{\"a\":1},{\"a\":2}]"
, testCase "setDeepMany" $
let v = (1,[(10,11)]) :: (Int,[(Int,Int)])
in "{my,complex:[{data,structure}]}" .% v
@?= d "{\"my\":1,\"complex\":[{\"data\":10,\"structure\":11}]}"
]
where val = d "{\"a\":1}"
asLens :: TestTree
asLens = testGroup "asLens"
[ testCase "get" $
let l = queLens "{a,b}" :: Lens' Value (Int,Int)
in val ^. l . _2 @?= two
, testCase "getDoesNotExist" $
-- doesn't work, make a Traversal?
--d "{}" ^? queLens "{a}" @?= (Nothing :: Maybe (Int,Int))
putStr "SKIPPED " >> pure ()
, testCase "set" $
(val & (queLens "{a,b}") .~ (two,one)) `jt` "{\"a\":2,\"b\":1}"
]
where
val = d "{\"a\":1,\"b\":2}"
queLens :: (FromJSON a, ToJSON a) => Structure -> Lens' Value a
queLens s = lens (.!s) (build s)
parseInvalid :: TestTree
parseInvalid = testGroup "parseInvalid"
[ testCase "noKey" $
isLeft (parseStructure "{a,{b}}") @?= True
]
showStructure :: TestTree
showStructure = testGroup "showStructure"
[ testCase "all" $
show ("[{a:[{b?,c}]}]"::Structure) @?= "[{a:[{b?,c}]}]"
]
quotedKey :: TestTree
quotedKey = testGroup "quotedKey"
[ testCase "chars" $
("{\"_:,}\"?}") @?= Obj [("_:,}", True, Val)]
]
one, two :: Int
one = 1
two = 2
jt :: Value -> ByteString -> IO ()
jt v b = encode v @?= b
d :: ByteString -> Value
d s = case decode s of
Just v -> v
Nothing -> error $ "Coult not decode JSON: " ++ show s
isLeft :: Either a b -> Bool
isLeft e = case e of Left _ -> True
_ -> False
| libscott/quickson | test/Test.hs | bsd-3-clause | 3,830 | 0 | 14 | 912 | 1,191 | 639 | 552 | -1 | -1 |
{-| Module describing a node.
All updates are functional (copy-based) and return a new node with
updated value.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
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., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.HTools.Node
( Node(..)
, List
-- * Constructor
, create
-- ** Finalization after data loading
, buildPeers
, setIdx
, setAlias
, setOffline
, setXmem
, setFmem
, setPri
, setSec
, setMaster
, setNodeTags
, setMdsk
, setMcpu
, setPolicy
-- * Tag maps
, addTags
, delTags
, rejectAddTags
-- * Instance (re)location
, removePri
, removeSec
, addPri
, addPriEx
, addSec
, addSecEx
-- * Stats
, availDisk
, availMem
, availCpu
, iMem
, iDsk
, conflictingPrimaries
-- * Formatting
, defaultFields
, showHeader
, showField
, list
-- * Misc stuff
, AssocList
, AllocElement
, noSecondary
, computeGroups
, mkNodeGraph
, mkRebootNodeGraph
, haveExclStorage
) where
import Control.Monad (liftM, liftM2)
import Control.Applicative ((<$>), (<*>))
import qualified Data.Foldable as Foldable
import Data.Function (on)
import qualified Data.Graph as Graph
import qualified Data.IntMap as IntMap
import Data.List hiding (group)
import qualified Data.Map as Map
import Data.Ord (comparing)
import Text.Printf (printf)
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.PeerMap as P
import Ganeti.BasicTypes
import qualified Ganeti.HTools.Types as T
-- * Type declarations
-- | The tag map type.
type TagMap = Map.Map String Int
-- | The node type.
data Node = Node
{ name :: String -- ^ The node name
, alias :: String -- ^ The shortened name (for display purposes)
, tMem :: Double -- ^ Total memory (MiB)
, nMem :: Int -- ^ Node memory (MiB)
, fMem :: Int -- ^ Free memory (MiB)
, xMem :: Int -- ^ Unaccounted memory (MiB)
, tDsk :: Double -- ^ Total disk space (MiB)
, fDsk :: Int -- ^ Free disk space (MiB)
, tCpu :: Double -- ^ Total CPU count
, nCpu :: Int -- ^ VCPUs used by the node OS
, uCpu :: Int -- ^ Used VCPU count
, tSpindles :: Int -- ^ Node spindles (spindle_count node parameter,
-- or actual spindles, see note below)
, fSpindles :: Int -- ^ Free spindles (see note below)
, pList :: [T.Idx] -- ^ List of primary instance indices
, sList :: [T.Idx] -- ^ List of secondary instance indices
, idx :: T.Ndx -- ^ Internal index for book-keeping
, peers :: P.PeerMap -- ^ Pnode to instance mapping
, failN1 :: Bool -- ^ Whether the node has failed n1
, rMem :: Int -- ^ Maximum memory needed for failover by
-- primaries of this node
, pMem :: Double -- ^ Percent of free memory
, pDsk :: Double -- ^ Percent of free disk
, pRem :: Double -- ^ Percent of reserved memory
, pCpu :: Double -- ^ Ratio of virtual to physical CPUs
, mDsk :: Double -- ^ Minimum free disk ratio
, loDsk :: Int -- ^ Autocomputed from mDsk low disk
-- threshold
, hiCpu :: Int -- ^ Autocomputed from mCpu high cpu
-- threshold
, hiSpindles :: Double -- ^ Limit auto-computed from policy spindle_ratio
-- and the node spindle count (see note below)
, instSpindles :: Double -- ^ Spindles used by instances (see note below)
, offline :: Bool -- ^ Whether the node should not be used for
-- allocations and skipped from score
-- computations
, isMaster :: Bool -- ^ Whether the node is the master node
, nTags :: [String] -- ^ The node tags for this node
, utilPool :: T.DynUtil -- ^ Total utilisation capacity
, utilLoad :: T.DynUtil -- ^ Sum of instance utilisation
, pTags :: TagMap -- ^ Primary instance exclusion tags and their count
, group :: T.Gdx -- ^ The node's group (index)
, iPolicy :: T.IPolicy -- ^ The instance policy (of the node's group)
, exclStorage :: Bool -- ^ Effective value of exclusive_storage
} deriving (Show, Eq)
{- A note on how we handle spindles
With exclusive storage spindles is a resource, so we track the number of
spindles still available (fSpindles). This is the only reliable way, as some
spindles could be used outside of Ganeti. When exclusive storage is off,
spindles are a way to represent disk I/O pressure, and hence we track the amount
used by the instances. We compare it against 'hiSpindles', computed from the
instance policy, to avoid policy violations. In both cases we store the total
spindles in 'tSpindles'.
-}
instance T.Element Node where
nameOf = name
idxOf = idx
setAlias = setAlias
setIdx = setIdx
allNames n = [name n, alias n]
-- | A simple name for the int, node association list.
type AssocList = [(T.Ndx, Node)]
-- | A simple name for a node map.
type List = Container.Container Node
-- | A simple name for an allocation element (here just for logistic
-- reasons).
type AllocElement = (List, Instance.Instance, [Node], T.Score)
-- | Constant node index for a non-moveable instance.
noSecondary :: T.Ndx
noSecondary = -1
-- * Helper functions
-- | Add a tag to a tagmap.
addTag :: TagMap -> String -> TagMap
addTag t s = Map.insertWith (+) s 1 t
-- | Add multiple tags.
addTags :: TagMap -> [String] -> TagMap
addTags = foldl' addTag
-- | Adjust or delete a tag from a tagmap.
delTag :: TagMap -> String -> TagMap
delTag t s = Map.update (\v -> if v > 1
then Just (v-1)
else Nothing)
s t
-- | Remove multiple tags.
delTags :: TagMap -> [String] -> TagMap
delTags = foldl' delTag
-- | Check if we can add a list of tags to a tagmap.
rejectAddTags :: TagMap -> [String] -> Bool
rejectAddTags t = any (`Map.member` t)
-- | Check how many primary instances have conflicting tags. The
-- algorithm to compute this is to sum the count of all tags, then
-- subtract the size of the tag map (since each tag has at least one,
-- non-conflicting instance); this is equivalent to summing the
-- values in the tag map minus one.
conflictingPrimaries :: Node -> Int
conflictingPrimaries (Node { pTags = t }) = Foldable.sum t - Map.size t
-- | Helper function to increment a base value depending on the passed
-- boolean argument.
incIf :: (Num a) => Bool -> a -> a -> a
incIf True base delta = base + delta
incIf False base _ = base
-- | Helper function to decrement a base value depending on the passed
-- boolean argument.
decIf :: (Num a) => Bool -> a -> a -> a
decIf True base delta = base - delta
decIf False base _ = base
-- | Is exclusive storage enabled on any node?
haveExclStorage :: List -> Bool
haveExclStorage nl =
any exclStorage $ Container.elems nl
-- * Initialization functions
-- | Create a new node.
--
-- The index and the peers maps are empty, and will be need to be
-- update later via the 'setIdx' and 'buildPeers' functions.
create :: String -> Double -> Int -> Int
-> Double -> Int -> Double -> Int -> Bool
-> Int -> Int -> T.Gdx -> Bool
-> Node
create name_init mem_t_init mem_n_init mem_f_init
dsk_t_init dsk_f_init cpu_t_init cpu_n_init offline_init
spindles_t_init spindles_f_init group_init excl_stor =
Node { name = name_init
, alias = name_init
, tMem = mem_t_init
, nMem = mem_n_init
, fMem = mem_f_init
, tDsk = dsk_t_init
, fDsk = dsk_f_init
, tCpu = cpu_t_init
, nCpu = cpu_n_init
, uCpu = cpu_n_init
, tSpindles = spindles_t_init
, fSpindles = spindles_f_init
, pList = []
, sList = []
, failN1 = True
, idx = -1
, peers = P.empty
, rMem = 0
, pMem = fromIntegral mem_f_init / mem_t_init
, pDsk = if excl_stor
then computePDsk spindles_f_init $ fromIntegral spindles_t_init
else computePDsk dsk_f_init dsk_t_init
, pRem = 0
, pCpu = fromIntegral cpu_n_init / cpu_t_init
, offline = offline_init
, isMaster = False
, nTags = []
, xMem = 0
, mDsk = T.defReservedDiskRatio
, loDsk = mDskToloDsk T.defReservedDiskRatio dsk_t_init
, hiCpu = mCpuTohiCpu (T.iPolicyVcpuRatio T.defIPolicy) cpu_t_init
, hiSpindles = computeHiSpindles (T.iPolicySpindleRatio T.defIPolicy)
spindles_t_init
, instSpindles = 0
, utilPool = T.baseUtil
, utilLoad = T.zeroUtil
, pTags = Map.empty
, group = group_init
, iPolicy = T.defIPolicy
, exclStorage = excl_stor
}
-- | Conversion formula from mDsk\/tDsk to loDsk.
mDskToloDsk :: Double -> Double -> Int
mDskToloDsk mval = floor . (mval *)
-- | Conversion formula from mCpu\/tCpu to hiCpu.
mCpuTohiCpu :: Double -> Double -> Int
mCpuTohiCpu mval = floor . (mval *)
-- | Conversiojn formula from spindles and spindle ratio to hiSpindles.
computeHiSpindles :: Double -> Int -> Double
computeHiSpindles spindle_ratio = (spindle_ratio *) . fromIntegral
-- | Changes the index.
--
-- This is used only during the building of the data structures.
setIdx :: Node -> T.Ndx -> Node
setIdx t i = t {idx = i}
-- | Changes the alias.
--
-- This is used only during the building of the data structures.
setAlias :: Node -> String -> Node
setAlias t s = t { alias = s }
-- | Sets the offline attribute.
setOffline :: Node -> Bool -> Node
setOffline t val = t { offline = val }
-- | Sets the master attribute
setMaster :: Node -> Bool -> Node
setMaster t val = t { isMaster = val }
-- | Sets the node tags attribute
setNodeTags :: Node -> [String] -> Node
setNodeTags t val = t { nTags = val }
-- | Sets the unnaccounted memory.
setXmem :: Node -> Int -> Node
setXmem t val = t { xMem = val }
-- | Sets the max disk usage ratio.
setMdsk :: Node -> Double -> Node
setMdsk t val = t { mDsk = val, loDsk = mDskToloDsk val (tDsk t) }
-- | Sets the max cpu usage ratio. This will update the node's
-- ipolicy, losing sharing (but it should be a seldomly done operation).
setMcpu :: Node -> Double -> Node
setMcpu t val =
let new_ipol = (iPolicy t) { T.iPolicyVcpuRatio = val }
in t { hiCpu = mCpuTohiCpu val (tCpu t), iPolicy = new_ipol }
-- | Sets the policy.
setPolicy :: T.IPolicy -> Node -> Node
setPolicy pol node =
node { iPolicy = pol
, hiCpu = mCpuTohiCpu (T.iPolicyVcpuRatio pol) (tCpu node)
, hiSpindles = computeHiSpindles (T.iPolicySpindleRatio pol)
(tSpindles node)
}
-- | Computes the maximum reserved memory for peers from a peer map.
computeMaxRes :: P.PeerMap -> P.Elem
computeMaxRes = P.maxElem
-- | Builds the peer map for a given node.
buildPeers :: Node -> Instance.List -> Node
buildPeers t il =
let mdata = map
(\i_idx -> let inst = Container.find i_idx il
mem = if Instance.usesSecMem inst
then Instance.mem inst
else 0
in (Instance.pNode inst, mem))
(sList t)
pmap = P.accumArray (+) mdata
new_rmem = computeMaxRes pmap
new_failN1 = fMem t <= new_rmem
new_prem = fromIntegral new_rmem / tMem t
in t {peers=pmap, failN1 = new_failN1, rMem = new_rmem, pRem = new_prem}
-- | Calculate the new spindle usage
calcSpindleUse ::
Bool -- Action: True = adding instance, False = removing it
-> Node -> Instance.Instance -> Double
calcSpindleUse _ (Node {exclStorage = True}) _ = 0.0
calcSpindleUse act n@(Node {exclStorage = False}) i =
f (Instance.usesLocalStorage i) (instSpindles n)
(fromIntegral $ Instance.spindleUse i)
where
f :: Bool -> Double -> Double -> Double -- avoid monomorphism restriction
f = if act then incIf else decIf
-- | Calculate the new number of free spindles
calcNewFreeSpindles ::
Bool -- Action: True = adding instance, False = removing
-> Node -> Instance.Instance -> Int
calcNewFreeSpindles _ (Node {exclStorage = False}) _ = 0
calcNewFreeSpindles act n@(Node {exclStorage = True}) i =
case Instance.getTotalSpindles i of
Nothing -> if act
then -1 -- Force a spindle error, so the instance don't go here
else fSpindles n -- No change, as we aren't sure
Just s -> (if act then (-) else (+)) (fSpindles n) s
-- | Assigns an instance to a node as primary and update the used VCPU
-- count, utilisation data and tags map.
setPri :: Node -> Instance.Instance -> Node
setPri t inst = t { pList = Instance.idx inst:pList t
, uCpu = new_count
, pCpu = fromIntegral new_count / tCpu t
, utilLoad = utilLoad t `T.addUtil` Instance.util inst
, pTags = addTags (pTags t) (Instance.exclTags inst)
, instSpindles = calcSpindleUse True t inst
}
where new_count = Instance.applyIfOnline inst (+ Instance.vcpus inst)
(uCpu t )
-- | Assigns an instance to a node as secondary and updates disk utilisation.
setSec :: Node -> Instance.Instance -> Node
setSec t inst = t { sList = Instance.idx inst:sList t
, utilLoad = old_load { T.dskWeight = T.dskWeight old_load +
T.dskWeight (Instance.util inst) }
, instSpindles = calcSpindleUse True t inst
}
where old_load = utilLoad t
-- | Computes the new 'pDsk' value, handling nodes without local disk
-- storage (we consider all their disk unused).
computePDsk :: Int -> Double -> Double
computePDsk _ 0 = 1
computePDsk free total = fromIntegral free / total
-- | Computes the new 'pDsk' value, handling the exclusive storage state.
computeNewPDsk :: Node -> Int -> Int -> Double
computeNewPDsk node new_free_sp new_free_dsk =
if exclStorage node
then computePDsk new_free_sp . fromIntegral $ tSpindles node
else computePDsk new_free_dsk $ tDsk node
-- * Update functions
-- | Sets the free memory.
setFmem :: Node -> Int -> Node
setFmem t new_mem =
let new_n1 = new_mem < rMem t
new_mp = fromIntegral new_mem / tMem t
in t { fMem = new_mem, failN1 = new_n1, pMem = new_mp }
-- | Removes a primary instance.
removePri :: Node -> Instance.Instance -> Node
removePri t inst =
let iname = Instance.idx inst
i_online = Instance.notOffline inst
uses_disk = Instance.usesLocalStorage inst
new_plist = delete iname (pList t)
new_mem = incIf i_online (fMem t) (Instance.mem inst)
new_dsk = incIf uses_disk (fDsk t) (Instance.dsk inst)
new_free_sp = calcNewFreeSpindles False t inst
new_inst_sp = calcSpindleUse False t inst
new_mp = fromIntegral new_mem / tMem t
new_dp = computeNewPDsk t new_free_sp new_dsk
new_failn1 = new_mem <= rMem t
new_ucpu = decIf i_online (uCpu t) (Instance.vcpus inst)
new_rcpu = fromIntegral new_ucpu / tCpu t
new_load = utilLoad t `T.subUtil` Instance.util inst
in t { pList = new_plist, fMem = new_mem, fDsk = new_dsk
, failN1 = new_failn1, pMem = new_mp, pDsk = new_dp
, uCpu = new_ucpu, pCpu = new_rcpu, utilLoad = new_load
, pTags = delTags (pTags t) (Instance.exclTags inst)
, instSpindles = new_inst_sp, fSpindles = new_free_sp
}
-- | Removes a secondary instance.
removeSec :: Node -> Instance.Instance -> Node
removeSec t inst =
let iname = Instance.idx inst
uses_disk = Instance.usesLocalStorage inst
cur_dsk = fDsk t
pnode = Instance.pNode inst
new_slist = delete iname (sList t)
new_dsk = incIf uses_disk cur_dsk (Instance.dsk inst)
new_free_sp = calcNewFreeSpindles False t inst
new_inst_sp = calcSpindleUse False t inst
old_peers = peers t
old_peem = P.find pnode old_peers
new_peem = decIf (Instance.usesSecMem inst) old_peem (Instance.mem inst)
new_peers = if new_peem > 0
then P.add pnode new_peem old_peers
else P.remove pnode old_peers
old_rmem = rMem t
new_rmem = if old_peem < old_rmem
then old_rmem
else computeMaxRes new_peers
new_prem = fromIntegral new_rmem / tMem t
new_failn1 = fMem t <= new_rmem
new_dp = computeNewPDsk t new_free_sp new_dsk
old_load = utilLoad t
new_load = old_load { T.dskWeight = T.dskWeight old_load -
T.dskWeight (Instance.util inst) }
in t { sList = new_slist, fDsk = new_dsk, peers = new_peers
, failN1 = new_failn1, rMem = new_rmem, pDsk = new_dp
, pRem = new_prem, utilLoad = new_load
, instSpindles = new_inst_sp, fSpindles = new_free_sp
}
-- | Adds a primary instance (basic version).
addPri :: Node -> Instance.Instance -> T.OpResult Node
addPri = addPriEx False
-- | Adds a primary instance (extended version).
addPriEx :: Bool -- ^ Whether to override the N+1 and
-- other /soft/ checks, useful if we
-- come from a worse status
-- (e.g. offline)
-> Node -- ^ The target node
-> Instance.Instance -- ^ The instance to add
-> T.OpResult Node -- ^ The result of the operation,
-- either the new version of the node
-- or a failure mode
addPriEx force t inst =
let iname = Instance.idx inst
i_online = Instance.notOffline inst
uses_disk = Instance.usesLocalStorage inst
cur_dsk = fDsk t
new_mem = decIf i_online (fMem t) (Instance.mem inst)
new_dsk = decIf uses_disk cur_dsk (Instance.dsk inst)
new_free_sp = calcNewFreeSpindles True t inst
new_inst_sp = calcSpindleUse True t inst
new_failn1 = new_mem <= rMem t
new_ucpu = incIf i_online (uCpu t) (Instance.vcpus inst)
new_pcpu = fromIntegral new_ucpu / tCpu t
new_dp = computeNewPDsk t new_free_sp new_dsk
l_cpu = T.iPolicyVcpuRatio $ iPolicy t
new_load = utilLoad t `T.addUtil` Instance.util inst
inst_tags = Instance.exclTags inst
old_tags = pTags t
strict = not force
in case () of
_ | new_mem <= 0 -> Bad T.FailMem
| uses_disk && new_dsk <= 0 -> Bad T.FailDisk
| uses_disk && new_dsk < loDsk t && strict -> Bad T.FailDisk
| uses_disk && exclStorage t && new_free_sp < 0 -> Bad T.FailSpindles
| uses_disk && new_inst_sp > hiSpindles t && strict -> Bad T.FailDisk
| new_failn1 && not (failN1 t) && strict -> Bad T.FailMem
| l_cpu >= 0 && l_cpu < new_pcpu && strict -> Bad T.FailCPU
| rejectAddTags old_tags inst_tags -> Bad T.FailTags
| otherwise ->
let new_plist = iname:pList t
new_mp = fromIntegral new_mem / tMem t
r = t { pList = new_plist, fMem = new_mem, fDsk = new_dsk
, failN1 = new_failn1, pMem = new_mp, pDsk = new_dp
, uCpu = new_ucpu, pCpu = new_pcpu
, utilLoad = new_load
, pTags = addTags old_tags inst_tags
, instSpindles = new_inst_sp
, fSpindles = new_free_sp
}
in Ok r
-- | Adds a secondary instance (basic version).
addSec :: Node -> Instance.Instance -> T.Ndx -> T.OpResult Node
addSec = addSecEx False
-- | Adds a secondary instance (extended version).
addSecEx :: Bool -> Node -> Instance.Instance -> T.Ndx -> T.OpResult Node
addSecEx force t inst pdx =
let iname = Instance.idx inst
old_peers = peers t
old_mem = fMem t
new_dsk = fDsk t - Instance.dsk inst
new_free_sp = calcNewFreeSpindles True t inst
new_inst_sp = calcSpindleUse True t inst
secondary_needed_mem = if Instance.usesSecMem inst
then Instance.mem inst
else 0
new_peem = P.find pdx old_peers + secondary_needed_mem
new_peers = P.add pdx new_peem old_peers
new_rmem = max (rMem t) new_peem
new_prem = fromIntegral new_rmem / tMem t
new_failn1 = old_mem <= new_rmem
new_dp = computeNewPDsk t new_free_sp new_dsk
old_load = utilLoad t
new_load = old_load { T.dskWeight = T.dskWeight old_load +
T.dskWeight (Instance.util inst) }
strict = not force
in case () of
_ | not (Instance.hasSecondary inst) -> Bad T.FailDisk
| new_dsk <= 0 -> Bad T.FailDisk
| new_dsk < loDsk t && strict -> Bad T.FailDisk
| exclStorage t && new_free_sp < 0 -> Bad T.FailSpindles
| new_inst_sp > hiSpindles t && strict -> Bad T.FailDisk
| secondary_needed_mem >= old_mem && strict -> Bad T.FailMem
| new_failn1 && not (failN1 t) && strict -> Bad T.FailMem
| otherwise ->
let new_slist = iname:sList t
r = t { sList = new_slist, fDsk = new_dsk
, peers = new_peers, failN1 = new_failn1
, rMem = new_rmem, pDsk = new_dp
, pRem = new_prem, utilLoad = new_load
, instSpindles = new_inst_sp
, fSpindles = new_free_sp
}
in Ok r
-- * Stats functions
-- | Computes the amount of available disk on a given node.
availDisk :: Node -> Int
availDisk t =
let _f = fDsk t
_l = loDsk t
in if _f < _l
then 0
else _f - _l
-- | Computes the amount of used disk on a given node.
iDsk :: Node -> Int
iDsk t = truncate (tDsk t) - fDsk t
-- | Computes the amount of available memory on a given node.
availMem :: Node -> Int
availMem t =
let _f = fMem t
_l = rMem t
in if _f < _l
then 0
else _f - _l
-- | Computes the amount of available memory on a given node.
availCpu :: Node -> Int
availCpu t =
let _u = uCpu t
_l = hiCpu t
in if _l >= _u
then _l - _u
else 0
-- | The memory used by instances on a given node.
iMem :: Node -> Int
iMem t = truncate (tMem t) - nMem t - xMem t - fMem t
-- * Node graph functions
-- These functions do the transformations needed so that nodes can be
-- represented as a graph connected by the instances that are replicated
-- on them.
-- * Making of a Graph from a node/instance list
-- | Transform an instance into a list of edges on the node graph
instanceToEdges :: Instance.Instance -> [Graph.Edge]
instanceToEdges i
| Instance.hasSecondary i = [(pnode,snode), (snode,pnode)]
| otherwise = []
where pnode = Instance.pNode i
snode = Instance.sNode i
-- | Transform the list of instances into list of destination edges
instancesToEdges :: Instance.List -> [Graph.Edge]
instancesToEdges = concatMap instanceToEdges . Container.elems
-- | Transform the list of nodes into vertices bounds.
-- Returns Nothing is the list is empty.
nodesToBounds :: List -> Maybe Graph.Bounds
nodesToBounds nl = liftM2 (,) nmin nmax
where nmin = fmap (fst . fst) (IntMap.minViewWithKey nl)
nmax = fmap (fst . fst) (IntMap.maxViewWithKey nl)
-- | The clique of the primary nodes of the instances with a given secondary.
-- Return the full graph of those nodes that are primary node of at least one
-- instance that has the given node as secondary.
nodeToSharedSecondaryEdge :: Instance.List -> Node -> [Graph.Edge]
nodeToSharedSecondaryEdge il n = (,) <$> primaries <*> primaries
where primaries = map (Instance.pNode . flip Container.find il) $ sList n
-- | Predicate of an edge having both vertices in a set of nodes.
filterValid :: List -> [Graph.Edge] -> [Graph.Edge]
filterValid nl = filter $ \(x,y) -> IntMap.member x nl && IntMap.member y nl
-- | Transform a Node + Instance list into a NodeGraph type.
-- Returns Nothing if the node list is empty.
mkNodeGraph :: List -> Instance.List -> Maybe Graph.Graph
mkNodeGraph nl il =
liftM (`Graph.buildG` (filterValid nl . instancesToEdges $ il))
(nodesToBounds nl)
-- | Transform a Nodes + Instances into a NodeGraph with all reboot exclusions.
-- This includes edges between nodes that are the primary nodes of instances
-- that have the same secondary node. Nodes not in the node list will not be
-- part of the graph, but they are still considered for the edges arising from
-- two instances having the same secondary node.
-- Return Nothing if the node list is empty.
mkRebootNodeGraph :: List -> List -> Instance.List -> Maybe Graph.Graph
mkRebootNodeGraph allnodes nl il =
liftM (`Graph.buildG` filterValid nl edges) (nodesToBounds nl)
where
edges = instancesToEdges il `union`
(Container.elems allnodes >>= nodeToSharedSecondaryEdge il)
-- * Display functions
-- | Return a field for a given node.
showField :: Node -- ^ Node which we're querying
-> String -- ^ Field name
-> String -- ^ Field value as string
showField t field =
case field of
"idx" -> printf "%4d" $ idx t
"name" -> alias t
"fqdn" -> name t
"status" -> case () of
_ | offline t -> "-"
| failN1 t -> "*"
| otherwise -> " "
"tmem" -> printf "%5.0f" $ tMem t
"nmem" -> printf "%5d" $ nMem t
"xmem" -> printf "%5d" $ xMem t
"fmem" -> printf "%5d" $ fMem t
"imem" -> printf "%5d" $ iMem t
"rmem" -> printf "%5d" $ rMem t
"amem" -> printf "%5d" $ fMem t - rMem t
"tdsk" -> printf "%5.0f" $ tDsk t / 1024
"fdsk" -> printf "%5d" $ fDsk t `div` 1024
"tcpu" -> printf "%4.0f" $ tCpu t
"ucpu" -> printf "%4d" $ uCpu t
"pcnt" -> printf "%3d" $ length (pList t)
"scnt" -> printf "%3d" $ length (sList t)
"plist" -> show $ pList t
"slist" -> show $ sList t
"pfmem" -> printf "%6.4f" $ pMem t
"pfdsk" -> printf "%6.4f" $ pDsk t
"rcpu" -> printf "%5.2f" $ pCpu t
"cload" -> printf "%5.3f" uC
"mload" -> printf "%5.3f" uM
"dload" -> printf "%5.3f" uD
"nload" -> printf "%5.3f" uN
"ptags" -> intercalate "," . map (uncurry (printf "%s=%d")) .
Map.toList $ pTags t
"peermap" -> show $ peers t
"spindle_count" -> show $ tSpindles t
"hi_spindles" -> show $ hiSpindles t
"inst_spindles" -> show $ instSpindles t
_ -> T.unknownField
where
T.DynUtil { T.cpuWeight = uC, T.memWeight = uM,
T.dskWeight = uD, T.netWeight = uN } = utilLoad t
-- | Returns the header and numeric propery of a field.
showHeader :: String -> (String, Bool)
showHeader field =
case field of
"idx" -> ("Index", True)
"name" -> ("Name", False)
"fqdn" -> ("Name", False)
"status" -> ("F", False)
"tmem" -> ("t_mem", True)
"nmem" -> ("n_mem", True)
"xmem" -> ("x_mem", True)
"fmem" -> ("f_mem", True)
"imem" -> ("i_mem", True)
"rmem" -> ("r_mem", True)
"amem" -> ("a_mem", True)
"tdsk" -> ("t_dsk", True)
"fdsk" -> ("f_dsk", True)
"tcpu" -> ("pcpu", True)
"ucpu" -> ("vcpu", True)
"pcnt" -> ("pcnt", True)
"scnt" -> ("scnt", True)
"plist" -> ("primaries", True)
"slist" -> ("secondaries", True)
"pfmem" -> ("p_fmem", True)
"pfdsk" -> ("p_fdsk", True)
"rcpu" -> ("r_cpu", True)
"cload" -> ("lCpu", True)
"mload" -> ("lMem", True)
"dload" -> ("lDsk", True)
"nload" -> ("lNet", True)
"ptags" -> ("PrimaryTags", False)
"peermap" -> ("PeerMap", False)
"spindle_count" -> ("NodeSpindles", True)
"hi_spindles" -> ("MaxSpindles", True)
"inst_spindles" -> ("InstSpindles", True)
-- TODO: add node fields (group.uuid, group)
_ -> (T.unknownField, False)
-- | String converter for the node list functionality.
list :: [String] -> Node -> [String]
list fields t = map (showField t) fields
-- | Constant holding the fields we're displaying by default.
defaultFields :: [String]
defaultFields =
[ "status", "name", "tmem", "nmem", "imem", "xmem", "fmem"
, "rmem", "tdsk", "fdsk", "tcpu", "ucpu", "pcnt", "scnt"
, "pfmem", "pfdsk", "rcpu"
, "cload", "mload", "dload", "nload" ]
{-# ANN computeGroups "HLint: ignore Use alternative" #-}
-- | Split a list of nodes into a list of (node group UUID, list of
-- associated nodes).
computeGroups :: [Node] -> [(T.Gdx, [Node])]
computeGroups nodes =
let nodes' = sortBy (comparing group) nodes
nodes'' = groupBy ((==) `on` group) nodes'
-- use of head here is OK, since groupBy returns non-empty lists; if
-- you remove groupBy, also remove use of head
in map (\nl -> (group (head nl), nl)) nodes''
| vladimir-ipatov/ganeti | src/Ganeti/HTools/Node.hs | gpl-2.0 | 29,560 | 0 | 18 | 8,238 | 6,971 | 3,816 | 3,155 | 551 | 32 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveFunctor, PackageImports, FlexibleInstances, MultiParamTypeClasses #-}
module Rpc where
import Data.String
import Rpc.Autogen.DbServer (DbServer, interfaces)
import Rpc.Core
import Control.Applicative
import "mtl" Control.Monad.Error
import Tools.FreezeIOM
dbObjectPath :: ObjectPath
dbObjectPath = fromString "/"
service = "com.citrix.xenclient.db"
data RpcError = RpcError { remoteErr :: Maybe RemoteErr, localErr :: Maybe String }
deriving (Show)
instance IsRemoteError RpcError where
fromRemoteErr _ remote_err = RpcError (Just remote_err) Nothing
toRemoteErr e = remoteErr e
newtype Rpc a = Rpc (RpcM RpcError a)
deriving (Functor, Applicative, Monad, MonadIO
, MonadError RpcError, MonadRpc RpcError, FreezeIOM RpcContext (Either RpcError))
expose :: DbServer Rpc -> Rpc ()
expose imp = rpcExpose dbObjectPath (interfaces $ imp)
rpc ctx (Rpc f) = runRpcM f ctx
| jean-edouard/manager | dbd2/Rpc.hs | gpl-2.0 | 1,740 | 0 | 9 | 315 | 275 | 156 | 119 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Copyright : (c) 2016 Dominik Schoop
License : GPL v3 (see LICENSE)
Maintainer : Dominik Schoop [email protected]
Portability : GHC only
Conversion of the graph part of a sequent (constraint system) to a JSON graph format
ADVISE:
- DO NOT USE sequentToJSONPretty IN OPERATIONAL MODE.
Remember to replace sequentToJSONPretty with sequentToJSON in getTheoryGraphR in Handler.hs.
- The time consuming pretty printing of facts and terms can be disabeled by a parameter of
sequentToJSONPretty and sequentToJSON. Currently, everything is pretty with sequentToJSONPretty
and nothing is pretty with sequentToJSON.
TO DO:
- generate JSON in non-interactive mode
- make it work for observational equivalence
- encode historic information in the graph: sequence of nodes added
OPEN PROBLEMS:
- JSON encodePretty converts < and > to "\u003c" and "\u003e"
ghastly postprocessing has been applied to sequentToJSONPretty
-}
module Theory.Constraint.System.JSON (
sequentToJSON,
writeSequentAsJSONToFile,
sequentToJSONPretty,
writeSequentAsJSONPrettyToFile
) where
import Extension.Data.Label as L (get)
import Data.Aeson
import Data.Aeson.TH
import Data.Aeson.Encode.Pretty -- to do pretty printing of JSON
import Data.Foldable
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set as S
import qualified Data.ByteString.Lazy.Char8 as BC (unpack)
import Text.PrettyPrint.Class -- for Doc and the pretty printing functions
import Theory.Constraint.System
import Theory.Model
-------------------------------------------------------------------------------------------------
-- Data structure for JSON graphs --
-- adapted from https://github.com/jsongraph/json-graph-specification --
-------------------------------------------------------------------------------------------------
-- | Representation of a term in a JSON graph node.
data JSONGraphNodeTerm =
Const String
| Funct String [JSONGraphNodeTerm] String
deriving (Show)
-- | Automatically derived instances have unnecessarily many tag-value pairs.
-- Hence, we have our own here.
instance FromJSON JSONGraphNodeTerm where
parseJSON = withObject "JSONGraphNodeTerm" $ \o -> asum [
Const <$> o .: "jgnConst",
Funct <$> o .: "jgnFunct" <*> o .: "jgnParams" <*> o .: "jgnShow" ]
instance ToJSON JSONGraphNodeTerm where
toJSON (Const s) = object [ "jgnConst" .= s ]
toJSON (Funct f p s) = object
[ "jgnFunct" .= f
, "jgnParams" .= toJSON p
, "jgnShow" .= s
]
-- | Representation of a fact in a JSON graph node.
data JSONGraphNodeFact = JSONGraphNodeFact
{
jgnFactId :: String
, jgnFactTag :: String -- ^ ProtoFact, FreshFact, OutFact, InFact, KUFact, KDFact, DedFact
, jgnFactName :: String -- ^ Fr, Out, In, !KU, ...
, jgnFactMult :: String -- ^ "!" = persistent, "" = linear
, jgnFactTerms :: [JSONGraphNodeTerm]
, jgnFactShow :: String
} deriving (Show)
-- | Representation of meta data of a JSON graph node.
data JSONGraphNodeMetadata = JSONGraphNodeMetadata
{
jgnPrems :: [JSONGraphNodeFact]
, jgnActs :: [JSONGraphNodeFact]
, jgnConcs :: [JSONGraphNodeFact]
} deriving (Show)
-- | Representation of a node of a JSON graph.
data JSONGraphNode = JSONGraphNode
{
jgnId :: String
, jgnType :: String
, jgnLabel :: String
, jgnMetadata :: Maybe JSONGraphNodeMetadata
} deriving (Show)
-- | Optional fields are not handled correctly with automatically derived instances
-- hence, we have our own here.
instance FromJSON JSONGraphNode where
parseJSON = withObject "JSONGraphNode" $ \o -> JSONGraphNode
<$> o .: "jgnId"
<*> o .: "jgnType"
<*> o .: "jgnLabel"
<*> o .:? "jgnMetadata"
instance ToJSON JSONGraphNode where
toJSON (JSONGraphNode jgnId' jgnType' jgnLabel' jgnMetadata') = object $ catMaybes
[ ("jgnId" .=) <$> pure jgnId'
, ("jgnType" .=) <$> pure jgnType'
, ("jgnLabel" .=) <$> pure jgnLabel'
, ("jgnMetadata" .=) <$> jgnMetadata' ]
-- | Representation of an edge of a JSON graph.
data JSONGraphEdge = JSONGraphEdge
{
jgeSource :: String
, jgeRelation :: String
, jgeTarget :: String
-- , jgeDirected :: Maybe Bool
-- , jgeLabel :: Maybe String
} deriving (Show)
-- | Representation of a JSON graph.
data JSONGraph = JSONGraph
{
jgDirected :: Bool
, jgType :: String
, jgLabel :: String
, jgNodes :: [JSONGraphNode]
, jgEdges :: [JSONGraphEdge]
-- , jgmetadata :: JSONGraphMetadata
} deriving (Show)
-- | Representation of a collection of JSON graphs.
data JSONGraphs = JSONGraphs
{
graphs :: [JSONGraph]
} deriving (Show)
-- | Derive ToJSON and FromJSON.
concat <$> mapM (deriveJSON defaultOptions) [''JSONGraphNodeFact, ''JSONGraphNodeMetadata, ''JSONGraphEdge, ''JSONGraph, ''JSONGraphs]
-- | Generation of JSON text from JSON graphs.
-- | Flatten out pretty printed facts from prettyLNFact etc.
cleanString :: [Char] -> [Char]
cleanString [] = []
cleanString (' ':'\n':' ':xs) = cleanString (' ':xs)
cleanString ('\n':xs) = cleanString xs
cleanString (' ':' ':xs) = cleanString (' ':xs)
cleanString (c:xs) = (c:cleanString xs)
-- | Convert output of pretty print functions to string.
pps :: Doc -> String
pps d = cleanString $ render d
-- | EncodePretty encodes '<' as "\u003c" and '>' as "\u003e".
-- This function replaces these characters.
removePseudoUnicode :: [Char] -> [Char]
removePseudoUnicode [] = []
removePseudoUnicode ('\\':'u':'0':'0':'3':'c':xs) = ('<':removePseudoUnicode xs)
removePseudoUnicode ('\\':'u':'0':'0':'3':'e':xs) = ('>':removePseudoUnicode xs)
removePseudoUnicode (x:xs) = (x:removePseudoUnicode xs)
-- | Remove " from start and end of string.
plainstring :: String -> String
plainstring ('\"':s) = reverse $ plainstring $ reverse s
plainstring s = s
-- | Determine the type of rule for a JSON node.
getRuleType :: HasRuleName r => r -> String
getRuleType r
| isIntruderRule r = "isIntruderRule"
| isDestrRule r = "isDestrRule"
| isIEqualityRule r = "isIEqualityRule"
| isConstrRule r = "isConstrRule"
| isPubConstrRule r = "isPubConstrRule"
| isFreshRule r = "isFreshRule"
| isIRecvRule r = "isIRecvRule"
| isISendRule r = "isISendRule"
| isCoerceRule r = "isCoerceRule"
| isProtocolRule r = "isProtocolRule"
| otherwise = "unknown rule type"
-- | Generate the JSON data structure from a term.
-- | "instance Show a" in Raw.hs served as example.
lntermToJSONGraphNodeTerm :: Bool -> LNTerm -> JSONGraphNodeTerm
lntermToJSONGraphNodeTerm pretty t =
case viewTerm t of
Lit l -> Const (show l)
FApp (NoEq (s,_)) []
-> Funct (plainstring $ show s) [] res
FApp (NoEq (s,_)) as
-> Funct (plainstring $ show s) (map (lntermToJSONGraphNodeTerm pretty) as) res
FApp (AC o) as
-> Funct (show o) (map (lntermToJSONGraphNodeTerm pretty) as) res
_ -> Const ("unknown term type: " ++ show t)
where
res = case pretty of
True -> show t
False -> ""
-- | Generate the JSON data structure for items such as facts and actions.
itemToJSONGraphNodeFact :: Bool -> String -> LNFact -> JSONGraphNodeFact
itemToJSONGraphNodeFact pretty id' f =
JSONGraphNodeFact { jgnFactId = id'
, jgnFactTag = case isProtoFact f of
True -> "ProtoFact"
False -> show (factTag f)
, jgnFactName = showFactTag $ factTag f
, jgnFactMult = case factTagMultiplicity $ factTag f of
Linear -> ""
Persistent -> "!"
, jgnFactTerms = map (lntermToJSONGraphNodeTerm pretty) (factTerms f)
, jgnFactShow = case pretty of
True -> pps $ prettyLNFact f
False -> ""
}
{-|
Generate JSON data structure for facts in premises and conclusion of rules.
Since facts are ordered in the premises and conclusions, the ordering number as well as a prefix
("p" (premise) and "c" (conclusion)) are given to the function.
-}
factToJSONGraphNodeFact :: Bool -> String -> NodeId -> (Int,LNFact) -> JSONGraphNodeFact
factToJSONGraphNodeFact pretty prefix n (idx, f) =
itemToJSONGraphNodeFact pretty (show n ++ ":" ++ prefix ++ show idx) f
-- | Generate JSONGraphNode from node of sequent (metadata part).
-- Facts and actions as are represented as metadata to keep close to the original JSON graph schema.
nodeToJSONGraphNodeMetadata :: Bool -> (NodeId, RuleACInst) -> JSONGraphNodeMetadata
nodeToJSONGraphNodeMetadata pretty (n, ru) =
JSONGraphNodeMetadata { jgnPrems = map (factToJSONGraphNodeFact pretty "p" n)
$ zip [0..] $ L.get rPrems ru
, jgnActs = map (itemToJSONGraphNodeFact pretty "action") $ L.get rActs ru
, jgnConcs = map (factToJSONGraphNodeFact pretty "c" n)
$ zip [0..] $ L.get rConcs ru
}
-- | Generate JSONGraphNode from node of sequent.
nodeToJSONGraphNode :: Bool -> (NodeId, RuleACInst) -> JSONGraphNode
nodeToJSONGraphNode pretty (n, ru) =
JSONGraphNode { jgnId = show n
, jgnType = getRuleType ru
, jgnLabel = getRuleName ru
, jgnMetadata = Just (nodeToJSONGraphNodeMetadata pretty (n, ru))
}
-- | Determine the type of an edge.
getRelationType :: NodeConc -> NodePrem -> System -> String
getRelationType src tgt se =
let check p = maybe False p (resolveNodePremFact tgt se) ||
maybe False p (resolveNodeConcFact src se)
relationType | check isKFact = "KFact"
| check isPersistentFact = "PersistentFact"
| check isProtoFact = "ProtoFact"
| otherwise = "default"
in
relationType
-- | Generate JSON data structure for lastAtom.
lastAtomToJSONGraphNode :: Maybe NodeId -> [JSONGraphNode]
lastAtomToJSONGraphNode n = case n of
Nothing -> []
Just n' -> [JSONGraphNode { jgnId = show n'
, jgnType = "lastAtom"
, jgnLabel = show n'
, jgnMetadata = Nothing
}]
-- | Generate JSON data structure for unsolvedActionAtom.
unsolvedActionAtomsToJSONGraphNode :: Bool -> (NodeId, LNFact) -> JSONGraphNode
unsolvedActionAtomsToJSONGraphNode pretty (n, f) =
JSONGraphNode
{ jgnId = show n
, jgnType = "unsolvedActionAtom"
, jgnLabel = case pretty of
True -> pps $ prettyLNFact f
False -> ""
, jgnMetadata =
Just JSONGraphNodeMetadata
{ jgnPrems = []
, jgnActs = [itemToJSONGraphNodeFact pretty "action" f]
, jgnConcs = []
}
}
{-|
Generate a JSONGraphNode for those nodes in sEdges that are not present in sNodes.
This might occur in the case distinctions shown in the GUI.
Since a fact is missing, the id is encoded as jgnFactId, could also be done directly in jgnId.
-}
missingNodesToJSONGraphNodes :: System -> [Edge] -> [JSONGraphNode]
missingNodesToJSONGraphNodes _ [] = []
missingNodesToJSONGraphNodes se ((Edge (sid, _) (tid, _)):el)
| notElem sid nodelist =
(JSONGraphNode
{ jgnId = show sid
, jgnType = "missingNodeConc"
, jgnLabel = ""
, jgnMetadata =
Just JSONGraphNodeMetadata
{ jgnPrems = []
, jgnActs = []
, jgnConcs =
[ JSONGraphNodeFact
{ jgnFactId = show sid ++":c0"
, jgnFactTag = ""
, jgnFactName = ""
, jgnFactMult = ""
, jgnFactTerms = []
, jgnFactShow = ""
}
]
}
}: missingNodesToJSONGraphNodes se el)
| notElem tid nodelist =
(JSONGraphNode
{ jgnId = show tid
, jgnType = "missingNodePrem"
, jgnLabel = ""
, jgnMetadata =
Just JSONGraphNodeMetadata
{ jgnPrems =
[ JSONGraphNodeFact
{ jgnFactId = show tid ++":p0"
, jgnFactTag = ""
, jgnFactName = ""
, jgnFactMult = ""
, jgnFactTerms = []
, jgnFactShow = ""
}
]
, jgnActs = []
, jgnConcs = []
}
}: missingNodesToJSONGraphNodes se el)
| otherwise = (missingNodesToJSONGraphNodes se el)
where
nodelist = map fst $ M.toList $ L.get sNodes se
-- | Generate JSON data structure for edges.
edgeToJSONGraphEdge :: System -> Edge -> JSONGraphEdge
edgeToJSONGraphEdge se (Edge src tgt) =
JSONGraphEdge { jgeSource = show sid ++ ":c" ++ show concidx
, jgeTarget = show tid ++ ":p" ++ show premidx
, jgeRelation = getRelationType src tgt se
}
where
(sid, ConcIdx concidx) = src
(tid, PremIdx premidx) = tgt
-- | Generate JSON data structure for lessAtoms edge.
lessAtomsToJSONGraphEdge :: (NodeId, NodeId) -> JSONGraphEdge
lessAtomsToJSONGraphEdge (src, tgt) =
JSONGraphEdge { jgeSource = show src
, jgeRelation = "LessAtoms"
, jgeTarget = show tgt
}
-- | Generate JSON data structure for unsolvedChain edge.
unsolvedchainToJSONGraphEdge :: (NodeConc, NodePrem) -> JSONGraphEdge
unsolvedchainToJSONGraphEdge (src, tgt) =
JSONGraphEdge { jgeSource = show sid ++ ":c" ++ show concidx
, jgeTarget = show tid ++ ":p" ++ show premidx
, jgeRelation = "unsolvedChain"
}
where
(sid, ConcIdx concidx) = src
(tid, PremIdx premidx) = tgt
-- | Generate JSON graph(s) data structure from sequent.
sequentToJSONGraphs :: Bool -- ^ determines whether facts etc are also pretty printed
-> String -- ^ label of graph
-> System -- ^ sequent to dump to JSON
-> JSONGraphs
sequentToJSONGraphs pretty label se =
JSONGraphs
{ graphs =
[ JSONGraph
{ jgDirected = True
, jgType = "Tamarin prover constraint system"
, jgLabel = label
, jgNodes = (map (nodeToJSONGraphNode pretty) $ M.toList $ L.get sNodes se)
++ (lastAtomToJSONGraphNode $ L.get sLastAtom se)
++ (map (unsolvedActionAtomsToJSONGraphNode pretty) $ unsolvedActionAtoms se)
++ (missingNodesToJSONGraphNodes se $ S.toList $ L.get sEdges se)
, jgEdges = (map (edgeToJSONGraphEdge se) $ S.toList $ L.get sEdges se)
++ (map lessAtomsToJSONGraphEdge $ S.toList $ L.get sLessAtoms se)
++ (map unsolvedchainToJSONGraphEdge $ unsolvedChains se)
}
]
}
-- | Generate JSON bytestring from sequent.
sequentToJSON :: String -> System -> String
sequentToJSON l se =
BC.unpack $ encode (sequentToJSONGraphs False l se)
-- | NOTE (dschoop): encodePretty encodes < and > as "\u003c" and "\u003e" respectively.
-- The encoding is removed with function removePseudoUnicode since Data.Strings.Util is non-standard.
-- The function encodePretty returns Data.ByteString.Lazy.Internal.ByteString containing
-- 8-bit bytes. However, eventually some other ByteString or String is expected by writeFile
-- in /src/Web/Theory.hs.
sequentToJSONPretty :: String -> System -> String
sequentToJSONPretty l se =
removePseudoUnicode $ BC.unpack $ encodePretty $ sequentToJSONGraphs True l se
writeSequentAsJSONToFile :: FilePath -> String -> System -> IO ()
writeSequentAsJSONToFile fp l se =
do writeFile fp $ sequentToJSON l se
writeSequentAsJSONPrettyToFile :: FilePath -> String -> System -> IO ()
writeSequentAsJSONPrettyToFile fp l se =
do writeFile fp $ sequentToJSONPretty l se
| rsasse/tamarin-prover | lib/theory/src/Theory/Constraint/System/JSON.hs | gpl-3.0 | 17,311 | 3 | 18 | 5,535 | 3,347 | 1,812 | 1,535 | 272 | 6 |
{--------------------------------------------------------------------------------
The 'hello world' demo from the wxWidgets site.
--------------------------------------------------------------------------------}
module Main where
import Graphics.UI.WXCore
main
= run helloWorld
helloWorld
= do -- create file menu
fm <- menuCreate "" 0
menuAppend fm wxID_ABOUT "&About.." "About wxHaskell" False {- not checkable -}
menuAppendSeparator fm
menuAppend fm wxID_EXIT "&Quit\tCtrl-Q" "Quit the demo" False
-- create menu bar
m <- menuBarCreate 0
menuBarAppend m fm "&File"
-- create top frame
f <- frameCreate objectNull idAny "Hello world" rectZero frameDefaultStyle
windowSetBackgroundColour f white
windowSetClientSize f (sz 600 250)
-- set status bar with 1 field
frameCreateStatusBar f 1 0
frameSetStatusText f "Welcome to wxHaskell" 0
-- connect menu
frameSetMenuBar f m
evtHandlerOnMenuCommand f wxID_ABOUT (onAbout f)
evtHandlerOnMenuCommand f wxID_EXIT (onQuit f)
-- show it
windowShow f
windowRaise f
return ()
where
onAbout f
= do version <- versionNumber
messageDialog f "About 'Hello World'" ("This is a wxHaskell " ++ show version ++ " sample") (wxOK + wxICON_INFORMATION)
return ()
onQuit f
= do windowClose f True {- force close -}
return ()
| ekmett/wxHaskell | samples/wxcore/HelloWorld.hs | lgpl-2.1 | 1,484 | 0 | 13 | 400 | 302 | 137 | 165 | 30 | 1 |
{- -*- Mode: haskell; -*-
Haskell LDAP Interface
Copyright (C) 2005 John Goerzen <[email protected]>
This code is under a 3-clause BSD license; see COPYING for details.
-}
{- |
Module : LDAP.TypesLL
Copyright : Copyright (C) 2005-2006 John Goerzen
License : BSD
Maintainer : John Goerzen,
Maintainer : jgoerzen\@complete.org
Stability : provisional
Portability: portable
Low-level types for LDAP programs.
Written by John Goerzen, jgoerzen\@complete.org
-}
module LDAP.TypesLL(CLDAP, Berval)
where
data CLDAP
data Berval
| ezyang/ldap-haskell | LDAP/TypesLL.hs | bsd-3-clause | 563 | 0 | 4 | 111 | 22 | 15 | 7 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Network.Wai.Handler.Warp.Internal (
-- * Settings
Settings (..)
, ProxyProtocol(..)
-- * Low level run functions
, runSettingsConnection
, runSettingsConnectionMaker
, runSettingsConnectionMakerSecure
, runServe
, runServeEnv
, runServeSettings
, runServeSettingsSocket
, runServeSettingsConnection
, runServeSettingsConnectionMaker
, runServeSettingsConnectionMakerSecure
, Transport (..)
-- * ServeConnection
, ServeConnection
, serveDefault
, serveHTTP2
-- * Connection
, Connection (..)
, socketConnection
-- ** Receive
, Recv
, RecvBuf
, makePlainReceiveN
-- ** Buffer
, Buffer
, BufSize
, bufferSize
, allocateBuffer
, freeBuffer
, copy
-- ** Sendfile
, FileId (..)
, SendFile
, sendFile
, readSendFile
-- * Version
, warpVersion
-- * Data types
, InternalInfo (..)
, HeaderValue
, IndexedHeader
, requestMaxIndex
-- * Time out manager
-- |
--
-- In order to provide slowloris protection, Warp provides timeout handlers. We
-- follow these rules:
--
-- * A timeout is created when a connection is opened.
--
-- * When all request headers are read, the timeout is tickled.
--
-- * Every time at least the slowloris size settings number of bytes of the request
-- body are read, the timeout is tickled.
--
-- * The timeout is paused while executing user code. This will apply to both
-- the application itself, and a ResponseSource response. The timeout is
-- resumed as soon as we return from user code.
--
-- * Every time data is successfully sent to the client, the timeout is tickled.
, module Network.Wai.Handler.Warp.Timeout
-- * File descriptor cache
, module Network.Wai.Handler.Warp.FdCache
-- * Date
, module Network.Wai.Handler.Warp.Date
-- * Request and response
, Source
, recvRequest
, sendResponse
) where
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.Date
import Network.Wai.Handler.Warp.FdCache
import Network.Wai.Handler.Warp.Header
import Network.Wai.Handler.Warp.Recv
import Network.Wai.Handler.Warp.Request
import Network.Wai.Handler.Warp.Response
import Network.Wai.Handler.Warp.Run
import Network.Wai.Handler.Warp.SendFile
import Network.Wai.Handler.Warp.Settings
import Network.Wai.Handler.Warp.Timeout
import Network.Wai.Handler.Warp.Types
| rgrinberg/wai | warp/Network/Wai/Handler/Warp/Internal.hs | mit | 2,460 | 0 | 5 | 511 | 306 | 228 | 78 | 56 | 0 |
{-# LANGUAGE ExistentialQuantification, FlexibleInstances, GeneralizedNewtypeDeriving,
MultiParamTypeClasses, TypeSynonymInstances, CPP, DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Core
-- Copyright : (c) Spencer Janssen 2007
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : not portable, uses cunning newtype deriving
--
-- The 'X' monad, a state monad transformer over 'IO', for the window
-- manager state, and support routines.
--
-----------------------------------------------------------------------------
module XMonad.Core (
X, WindowSet, WindowSpace, WorkspaceId,
ScreenId(..), ScreenDetail(..), XState(..),
XConf(..), XConfig(..), LayoutClass(..),
Layout(..), readsLayout, Typeable, Message,
SomeMessage(..), fromMessage, LayoutMessages(..),
StateExtension(..), ExtensionClass(..),
runX, catchX, userCode, userCodeDef, io, catchIO, installSignalHandlers, uninstallSignalHandlers,
withDisplay, withWindowSet, isRoot, runOnWorkspaces,
getAtom, spawn, spawnPID, xfork, getXMonadDir, recompile, trace, whenJust, whenX,
atom_WM_STATE, atom_WM_PROTOCOLS, atom_WM_DELETE_WINDOW, ManageHook, Query(..), runQuery
) where
import XMonad.StackSet hiding (modify)
import Prelude hiding ( catch )
import Codec.Binary.UTF8.String (encodeString)
import Control.Exception.Extensible (catch, fromException, try, bracket, throw, finally, SomeException(..))
import Control.Applicative
import Control.Monad.State
import Control.Monad.Reader
import System.FilePath
import System.IO
import System.Info
import System.Posix.Process (executeFile, forkProcess, getAnyProcessStatus, createSession)
import System.Posix.Signals
import System.Posix.IO
import System.Posix.Types (ProcessID)
import System.Process
import System.Directory
import System.Exit
import Graphics.X11.Xlib
import Graphics.X11.Xlib.Extras (Event)
import Data.Typeable
import Data.List ((\\))
import Data.Maybe (isJust,fromMaybe)
import Data.Monoid
import qualified Data.Map as M
import qualified Data.Set as S
-- | XState, the (mutable) window manager state.
data XState = XState
{ windowset :: !WindowSet -- ^ workspace list
, mapped :: !(S.Set Window) -- ^ the Set of mapped windows
, waitingUnmap :: !(M.Map Window Int) -- ^ the number of expected UnmapEvents
, dragging :: !(Maybe (Position -> Position -> X (), X ()))
, numberlockMask :: !KeyMask -- ^ The numlock modifier
, extensibleState :: !(M.Map String (Either String StateExtension))
-- ^ stores custom state information.
--
-- The module "XMonad.Utils.ExtensibleState" in xmonad-contrib
-- provides additional information and a simple interface for using this.
}
-- | XConf, the (read-only) window manager configuration.
data XConf = XConf
{ display :: Display -- ^ the X11 display
, config :: !(XConfig Layout) -- ^ initial user configuration
, theRoot :: !Window -- ^ the root window
, normalBorder :: !Pixel -- ^ border color of unfocused windows
, focusedBorder :: !Pixel -- ^ border color of the focused window
, keyActions :: !(M.Map (KeyMask, KeySym) (X ()))
-- ^ a mapping of key presses to actions
, buttonActions :: !(M.Map (KeyMask, Button) (Window -> X ()))
-- ^ a mapping of button presses to actions
, mouseFocused :: !Bool -- ^ was refocus caused by mouse action?
, mousePosition :: !(Maybe (Position, Position))
-- ^ position of the mouse according to
-- the event currently being processed
}
-- todo, better name
data XConfig l = XConfig
{ normalBorderColor :: !String -- ^ Non focused windows border color. Default: \"#dddddd\"
, focusedBorderColor :: !String -- ^ Focused windows border color. Default: \"#ff0000\"
, terminal :: !String -- ^ The preferred terminal application. Default: \"xterm\"
, layoutHook :: !(l Window) -- ^ The available layouts
, manageHook :: !ManageHook -- ^ The action to run when a new window is opened
, handleEventHook :: !(Event -> X All) -- ^ Handle an X event, returns (All True) if the default handler
-- should also be run afterwards. mappend should be used for combining
-- event hooks in most cases.
, workspaces :: ![String] -- ^ The list of workspaces' names
, modMask :: !KeyMask -- ^ the mod modifier
, keys :: !(XConfig Layout -> M.Map (ButtonMask,KeySym) (X ()))
-- ^ The key binding: a map from key presses and actions
, mouseBindings :: !(XConfig Layout -> M.Map (ButtonMask, Button) (Window -> X ()))
-- ^ The mouse bindings
, borderWidth :: !Dimension -- ^ The border width
, logHook :: !(X ()) -- ^ The action to perform when the windows set is changed
, startupHook :: !(X ()) -- ^ The action to perform on startup
, focusFollowsMouse :: !Bool -- ^ Whether window entry events can change focus
}
type WindowSet = StackSet WorkspaceId (Layout Window) Window ScreenId ScreenDetail
type WindowSpace = Workspace WorkspaceId (Layout Window) Window
-- | Virtual workspace indices
type WorkspaceId = String
-- | Physical screen indices
newtype ScreenId = S Int deriving (Eq,Ord,Show,Read,Enum,Num,Integral,Real)
-- | The 'Rectangle' with screen dimensions
data ScreenDetail = SD { screenRect :: !Rectangle } deriving (Eq,Show, Read)
------------------------------------------------------------------------
-- | The X monad, 'ReaderT' and 'StateT' transformers over 'IO'
-- encapsulating the window manager configuration and state,
-- respectively.
--
-- Dynamic components may be retrieved with 'get', static components
-- with 'ask'. With newtype deriving we get readers and state monads
-- instantiated on 'XConf' and 'XState' automatically.
--
newtype X a = X (ReaderT XConf (StateT XState IO) a)
deriving (Functor, Monad, MonadIO, MonadState XState, MonadReader XConf, Typeable)
instance Applicative X where
pure = return
(<*>) = ap
instance (Monoid a) => Monoid (X a) where
mempty = return mempty
mappend = liftM2 mappend
type ManageHook = Query (Endo WindowSet)
newtype Query a = Query (ReaderT Window X a)
deriving (Functor, Monad, MonadReader Window, MonadIO)
runQuery :: Query a -> Window -> X a
runQuery (Query m) w = runReaderT m w
instance Monoid a => Monoid (Query a) where
mempty = return mempty
mappend = liftM2 mappend
-- | Run the 'X' monad, given a chunk of 'X' monad code, and an initial state
-- Return the result, and final state
runX :: XConf -> XState -> X a -> IO (a, XState)
runX c st (X a) = runStateT (runReaderT a c) st
-- | Run in the 'X' monad, and in case of exception, and catch it and log it
-- to stderr, and run the error case.
catchX :: X a -> X a -> X a
catchX job errcase = do
st <- get
c <- ask
(a, s') <- io $ runX c st job `catch` \e -> case fromException e of
Just x -> throw e `const` (x `asTypeOf` ExitSuccess)
_ -> do hPrint stderr e; runX c st errcase
put s'
return a
-- | Execute the argument, catching all exceptions. Either this function or
-- 'catchX' should be used at all callsites of user customized code.
userCode :: X a -> X (Maybe a)
userCode a = catchX (Just `liftM` a) (return Nothing)
-- | Same as userCode but with a default argument to return instead of using
-- Maybe, provided for convenience.
userCodeDef :: a -> X a -> X a
userCodeDef def a = fromMaybe def `liftM` userCode a
-- ---------------------------------------------------------------------
-- Convenient wrappers to state
-- | Run a monad action with the current display settings
withDisplay :: (Display -> X a) -> X a
withDisplay f = asks display >>= f
-- | Run a monadic action with the current stack set
withWindowSet :: (WindowSet -> X a) -> X a
withWindowSet f = gets windowset >>= f
-- | True if the given window is the root window
isRoot :: Window -> X Bool
isRoot w = (w==) <$> asks theRoot
-- | Wrapper for the common case of atom internment
getAtom :: String -> X Atom
getAtom str = withDisplay $ \dpy -> io $ internAtom dpy str False
-- | Common non-predefined atoms
atom_WM_PROTOCOLS, atom_WM_DELETE_WINDOW, atom_WM_STATE :: X Atom
atom_WM_PROTOCOLS = getAtom "WM_PROTOCOLS"
atom_WM_DELETE_WINDOW = getAtom "WM_DELETE_WINDOW"
atom_WM_STATE = getAtom "WM_STATE"
------------------------------------------------------------------------
-- LayoutClass handling. See particular instances in Operations.hs
-- | An existential type that can hold any object that is in 'Read'
-- and 'LayoutClass'.
data Layout a = forall l. (LayoutClass l a, Read (l a)) => Layout (l a)
-- | Using the 'Layout' as a witness, parse existentially wrapped windows
-- from a 'String'.
readsLayout :: Layout a -> String -> [(Layout a, String)]
readsLayout (Layout l) s = [(Layout (asTypeOf x l), rs) | (x, rs) <- reads s]
-- | Every layout must be an instance of 'LayoutClass', which defines
-- the basic layout operations along with a sensible default for each.
--
-- Minimal complete definition:
--
-- * 'runLayout' || (('doLayout' || 'pureLayout') && 'emptyLayout'), and
--
-- * 'handleMessage' || 'pureMessage'
--
-- You should also strongly consider implementing 'description',
-- although it is not required.
--
-- Note that any code which /uses/ 'LayoutClass' methods should only
-- ever call 'runLayout', 'handleMessage', and 'description'! In
-- other words, the only calls to 'doLayout', 'pureMessage', and other
-- such methods should be from the default implementations of
-- 'runLayout', 'handleMessage', and so on. This ensures that the
-- proper methods will be used, regardless of the particular methods
-- that any 'LayoutClass' instance chooses to define.
class Show (layout a) => LayoutClass layout a where
-- | By default, 'runLayout' calls 'doLayout' if there are any
-- windows to be laid out, and 'emptyLayout' otherwise. Most
-- instances of 'LayoutClass' probably do not need to implement
-- 'runLayout'; it is only useful for layouts which wish to make
-- use of more of the 'Workspace' information (for example,
-- "XMonad.Layout.PerWorkspace").
runLayout :: Workspace WorkspaceId (layout a) a
-> Rectangle
-> X ([(a, Rectangle)], Maybe (layout a))
runLayout (Workspace _ l ms) r = maybe (emptyLayout l r) (doLayout l r) ms
-- | Given a 'Rectangle' in which to place the windows, and a 'Stack'
-- of windows, return a list of windows and their corresponding
-- Rectangles. If an element is not given a Rectangle by
-- 'doLayout', then it is not shown on screen. The order of
-- windows in this list should be the desired stacking order.
--
-- Also possibly return a modified layout (by returning @Just
-- newLayout@), if this layout needs to be modified (e.g. if it
-- keeps track of some sort of state). Return @Nothing@ if the
-- layout does not need to be modified.
--
-- Layouts which do not need access to the 'X' monad ('IO', window
-- manager state, or configuration) and do not keep track of their
-- own state should implement 'pureLayout' instead of 'doLayout'.
doLayout :: layout a -> Rectangle -> Stack a
-> X ([(a, Rectangle)], Maybe (layout a))
doLayout l r s = return (pureLayout l r s, Nothing)
-- | This is a pure version of 'doLayout', for cases where we
-- don't need access to the 'X' monad to determine how to lay out
-- the windows, and we don't need to modify the layout itself.
pureLayout :: layout a -> Rectangle -> Stack a -> [(a, Rectangle)]
pureLayout _ r s = [(focus s, r)]
-- | 'emptyLayout' is called when there are no windows.
emptyLayout :: layout a -> Rectangle -> X ([(a, Rectangle)], Maybe (layout a))
emptyLayout _ _ = return ([], Nothing)
-- | 'handleMessage' performs message handling. If
-- 'handleMessage' returns @Nothing@, then the layout did not
-- respond to the message and the screen is not refreshed.
-- Otherwise, 'handleMessage' returns an updated layout and the
-- screen is refreshed.
--
-- Layouts which do not need access to the 'X' monad to decide how
-- to handle messages should implement 'pureMessage' instead of
-- 'handleMessage' (this restricts the risk of error, and makes
-- testing much easier).
handleMessage :: layout a -> SomeMessage -> X (Maybe (layout a))
handleMessage l = return . pureMessage l
-- | Respond to a message by (possibly) changing our layout, but
-- taking no other action. If the layout changes, the screen will
-- be refreshed.
pureMessage :: layout a -> SomeMessage -> Maybe (layout a)
pureMessage _ _ = Nothing
-- | This should be a human-readable string that is used when
-- selecting layouts by name. The default implementation is
-- 'show', which is in some cases a poor default.
description :: layout a -> String
description = show
instance LayoutClass Layout Window where
runLayout (Workspace i (Layout l) ms) r = fmap (fmap Layout) `fmap` runLayout (Workspace i l ms) r
doLayout (Layout l) r s = fmap (fmap Layout) `fmap` doLayout l r s
emptyLayout (Layout l) r = fmap (fmap Layout) `fmap` emptyLayout l r
handleMessage (Layout l) = fmap (fmap Layout) . handleMessage l
description (Layout l) = description l
instance Show (Layout a) where show (Layout l) = show l
-- | Based on ideas in /An Extensible Dynamically-Typed Hierarchy of
-- Exceptions/, Simon Marlow, 2006. Use extensible messages to the
-- 'handleMessage' handler.
--
-- User-extensible messages must be a member of this class.
--
class Typeable a => Message a
-- |
-- A wrapped value of some type in the 'Message' class.
--
data SomeMessage = forall a. Message a => SomeMessage a
-- |
-- And now, unwrap a given, unknown 'Message' type, performing a (dynamic)
-- type check on the result.
--
fromMessage :: Message m => SomeMessage -> Maybe m
fromMessage (SomeMessage m) = cast m
-- X Events are valid Messages.
instance Message Event
-- | 'LayoutMessages' are core messages that all layouts (especially stateful
-- layouts) should consider handling.
data LayoutMessages = Hide -- ^ sent when a layout becomes non-visible
| ReleaseResources -- ^ sent when xmonad is exiting or restarting
deriving (Typeable, Eq)
instance Message LayoutMessages
-- ---------------------------------------------------------------------
-- Extensible state
--
-- | Every module must make the data it wants to store
-- an instance of this class.
--
-- Minimal complete definition: initialValue
class Typeable a => ExtensionClass a where
-- | Defines an initial value for the state extension
initialValue :: a
-- | Specifies whether the state extension should be
-- persistent. Setting this method to 'PersistentExtension'
-- will make the stored data survive restarts, but
-- requires a to be an instance of Read and Show.
--
-- It defaults to 'StateExtension', i.e. no persistence.
extensionType :: a -> StateExtension
extensionType = StateExtension
-- | Existential type to store a state extension.
data StateExtension =
forall a. ExtensionClass a => StateExtension a
-- ^ Non-persistent state extension
| forall a. (Read a, Show a, ExtensionClass a) => PersistentExtension a
-- ^ Persistent extension
-- ---------------------------------------------------------------------
-- | General utilities
--
-- Lift an 'IO' action into the 'X' monad
io :: MonadIO m => IO a -> m a
io = liftIO
-- | Lift an 'IO' action into the 'X' monad. If the action results in an 'IO'
-- exception, log the exception to stderr and continue normal execution.
catchIO :: MonadIO m => IO () -> m ()
catchIO f = io (f `catch` \(SomeException e) -> hPrint stderr e >> hFlush stderr)
-- | spawn. Launch an external application. Specifically, it double-forks and
-- runs the 'String' you pass as a command to \/bin\/sh.
--
-- Note this function assumes your locale uses utf8.
spawn :: MonadIO m => String -> m ()
spawn x = spawnPID x >> return ()
-- | Like 'spawn', but returns the 'ProcessID' of the launched application
spawnPID :: MonadIO m => String -> m ProcessID
spawnPID x = xfork $ executeFile "/bin/sh" False ["-c", encodeString x] Nothing
-- | A replacement for 'forkProcess' which resets default signal handlers.
xfork :: MonadIO m => IO () -> m ProcessID
xfork x = io . forkProcess . finally nullStdin $ do
uninstallSignalHandlers
createSession
x
where
nullStdin = do
fd <- openFd "/dev/null" ReadOnly Nothing defaultFileFlags
dupTo fd stdInput
closeFd fd
-- | This is basically a map function, running a function in the 'X' monad on
-- each workspace with the output of that function being the modified workspace.
runOnWorkspaces :: (WindowSpace -> X WindowSpace) -> X ()
runOnWorkspaces job = do
ws <- gets windowset
h <- mapM job $ hidden ws
c:v <- mapM (\s -> (\w -> s { workspace = w}) <$> job (workspace s))
$ current ws : visible ws
modify $ \s -> s { windowset = ws { current = c, visible = v, hidden = h } }
-- | Return the path to @~\/.xmonad@.
getXMonadDir :: MonadIO m => m String
getXMonadDir = io $ getAppUserDataDirectory "xmonad"
-- | 'recompile force', recompile @~\/.xmonad\/xmonad.hs@ when any of the
-- following apply:
--
-- * force is 'True'
--
-- * the xmonad executable does not exist
--
-- * the xmonad executable is older than xmonad.hs or any file in
-- ~\/.xmonad\/lib
--
-- The -i flag is used to restrict recompilation to the xmonad.hs file only,
-- and any files in the ~\/.xmonad\/lib directory.
--
-- Compilation errors (if any) are logged to ~\/.xmonad\/xmonad.errors. If
-- GHC indicates failure with a non-zero exit code, an xmessage displaying
-- that file is spawned.
--
-- 'False' is returned if there are compilation errors.
--
recompile :: MonadIO m => Bool -> m Bool
recompile force = io $ do
dir <- getXMonadDir
let binn = "xmonad-"++arch++"-"++os
bin = dir </> binn
base = dir </> "xmonad"
err = base ++ ".errors"
src = base ++ ".hs"
lib = dir </> "lib"
libTs <- mapM getModTime . Prelude.filter isSource =<< allFiles lib
srcT <- getModTime src
binT <- getModTime bin
if force || any (binT <) (srcT : libTs)
then do
-- temporarily disable SIGCHLD ignoring:
uninstallSignalHandlers
status <- bracket (openFile err WriteMode) hClose $ \h ->
waitForProcess =<< runProcess "ghc" ["--make", "xmonad.hs", "-i", "-ilib", "-fforce-recomp", "-v0", "-o",binn] (Just dir)
Nothing Nothing Nothing (Just h)
-- re-enable SIGCHLD:
installSignalHandlers
-- now, if it fails, run xmessage to let the user know:
when (status /= ExitSuccess) $ do
ghcErr <- readFile err
let msg = unlines $
["Error detected while loading xmonad configuration file: " ++ src]
++ lines (if null ghcErr then show status else ghcErr)
++ ["","Please check the file for errors."]
-- nb, the ordering of printing, then forking, is crucial due to
-- lazy evaluation
hPutStrLn stderr msg
forkProcess $ executeFile "xmessage" True ["-default", "okay", msg] Nothing
return ()
return (status == ExitSuccess)
else return True
where getModTime f = catch (Just <$> getModificationTime f) (\(SomeException _) -> return Nothing)
isSource = flip elem [".hs",".lhs",".hsc"]
allFiles t = do
let prep = map (t</>) . Prelude.filter (`notElem` [".",".."])
cs <- prep <$> catch (getDirectoryContents t) (\(SomeException _) -> return [])
ds <- filterM doesDirectoryExist cs
concat . ((cs \\ ds):) <$> mapM allFiles ds
-- | Conditionally run an action, using a @Maybe a@ to decide.
whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
whenJust mg f = maybe (return ()) f mg
-- | Conditionally run an action, using a 'X' event to decide
whenX :: X Bool -> X () -> X ()
whenX a f = a >>= \b -> when b f
-- | A 'trace' for the 'X' monad. Logs a string to stderr. The result may
-- be found in your .xsession-errors file
trace :: MonadIO m => String -> m ()
trace = io . hPutStrLn stderr
-- | Ignore SIGPIPE to avoid termination when a pipe is full, and SIGCHLD to
-- avoid zombie processes, and clean up any extant zombie processes.
installSignalHandlers :: MonadIO m => m ()
installSignalHandlers = io $ do
installHandler openEndedPipe Ignore Nothing
installHandler sigCHLD Ignore Nothing
(try :: IO a -> IO (Either SomeException a))
$ fix $ \more -> do
x <- getAnyProcessStatus False False
when (isJust x) more
return ()
uninstallSignalHandlers :: MonadIO m => m ()
uninstallSignalHandlers = io $ do
installHandler openEndedPipe Default Nothing
installHandler sigCHLD Default Nothing
return ()
| mightymoose/liquidhaskell | benchmarks/xmonad-0.10/XMonad/Core.hs | bsd-3-clause | 22,012 | 0 | 22 | 5,375 | 4,304 | 2,355 | 1,949 | -1 | -1 |
module Definition.Definition where
seven :: Int
seven = 7 | charleso/intellij-haskforce | tests/gold/codeInsight/QualifiedImport_QualifierResolvesMultipleCons_Cons2_NoAs/Definition.hs | apache-2.0 | 58 | 0 | 4 | 9 | 16 | 10 | 6 | 3 | 1 |
module Comonad where
class Functor f => Comonad f where
extract :: f a -> a
duplicate :: f a -> f (f a)
(=>>) :: f a -> (f a -> b) -> f b
x =>> f = fmap f (duplicate x)
| lukegrehan/comonadLife | Comonad.hs | mit | 179 | 0 | 11 | 54 | 106 | 52 | 54 | 6 | 0 |
module D20.Internal.Character.TalentEffect where
-- TODO as much modelling as in FeatEffect.
-- TODO see how much can be extracted into a generic Effect.
data TalentEffect = PermanentTalentEffect | TalentAction
| elkorn/d20 | src/D20/Internal/Character/TalentEffect.hs | mit | 212 | 0 | 5 | 30 | 20 | 14 | 6 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.Ratio ((%))
import Text.Trifecta
badFraction = "1/0"
alsoBad = "10"
shouldWork = "1/2"
shouldAlsoWork = "2/1"
-- Then we’ll write our actual parser:
parseFraction :: Parser Rational
parseFraction = do
numerator <- decimal
char '/'
denominator <- decimal
return (numerator % denominator)
main :: IO ()
main = do
print $ parseString parseFraction mempty shouldWork
print $ parseString parseFraction mempty shouldAlsoWork
print $ parseString parseFraction mempty alsoBad
print $ parseString parseFraction mempty badFraction
virtuousFraction :: Parser Rational
virtuousFraction = do
numerator <- decimal
char '/'
denominator <- decimal
case denominator of
0 -> fail "Denominator cannot be zero"
_ -> return (numerator % denominator)
testVirtuous :: IO ()
testVirtuous = do
print $ parseString virtuousFraction mempty badFraction
print $ parseString virtuousFraction mempty alsoBad
print $ parseString virtuousFraction mempty shouldWork
print $ parseString virtuousFraction mempty shouldAlsoWork
parseAndReturn :: Parser Integer
parseAndReturn = do myNum <- integer
eof
return myNum
myMain = do print $ parseString parseAndReturn mempty "123"
print $ parseString parseAndReturn mempty "123abc"
| diminishedprime/.org | reading-list/haskell_programming_from_first_principles/24_04.hs | mit | 1,368 | 0 | 12 | 273 | 360 | 171 | 189 | 40 | 2 |
{-# LANGUAGE TupleSections #-}
newtype Point = Point (Integer, Integer) deriving Show
vec (Point (x0, y0)) (Point (x1, y1)) = Point (x0 - x1, y0 - y1)
nrm2 (Point (x, y)) = x * x + y * y
r a b c
| c > a && c > b = c == a + b
| a > c && a > b = a == b + c
| b > c && b > a = b == a + c
| otherwise = False
-- right triangles
isRight a b = r (nrm2 a) (nrm2 b) (nrm2 (vec a b))
-- drop first (0,0)
grid n m = tail [Point (x, y) | x <- [0..n], y <- [0..m]]
comb2 [x,y] = [(x, y)]
comb2 (x:xs) = map (x,) xs ++ comb2 xs
rightTri n m = filter (uncurry isRight) $ comb2 $ grid n m
main = print $ length $ rightTri 50 50
| liuyang1/euler | square.091.hs | mit | 629 | 0 | 10 | 176 | 407 | 211 | 196 | 15 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleContexts #-}
module Demos.Animation
( AnimationDemo(..)
, allocDemo
, renderDemo
, freeDemo
) where
import Control.Lens hiding (to)
import Control.Varying
import Linear hiding (rotate)
import Gelatin hiding (move,rotate)
import Data.Char.FontAwesome
import Odin.Core
import Odin.GUI.Text.Internal
import Odin.GUI.Button.Internal
import Odin.GUI.Picture
import Odin.GUI.Animation.Internal
import Odin.GUI.Styles
data AnimationDemo m = AnimationDemo { demoRenderer :: (m (), [RenderTransform] -> m ())
, pauseDemo :: m ()
, resumeDemo :: m ()
}
data MyTween = MyTween { tweenPos :: V2 Float
, tweenScale :: V2 Float
, tweenMultiply :: V4 Float
}
posTween :: Monad m => VarT m Float (V2 Float)
posTween = V2 <$> x <*> y
where x = flip tweenStream 0 $ fix $ \nxt -> do
tween_ easeInExpo 0 100 1
tween_ easeOutExpo 100 200 1
constant 200 1
tween_ easeInExpo 200 100 1
tween_ easeOutExpo 100 0 1
constant 0 1
step 0
nxt
y = flip tweenStream 0 $ fix $ \nxt -> do
constant 0 1
tween_ easeInExpo 0 100 1
tween_ easeOutExpo 100 200 1
constant 200 1
tween_ easeInExpo 200 100 1
tween_ easeOutExpo 100 0 1
step 0
nxt
scaleTween :: Monad m => VarT m Float (V2 Float)
scaleTween = V2 <$> x <*> y
where x = flip tweenStream 1 $ fix $ \nxt -> do
tween_ easeInExpo 1 2 1
tween_ easeOutExpo 2 4 1
tween_ easeInExpo 4 2 1
tween_ easeOutExpo 2 1 1
nxt
y = flip tweenStream 1 $ fix $ \nxt -> do
tween_ easeInExpo 1 2 1
tween_ easeOutExpo 2 4 1
tween_ easeInExpo 4 2 1
tween_ easeOutExpo 2 1 1
nxt
colorTween :: Monad m => VarT m Float (V4 Float)
colorTween = V4 <$> r <*> g <*> b <*> pure 1
where r = flip tweenStream 1 $ fix $ \nxt -> do
step 1
tween easeInExpo 1 0 1
constant 0 2
tween easeInExpo 0 1 1
constant 1 2
nxt
g = flip tweenStream 1 $ fix $ \nxt -> do
step 1
constant 1 1
tween easeInExpo 1 0 1
constant 0 2
tween easeInExpo 0 1 1
constant 1 1
step 1
nxt
b = flip tweenStream 1 $ fix $ \nxt -> do
step 1
constant 1 2
tween easeInExpo 1 0 1
constant 0 2
tween easeInExpo 0 1 1
step 1
step 1
step 1
nxt
myTween :: Monad m => VarT m Float [RenderTransform]
myTween = sequenceA [moveV2 <$> posTween
,scaleV2 <$> scaleTween
,multiplyV4 <$> colorTween
]
allocDemo :: (MonadIO m, Rezed s m, Fonts s m, Time s m, Resources s m)
=> m (AnimationDemo m)
allocDemo = do
comicFont <- getFontPath "KMKDSP__.ttf"
let cdesc = fontDescriptor comicFont 16
title <- allocText cdesc white "Animation Demo"
playBtn <- allocButton (iconButtonPainter 32) [faPlay]
pauseBtn <- allocButton (iconButtonPainter 32) [faPause]
pause <- slot False
anime <- allocAnime myTween
lastRs <- slot []
(_,square) <- allocColorPicture $
setGeometry $ fan $ mapVertices (,white) $ rectangle (-10) 10
V2 tw _ <- sizeOfText title
V2 playw _ <- sizeOfButton playBtn
let render rs = do
renderText title $ move 0 16 : rs
isPaused <- unslot pause
stillPaused <- if isPaused
then (renderButton playBtn $ move (tw + 4) 0 : rs) >>= \case
ButtonStateClicked -> return False
_ -> return isPaused
else (renderButton pauseBtn $ move (tw + 4) 0 : rs) >>= \case
ButtonStateClicked -> return True
_ -> return isPaused
unless stillPaused $
stepAnime anime >>= reslot lastRs
rrs <- unslot lastRs
(_,rnd) <- unslot square
io $ rnd $ rrs ++ rs
pause `is` stillPaused
free = do
freeText title
freeButton playBtn
freeButton pauseBtn
return
AnimationDemo{ demoRenderer = (free, render)
, pauseDemo = pause `is` True
, resumeDemo = pause `is` False
}
renderDemo :: MonadIO m => AnimationDemo m -> [RenderTransform] -> m ()
renderDemo a rs = snd (demoRenderer a) rs
freeDemo :: MonadIO m => AnimationDemo m -> m ()
freeDemo a = fst $ demoRenderer a
| schell/odin | app/Demos/Animation.hs | mit | 5,004 | 0 | 20 | 1,987 | 1,608 | 772 | 836 | 135 | 4 |
{-# LANGUAGE TemplateHaskell #-}
module UnitTest.CallbackParse.MessageCallback where
import Data.Aeson (Value)
import Data.Yaml.TH (decodeFile)
import Test.Tasty as Tasty
import Web.Facebook.Messenger
import UnitTest.Internal
--------------
-- MESSAGES --
--------------
messageTests :: TestTree
messageTests = Tasty.testGroup "Message Callbacks"
[ textCallbackQR
, attachmentImage
, attachmentAudio
, attachmentVideo
, attachmentFallback
, attachmentTemplate
, attachmentLocation
, attachmentSticker
]
textQRVal :: Value
textQRVal = $$(decodeFile "test/json/callback/text_qr_callback.json")
imageVal :: Value
imageVal = $$(decodeFile "test/json/callback/attachment_callback_image.json")
videoVal :: Value
videoVal = $$(decodeFile "test/json/callback/attachment_callback_video.json")
audioVal :: Value
audioVal = $$(decodeFile "test/json/callback/attachment_callback_audio.json")
fallbackVal :: Value
fallbackVal = $$(decodeFile "test/json/callback/attachment_callback_fallback.json")
templateVal :: Value
templateVal = $$(decodeFile "test/json/callback/attachment_callback_template.json")
locationVal :: Value
locationVal = $$(decodeFile "test/json/callback/attachment_callback_location.json")
stickerVal :: Value
stickerVal = $$(decodeFile "test/json/callback/attachment_callback_sticker.json")
textCallbackQR :: TestTree
textCallbackQR = parseTest "Text with QR" textQRVal
$ standardMessaging (Just 1485785260154)
Nothing
contnt
where contnt = CMMessage $ Message "mid.1483715260354:77ac33da15"
(Just 8668)
msgContent
[]
msgContent = MText $ MessageText "CLICK HERE" (Just $ CallbackQuickReply "some_payload")
attachmentImage :: TestTree
attachmentImage = parseTest "Image attachment" imageVal
$ standardMessaging (Just 1521927088604)
Nothing
contnt
where contnt = CMMessage $ Message "mid.$cAAFSuiOlE3doibGxAFiWxoQ_dosX"
(Just 9583)
msgContent
[]
msgContent = MAttachment $ MessageAttachment [att]
att = CAMultimedia $ MultimediaAttachment IMAGE
$ CallbackMultimediaPayload "https://scontent-ort2-2.xx.fbcdn.net/v/t34.0-12/29138552_211240296290531_291369741_n.jpg?_nc_cat=0&_nc_ad=z-m&_nc_cid=0&oh=65d9fcb6baefd7481f5dc477a76571c3&oe=5AB85055"
attachmentAudio :: TestTree
attachmentAudio = parseTest "Audio attachment" audioVal
$ standardMessaging (Just 1522751139155)
Nothing
contnt
where contnt = CMMessage $ Message "mid.$cAAFSsSTn2XdcvE-1U1i5wpqbrOHw"
(Just 3808)
msgContent
[]
msgContent = MAttachment $ MessageAttachment [att]
att = CAMultimedia $ MultimediaAttachment AUDIO
$ CallbackMultimediaPayload "https://cdn.fbsbx.com/v/t59.3654-21/29451513_1977941472233841_8301729723659059200_n.aac/audioclip-1522751138417-2894.aac?_nc_cat=0&oh=a395e53726c98b7e0d60a5d30edcbeab&oe=5AC60884"
attachmentVideo :: TestTree
attachmentVideo = parseTest "Video attachment" videoVal
$ standardMessaging (Just 1524463431537)
Nothing
contnt
where contnt = CMMessage $ Message "mid.$cAAFSt2aYrFJpI8x3ci8RnJfhPTsQ"
(Just 2869)
msgContent
[]
msgContent = MAttachment $ MessageAttachment [att]
att = CAMultimedia $ MultimediaAttachment VIDEO
$ CallbackMultimediaPayload "https://video-ort2-2.xx.fbcdn.net/v/t42.3356-2/31126804_1758684374210244_6397927484334269799_n.mp4/video-1524463431.mp4?_nc_cat=0&vabr=88639&oh=b5ccd0dbf1547bbf3b1c9fcaf4007cd3&oe=5ADF020B"
attachmentFallback :: TestTree
attachmentFallback = parseTest "Fallback attachment" fallbackVal
$ standardMessaging (Just 1484828179384)
Nothing
contnt
where contnt = CMMessage $ Message "mid.1484828179384:02c39cc697"
(Just 5322)
msgContent
[]
msgContent = MAttachment $ MessageAttachment [att]
att = CAFallback $ Fallback (Just "Check us out!")
(Just "https://www.facebook.com/Thisisus/")
Nothing
attachmentTemplate :: TestTree
attachmentTemplate = parseTest "Template attachment" templateVal
$ standardMessaging (Just 1497895209689)
Nothing
contnt
where contnt = CMMessage $ Message "mid.$cAAD2N5dYXFdi8shS2VcwYMKB82oI"
(Just 126384)
msgContent
[]
msgContent = MAttachment $ MessageAttachment [att]
att = CATemplate $ TemplateAttachment (Just "<SOME_TITLE>")
Nothing
(Just "https://www.example.com/")
$ CallbackTemplate (Just True) [e]
e = GenericElement "<ELEMENT_TITLE>"
(Just " ")
(Just "https://www.example.com/some_image.jpg")
(Just $ DefaultAction "http://www.example.com/" FULL False Nothing SHOW)
Nothing
[]
attachmentLocation :: TestTree
attachmentLocation = parseTest "Location attachment" locationVal
$ standardMessaging (Just 1519133473383)
Nothing
contnt
where contnt = CMMessage $ Message "mid.$cAAFSsb24gKln5K6Sb1hshk46ukmJ"
(Just 115715)
msgContent
[]
msgContent = MLocation $ MessageLocation [att]
att = CallbackLocation (Just "Someone's Location")
(Just "<SOME URL USING BING MAPS>")
$ CallbackLocationPayload
$ CallbackCoordinates 52.376232 4.838296
attachmentSticker :: TestTree
attachmentSticker = parseTest "Sticker attachment" stickerVal
$ standardMessaging (Just 1486142376165)
Nothing
contnt
where contnt = CMMessage $ Message "mid.1482142576415:5aaf79ce93"
(Just 31674)
msgContent
[]
msgContent = MSticker $ MessageSticker [att] 369239263222822
att = StickerAttachment
$ CallbackStickerPayload "https://scontent.xx.fbcdn.net/v/t39.1997-6/851557_369239266556155_759568595_n.png?_nc_ad=z-m&oh=6db01d9d3eb168d058cbb2d6692af58f&oe=58978D5C"
369239263222822
| Vlix/facebookmessenger | test/UnitTest/CallbackParse/MessageCallback.hs | mit | 7,634 | 0 | 11 | 2,871 | 1,068 | 553 | 515 | -1 | -1 |
{-# LANGUAGE JavaScriptFFI #-}
-- | An implementation of the NodeJS Certificate API, as documented
-- <https://nodejs.org/api/crypto.html#crypto_class_certificate here>.
module GHCJS.Node.Crypto.Certificate
( SPKAC (..), Challenge (..), PublicKey (..)
, spkacChallenge, spkacPublicKey, spkacVerify
) where
import GHCJS.Array
import GHCJS.Foreign.Callback
import GHCJS.Types
import GHCJS.Node.Buffer
-- | A SPKAC, or Signed Public Key and Challenge, is a buffer representing
-- a certificate signing request.
newtype SPKAC
= MkSPKAC Buffer
-- | A Challenge is a buffer representing the challenge component of a SPKAC.
newtype Challenge
= MkChallenge Buffer
-- | A PublicKey is a buffer representing the public key component of a SPKAC.
newtype PublicKey
= MkPublicKey Buffer
-- | Given a 'SPKAC', returns the challenge component.
foreign import javascript safe
"$r = crypto.Certificate().exportChallenge($1);"
spkacChallenge :: SPKAC
-> IO Challenge
-- | Given a 'SPKAC', returns the public key component.
foreign import javascript safe
"$r = crypto.Certificate().exportPublicKey($1);"
spkacPublicKey :: SPKAC
-> IO PublicKey
-- | Given a 'SPKAC', return @True@ if it is valid and @False@ otherwise.
foreign import javascript safe
"$r = crypto.Certificate().verifySpkac($1);"
spkacVerify :: SPKAC
-> IO Bool
| taktoa/ghcjs-electron | src/GHCJS/Node/Crypto/Certificate.hs | mit | 1,432 | 8 | 6 | 301 | 160 | 100 | 60 | 23 | 0 |
{-# LANGUAGE DeriveGeneric, ScopedTypeVariables, TemplateHaskell, TypeInType, TypeFamilies, KindSignatures, DataKinds, TypeOperators, GADTs, TypeSynonymInstances, FlexibleInstances #-}
module Example.Example07 where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Control.Exception.Safe (Exception, MonadThrow, SomeException, throwM, bracket, catch)
import qualified Data.Aeson as JSON
import qualified Data.ByteString as B
import qualified Data.Binary as Bin
import qualified Data.Binary.Get as BinG
import qualified Data.Binary.Strict.BitGet as SBinG
import qualified Data.ByteString.Lazy as BL
import qualified Data.Int as I
import Data.Kind
import qualified Data.Sequence as Seq
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Word as W
-- protocolbuffers
import qualified Text.ProtocolBuffers.WireMessage as PBW
import qualified Text.ProtocolBuffers.Extensions as PBE
import qualified Text.ProtocolBuffers as PB
-- protocol buffer library
import qualified Text.ProtocolBuffers as PB
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.ColumnMetaData as PCMD
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.DataModel as PDM
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.Delete as PD
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.Find as PF
-- my library
import DataBase.MySQLX.Exception
import DataBase.MySQLX.Model as XM
import DataBase.MySQLX.NodeSession
import DataBase.MySQLX.Statement
import DataBase.MySQLX.TH
import DataBase.MySQLX.Util
import DataBase.MySQLX.CRUD as CRUD
import GHC.Generics
-- ======================================================================= --
-- Enum
-- ======================================================================= --
{-
mysql-sql> create table data_type_enum (my_enum enum('aaa', 'bbb', 'ccc'));
Query OK, 0 rows affected (0.06 sec)
mysql-sql> insert into data_type_enum values ('ddd');
Query OK, 1 row affected, 1 warning (0.01 sec)
Warning (code 1265): Data truncated for column 'my_enum' at row 1
mysql-sql> select * from data_type_enum;
+---------+
| my_enum |
+---------+
| |
+---------+
1 row in set (0.00 sec)
mysql-sql> insert into data_type_enum values ('aaa');
Query OK, 1 row affected (0.00 sec)
mysql-sql> select * from data_type_enum;
+---------+
| my_enum |
+---------+
| |
| aaa |
+---------+
2 rows in set (0.00 sec)
mysql-sql> delete from data_type_enum;
Query OK, 2 rows affected (0.01 sec)
mysql-sql> insert into data_type_enum values ('bbb');
Query OK, 1 row affected (0.01 sec)
mysql-sql> select * from data_type_enum;
+---------+
| my_enum |
+---------+
| bbb |
+---------+
1 row in set (0.00 sec)
mysql-sql>
-}
example07_01 :: IO ()
example07_01 = do
putStrLn "start example07_01"
nodeSess <- openNodeSession $ defaultNodeSesssionInfo {database = "x_protocol_test", user = "root", password="root"}
(meta, ret@(x:xs)) <- executeRawSqlMetaData "select * from data_type_enum limit 1" nodeSess
print meta
print ret
print $ (BL.length (Seq.index x 0) )
return ()
| naoto-ogawa/h-xproto-mysql | src/Example/Example07.hs | mit | 3,294 | 0 | 12 | 653 | 409 | 275 | 134 | 42 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Data.Aeson as JSON
import qualified Data.Bits as Bits
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Data.Text.IO as Text
import qualified Database.SQLite3 as SQL
import qualified Network.HTTP as HTTP
import qualified Network.Info as Network
import qualified Network.Socket as Network
import qualified System.Environment as System
import Control.Applicative
import Control.Concurrent
import Control.Monad.State
import Data.Int
import Data.String
data Configuration =
Configuration {
configurationDatabaseFilename :: FilePath,
configurationLogFilename :: FilePath,
configurationUserName :: Maybe String,
configurationGroupName :: Maybe String,
configurationListeners :: [Listener]
}
instance JSON.FromJSON Configuration where
parseJSON (JSON.Object v) =
Configuration <$> v JSON..: "database"
<*> v JSON..: "log"
<*> v JSON..:? "user"
<*> v JSON..:? "group"
<*> v JSON..: "listeners"
parseJSON _ = mzero
data Listener =
Listener {
listenerInterface :: Maybe Network.HostAddress,
listenerPort :: Network.PortNumber
}
deriving (Show)
instance JSON.FromJSON Listener where
parseJSON (JSON.Object v) = do
port <- v JSON..: "port" >>= \port -> return $ fromIntegral (port :: Int)
Listener <$> v JSON..:? "interface"
<*> pure port
parseJSON _ = mzero
data ServerState =
ServerState {
serverStateDatabase :: MVar SQL.Database,
serverStateCaptchaCache :: MVar (Map.Map Int64 (String, BS.ByteString)),
serverStateSessionID :: Maybe Int64
}
type Server = StateT ServerState HTTP.HTTP
main :: IO ()
main = do
arguments <- System.getArgs
case arguments of
[configurationFilename] -> runService configurationFilename
_ -> help
help :: IO ()
help = do
putStrLn "Usage: deltavee configuration.json"
runService :: FilePath -> IO ()
runService configurationFilename = do
configurationText <- Text.readFile configurationFilename
case JSON.eitherDecode'
$ LBS.fromChunks [Text.encodeUtf8 configurationText] of
Left message -> do
putStrLn $ "Invalid configuration: " ++ message
Right configuration -> do
database <-
SQL.open $ Text.pack $ configurationDatabaseFilename configuration
databaseMVar <- newMVar database
captchaCacheMVar <- newMVar Map.empty
allInterfaces <- getAllInterfaces
let state = ServerState {
serverStateDatabase = databaseMVar,
serverStateCaptchaCache = captchaCacheMVar,
serverStateSessionID = Nothing
}
serverParameters = HTTP.HTTPServerParameters {
HTTP.serverParametersAccessLogPath = Nothing,
HTTP.serverParametersErrorLogPath =
Just $ configurationLogFilename configuration,
HTTP.serverParametersDaemonize = True,
HTTP.serverParametersUserToChangeTo =
configurationUserName configuration,
HTTP.serverParametersGroupToChangeTo =
configurationGroupName configuration,
HTTP.serverParametersForkPrimitive = forkIO,
HTTP.serverParametersListenSockets =
concatMap
(\listener ->
let portNumber = listenerPort listener
socketAddresses =
case listenerInterface listener of
Nothing ->
map (\interface ->
Network.SockAddrInet portNumber
interface)
allInterfaces
Just hostAddress ->
[Network.SockAddrInet portNumber hostAddress]
in map (\socketAddress ->
HTTP.HTTPListenSocketParameters {
HTTP.listenSocketParametersAddress =
socketAddress,
HTTP.listenSocketParametersSecure = False
})
socketAddresses)
(configurationListeners configuration)
}
HTTP.acceptLoop serverParameters $ evalStateT accept state
getAllInterfaces :: IO [Network.HostAddress]
getAllInterfaces = do
interfaces <- Network.getNetworkInterfaces
return $ map (\interface ->
let Network.IPv4 hostAddress = Network.ipv4 interface
in hostAddress)
interfaces
accept :: Server ()
accept = do
uri <- lift $ HTTP.getRequestURI
case uri of
"/" -> do
lift $ HTTP.setResponseHeader HTTP.HttpContentType
"text/html; charset=utf-8"
lift $ HTTP.httpPutStr "Foo."
"/api" -> do
lift $ HTTP.setResponseHeader HTTP.HttpContentType
"text/html; charset=utf-8"
lift $ HTTP.httpPutStr "Bar."
_ -> do
lift $ HTTP.setResponseHeader HTTP.HttpContentType
"text/html; charset=utf-8"
lift $ HTTP.setResponseStatus 404
| IreneKnapp/deltavee | Haskell/DeltaVee.hs | mit | 5,436 | 0 | 31 | 1,716 | 1,131 | 601 | 530 | 132 | 3 |
-- | assorted functionality, imported by most modules in this package.
module Workflow.OSX.Extra
( module Workflow.OSX.Extra
, module X
) where
import Workflow.Types (MilliSeconds)
import Control.DeepSeq as X (NFData)
import Data.Hashable as X (Hashable)
import Data.String.Conv as X
import Data.Data as X (Data)
import GHC.Generics as X (Generic)
import Data.Foldable as X (traverse_)
import Data.Monoid as X ((<>))
import Data.List as X
import Control.Arrow as X ((>>>))
import Data.Maybe as X (catMaybes)
import Numeric.Natural as X (Natural)
import Control.Concurrent (threadDelay)
import Data.Word (Word16,Word32)
import qualified Turtle as SH
import Prelude hiding (FilePath)
import qualified Prelude
delayMilliseconds :: Int -> IO ()
delayMilliseconds t = threadDelay (t*1000)
-- | may overflow.
unsafeIntToWord16 :: Int -> Word16
unsafeIntToWord16 = fromInteger . toInteger
-- | may overflow.
unsafeNatToWord32 :: Natural -> Word32
unsafeNatToWord32 = fromInteger . toInteger
nat2ms :: Natural -> MilliSeconds
nat2ms = fromIntegral
fp2s :: SH.FilePath -> Prelude.FilePath
fp2s = fp2t >>> toS
fp2t :: SH.FilePath -> SH.Text
fp2t = SH.format SH.fp
| sboosali/workflow-osx | workflow-osx/sources/Workflow/OSX/Extra.hs | mit | 1,232 | 0 | 7 | 239 | 331 | 207 | 124 | 32 | 1 |
module Handler.ModelsSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getModelsR" $ do
error "Spec not implemented: getModelsR"
| swamp-agr/carbuyer-advisor | test/Handler/ModelsSpec.hs | mit | 174 | 0 | 11 | 39 | 44 | 23 | 21 | 6 | 1 |
{-# htermination isIEEE :: Float -> Bool #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_isIEEE_1.hs | mit | 45 | 0 | 2 | 8 | 3 | 2 | 1 | 1 | 0 |
module SimpleAsmArchitecture(
Word,
word,
int,
word_size,
op_size,
obj_size,
wordJoin,
wordSplit
) where
word_size = op_size + obj_size
op_size = 2
obj_size = 3
complement = 10 ^ word_size
min_word = complement `div` 2
max_word = min_word - 1
newtype Word = Word { runWord :: Int } deriving (Eq)
tensComplement x = complement - x
word :: Int -> Word
word x = if x < 0
then Word . tensComplement . trunc . abs $ x
else Word . trunc $ x
where trunc = (`mod` complement)
int (Word x) = if x < min_word
then x
else negate . tensComplement $ x
wordJoin :: Int -> Int -> Word
wordJoin op obj = Word $ (abs op) * 10 ^ obj_size + (abs obj) `mod` 10^ obj_size
wordSplit :: Word -> (Int,Int)
wordSplit (Word x) = (x `div` 10 ^ obj_size, x `mod` 10 ^ obj_size)
inspect (Word x) = "Word { runWord = " ++ (show x) ++ " }"
instance Show Word where
show (Word x) = frmt $ show x
instance Num Word where
w1 + w2 = word $ (int w1) + (int w2)
w1 * w2 = word $ (int w1) * (int w2)
negate = word . negate . int
abs = word . abs . int
signum = word . signum . int
fromInteger = word . fromIntegral
instance Ord Word where
w1 `compare` w2 = int w1 `compare` int w2
frmt :: String -> String
frmt x
| len > word_size = drop (len - word_size) x
| len < word_size = pad word_size '0' x
| otherwise = x
where len = length x
pad p c x = replicate (p - length x) c ++ x
| kyle-ilantzis/Simple-ASM | SimpleAsmArchitecture.hs | mit | 1,440 | 119 | 13 | 387 | 702 | 376 | 326 | 48 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsconfiguration.html
module Stratosphere.ResourceProperties.EMRClusterEbsConfiguration where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.EMRClusterEbsBlockDeviceConfig
-- | Full data type definition for EMRClusterEbsConfiguration. See
-- 'emrClusterEbsConfiguration' for a more convenient constructor.
data EMRClusterEbsConfiguration =
EMRClusterEbsConfiguration
{ _eMRClusterEbsConfigurationEbsBlockDeviceConfigs :: Maybe [EMRClusterEbsBlockDeviceConfig]
, _eMRClusterEbsConfigurationEbsOptimized :: Maybe (Val Bool)
} deriving (Show, Eq)
instance ToJSON EMRClusterEbsConfiguration where
toJSON EMRClusterEbsConfiguration{..} =
object $
catMaybes
[ fmap (("EbsBlockDeviceConfigs",) . toJSON) _eMRClusterEbsConfigurationEbsBlockDeviceConfigs
, fmap (("EbsOptimized",) . toJSON) _eMRClusterEbsConfigurationEbsOptimized
]
-- | Constructor for 'EMRClusterEbsConfiguration' containing required fields
-- as arguments.
emrClusterEbsConfiguration
:: EMRClusterEbsConfiguration
emrClusterEbsConfiguration =
EMRClusterEbsConfiguration
{ _eMRClusterEbsConfigurationEbsBlockDeviceConfigs = Nothing
, _eMRClusterEbsConfigurationEbsOptimized = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsconfiguration.html#cfn-elasticmapreduce-cluster-ebsconfiguration-ebsblockdeviceconfigs
emrcecEbsBlockDeviceConfigs :: Lens' EMRClusterEbsConfiguration (Maybe [EMRClusterEbsBlockDeviceConfig])
emrcecEbsBlockDeviceConfigs = lens _eMRClusterEbsConfigurationEbsBlockDeviceConfigs (\s a -> s { _eMRClusterEbsConfigurationEbsBlockDeviceConfigs = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsconfiguration.html#cfn-elasticmapreduce-cluster-ebsconfiguration-ebsoptimized
emrcecEbsOptimized :: Lens' EMRClusterEbsConfiguration (Maybe (Val Bool))
emrcecEbsOptimized = lens _eMRClusterEbsConfigurationEbsOptimized (\s a -> s { _eMRClusterEbsConfigurationEbsOptimized = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EMRClusterEbsConfiguration.hs | mit | 2,300 | 0 | 12 | 204 | 264 | 153 | 111 | 28 | 1 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
-- $Id$
module Graph.Circle.Config where
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data Config = Config
{ nodes_circle :: Int -- ^ knoten im kreis
, nodes_complete :: Int -- ^ knoten insgesamt
, edges :: Int -- ^ extra kanten
}
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Config])
rc :: Config
rc = Config { nodes_circle = 5
, nodes_complete = 10
, edges = 20
}
| Erdwolf/autotool-bonn | src/Graph/Circle/Config.hs | gpl-2.0 | 550 | 6 | 9 | 151 | 121 | 75 | 46 | 15 | 1 |
module CornerPoints.CornerPoints(
CornerPoints(..),
(+++),
(+++-),
(|+++|),
(+++>),
(@+++#@),
(&+++#@),
(|@+++#@|),
scaleCornerPoints,
scaleCornerPointsZ,
CornerPointsBuilder(..),
) where
import CornerPoints.Points (Point(..))
import Control.Applicative
infix 7 +++
infix 6 +++-
infix 5 @+++#@
infix 5 +++>
infix 4 |+++|
--infix 3 +++^
data CornerPoints =
CornerPointsError
{
errMessage :: String
}
|
CubePoints
{ f1 :: Point,
f2 :: Point,
f3 :: Point,
f4 :: Point,
b1 :: Point,
b2 :: Point,
b3 :: Point,
b4 :: Point
}
|
-------------------------------------- Faces --------------------
BackFace
{ b1 :: Point,
b2 :: Point,
b3 :: Point,
b4 :: Point
}
|
BottomFace
{ b1 :: Point,
f1 :: Point,
b4 :: Point,
f4 :: Point
}
|
FrontFace
{ f1 :: Point,
f2 :: Point,
f3 :: Point,
f4 :: Point
}
|
LeftFace
{ b1 :: Point,
b2 :: Point,
f1 :: Point,
f2 :: Point
}
|
RightFace
{ b3 :: Point,
b4 :: Point,
f3 :: Point,
f4 :: Point
}
|
TopFace
{ b2 :: Point,
f2 :: Point,
b3 :: Point,
f3 :: Point
}
|
------------------------------ lines -------------------------
BackBottomLine
{
b1 :: Point,
b4 :: Point
}
|
BackTopLine
{
b2 :: Point,
b3 :: Point
}
|
BottomFrontLine
{
f1 :: Point,
f4 :: Point
}
|
BottomLeftLine
{
b1 :: Point,
f1 :: Point
}
|
BackRightLine
{
b3 :: Point,
b4 :: Point
}
|
BottomRightLine
{
b4 :: Point,
f4 :: Point
}
|
FrontLeftLine
{ f1 :: Point,
f2 :: Point
}
|
FrontRightLine
{ f3 :: Point,
f4 :: Point
}
|
FrontTopLine
{ f2 :: Point,
f3 :: Point
}
|
TopLeftLine
{
b2 :: Point,
f2 :: Point
}
|
TopRightLine
{
b3 :: Point,
f3 :: Point
}
--------------------------------- points ------------------------------
|
B1
{
b1 :: Point
}
|
B2
{
b2 :: Point
}
|
B3
{
b3 :: Point
}
|
B4
{
b4 :: Point
}
|
F1
{
f1 :: Point
}
|
F2
{
f2 :: Point
}
|
F3
{
f3 :: Point
}
|
F4
{
f4 :: Point
}
deriving (Show)
--------------------------------------------------- Equal-----------------------------------------------------------
{-
Implement as part of Equal class.
Used for:
So that assertions can be made for testing.
Equal if:
They are both the same type of CornerPoint and each of the axis is equal
Not equal if:
They are not the same constructor.
x y z axis are not all equal.
Need to be implemented for each constuctor
Due to rounding errors, etc. a special function to compare x y z axis values is required
to make sure they are withing 0.01 of each othere
-}
instance Eq CornerPoints where
-------------------------- points -------------------
B4 b4 == B4 b4a
| b4 == b4a = True
| otherwise = False
F1 f1 == F1 f1a
| f1 == f1a = True
| otherwise = False
F4 f4 == F4 f4a
| f4 == f4a = True
| otherwise = False
F3 f3 == F3 f3a
| f3 == f3a = True
| otherwise = False
--------------------------- lines ----------------------
BackBottomLine b1 b4 == BackBottomLine b1a b4a
| (b1 == b1a) && (b4 == b4a) = True
| otherwise = False
BackTopLine b2 b3 == BackTopLine b2a b3a
| (b2 == b2a) && (b3 == b3a) = True
| otherwise = False
BottomFrontLine f1 f4 == BottomFrontLine f1a f4a
| (f1 == f1a) && (f4 == f4a) = True
| otherwise = False
BottomLeftLine b1 f1 == BottomLeftLine b1a f1a
| (b1 == b1a) && (f1 == f1a) = True
| otherwise = False
BottomRightLine b4 f4 == BottomRightLine b4a f4a
| (b4 == b4a) && (f4 == f4a) = True
| otherwise = False
FrontTopLine f2 f3 == FrontTopLine f2a f3a
| (f2 == f2a) && (f3 == f3a) = True
| otherwise = False
TopLeftLine b2 f2 == TopLeftLine b2a f2a
| (b2 == b2a) && (f2 == f2a) = True
| otherwise = False
TopRightLine b3 f3 == TopRightLine b3a f3a
| (b3 == b3a) && (f3 == f3a) = True
| otherwise = False
------------------------------- faces ---------------------------
FrontFace f1 f2 f3 f4 == FrontFace f1a f2a f3a f4a
| (f1 == f1a) && (f2 == f2a) && (f3 == f3a) && (f4 == f4a) = True
| otherwise = False
BottomFace b1 f1 b4 f4 == BottomFace b1a f1a b4a f4a
| (b1 == b1a) && (f1 == f1a) && (b4 == b4a) && (f4 == f4a) = True
| otherwise = False
TopFace b2 f2 b3 f3 == TopFace b2a f2a b3a f3a
| (b2 == b2a) && (f2 == f2a) && (b3 == b3a) && (f3 == f3a) = True
| otherwise = False
RightFace b3 b4 f3 f4 == RightFace b3a b4a f3a f4a
| (b3 == b3a) && (b4 == b4a) && (f3 == f3a) && (f4 == f4a) = True
| otherwise = False
LeftFace b1 b2 f1 f2 == LeftFace b1a b2a f1a f2a
| (b1 == b1a) && (b2 == b2a) && (f1 == f1a) && (f2 == f2a) = True
| otherwise = False
BackFace b1 b2 b3 b4 == BackFace b1a b2a b3a b4a
| (b1 == b1a) && (b2 == b2a) && (b3 == b3a) && (b4 == b4a) = True
| otherwise = False
---------------------------------- cubes --------------------
CubePoints f1 f2 f3 f4 b1 b2 b3 b4 == CubePoints f1a f2a f3a f4a b1a b2a b3a b4a
| (f1 == f1a) && (f2 == f2a) && (f3 == f3a) && (f4 == f4a) && (b1 == b1a) && ( b2 == b2a) && (b3 == b3a) && (b4 == b4a) = True
| otherwise = False
a == b = False
--------------------------------------------------- add cubes +++ ---------------------------------------------------
----------------------------------------------------------------------------------------------------------------------
-- || between to lines means done to a list
-- @ is a cornerpoint
-- & is a CornerPointsBuilder
-- # is a function
{- |Add [CornerPoints] to [CornerPoints].
-}
(|+++|) :: [CornerPoints] -> [CornerPoints] -> [CornerPoints]
c1 |+++| c2 = zipWith (+++) c1 c2
{-- |A lower infix version of +++. Usefull for chaining together +++
Ex: BackBottomLine +++ BottomFrontLine +++$ BackTopLine +++ FrontTopLine
-}
--ToDo: Consider getting rid of it as it is rarely used.
(+++-) :: CornerPoints -> CornerPoints -> CornerPoints
(+++-) = (+++)
{- |A monadic style +++ that adds the result of f input to input.
-}
{- |Similar to +++> except that it can apply any function, rather than just f +++
So it applies a function to the first argument, and returns another CornerPoint based on that.
Eg: Transpose a [CornerPoints] upwards in order to create a new layer of [CornerPoints]-}
(@+++#@) :: CornerPoints -> (CornerPoints -> CornerPoints) -> CornerPoints
(BottomFace b1 f1 b4 f4) @+++#@ f = (BottomFace b1 f1 b4 f4) +++ (f (BottomFace b1 f1 b4 f4))
(CubePoints f1 f2 f3 f4 b1 b2 b3 b4) @+++#@ f = (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) +++ (f (CubePoints f1 f2 f3 f4 b1 b2 b3 b4))
(TopFace b2 f2 b3 f3) @+++#@ f = (TopFace b2 f2 b3 f3) +++ (f (TopFace b2 f2 b3 f3))
-- |@+++#@| ++++>>
-- |Apply @+++#@ to a [CornerPoints].
(|@+++#@|) :: [CornerPoints] -> (CornerPoints -> CornerPoints) -> [CornerPoints]
faces |@+++#@| f = [ x @+++#@ f | x <- faces]
-- |Building up a shape usually involves [[CornerPoints]]. This allow use of infix operators
-- to build up the shape in an monadic way, along with the use of &+++#@.
data CornerPointsBuilder = CornerPointsBuilder {getCornerPoints :: [[CornerPoints]]}
deriving (Eq, Show)
-- |The infix operator to go along with CornerPointsBuilder for building up shapes as [[CornerPoints]]
(&+++#@) :: CornerPointsBuilder -> ([CornerPoints] -> [CornerPoints]) -> CornerPointsBuilder
(CornerPointsBuilder cornerPoints) &+++#@ f = CornerPointsBuilder ( (f $ head cornerPoints) : cornerPoints)
-- |Add each face to the next face, left -> right, resulting in CubePoints.
-- Ex: pass a RightFace into a list of LeftFaces, resulting in a list of CubePoints
(+++>) :: CornerPoints -> [CornerPoints] -> [CornerPoints]
a +++> bs =
tail $ scanl (+++) a bs
{-Add CornerPoints together.
Must follow all the rules of adding.
Ex: FrontFace can be added to BackFace
but
FrontFace can't be added to a TopFace.-}
(+++) :: CornerPoints -> CornerPoints -> CornerPoints
(BottomFace b1 f1 b4 f4) +++ (TopFace b2 f2 b3 f3) =
CubePoints {f1=f1, f2=f2, f3=f3, f4=f4, b1=b1, b2=b2, b3=b3, b4=b4}
(TopFace b2 f2 b3 f3) +++ (BottomFace b1 f1 b4 f4) =
CubePoints {f1=f1, f2=f2, f3=f3, f4=f4, b1=b1, b2=b2, b3=b3, b4=b4}
(BackFace b1 b2 b3 b4) +++ (FrontFace f1 f2 f3 f4) =
CubePoints {b1=b1, b2=b2, b3=b3, b4=b4, f1=f1, f2=f2, f3=f3, f4=f4}
(LeftFace b1 b2 f1 f2) +++ (RightFace b3 b4 f3 f4) =
CubePoints {b1=b1, b2=b2, b3=b3, b4=b4, f1=f1, f2=f2, f3=f3, f4=f4}
(RightFace b3 b4 f3 f4) +++ (LeftFace b1 b2 f1 f2) =
CubePoints {b1=b1, b2=b2, b3=b3, b4=b4, f1=f1, f2=f2, f3=f3, f4=f4}
(CubePoints f1 f2 f3 f4 b1 b2 b3 b4) +++ (FrontFace f1r f2r f3r f4r) =
(BackFace {b1=f1, b2=f2, b3=f3, b4=f4}) +++ (FrontFace f1r f2r f3r f4r)
(CubePoints f1 f2 f3 f4 b1 b2 b3 b4) +++ (TopFace b2t f2t b3t f3t) =
(BottomFace {b1=b2, b4=b3, f1=f2, f4=f3}) +++ (TopFace b2t f2t b3t f3t)
---------------------------------------------------------------------------------------------
(CubePoints f1 f2 f3 f4 b1 b2 b3 b4) +++ (BottomFace b1b f1b b4b f4b) =
(BottomFace {b1=b1b, b4=b4b, f1=f1b, f4=f4b}) +++ (TopFace b1 f1 b4 f4)
(TopFace b2t f2t b3t f3t) +++ (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) =
CubePoints {b1=b2, b2=b2t, b3=b3t, b4=b3, f1=f2, f2=f2t, f3=f3t, f4=f3}
(LeftFace b1t b2t f1t f2t) +++ (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) =
CubePoints {b1=b1t, b4=b1, b2=b2t, b3=b2, f1=f1t, f2=f2t, f3=f2, f4=f1}
(LeftFace b1 b2 f1 f2) +++ (BottomLeftLine b1a f1a) =
(LeftFace b1a b1 f1a f1)
(CubePoints f1 f2 f3 f4 b1 b2 b3 b4) +++ (LeftFace b1t b2t f1t f2t) =
CubePoints {b1=b1t, b4=b1, b2=b2t, b3=b2, f1=f1t, f2=f2t, f3=f2, f4=f1}
(RightFace b3t b4t f3t f4t) +++ (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) =
CubePoints {b1=b4, b4=b4t, b2=b3, b3=b3t, f1=f4, f2=f3, f3=f3t, f4=f4t}
(RightFace b3f b4f f3f f4f) +++ (BottomRightLine b4l f4l) =
(RightFace b4f b4l f4f f4l)
(CubePoints f1 f2 f3 f4 b1 b2 b3 b4) +++ (RightFace b3t b4t f3t f4t) =
CubePoints {b1=b4, b4=b4t, b2=b3, b3=b3t, f1=f4, f2=f3, f3=f3t, f4=f4t}
(BackFace b1t b2t b3t b4t) +++ (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) =
CubePoints {b1=b1t, b2=b2t, b3=b3t, b4=b4t, f1=b1, f2=b2, f3=b3, f4=b4}
(TopFace b2 f2 b3 f3) +++ (TopRightLine b3t f3t) =
(TopFace b3 f3 b3t f3t)
(FrontTopLine f2 f3) +++ (BottomFrontLine f1 f4) =
FrontFace f1 f2 f3 f4
(BackBottomLine b1 b4) +++ (BottomFrontLine f1 f4) =
BottomFace b1 f1 b4 f4
(BottomFrontLine f1 f4) +++ (BackBottomLine b1 b4) =
BottomFace b1 f1 b4 f4
(BottomRightLine b4 f4) +++ (BottomLeftLine b1 f1) =
BottomFace b1 f1 b4 f4
(TopLeftLine b2 f2) +++ (TopRightLine b3 f3) =
TopFace b2 f2 b3 f3
(TopLeftLine b2 f2) +++ (BottomLeftLine b1 f1) =
LeftFace b1 b2 f1 f2
(TopRightLine b3 f3) +++ (TopLeftLine b2 f2) =
TopFace b2 f2 b3 f3
(TopRightLine b3 f3) +++ (BottomRightLine b4 f4) =
(RightFace b3 b4 f3 f4)
(TopLeftLine b2t f2t) +++ (TopFace b2 f2 b3 f3) =
(TopFace b2t f2t b2 f2)
(TopFace b2 f2 b3 f3) +++ (TopLeftLine b2t f2t) =
(TopFace b2t f2t b2 f2)
(BackTopLine b2 b3) +++ (FrontTopLine f2 f3) =
TopFace b2 f2 b3 f3
(BottomFace b1 f1 b4 f4) +++ (BottomFrontLine f1a f4a) =
BottomFace {b1=f1, b4=f4, f1=f1a, f4=f4a}
(BottomFace b1 f1 b4 f4) +++ (BottomLeftLine b1a f1a) =
BottomFace {b1=b1a, f1=f1a, b4=b1, f4=f1}
(TopFace b2 f2 b3 f3) +++ (FrontTopLine f2a f3a) =
TopFace {b2=f2, b3=f3, f2=f2a, f3=f3a}
(BottomFrontLine f1 f4) +++ (FrontTopLine f2 f3) =
FrontFace f1 f2 f3 f4
(B1 b1) +++ (B4 b4) =
BackBottomLine {b1=b1, b4=b4}
(B4 b4) +++ (B1 b1) =
BackBottomLine {b1=b1, b4=b4}
(B2 b2) +++ (B3 b3) =
BackTopLine {b2=b2, b3=b3}
(F1 f1) +++ (F4 f4) =
BottomFrontLine {f1=f1, f4=f4}
(F1 f1) +++ (BottomFrontLine f1a f4a) = BottomFrontLine f1 f1a
(BottomFrontLine f1a f4a) +++ (F1 f1) = BottomFrontLine f1a f1
(F1 f1) +++ (B1 b1) =
BottomLeftLine b1 f1
(F2 f2) +++ (F3 f3) =
FrontTopLine {f2=f2, f3=f3}
(F2 f2) +++ (B2 b2) =
TopLeftLine b2 f2
(F3 f3) +++ (F2 f2) =
FrontTopLine {f2=f2, f3=f3}
(F3 f3) +++ (B3 b3) =
(TopRightLine b3 f3)
(F4 f4) +++ (B4 b4) =
(BottomRightLine b4 f4)
(F4 f4) +++ (F1 f1) =
(BottomFrontLine f1 f4)
(BottomFrontLine f1 f4t) +++ (F4 f4) =
BottomFrontLine f4t f4
(FrontTopLine f2 f3) +++ (F3 f3t) =
FrontTopLine f3 f3t
(FrontTopLine f2 f3) +++ (BackTopLine b2 b3) =
TopFace b2 f2 b3 f3
(FrontTopLine f2 f3) +++ (F2 f2t) =
FrontTopLine f2t f2
(F2 f2t) +++ (FrontTopLine f2 f3) =
FrontTopLine f2t f2
(CornerPointsError _) +++ b = CornerPointsError "illegal CornerPointsError +++ _ operation"
--faces
(BackFace _ _ _ _) +++ (BackFace _ _ _ _) = CornerPointsError "illegal BackFace +++ BackFace operation"
(BottomFace _ _ _ _) +++ (BottomFace _ _ _ _) = CornerPointsError "illegal BottomFace +++ BottomFace operation"
(FrontFace _ _ _ _) +++ (FrontFace _ _ _ _) = CornerPointsError "illegal FrontFace +++ FrontFace operation"
(LeftFace _ _ _ _) +++ (LeftFace _ _ _ _) = CornerPointsError "illegal LeftFace +++ LeftFace operation"
(RightFace _ _ _ _) +++ (RightFace _ _ _ _) = CornerPointsError "illegal RightFace +++ RightFace operation"
(TopFace _ _ _ _) +++ (TopFace _ _ _ _) = CornerPointsError "illegal TopFace +++ TopFace operation"
--lines
(BackBottomLine _ _) +++ (BackBottomLine _ _) = CornerPointsError "illegal BackBottomLine +++ BackBottomLine operation"
(BackTopLine _ _) +++ (BackTopLine _ _) = CornerPointsError "illegal BackTopLine +++ BackTopLine operation"
(BottomFrontLine _ _) +++ (BottomFrontLine _ _) = CornerPointsError "illegal BottomFrontLine +++ BottomFrontLine operation"
(FrontTopLine _ _) +++ (FrontTopLine _ _) = CornerPointsError "illegal FrontTopLine +++ FrontTopLine operation"
a +++ b = CornerPointsError "illegal +++ operation"
----------------------------------------------- scale cubes/points ------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
{- Over view
Allow the scaling of a shape. This can be done on all 3 axis at once, or on a single axis. So far only the z-axis scale has been created.
-}
--used to change just the z axis of a CornerPoints
scaleCornerPointsZ :: Double -> CornerPoints -> CornerPoints
scaleCornerPointsZ scaleFactor (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) =
CubePoints
{
f1=scalePointZ f1 scaleFactor,
f2=scalePointZ f2 scaleFactor,
f3=scalePointZ f3 scaleFactor,
f4=scalePointZ f4 scaleFactor,
b1=scalePointZ b1 scaleFactor,
b2=scalePointZ b2 scaleFactor,
b3=scalePointZ b3 scaleFactor,
b4=scalePointZ b4 scaleFactor
}
scaleCornerPoints :: Double -> CornerPoints -> CornerPoints
scaleCornerPoints scaleFactor (CubePoints f1 f2 f3 f4 b1 b2 b3 b4) =
CubePoints
{
f1=scalePoint f1 scaleFactor,
f2=scalePoint f2 scaleFactor,
f3=scalePoint f3 scaleFactor,
f4=scalePoint f4 scaleFactor,
b1=scalePoint b1 scaleFactor,
b2=scalePoint b2 scaleFactor,
b3=scalePoint b3 scaleFactor,
b4=scalePoint b4 scaleFactor
}
{------------ scale internal support functions -------------}
scalePoint :: Point -> Double -> Point
scalePoint (Point x y z) scaleFactor = Point {x_axis=x*scaleFactor, y_axis=y*scaleFactor, z_axis=z*scaleFactor}
--used to change just the z axis of a Point
scalePointZ :: Point -> Double -> Point
scalePointZ (Point x y z) scaleFactor = Point {x_axis=x, y_axis=y, z_axis=z*scaleFactor}
| heathweiss/Tricad | src/CornerPoints/CornerPoints.hs | gpl-2.0 | 17,385 | 0 | 17 | 5,282 | 5,762 | 3,080 | 2,682 | 324 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Bachelor.DataBase where
{-
- Provides a interface for reading/writing RTS State Events to and from
- a database.
- -}
--instance IOEventData where
import Bachelor.Types
import Database.PostgreSQL.Simple
import GHC.RTS.Events
import qualified Data.HashMap.Strict as M
import Control.Applicative
import qualified Data.ByteString as B
--the number of events to be commited at once
bufferlimit = 1000
mkConnection = do
connectionString <- B.readFile "pq.conf"
conn <- connectPostgreSQL connectionString
_ <- execute_ conn "SET SESSION synchronous_commit TO off"
return conn
-- the information necessary for entering events into the database.
-- because the database should be able to contain multiple traces,
-- we keep a set of keys to uniquely identify the machines, processes and
-- threads within the current trace.
data DBInfo = DBInfo {
db_threadbuffer :: [(MachineId, ThreadId, Timestamp, Timestamp, RunState)],
db_processbuffer :: [(MachineId, ProcessId, Timestamp, Timestamp, RunState)],
db_machinebuffer :: [(MachineId, Timestamp, Timestamp, RunState)],
db_traceKey :: Int,
db_machines :: M.HashMap MachineId Int,
db_processes :: M.HashMap (MachineId,ProcessId) Int,
db_threads :: M.HashMap (MachineId,ThreadId) Int,
db_connection :: Connection
}
instance Show DBInfo where
show dbi =
"\n\n####BEGIN DB INFO\n\n"
++ "Trace ID : " ++ (show $ db_traceKey dbi) ++ "\n"
++ "Machines: " ++ (show $ db_machines dbi) ++ "\n"
++ "Processes: " ++ (show $ db_processes dbi) ++ "\n"
++ "Threads: " ++ (show $ db_threads dbi) ++ "\n"
++ "\n\n####END DB INFO\n\n"
-- when starting to parse a new file, we need to create a new connection,
-- and then insert a new trace into our list of traces, then store the trace_id
-- into a new DBInfo value.
insertTraceQuery :: Query
insertTraceQuery = "Insert Into Traces (filename, creation_date)\
\values( ? , now()) returning trace_id;"
insertTrace :: Connection -> FilePath -> IO DBInfo
insertTrace conn file = do
traceKey <- head <$> query conn insertTraceQuery (Only file)
case traceKey of
Only key -> do
return $ DBInfo {
db_processbuffer = [],
db_threadbuffer = [],
db_machinebuffer = [],
db_traceKey = key,
db_machines = M.empty,
db_processes = M.empty,
db_threads = M.empty,
db_connection = conn
}
_ -> error "trace insertion failed"
insertMachineQuery :: Query
insertMachineQuery = "Insert Into Machines(num,trace_id)\
\values( ? , ? ) returning machine_id;"
insertMachine :: DBInfo -> MachineId-> IO DBInfo
insertMachine dbi mid = do
let conn = db_connection dbi
traceKey = db_traceKey dbi
machineKey <- head <$> query conn insertMachineQuery (mid, traceKey)
case machineKey of
Only key -> do
return $ dbi {
db_machines = M.insert mid key (db_machines dbi)
}
_ -> error "machine insertion failed"
insertProcessQuery :: Query
insertProcessQuery =
"Insert Into Processes(num,machine_id)\
\values( ? , ? ) returning process_id;"
insertProcess :: DBInfo -> MachineId -> ProcessId -> IO DBInfo
insertProcess dbi mid pid = do
let conn = db_connection dbi
machineKey = (db_machines dbi) M.! mid
processKey <- head <$> query conn insertProcessQuery (pid, machineKey)
case processKey of
Only key -> do
return $ dbi {
db_processes = M.insert (mid,pid) key (db_processes dbi)
}
_ -> error "machine insertion failed"
insertThreadQuery :: Query
insertThreadQuery =
"Insert into Threads(num, process_id)\
\values( ? , ? ) returning thread_id;"
insertThread :: DBInfo -> MachineId -> ProcessId -> ThreadId -> IO DBInfo
insertThread dbi mid pid tid = do
let conn = db_connection dbi
processKey = (db_processes dbi) M.! (mid,pid)
threadKey <- head <$> query conn insertThreadQuery (tid, processKey)
case threadKey of
Only key -> do
return $ dbi {
db_threads = M.insert (mid,tid) key (db_threads dbi)
}
_ -> error "machine insertion failed"
insertEvent :: DBInfo -> GUIEvent -> IO DBInfo
insertEvent dbi g@(NewMachine mid) = insertMachine dbi mid
insertEvent dbi g@(NewProcess mid pid) = insertProcess dbi mid pid
insertEvent dbi g@(NewThread mid pid tid) = insertThread dbi mid pid tid
insertEvent dbi g@(GUIEvent mtpType start dur state) =
case mtpType of
Machine mid -> case ((length $ db_machinebuffer dbi) >= bufferlimit) of
True -> do
--putStrLn "inserting Machine events"
insertMachineState dbi
False -> return dbi {
db_machinebuffer = (mid,start,dur,state) : db_machinebuffer dbi
}
Process mid pid -> case ((length $ db_processbuffer dbi) >= bufferlimit) of
True -> do
--putStrLn "inserting Process events"
insertProcessState dbi
False -> return dbi {
db_processbuffer = (mid,pid,start,dur,state) : db_processbuffer dbi
}
Thread mid tid -> case ((length $ db_threadbuffer dbi) >= bufferlimit) of
True -> do
--putStrLn "inserting Thread events"
insertThreadState dbi
False -> return dbi {
db_threadbuffer = (mid,tid,start,dur,state) : db_threadbuffer dbi
}
finalize :: DBInfo -> IO DBInfo
finalize dbi = do
dbi <- insertMachineState dbi
dbi <- insertProcessState dbi
dbi <- insertThreadState dbi
return dbi
insertMachineStateQuery :: Query
insertMachineStateQuery =
"Insert into machine_events(machine_id, starttime, duration, state)\
\values( ? , ? , ? , ? );"
insertMachineState :: DBInfo -> IO DBInfo
insertMachineState dbi = do
let conn = db_connection dbi
inlist = map (\(mid,start,duration,state) ->
((db_machines dbi) M.! mid, start, duration, stateToInt state))
$ db_machinebuffer dbi
executeMany conn insertMachineStateQuery inlist
return dbi {db_machinebuffer = []}
insertProcessStateQuery :: Query
insertProcessStateQuery =
"Insert into process_events(process_id, starttime, duration, state)\
\values( ? , ? , ? , ? );"
insertProcessState :: DBInfo -> IO DBInfo
insertProcessState dbi = do
let conn = db_connection dbi
inlist = map (\(mid,pid,start,duration,state) ->
((db_processes dbi) M.! (mid,pid), start, duration, stateToInt state))
$ db_processbuffer dbi
executeMany conn insertProcessStateQuery inlist
return dbi {db_processbuffer = []}
insertThreadStateQuery :: Query
insertThreadStateQuery =
"Insert into thread_events(thread_id, starttime, duration, state)\
\values( ? , ? , ? , ? );"
insertThreadState :: DBInfo -> IO DBInfo
insertThreadState dbi = do
let conn = db_connection dbi
inlist = map (\(mid,tid,start,duration,state) ->
((db_threads dbi) M.! (mid,tid), start, duration, stateToInt state))
$ db_threadbuffer dbi
executeMany conn insertThreadStateQuery inlist
return dbi {db_threadbuffer = []}
| brtmr/Eden-Tracelab-cli-tool | src/Bachelor/DataBase.hs | gpl-3.0 | 7,564 | 0 | 20 | 2,081 | 1,808 | 952 | 856 | 146 | 6 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE GADTs #-}
module Views where
import qualified Data.Map as M
import Data.Map(Map)
import Data.Maybe
import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Identity
import Control.Monad.Identity
import Control.Applicative
import Data.List hiding (insert)
import Test.QuickCheck
data Color = Red | Green | Blue deriving (Show,Eq,Ord)
type Position = Int
class Colored a where
color :: a -> Color
class Positioned a where
position :: a -> Position
data Obj where
Obj :: Color -> Position -> Obj
deriving(Show,Eq,Ord)
instance Colored Obj where
color (Obj c _) = c
instance Positioned Obj where
position (Obj _ p) = p
someObjects :: [Obj]
someObjects = [Obj Red 1, Obj Green 2, Obj Blue 3]
type Scene = [Obj]
type SceneM m a = StateT Scene m a
newtype SceneDB m a = SceneDB (SceneM m a) deriving (Monad)
insert :: Monad m => Obj -> SceneDB m ()
insert obj = SceneDB $ modify (obj :)
query :: Monad m => (Scene -> Scene) -> SceneDB m Scene
query f = SceneDB $ liftM f get
runScene :: Monad m => SceneDB m Scene -> m Scene
runScene (SceneDB m) = evalStateT m []
runSceneId :: SceneDB Identity Scene -> Scene
runSceneId = runIdentity . runScene
myScene = do
insert $ Obj Red 1
insert $ Obj Green 2
insert $ Obj Blue 3
redObjects :: Monad m => SceneDB m Scene
redObjects = query redOnes
where redOnes s = [obj | obj <- s, isRed obj]
isRed = (== Red) . color
testScene1 = runSceneId $ myScene >> redObjects
data Expr a where
NumOp :: (Num a, Show a) => (a -> a -> a) -> Expr a -> Expr a -> Expr a
Equals :: (Eq a, Show a) => Expr a -> Expr a -> Expr Bool
Constant :: Show a => a -> Expr a
If :: (Show a) => Expr Bool -> Then (Expr a) -> Else (Expr a) -> Expr a
Call :: (Expr a -> Expr b) -> Expr a -> Expr b
Match :: Expr a -> With [(Expr Bool, Expr b)] -> Expr b
deriving instance Show (Expr a)
instance Show (a -> b) where show _ = "hfun"
newtype Then a = Then a deriving (Show)
newtype Else a = Else a deriving (Show)
newtype With a = With a deriving (Show)
add = NumOp (+)
minus = NumOp (-)
eval :: Expr a -> a
eval (NumOp f x y) = eval x `f` eval y
eval (Constant x) = x
eval (If b (Then t) (Else f)) = if eval b then eval t else eval f
eval (Call f a) = eval $ f a
eval (Equals a b) = (eval a) == (eval b)
eval (Match e (With xs)) = let (_,((_,c):_)) = break ((== True) . eval . fst) xs
in eval c
testA = If (Constant True) (Then $ Constant 1) (Else $ Constant 2)
plus1 = add (Constant 1)
onePlus1 = Call plus1 (Constant 1)
aSum = foldr add (Constant 0) $ map Constant [1..10]
qTest = eval aSum == sum [1..10]
--mEq a b = Call (Lift (== eval a)
aFib :: Expr Int -> Expr Int
aFib n = Match n $ With [
(n `Equals` Constant 0, Constant 0),
(n `Equals` Constant 1, Constant 1),
(Constant True, add (aFib n') (aFib n'')) ]
where n' = n `minus` Constant 1
n'' = n `minus` Constant 2
fibTest n | n < 0 = True
| n < 30 = True
| otherwise = ( eval $ aFib (Constant n) ) == fib n
fib n' = case n' of
0 -> 0
1 -> 1
n -> fib (n'-1) + fib (n'-2)
data Tree a b = Node a (Tree a b) (Tree a b)
| Leaf b | TNil deriving (Show,Eq)
mkTree :: Ord a => [a] -> Tree a a
mkTree = mkTree' . sort
mkTree' :: Ord a => [a] -> Tree a a
mkTree' (x:[]) = Leaf x
mkTree' xs = Node (xs!!half) (mkTree' b) (mkTree' e)
where (b,e) = splitAt half xs
half = length xs `div` 2
| haraldsteinlechner/lambdaWolf | src/Views.hs | gpl-3.0 | 3,742 | 1 | 13 | 1,013 | 1,722 | 899 | 823 | 101 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Types where
import qualified Data.Text as T
import Lib
import Control.Lens
import Data.Time.Clock
data Order
= Normal
| Reversed
deriving (Show)
data Filter
= None
| OnlyToday UTCTime
deriving (Show)
data InputCase
= EmptyField
| ValidDate
| InvalidDate
deriving (Show)
data QueryDates
= Both T.Text T.Text
| From T.Text
| To T.Text
| Neither
deriving (Show)
data Command
= SetStatus Status
| UpdateMessages LogResponse
| SetOrder Order
| SetFilter Filter
deriving (Show)
data State
= State
{ _messages :: Maybe [PrivMsg]
, _fromDate :: Maybe FromDate
, _toDate :: Maybe ToDate
, _order :: Order
, _dateFilter :: Filter
, _httpStatus :: Status
} deriving (Show)
newtype FromDate = FD { runFD :: UTCTime } deriving (Show)
newtype ToDate = TD { runTD :: UTCTime } deriving (Show)
errorUpdate :: Command
errorUpdate = SetStatus Lib.Invalid
makeLenses ''State
initialState :: State
initialState = nullState Loading
nullState :: Status -> State
nullState = State Nothing Nothing Nothing Normal None
| Arguggi/irc-log | frontend/src/Types.hs | gpl-3.0 | 1,195 | 0 | 10 | 292 | 319 | 188 | 131 | 50 | 1 |
module Main where
import qualified Temper as T
import System.USB.Enumeration (getDevices, Device)
import System.USB.Initialization (newCtx)
import Control.Monad (filterM)
import Data.Vector (toList)
import System.USB.DeviceHandling (withDeviceHandle)
main:: IO()
main = do
usbContext <- newCtx
devices <- getDevices usbContext
temperDevices <- filterM T.isTemperDevice (toList devices)
if null temperDevices
then putStrLn "Could not find any temper devices"
else do
print (head temperDevices)
withDeviceHandle (head temperDevices) $ \device -> do
temp <- T.readTemperature device
print temp
| bneijt/temper | src/main/Main.hs | gpl-3.0 | 681 | 0 | 16 | 161 | 186 | 97 | 89 | 19 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-- Module : Keiretsu.Log
-- 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)
module Keiretsu.Log where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text.Encoding as Text
import System.Console.ANSI
import System.IO
import System.Log.Handler.Simple
import System.Log.Logger
logName :: String
logName = "log"
logDebugBS :: ByteString -> IO ()
logDebugBS = logDebug . BS.unpack
logError, logDebug :: String -> IO ()
logError = logMsg errorM
logDebug = logMsg debugM
logMsg :: (String -> a -> IO ()) -> a -> IO ()
logMsg f = f logName
setLogging :: Bool -> IO ()
setLogging debug = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
removeAllHandlers
hd <- streamHandler stderr prio
updateGlobalLogger logName (setLevel prio . setHandlers [hd])
where
prio = if debug then DEBUG else INFO
colours :: [Color]
colours = cycle [Red, Green, Blue, Magenta, Yellow, Cyan]
colourise :: Color -> Text -> ByteString -> ByteString
colourise c x y = prefix
<> Text.encodeUtf8 x
<> suffix
<> ": "
<> y
<> clear
where
prefix = BS.pack $ setSGRCode
[ SetColor Foreground Vivid c
, SetConsoleIntensity BoldIntensity
]
suffix = BS.pack $ setSGRCode
[ SetColor Foreground Vivid c
, SetConsoleIntensity NormalIntensity
]
clear = BS.pack $ setSGRCode []
| bnordbo/keiretsu | src/Keiretsu/Log.hs | mpl-2.0 | 2,026 | 0 | 11 | 548 | 453 | 247 | 206 | 44 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.BigQuery.Types.Sum
-- 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)
--
module Network.Google.BigQuery.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | The data frequency of a time series.
data TrainingOptionsDataFrequency
= DataFrequencyUnspecified
-- ^ @DATA_FREQUENCY_UNSPECIFIED@
| AutoFrequency
-- ^ @AUTO_FREQUENCY@
-- Automatically inferred from timestamps.
| Yearly
-- ^ @YEARLY@
-- Yearly data.
| Quarterly
-- ^ @QUARTERLY@
-- Quarterly data.
| Monthly
-- ^ @MONTHLY@
-- Monthly data.
| Weekly
-- ^ @WEEKLY@
-- Weekly data.
| Daily
-- ^ @DAILY@
-- Daily data.
| Hourly
-- ^ @HOURLY@
-- Hourly data.
| PerMinute
-- ^ @PER_MINUTE@
-- Per-minute data.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsDataFrequency
instance FromHttpApiData TrainingOptionsDataFrequency where
parseQueryParam = \case
"DATA_FREQUENCY_UNSPECIFIED" -> Right DataFrequencyUnspecified
"AUTO_FREQUENCY" -> Right AutoFrequency
"YEARLY" -> Right Yearly
"QUARTERLY" -> Right Quarterly
"MONTHLY" -> Right Monthly
"WEEKLY" -> Right Weekly
"DAILY" -> Right Daily
"HOURLY" -> Right Hourly
"PER_MINUTE" -> Right PerMinute
x -> Left ("Unable to parse TrainingOptionsDataFrequency from: " <> x)
instance ToHttpApiData TrainingOptionsDataFrequency where
toQueryParam = \case
DataFrequencyUnspecified -> "DATA_FREQUENCY_UNSPECIFIED"
AutoFrequency -> "AUTO_FREQUENCY"
Yearly -> "YEARLY"
Quarterly -> "QUARTERLY"
Monthly -> "MONTHLY"
Weekly -> "WEEKLY"
Daily -> "DAILY"
Hourly -> "HOURLY"
PerMinute -> "PER_MINUTE"
instance FromJSON TrainingOptionsDataFrequency where
parseJSON = parseJSONText "TrainingOptionsDataFrequency"
instance ToJSON TrainingOptionsDataFrequency where
toJSON = toJSONText
data ArimaSingleModelForecastingMetricsSeasonalPeriodsItem
= ASMFMSPISeasonalPeriodTypeUnspecified
-- ^ @SEASONAL_PERIOD_TYPE_UNSPECIFIED@
| ASMFMSPINoSeasonality
-- ^ @NO_SEASONALITY@
-- No seasonality
| ASMFMSPIDaily
-- ^ @DAILY@
-- Daily period, 24 hours.
| ASMFMSPIWeekly
-- ^ @WEEKLY@
-- Weekly period, 7 days.
| ASMFMSPIMonthly
-- ^ @MONTHLY@
-- Monthly period, 30 days or irregular.
| ASMFMSPIQuarterly
-- ^ @QUARTERLY@
-- Quarterly period, 90 days or irregular.
| ASMFMSPIYearly
-- ^ @YEARLY@
-- Yearly period, 365 days or irregular.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ArimaSingleModelForecastingMetricsSeasonalPeriodsItem
instance FromHttpApiData ArimaSingleModelForecastingMetricsSeasonalPeriodsItem where
parseQueryParam = \case
"SEASONAL_PERIOD_TYPE_UNSPECIFIED" -> Right ASMFMSPISeasonalPeriodTypeUnspecified
"NO_SEASONALITY" -> Right ASMFMSPINoSeasonality
"DAILY" -> Right ASMFMSPIDaily
"WEEKLY" -> Right ASMFMSPIWeekly
"MONTHLY" -> Right ASMFMSPIMonthly
"QUARTERLY" -> Right ASMFMSPIQuarterly
"YEARLY" -> Right ASMFMSPIYearly
x -> Left ("Unable to parse ArimaSingleModelForecastingMetricsSeasonalPeriodsItem from: " <> x)
instance ToHttpApiData ArimaSingleModelForecastingMetricsSeasonalPeriodsItem where
toQueryParam = \case
ASMFMSPISeasonalPeriodTypeUnspecified -> "SEASONAL_PERIOD_TYPE_UNSPECIFIED"
ASMFMSPINoSeasonality -> "NO_SEASONALITY"
ASMFMSPIDaily -> "DAILY"
ASMFMSPIWeekly -> "WEEKLY"
ASMFMSPIMonthly -> "MONTHLY"
ASMFMSPIQuarterly -> "QUARTERLY"
ASMFMSPIYearly -> "YEARLY"
instance FromJSON ArimaSingleModelForecastingMetricsSeasonalPeriodsItem where
parseJSON = parseJSONText "ArimaSingleModelForecastingMetricsSeasonalPeriodsItem"
instance ToJSON ArimaSingleModelForecastingMetricsSeasonalPeriodsItem where
toJSON = toJSONText
data ArimaResultSeasonalPeriodsItem
= ARSPISeasonalPeriodTypeUnspecified
-- ^ @SEASONAL_PERIOD_TYPE_UNSPECIFIED@
| ARSPINoSeasonality
-- ^ @NO_SEASONALITY@
-- No seasonality
| ARSPIDaily
-- ^ @DAILY@
-- Daily period, 24 hours.
| ARSPIWeekly
-- ^ @WEEKLY@
-- Weekly period, 7 days.
| ARSPIMonthly
-- ^ @MONTHLY@
-- Monthly period, 30 days or irregular.
| ARSPIQuarterly
-- ^ @QUARTERLY@
-- Quarterly period, 90 days or irregular.
| ARSPIYearly
-- ^ @YEARLY@
-- Yearly period, 365 days or irregular.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ArimaResultSeasonalPeriodsItem
instance FromHttpApiData ArimaResultSeasonalPeriodsItem where
parseQueryParam = \case
"SEASONAL_PERIOD_TYPE_UNSPECIFIED" -> Right ARSPISeasonalPeriodTypeUnspecified
"NO_SEASONALITY" -> Right ARSPINoSeasonality
"DAILY" -> Right ARSPIDaily
"WEEKLY" -> Right ARSPIWeekly
"MONTHLY" -> Right ARSPIMonthly
"QUARTERLY" -> Right ARSPIQuarterly
"YEARLY" -> Right ARSPIYearly
x -> Left ("Unable to parse ArimaResultSeasonalPeriodsItem from: " <> x)
instance ToHttpApiData ArimaResultSeasonalPeriodsItem where
toQueryParam = \case
ARSPISeasonalPeriodTypeUnspecified -> "SEASONAL_PERIOD_TYPE_UNSPECIFIED"
ARSPINoSeasonality -> "NO_SEASONALITY"
ARSPIDaily -> "DAILY"
ARSPIWeekly -> "WEEKLY"
ARSPIMonthly -> "MONTHLY"
ARSPIQuarterly -> "QUARTERLY"
ARSPIYearly -> "YEARLY"
instance FromJSON ArimaResultSeasonalPeriodsItem where
parseJSON = parseJSONText "ArimaResultSeasonalPeriodsItem"
instance ToJSON ArimaResultSeasonalPeriodsItem where
toJSON = toJSONText
-- | Optional. [Experimental] The determinism level of the JavaScript UDF if
-- defined.
data RoutineDeterminismLevel
= DeterminismLevelUnspecified
-- ^ @DETERMINISM_LEVEL_UNSPECIFIED@
-- The determinism of the UDF is unspecified.
| Deterministic
-- ^ @DETERMINISTIC@
-- The UDF is deterministic, meaning that 2 function calls with the same
-- inputs always produce the same result, even across 2 query runs.
| NotDeterministic
-- ^ @NOT_DETERMINISTIC@
-- The UDF is not deterministic.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RoutineDeterminismLevel
instance FromHttpApiData RoutineDeterminismLevel where
parseQueryParam = \case
"DETERMINISM_LEVEL_UNSPECIFIED" -> Right DeterminismLevelUnspecified
"DETERMINISTIC" -> Right Deterministic
"NOT_DETERMINISTIC" -> Right NotDeterministic
x -> Left ("Unable to parse RoutineDeterminismLevel from: " <> x)
instance ToHttpApiData RoutineDeterminismLevel where
toQueryParam = \case
DeterminismLevelUnspecified -> "DETERMINISM_LEVEL_UNSPECIFIED"
Deterministic -> "DETERMINISTIC"
NotDeterministic -> "NOT_DETERMINISTIC"
instance FromJSON RoutineDeterminismLevel where
parseJSON = parseJSONText "RoutineDeterminismLevel"
instance ToJSON RoutineDeterminismLevel where
toJSON = toJSONText
-- | The method used to initialize the centroids for kmeans algorithm.
data TrainingOptionsKmeansInitializationMethod
= KmeansInitializationMethodUnspecified
-- ^ @KMEANS_INITIALIZATION_METHOD_UNSPECIFIED@
-- Unspecified initialization method.
| Random
-- ^ @RANDOM@
-- Initializes the centroids randomly.
| Custom
-- ^ @CUSTOM@
-- Initializes the centroids using data specified in
-- kmeans_initialization_column.
| KmeansPlusPlus
-- ^ @KMEANS_PLUS_PLUS@
-- Initializes with kmeans++.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsKmeansInitializationMethod
instance FromHttpApiData TrainingOptionsKmeansInitializationMethod where
parseQueryParam = \case
"KMEANS_INITIALIZATION_METHOD_UNSPECIFIED" -> Right KmeansInitializationMethodUnspecified
"RANDOM" -> Right Random
"CUSTOM" -> Right Custom
"KMEANS_PLUS_PLUS" -> Right KmeansPlusPlus
x -> Left ("Unable to parse TrainingOptionsKmeansInitializationMethod from: " <> x)
instance ToHttpApiData TrainingOptionsKmeansInitializationMethod where
toQueryParam = \case
KmeansInitializationMethodUnspecified -> "KMEANS_INITIALIZATION_METHOD_UNSPECIFIED"
Random -> "RANDOM"
Custom -> "CUSTOM"
KmeansPlusPlus -> "KMEANS_PLUS_PLUS"
instance FromJSON TrainingOptionsKmeansInitializationMethod where
parseJSON = parseJSONText "TrainingOptionsKmeansInitializationMethod"
instance ToJSON TrainingOptionsKmeansInitializationMethod where
toJSON = toJSONText
-- | Optional. Defaults to FIXED_TYPE.
data ArgumentArgumentKind
= ArgumentKindUnspecified
-- ^ @ARGUMENT_KIND_UNSPECIFIED@
| FixedType
-- ^ @FIXED_TYPE@
-- The argument is a variable with fully specified type, which can be a
-- struct or an array, but not a table.
| AnyType
-- ^ @ANY_TYPE@
-- The argument is any type, including struct or array, but not a table. To
-- be added: FIXED_TABLE, ANY_TABLE
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ArgumentArgumentKind
instance FromHttpApiData ArgumentArgumentKind where
parseQueryParam = \case
"ARGUMENT_KIND_UNSPECIFIED" -> Right ArgumentKindUnspecified
"FIXED_TYPE" -> Right FixedType
"ANY_TYPE" -> Right AnyType
x -> Left ("Unable to parse ArgumentArgumentKind from: " <> x)
instance ToHttpApiData ArgumentArgumentKind where
toQueryParam = \case
ArgumentKindUnspecified -> "ARGUMENT_KIND_UNSPECIFIED"
FixedType -> "FIXED_TYPE"
AnyType -> "ANY_TYPE"
instance FromJSON ArgumentArgumentKind where
parseJSON = parseJSONText "ArgumentArgumentKind"
instance ToJSON ArgumentArgumentKind where
toJSON = toJSONText
-- | Optional. Specifies whether the argument is input or output. Can be set
-- for procedures only.
data ArgumentMode
= ModeUnspecified
-- ^ @MODE_UNSPECIFIED@
| IN
-- ^ @IN@
-- The argument is input-only.
| Out
-- ^ @OUT@
-- The argument is output-only.
| Inout
-- ^ @INOUT@
-- The argument is both an input and an output.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ArgumentMode
instance FromHttpApiData ArgumentMode where
parseQueryParam = \case
"MODE_UNSPECIFIED" -> Right ModeUnspecified
"IN" -> Right IN
"OUT" -> Right Out
"INOUT" -> Right Inout
x -> Left ("Unable to parse ArgumentMode from: " <> x)
instance ToHttpApiData ArgumentMode where
toQueryParam = \case
ModeUnspecified -> "MODE_UNSPECIFIED"
IN -> "IN"
Out -> "OUT"
Inout -> "INOUT"
instance FromJSON ArgumentMode where
parseJSON = parseJSONText "ArgumentMode"
instance ToJSON ArgumentMode where
toJSON = toJSONText
-- | Output only. Type of the model resource.
data ModelModelType
= ModelTypeUnspecified
-- ^ @MODEL_TYPE_UNSPECIFIED@
| LinearRegression
-- ^ @LINEAR_REGRESSION@
-- Linear regression model.
| LogisticRegression
-- ^ @LOGISTIC_REGRESSION@
-- Logistic regression based classification model.
| Kmeans
-- ^ @KMEANS@
-- K-means clustering model.
| MatrixFactorization
-- ^ @MATRIX_FACTORIZATION@
-- Matrix factorization model.
| DnnClassifier
-- ^ @DNN_CLASSIFIER@
-- DNN classifier model.
| Tensorflow
-- ^ @TENSORFLOW@
-- An imported TensorFlow model.
| DnnRegressor
-- ^ @DNN_REGRESSOR@
-- DNN regressor model.
| BoostedTreeRegressor
-- ^ @BOOSTED_TREE_REGRESSOR@
-- Boosted tree regressor model.
| BoostedTreeClassifier
-- ^ @BOOSTED_TREE_CLASSIFIER@
-- Boosted tree classifier model.
| Arima
-- ^ @ARIMA@
-- ARIMA model.
| AutomlRegressor
-- ^ @AUTOML_REGRESSOR@
-- [Beta] AutoML Tables regression model.
| AutomlClassifier
-- ^ @AUTOML_CLASSIFIER@
-- [Beta] AutoML Tables classification model.
| ArimaPlus
-- ^ @ARIMA_PLUS@
-- New name for the ARIMA model.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ModelModelType
instance FromHttpApiData ModelModelType where
parseQueryParam = \case
"MODEL_TYPE_UNSPECIFIED" -> Right ModelTypeUnspecified
"LINEAR_REGRESSION" -> Right LinearRegression
"LOGISTIC_REGRESSION" -> Right LogisticRegression
"KMEANS" -> Right Kmeans
"MATRIX_FACTORIZATION" -> Right MatrixFactorization
"DNN_CLASSIFIER" -> Right DnnClassifier
"TENSORFLOW" -> Right Tensorflow
"DNN_REGRESSOR" -> Right DnnRegressor
"BOOSTED_TREE_REGRESSOR" -> Right BoostedTreeRegressor
"BOOSTED_TREE_CLASSIFIER" -> Right BoostedTreeClassifier
"ARIMA" -> Right Arima
"AUTOML_REGRESSOR" -> Right AutomlRegressor
"AUTOML_CLASSIFIER" -> Right AutomlClassifier
"ARIMA_PLUS" -> Right ArimaPlus
x -> Left ("Unable to parse ModelModelType from: " <> x)
instance ToHttpApiData ModelModelType where
toQueryParam = \case
ModelTypeUnspecified -> "MODEL_TYPE_UNSPECIFIED"
LinearRegression -> "LINEAR_REGRESSION"
LogisticRegression -> "LOGISTIC_REGRESSION"
Kmeans -> "KMEANS"
MatrixFactorization -> "MATRIX_FACTORIZATION"
DnnClassifier -> "DNN_CLASSIFIER"
Tensorflow -> "TENSORFLOW"
DnnRegressor -> "DNN_REGRESSOR"
BoostedTreeRegressor -> "BOOSTED_TREE_REGRESSOR"
BoostedTreeClassifier -> "BOOSTED_TREE_CLASSIFIER"
Arima -> "ARIMA"
AutomlRegressor -> "AUTOML_REGRESSOR"
AutomlClassifier -> "AUTOML_CLASSIFIER"
ArimaPlus -> "ARIMA_PLUS"
instance FromJSON ModelModelType where
parseJSON = parseJSONText "ModelModelType"
instance ToJSON ModelModelType where
toJSON = toJSONText
-- | Restrict information returned to a set of selected fields
data JobsListProjection
= Full
-- ^ @full@
-- Includes all job data
| Minimal
-- ^ @minimal@
-- Does not include the job configuration
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobsListProjection
instance FromHttpApiData JobsListProjection where
parseQueryParam = \case
"full" -> Right Full
"minimal" -> Right Minimal
x -> Left ("Unable to parse JobsListProjection from: " <> x)
instance ToHttpApiData JobsListProjection where
toQueryParam = \case
Full -> "full"
Minimal -> "minimal"
instance FromJSON JobsListProjection where
parseJSON = parseJSONText "JobsListProjection"
instance ToJSON JobsListProjection where
toJSON = toJSONText
-- | The geographical region based on which the holidays are considered in
-- time series modeling. If a valid value is specified, then holiday
-- effects modeling is enabled.
data TrainingOptionsHolidayRegion
= TOHRHolidayRegionUnspecified
-- ^ @HOLIDAY_REGION_UNSPECIFIED@
-- Holiday region unspecified.
| TOHRGlobal
-- ^ @GLOBAL@
-- Global.
| TOHRNA
-- ^ @NA@
-- North America.
| TOHRJapac
-- ^ @JAPAC@
-- Japan and Asia Pacific: Korea, Greater China, India, Australia, and New
-- Zealand.
| TOHREmea
-- ^ @EMEA@
-- Europe, the Middle East and Africa.
| TOHRLac
-- ^ @LAC@
-- Latin America and the Caribbean.
| TOHRAE
-- ^ @AE@
-- United Arab Emirates
| TOHRAR
-- ^ @AR@
-- Argentina
| TOHRAT
-- ^ @AT@
-- Austria
| TOHRAU
-- ^ @AU@
-- Australia
| TOHRBE
-- ^ @BE@
-- Belgium
| TOHRBR
-- ^ @BR@
-- Brazil
| TOHRCA
-- ^ @CA@
-- Canada
| TOHRCH
-- ^ @CH@
-- Switzerland
| TOHRCL
-- ^ @CL@
-- Chile
| TOHRCN
-- ^ @CN@
-- China
| TOHRCO
-- ^ @CO@
-- Colombia
| TOHRCS
-- ^ @CS@
-- Czechoslovakia
| TOHRCZ
-- ^ @CZ@
-- Czech Republic
| TOHRDE
-- ^ @DE@
-- Germany
| TOHRDK
-- ^ @DK@
-- Denmark
| TOHRDZ
-- ^ @DZ@
-- Algeria
| TOHREC
-- ^ @EC@
-- Ecuador
| TOHREE
-- ^ @EE@
-- Estonia
| TOHREG
-- ^ @EG@
-- Egypt
| TOHRES
-- ^ @ES@
-- Spain
| TOHRFI
-- ^ @FI@
-- Finland
| TOHRFR
-- ^ @FR@
-- France
| TOHRGB
-- ^ @GB@
-- Great Britain (United Kingdom)
| TOHRGR
-- ^ @GR@
-- Greece
| TOHRHK
-- ^ @HK@
-- Hong Kong
| TOHRHU
-- ^ @HU@
-- Hungary
| TOHRID
-- ^ @ID@
-- Indonesia
| TOHRIE
-- ^ @IE@
-- Ireland
| TOHRIL
-- ^ @IL@
-- Israel
| TOHRIN
-- ^ @IN@
-- India
| TOHRIR
-- ^ @IR@
-- Iran
| TOHRIT
-- ^ @IT@
-- Italy
| TOHRJP
-- ^ @JP@
-- Japan
| TOHRKR
-- ^ @KR@
-- Korea (South)
| TOHRLV
-- ^ @LV@
-- Latvia
| TOHRMA
-- ^ @MA@
-- Morocco
| TOHRMX
-- ^ @MX@
-- Mexico
| TOHRMY
-- ^ @MY@
-- Malaysia
| TOHRNG
-- ^ @NG@
-- Nigeria
| TOHRNL
-- ^ @NL@
-- Netherlands
| TOHRNO
-- ^ @NO@
-- Norway
| TOHRNZ
-- ^ @NZ@
-- New Zealand
| TOHRPE
-- ^ @PE@
-- Peru
| TOHRPH
-- ^ @PH@
-- Philippines
| TOHRPK
-- ^ @PK@
-- Pakistan
| TOHRPL
-- ^ @PL@
-- Poland
| TOHRPT
-- ^ @PT@
-- Portugal
| TOHRRO
-- ^ @RO@
-- Romania
| TOHRRS
-- ^ @RS@
-- Serbia
| TOHRRU
-- ^ @RU@
-- Russian Federation
| TOHRSA
-- ^ @SA@
-- Saudi Arabia
| TOHRSE
-- ^ @SE@
-- Sweden
| TOHRSG
-- ^ @SG@
-- Singapore
| TOHRSI
-- ^ @SI@
-- Slovenia
| TOHRSK
-- ^ @SK@
-- Slovakia
| TOHRTH
-- ^ @TH@
-- Thailand
| TOHRTR
-- ^ @TR@
-- Turkey
| TOHRTW
-- ^ @TW@
-- Taiwan
| TOHRUA
-- ^ @UA@
-- Ukraine
| TOHRUS
-- ^ @US@
-- United States
| TOHRVE
-- ^ @VE@
-- Venezuela
| TOHRVN
-- ^ @VN@
-- Viet Nam
| TOHRZA
-- ^ @ZA@
-- South Africa
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsHolidayRegion
instance FromHttpApiData TrainingOptionsHolidayRegion where
parseQueryParam = \case
"HOLIDAY_REGION_UNSPECIFIED" -> Right TOHRHolidayRegionUnspecified
"GLOBAL" -> Right TOHRGlobal
"NA" -> Right TOHRNA
"JAPAC" -> Right TOHRJapac
"EMEA" -> Right TOHREmea
"LAC" -> Right TOHRLac
"AE" -> Right TOHRAE
"AR" -> Right TOHRAR
"AT" -> Right TOHRAT
"AU" -> Right TOHRAU
"BE" -> Right TOHRBE
"BR" -> Right TOHRBR
"CA" -> Right TOHRCA
"CH" -> Right TOHRCH
"CL" -> Right TOHRCL
"CN" -> Right TOHRCN
"CO" -> Right TOHRCO
"CS" -> Right TOHRCS
"CZ" -> Right TOHRCZ
"DE" -> Right TOHRDE
"DK" -> Right TOHRDK
"DZ" -> Right TOHRDZ
"EC" -> Right TOHREC
"EE" -> Right TOHREE
"EG" -> Right TOHREG
"ES" -> Right TOHRES
"FI" -> Right TOHRFI
"FR" -> Right TOHRFR
"GB" -> Right TOHRGB
"GR" -> Right TOHRGR
"HK" -> Right TOHRHK
"HU" -> Right TOHRHU
"ID" -> Right TOHRID
"IE" -> Right TOHRIE
"IL" -> Right TOHRIL
"IN" -> Right TOHRIN
"IR" -> Right TOHRIR
"IT" -> Right TOHRIT
"JP" -> Right TOHRJP
"KR" -> Right TOHRKR
"LV" -> Right TOHRLV
"MA" -> Right TOHRMA
"MX" -> Right TOHRMX
"MY" -> Right TOHRMY
"NG" -> Right TOHRNG
"NL" -> Right TOHRNL
"NO" -> Right TOHRNO
"NZ" -> Right TOHRNZ
"PE" -> Right TOHRPE
"PH" -> Right TOHRPH
"PK" -> Right TOHRPK
"PL" -> Right TOHRPL
"PT" -> Right TOHRPT
"RO" -> Right TOHRRO
"RS" -> Right TOHRRS
"RU" -> Right TOHRRU
"SA" -> Right TOHRSA
"SE" -> Right TOHRSE
"SG" -> Right TOHRSG
"SI" -> Right TOHRSI
"SK" -> Right TOHRSK
"TH" -> Right TOHRTH
"TR" -> Right TOHRTR
"TW" -> Right TOHRTW
"UA" -> Right TOHRUA
"US" -> Right TOHRUS
"VE" -> Right TOHRVE
"VN" -> Right TOHRVN
"ZA" -> Right TOHRZA
x -> Left ("Unable to parse TrainingOptionsHolidayRegion from: " <> x)
instance ToHttpApiData TrainingOptionsHolidayRegion where
toQueryParam = \case
TOHRHolidayRegionUnspecified -> "HOLIDAY_REGION_UNSPECIFIED"
TOHRGlobal -> "GLOBAL"
TOHRNA -> "NA"
TOHRJapac -> "JAPAC"
TOHREmea -> "EMEA"
TOHRLac -> "LAC"
TOHRAE -> "AE"
TOHRAR -> "AR"
TOHRAT -> "AT"
TOHRAU -> "AU"
TOHRBE -> "BE"
TOHRBR -> "BR"
TOHRCA -> "CA"
TOHRCH -> "CH"
TOHRCL -> "CL"
TOHRCN -> "CN"
TOHRCO -> "CO"
TOHRCS -> "CS"
TOHRCZ -> "CZ"
TOHRDE -> "DE"
TOHRDK -> "DK"
TOHRDZ -> "DZ"
TOHREC -> "EC"
TOHREE -> "EE"
TOHREG -> "EG"
TOHRES -> "ES"
TOHRFI -> "FI"
TOHRFR -> "FR"
TOHRGB -> "GB"
TOHRGR -> "GR"
TOHRHK -> "HK"
TOHRHU -> "HU"
TOHRID -> "ID"
TOHRIE -> "IE"
TOHRIL -> "IL"
TOHRIN -> "IN"
TOHRIR -> "IR"
TOHRIT -> "IT"
TOHRJP -> "JP"
TOHRKR -> "KR"
TOHRLV -> "LV"
TOHRMA -> "MA"
TOHRMX -> "MX"
TOHRMY -> "MY"
TOHRNG -> "NG"
TOHRNL -> "NL"
TOHRNO -> "NO"
TOHRNZ -> "NZ"
TOHRPE -> "PE"
TOHRPH -> "PH"
TOHRPK -> "PK"
TOHRPL -> "PL"
TOHRPT -> "PT"
TOHRRO -> "RO"
TOHRRS -> "RS"
TOHRRU -> "RU"
TOHRSA -> "SA"
TOHRSE -> "SE"
TOHRSG -> "SG"
TOHRSI -> "SI"
TOHRSK -> "SK"
TOHRTH -> "TH"
TOHRTR -> "TR"
TOHRTW -> "TW"
TOHRUA -> "UA"
TOHRUS -> "US"
TOHRVE -> "VE"
TOHRVN -> "VN"
TOHRZA -> "ZA"
instance FromJSON TrainingOptionsHolidayRegion where
parseJSON = parseJSONText "TrainingOptionsHolidayRegion"
instance ToJSON TrainingOptionsHolidayRegion where
toJSON = toJSONText
-- | Filter for job state
data JobsListStateFilter
= Done
-- ^ @done@
-- Finished jobs
| Pending
-- ^ @pending@
-- Pending jobs
| Running
-- ^ @running@
-- Running jobs
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable JobsListStateFilter
instance FromHttpApiData JobsListStateFilter where
parseQueryParam = \case
"done" -> Right Done
"pending" -> Right Pending
"running" -> Right Running
x -> Left ("Unable to parse JobsListStateFilter from: " <> x)
instance ToHttpApiData JobsListStateFilter where
toQueryParam = \case
Done -> "done"
Pending -> "pending"
Running -> "running"
instance FromJSON JobsListStateFilter where
parseJSON = parseJSONText "JobsListStateFilter"
instance ToJSON JobsListStateFilter where
toJSON = toJSONText
-- | Feedback type that specifies which algorithm to run for matrix
-- factorization.
data TrainingOptionsFeedbackType
= FeedbackTypeUnspecified
-- ^ @FEEDBACK_TYPE_UNSPECIFIED@
| Implicit
-- ^ @IMPLICIT@
-- Use weighted-als for implicit feedback problems.
| Explicit
-- ^ @EXPLICIT@
-- Use nonweighted-als for explicit feedback problems.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsFeedbackType
instance FromHttpApiData TrainingOptionsFeedbackType where
parseQueryParam = \case
"FEEDBACK_TYPE_UNSPECIFIED" -> Right FeedbackTypeUnspecified
"IMPLICIT" -> Right Implicit
"EXPLICIT" -> Right Explicit
x -> Left ("Unable to parse TrainingOptionsFeedbackType from: " <> x)
instance ToHttpApiData TrainingOptionsFeedbackType where
toQueryParam = \case
FeedbackTypeUnspecified -> "FEEDBACK_TYPE_UNSPECIFIED"
Implicit -> "IMPLICIT"
Explicit -> "EXPLICIT"
instance FromJSON TrainingOptionsFeedbackType where
parseJSON = parseJSONText "TrainingOptionsFeedbackType"
instance ToJSON TrainingOptionsFeedbackType where
toJSON = toJSONText
-- | Optional. Defaults to \"SQL\".
data RoutineLanguage
= LanguageUnspecified
-- ^ @LANGUAGE_UNSPECIFIED@
| SQL
-- ^ @SQL@
-- SQL language.
| Javascript
-- ^ @JAVASCRIPT@
-- JavaScript language.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RoutineLanguage
instance FromHttpApiData RoutineLanguage where
parseQueryParam = \case
"LANGUAGE_UNSPECIFIED" -> Right LanguageUnspecified
"SQL" -> Right SQL
"JAVASCRIPT" -> Right Javascript
x -> Left ("Unable to parse RoutineLanguage from: " <> x)
instance ToHttpApiData RoutineLanguage where
toQueryParam = \case
LanguageUnspecified -> "LANGUAGE_UNSPECIFIED"
SQL -> "SQL"
Javascript -> "JAVASCRIPT"
instance FromJSON RoutineLanguage where
parseJSON = parseJSONText "RoutineLanguage"
instance ToJSON RoutineLanguage where
toJSON = toJSONText
data ArimaModelInfoSeasonalPeriodsItem
= AMISPISeasonalPeriodTypeUnspecified
-- ^ @SEASONAL_PERIOD_TYPE_UNSPECIFIED@
| AMISPINoSeasonality
-- ^ @NO_SEASONALITY@
-- No seasonality
| AMISPIDaily
-- ^ @DAILY@
-- Daily period, 24 hours.
| AMISPIWeekly
-- ^ @WEEKLY@
-- Weekly period, 7 days.
| AMISPIMonthly
-- ^ @MONTHLY@
-- Monthly period, 30 days or irregular.
| AMISPIQuarterly
-- ^ @QUARTERLY@
-- Quarterly period, 90 days or irregular.
| AMISPIYearly
-- ^ @YEARLY@
-- Yearly period, 365 days or irregular.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ArimaModelInfoSeasonalPeriodsItem
instance FromHttpApiData ArimaModelInfoSeasonalPeriodsItem where
parseQueryParam = \case
"SEASONAL_PERIOD_TYPE_UNSPECIFIED" -> Right AMISPISeasonalPeriodTypeUnspecified
"NO_SEASONALITY" -> Right AMISPINoSeasonality
"DAILY" -> Right AMISPIDaily
"WEEKLY" -> Right AMISPIWeekly
"MONTHLY" -> Right AMISPIMonthly
"QUARTERLY" -> Right AMISPIQuarterly
"YEARLY" -> Right AMISPIYearly
x -> Left ("Unable to parse ArimaModelInfoSeasonalPeriodsItem from: " <> x)
instance ToHttpApiData ArimaModelInfoSeasonalPeriodsItem where
toQueryParam = \case
AMISPISeasonalPeriodTypeUnspecified -> "SEASONAL_PERIOD_TYPE_UNSPECIFIED"
AMISPINoSeasonality -> "NO_SEASONALITY"
AMISPIDaily -> "DAILY"
AMISPIWeekly -> "WEEKLY"
AMISPIMonthly -> "MONTHLY"
AMISPIQuarterly -> "QUARTERLY"
AMISPIYearly -> "YEARLY"
instance FromJSON ArimaModelInfoSeasonalPeriodsItem where
parseJSON = parseJSONText "ArimaModelInfoSeasonalPeriodsItem"
instance ToJSON ArimaModelInfoSeasonalPeriodsItem where
toJSON = toJSONText
-- | The log type that this config enables.
data AuditLogConfigLogType
= LogTypeUnspecified
-- ^ @LOG_TYPE_UNSPECIFIED@
-- Default case. Should never be this.
| AdminRead
-- ^ @ADMIN_READ@
-- Admin reads. Example: CloudIAM getIamPolicy
| DataWrite
-- ^ @DATA_WRITE@
-- Data writes. Example: CloudSQL Users create
| DataRead
-- ^ @DATA_READ@
-- Data reads. Example: CloudSQL Users list
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable AuditLogConfigLogType
instance FromHttpApiData AuditLogConfigLogType where
parseQueryParam = \case
"LOG_TYPE_UNSPECIFIED" -> Right LogTypeUnspecified
"ADMIN_READ" -> Right AdminRead
"DATA_WRITE" -> Right DataWrite
"DATA_READ" -> Right DataRead
x -> Left ("Unable to parse AuditLogConfigLogType from: " <> x)
instance ToHttpApiData AuditLogConfigLogType where
toQueryParam = \case
LogTypeUnspecified -> "LOG_TYPE_UNSPECIFIED"
AdminRead -> "ADMIN_READ"
DataWrite -> "DATA_WRITE"
DataRead -> "DATA_READ"
instance FromJSON AuditLogConfigLogType where
parseJSON = parseJSONText "AuditLogConfigLogType"
instance ToJSON AuditLogConfigLogType where
toJSON = toJSONText
-- | Optimization strategy for training linear regression models.
data TrainingOptionsOptimizationStrategy
= OptimizationStrategyUnspecified
-- ^ @OPTIMIZATION_STRATEGY_UNSPECIFIED@
| BatchGradientDescent
-- ^ @BATCH_GRADIENT_DESCENT@
-- Uses an iterative batch gradient descent algorithm.
| NormalEquation
-- ^ @NORMAL_EQUATION@
-- Uses a normal equation to solve linear regression problem.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsOptimizationStrategy
instance FromHttpApiData TrainingOptionsOptimizationStrategy where
parseQueryParam = \case
"OPTIMIZATION_STRATEGY_UNSPECIFIED" -> Right OptimizationStrategyUnspecified
"BATCH_GRADIENT_DESCENT" -> Right BatchGradientDescent
"NORMAL_EQUATION" -> Right NormalEquation
x -> Left ("Unable to parse TrainingOptionsOptimizationStrategy from: " <> x)
instance ToHttpApiData TrainingOptionsOptimizationStrategy where
toQueryParam = \case
OptimizationStrategyUnspecified -> "OPTIMIZATION_STRATEGY_UNSPECIFIED"
BatchGradientDescent -> "BATCH_GRADIENT_DESCENT"
NormalEquation -> "NORMAL_EQUATION"
instance FromJSON TrainingOptionsOptimizationStrategy where
parseJSON = parseJSONText "TrainingOptionsOptimizationStrategy"
instance ToJSON TrainingOptionsOptimizationStrategy where
toJSON = toJSONText
-- | The data split type for training and evaluation, e.g. RANDOM.
data TrainingOptionsDataSplitMethod
= TODSMDataSplitMethodUnspecified
-- ^ @DATA_SPLIT_METHOD_UNSPECIFIED@
| TODSMRandom
-- ^ @RANDOM@
-- Splits data randomly.
| TODSMCustom
-- ^ @CUSTOM@
-- Splits data with the user provided tags.
| TODSMSequential
-- ^ @SEQUENTIAL@
-- Splits data sequentially.
| TODSMNoSplit
-- ^ @NO_SPLIT@
-- Data split will be skipped.
| TODSMAutoSplit
-- ^ @AUTO_SPLIT@
-- Splits data automatically: Uses NO_SPLIT if the data size is small.
-- Otherwise uses RANDOM.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsDataSplitMethod
instance FromHttpApiData TrainingOptionsDataSplitMethod where
parseQueryParam = \case
"DATA_SPLIT_METHOD_UNSPECIFIED" -> Right TODSMDataSplitMethodUnspecified
"RANDOM" -> Right TODSMRandom
"CUSTOM" -> Right TODSMCustom
"SEQUENTIAL" -> Right TODSMSequential
"NO_SPLIT" -> Right TODSMNoSplit
"AUTO_SPLIT" -> Right TODSMAutoSplit
x -> Left ("Unable to parse TrainingOptionsDataSplitMethod from: " <> x)
instance ToHttpApiData TrainingOptionsDataSplitMethod where
toQueryParam = \case
TODSMDataSplitMethodUnspecified -> "DATA_SPLIT_METHOD_UNSPECIFIED"
TODSMRandom -> "RANDOM"
TODSMCustom -> "CUSTOM"
TODSMSequential -> "SEQUENTIAL"
TODSMNoSplit -> "NO_SPLIT"
TODSMAutoSplit -> "AUTO_SPLIT"
instance FromJSON TrainingOptionsDataSplitMethod where
parseJSON = parseJSONText "TrainingOptionsDataSplitMethod"
instance ToJSON TrainingOptionsDataSplitMethod where
toJSON = toJSONText
-- | Required. The top level type of this field. Can be any standard SQL data
-- type (e.g., \"INT64\", \"DATE\", \"ARRAY\").
data StandardSQLDataTypeTypeKind
= TypeKindUnspecified
-- ^ @TYPE_KIND_UNSPECIFIED@
-- Invalid type.
| INT64
-- ^ @INT64@
-- Encoded as a string in decimal format.
| Bool
-- ^ @BOOL@
-- Encoded as a boolean \"false\" or \"true\".
| FLOAT64
-- ^ @FLOAT64@
-- Encoded as a number, or string \"NaN\", \"Infinity\" or \"-Infinity\".
| String
-- ^ @STRING@
-- Encoded as a string value.
| Bytes
-- ^ @BYTES@
-- Encoded as a base64 string per RFC 4648, section 4.
| Timestamp
-- ^ @TIMESTAMP@
-- Encoded as an RFC 3339 timestamp with mandatory \"Z\" time zone string:
-- 1985-04-12T23:20:50.52Z
| Date
-- ^ @DATE@
-- Encoded as RFC 3339 full-date format string: 1985-04-12
| Time
-- ^ @TIME@
-- Encoded as RFC 3339 partial-time format string: 23:20:50.52
| Datetime
-- ^ @DATETIME@
-- Encoded as RFC 3339 full-date \"T\" partial-time: 1985-04-12T23:20:50.52
| Interval
-- ^ @INTERVAL@
-- Encoded as fully qualified 3 part: 0-5 15 2:30:45.6
| Geography
-- ^ @GEOGRAPHY@
-- Encoded as WKT
| Numeric
-- ^ @NUMERIC@
-- Encoded as a decimal string.
| Bignumeric
-- ^ @BIGNUMERIC@
-- Encoded as a decimal string.
| JSON
-- ^ @JSON@
-- Encoded as a string.
| Array
-- ^ @ARRAY@
-- Encoded as a list with types matching Type.array_type.
| Struct
-- ^ @STRUCT@
-- Encoded as a list with fields of type Type.struct_type[i]. List is used
-- because a JSON object cannot have duplicate field names.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable StandardSQLDataTypeTypeKind
instance FromHttpApiData StandardSQLDataTypeTypeKind where
parseQueryParam = \case
"TYPE_KIND_UNSPECIFIED" -> Right TypeKindUnspecified
"INT64" -> Right INT64
"BOOL" -> Right Bool
"FLOAT64" -> Right FLOAT64
"STRING" -> Right String
"BYTES" -> Right Bytes
"TIMESTAMP" -> Right Timestamp
"DATE" -> Right Date
"TIME" -> Right Time
"DATETIME" -> Right Datetime
"INTERVAL" -> Right Interval
"GEOGRAPHY" -> Right Geography
"NUMERIC" -> Right Numeric
"BIGNUMERIC" -> Right Bignumeric
"JSON" -> Right JSON
"ARRAY" -> Right Array
"STRUCT" -> Right Struct
x -> Left ("Unable to parse StandardSQLDataTypeTypeKind from: " <> x)
instance ToHttpApiData StandardSQLDataTypeTypeKind where
toQueryParam = \case
TypeKindUnspecified -> "TYPE_KIND_UNSPECIFIED"
INT64 -> "INT64"
Bool -> "BOOL"
FLOAT64 -> "FLOAT64"
String -> "STRING"
Bytes -> "BYTES"
Timestamp -> "TIMESTAMP"
Date -> "DATE"
Time -> "TIME"
Datetime -> "DATETIME"
Interval -> "INTERVAL"
Geography -> "GEOGRAPHY"
Numeric -> "NUMERIC"
Bignumeric -> "BIGNUMERIC"
JSON -> "JSON"
Array -> "ARRAY"
Struct -> "STRUCT"
instance FromJSON StandardSQLDataTypeTypeKind where
parseJSON = parseJSONText "StandardSQLDataTypeTypeKind"
instance ToJSON StandardSQLDataTypeTypeKind where
toJSON = toJSONText
-- | The strategy to determine learn rate for the current iteration.
data TrainingOptionsLearnRateStrategy
= LearnRateStrategyUnspecified
-- ^ @LEARN_RATE_STRATEGY_UNSPECIFIED@
| LineSearch
-- ^ @LINE_SEARCH@
-- Use line search to determine learning rate.
| Constant
-- ^ @CONSTANT@
-- Use a constant learning rate.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsLearnRateStrategy
instance FromHttpApiData TrainingOptionsLearnRateStrategy where
parseQueryParam = \case
"LEARN_RATE_STRATEGY_UNSPECIFIED" -> Right LearnRateStrategyUnspecified
"LINE_SEARCH" -> Right LineSearch
"CONSTANT" -> Right Constant
x -> Left ("Unable to parse TrainingOptionsLearnRateStrategy from: " <> x)
instance ToHttpApiData TrainingOptionsLearnRateStrategy where
toQueryParam = \case
LearnRateStrategyUnspecified -> "LEARN_RATE_STRATEGY_UNSPECIFIED"
LineSearch -> "LINE_SEARCH"
Constant -> "CONSTANT"
instance FromJSON TrainingOptionsLearnRateStrategy where
parseJSON = parseJSONText "TrainingOptionsLearnRateStrategy"
instance ToJSON TrainingOptionsLearnRateStrategy where
toJSON = toJSONText
-- | Required. The type of routine.
data RoutineRoutineType
= RoutineTypeUnspecified
-- ^ @ROUTINE_TYPE_UNSPECIFIED@
| ScalarFunction
-- ^ @SCALAR_FUNCTION@
-- Non-builtin permanent scalar function.
| Procedure
-- ^ @PROCEDURE@
-- Stored procedure.
| TableValuedFunction
-- ^ @TABLE_VALUED_FUNCTION@
-- Non-builtin permanent TVF.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable RoutineRoutineType
instance FromHttpApiData RoutineRoutineType where
parseQueryParam = \case
"ROUTINE_TYPE_UNSPECIFIED" -> Right RoutineTypeUnspecified
"SCALAR_FUNCTION" -> Right ScalarFunction
"PROCEDURE" -> Right Procedure
"TABLE_VALUED_FUNCTION" -> Right TableValuedFunction
x -> Left ("Unable to parse RoutineRoutineType from: " <> x)
instance ToHttpApiData RoutineRoutineType where
toQueryParam = \case
RoutineTypeUnspecified -> "ROUTINE_TYPE_UNSPECIFIED"
ScalarFunction -> "SCALAR_FUNCTION"
Procedure -> "PROCEDURE"
TableValuedFunction -> "TABLE_VALUED_FUNCTION"
instance FromJSON RoutineRoutineType where
parseJSON = parseJSONText "RoutineRoutineType"
instance ToJSON RoutineRoutineType where
toJSON = toJSONText
-- | Type of loss function used during training run.
data TrainingOptionsLossType
= LossTypeUnspecified
-- ^ @LOSS_TYPE_UNSPECIFIED@
| MeanSquaredLoss
-- ^ @MEAN_SQUARED_LOSS@
-- Mean squared loss, used for linear regression.
| MeanLogLoss
-- ^ @MEAN_LOG_LOSS@
-- Mean log loss, used for logistic regression.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsLossType
instance FromHttpApiData TrainingOptionsLossType where
parseQueryParam = \case
"LOSS_TYPE_UNSPECIFIED" -> Right LossTypeUnspecified
"MEAN_SQUARED_LOSS" -> Right MeanSquaredLoss
"MEAN_LOG_LOSS" -> Right MeanLogLoss
x -> Left ("Unable to parse TrainingOptionsLossType from: " <> x)
instance ToHttpApiData TrainingOptionsLossType where
toQueryParam = \case
LossTypeUnspecified -> "LOSS_TYPE_UNSPECIFIED"
MeanSquaredLoss -> "MEAN_SQUARED_LOSS"
MeanLogLoss -> "MEAN_LOG_LOSS"
instance FromJSON TrainingOptionsLossType where
parseJSON = parseJSONText "TrainingOptionsLossType"
instance ToJSON TrainingOptionsLossType where
toJSON = toJSONText
-- | Distance type for clustering models.
data TrainingOptionsDistanceType
= DistanceTypeUnspecified
-- ^ @DISTANCE_TYPE_UNSPECIFIED@
| Euclidean
-- ^ @EUCLIDEAN@
-- Eculidean distance.
| Cosine
-- ^ @COSINE@
-- Cosine distance.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TrainingOptionsDistanceType
instance FromHttpApiData TrainingOptionsDistanceType where
parseQueryParam = \case
"DISTANCE_TYPE_UNSPECIFIED" -> Right DistanceTypeUnspecified
"EUCLIDEAN" -> Right Euclidean
"COSINE" -> Right Cosine
x -> Left ("Unable to parse TrainingOptionsDistanceType from: " <> x)
instance ToHttpApiData TrainingOptionsDistanceType where
toQueryParam = \case
DistanceTypeUnspecified -> "DISTANCE_TYPE_UNSPECIFIED"
Euclidean -> "EUCLIDEAN"
Cosine -> "COSINE"
instance FromJSON TrainingOptionsDistanceType where
parseJSON = parseJSONText "TrainingOptionsDistanceType"
instance ToJSON TrainingOptionsDistanceType where
toJSON = toJSONText
data ArimaForecastingMetricsSeasonalPeriodsItem
= AFMSPISeasonalPeriodTypeUnspecified
-- ^ @SEASONAL_PERIOD_TYPE_UNSPECIFIED@
| AFMSPINoSeasonality
-- ^ @NO_SEASONALITY@
-- No seasonality
| AFMSPIDaily
-- ^ @DAILY@
-- Daily period, 24 hours.
| AFMSPIWeekly
-- ^ @WEEKLY@
-- Weekly period, 7 days.
| AFMSPIMonthly
-- ^ @MONTHLY@
-- Monthly period, 30 days or irregular.
| AFMSPIQuarterly
-- ^ @QUARTERLY@
-- Quarterly period, 90 days or irregular.
| AFMSPIYearly
-- ^ @YEARLY@
-- Yearly period, 365 days or irregular.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ArimaForecastingMetricsSeasonalPeriodsItem
instance FromHttpApiData ArimaForecastingMetricsSeasonalPeriodsItem where
parseQueryParam = \case
"SEASONAL_PERIOD_TYPE_UNSPECIFIED" -> Right AFMSPISeasonalPeriodTypeUnspecified
"NO_SEASONALITY" -> Right AFMSPINoSeasonality
"DAILY" -> Right AFMSPIDaily
"WEEKLY" -> Right AFMSPIWeekly
"MONTHLY" -> Right AFMSPIMonthly
"QUARTERLY" -> Right AFMSPIQuarterly
"YEARLY" -> Right AFMSPIYearly
x -> Left ("Unable to parse ArimaForecastingMetricsSeasonalPeriodsItem from: " <> x)
instance ToHttpApiData ArimaForecastingMetricsSeasonalPeriodsItem where
toQueryParam = \case
AFMSPISeasonalPeriodTypeUnspecified -> "SEASONAL_PERIOD_TYPE_UNSPECIFIED"
AFMSPINoSeasonality -> "NO_SEASONALITY"
AFMSPIDaily -> "DAILY"
AFMSPIWeekly -> "WEEKLY"
AFMSPIMonthly -> "MONTHLY"
AFMSPIQuarterly -> "QUARTERLY"
AFMSPIYearly -> "YEARLY"
instance FromJSON ArimaForecastingMetricsSeasonalPeriodsItem where
parseJSON = parseJSONText "ArimaForecastingMetricsSeasonalPeriodsItem"
instance ToJSON ArimaForecastingMetricsSeasonalPeriodsItem where
toJSON = toJSONText
| brendanhay/gogol | gogol-bigquery/gen/Network/Google/BigQuery/Types/Sum.hs | mpl-2.0 | 43,099 | 0 | 11 | 11,468 | 6,595 | 3,540 | 3,055 | 848 | 0 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, FlexibleInstances, RecordWildCards, UnicodeSyntax, Rank2Types #-}
module Papstehrenwort.Web.Html where
import Protolude as P
import Data.Time.Calendar (Day)
import Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes as A
import Text.Blaze (ToMarkup)
import Papstehrenwort.I18n ()
import qualified Papstehrenwort.Types as T
import qualified Papstehrenwort.Scheduler as S
import qualified Papstehrenwort.I18n as I
-- | Data the site needs to display its contents
data Site = Site { sTasks :: TaskList }
-- | A Translated thing is something that has a function which
-- can display localized messages in some varying rendered markup
data Translated a = Trans (∀ t. I.FromMarkup t => I.UIMessages -> t) a
-- note that ToMarkup comes from blaze, while FromMarkup is a local class
instance ToMarkup (Translated Site) where
toMarkup (Trans t Site{..}) =
docTypeHtml $ do
H.head $ do
H.title $ t I.Title
H.link ! href "/static/screen.css" ! rel "stylesheet"
meta ! charset "utf-8"
body $ do
main $ do
header $ do
h1 $ t I.Title
h2 . small $ t I.Tagline
p $ t I.Introduction
H.form ! action "/commit" ! method "post" $ do
let inp tag typ n = p $ do
t tag :: Html
br
input ! type_ typ ! name n ! class_ "form-control"
in do
inp I.MailAddress "email" "email"
inp I.DisplayName "text" "name"
H.div ! id "tasks" $ toMarkup $ Trans t sTasks
p $ button ! type_ "submit" ! name "submit" $ t I.CommitButton
script ! src "/static/jquery.min.js" $ mempty
script ! src "/js/check-table.js" $ mempty
data TaskList = TaskList { tlTasks :: [T.Task]
, tlToday :: Day }
instance ToMarkup (Translated TaskList) where
toMarkup (Trans t TaskList{..}) =
let desc = th . t
dat = td . toHtml in
table ! class_ "table" $ do
thead $ do
desc I.TaskTitle
desc I.TaskDescription
desc I.TaskUrl
desc I.TaskNextOccur
tbody $ do
mconcat $ flip P.map tlTasks $ \T.Task{..} -> do
dat tTitle
dat tDescription
dat $ maybe "" (T.exportURL) tUrl
dat . show $ S.nextOccurrence tStart tRecur tlToday
td $ input ! type_ "checkbox" ! name "tTitle" ! value "do"
| openlab-aux/papstehrenwort | src/Papstehrenwort/Web/Html.hs | agpl-3.0 | 2,483 | 0 | 31 | 754 | 734 | 359 | 375 | 57 | 0 |
{-# LANGUAGE DataKinds
, GeneralizedNewtypeDeriving
, TupleSections
, TypeFamilies
#-}
module Avro.Parser
( Parser(Parser, getAttoparsecParser)
, parse
)
where
import Control.Applicative (liftA2)
import qualified Data.Attoparsec.ByteString.Lazy as APS
import Data.Bits ((.&.), FiniteBits, shiftL, testBit)
import Data.List (genericReplicate)
import qualified Data.Map as Map
import Data.Binary.Get (runGet)
import Data.Binary.IEEE754 (getFloat32le, getFloat64le)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Text.Encoding (decodeUtf8')
import Data.Vinyl (rtraverse)
import Data.Vinyl.Functor (Identity(Identity))
import Avro.Records (Field(fieldSchema))
import Avro.Schema
( Schema
( avroNull
, avroBool
, avroInt
, avroFloat
, avroDouble
, avroLong
, avroBytes
, avroString
, avroRecord
, avroEnum
, avroArray
, avroMap
, avroFixed
)
)
import ZigZagCoding (zigZagDecode)
import Data.Functor.Polyvariant
( Polyvariant(VarianceOf)
, Variance(Covariance)
)
newtype Parser a = Parser { getAttoparsecParser :: APS.Parser a }
deriving (Functor, Applicative, Monad, MonadFail, Semigroup, Monoid)
parse :: Parser a -> LBS.ByteString -> APS.Result a
parse = APS.parse . getAttoparsecParser
instance Schema Parser
where avroNull = return ()
avroBool = (/= 0) <$> Parser APS.anyWord8
avroInt = zigZagDecode . decodeVarWord <$> getVarWordBytes
avroLong = zigZagDecode . decodeVarWord <$> getVarWordBytes
avroFloat = runGet getFloat32le . LBS.fromStrict <$> Parser (APS.take 4)
avroDouble = runGet getFloat64le . LBS.fromStrict <$> Parser (APS.take 8)
avroBytes = Parser . APS.take . fromIntegral =<< avroLong
avroString = either (fail . show) return . decodeUtf8' =<< avroBytes
avroRecord _ = rtraverse (fmap Identity . fieldSchema)
avroEnum = toEnum . fromIntegral <$> avroInt
avroArray itemSchema
= do count <- avroLong
let arrayBlock = flip genericCount itemSchema . abs
if count /= 0
then (++) <$> arrayBlock count <*> avroArray itemSchema
else return []
avroMap
= fmap Map.fromList
. avroArray
. uncurry (liftA2 (,))
. (avroString,)
avroFixed = Parser . APS.take . fromIntegral
instance Polyvariant Parser
where type VarianceOf Parser = 'Covariance
decodeVarWord :: (FiniteBits a, Integral a) => ByteString -> a
decodeVarWord = BS.foldr' f 0
where f b x = x `shiftL` 7 + fromIntegral (b .&. 0x7f)
getVarWordBytes :: Parser ByteString
getVarWordBytes
= Parser $ APS.scan True
$ \s b -> if s
then Just $ testBit b 7
else Nothing
genericCount :: (Monad m, Integral i) => i -> m a -> m [a]
genericCount n p = sequence (genericReplicate n p)
| cumber/havro | src/Avro/Parser.hs | lgpl-3.0 | 3,071 | 0 | 12 | 816 | 845 | 481 | 364 | 83 | 2 |
-- Copyright 2021 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
module Main where
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit ((@?=))
import Data.Portray
import Data.Portray.Pretty
main :: IO ()
main = defaultMain
[ testGroup "Atom"
[ testCase "()" $ prettyShowPortrayal (Tuple []) @?= "()"
, testCase "2" $ prettyShowPortrayal (LitInt 2) @?= "2"
]
, testGroup "Apply"
[ testCase "nullary" $
prettyShowPortrayal (Apply (Name "Nothing") []) @?= "Nothing"
, testCase "nullary 2" $
prettyShowPortrayal
(Apply (Name "id") [Apply (Name "Nothing") []]) @?=
"id Nothing"
, testCase "unary" $
prettyShowPortrayal (Apply (Name "Just") [LitInt 2]) @?= "Just 2"
, testCase "parens" $
prettyShowPortrayal
(Apply (Name "Just") [Apply (Name "Just") [LitInt 2]]) @?=
"Just (Just 2)"
, testCase "binary" $
prettyShowPortrayal (Apply (Name "These") [LitInt 2, LitInt 4]) @?=
"These 2 4"
, testCase "nested" $
prettyShowPortrayal
(Apply (Apply (Name "These") [LitInt 2]) [LitInt 4]) @?=
"These 2 4"
]
, testGroup "Binop"
[ testCase "operator" $
prettyShowPortrayal
(Binop ":|" (infixr_ 5) (LitInt 5) (List [])) @?=
"5 :| []"
, testCase "con" $
prettyShowPortrayal
(Binop
(Ident ConIdent "InfixCon")
(infixl_ 9)
(LitInt 2)
(Name "True")) @?=
"2 `InfixCon` True"
, testCase "nest prec" $
prettyShowPortrayal
(Binop
"+"
(infixl_ 6)
(Binop "*" (infixl_ 7) (LitInt 2) (LitInt 4))
(LitInt 6)) @?=
"2 * 4 + 6"
, testCase "nest anti-prec" $
prettyShowPortrayal
(Binop
"*"
(infixl_ 7)
(Binop "+" (infixl_ 6) (LitInt 2) (LitInt 4))
(LitInt 6)) @?=
"(2 + 4) * 6"
, testCase "nest assoc" $
prettyShowPortrayal
(Binop
"+"
(infixl_ 6)
(Binop "+" (infixl_ 6) (LitInt 2) (LitInt 4))
(LitInt 6)) @?=
"2 + 4 + 6"
, testCase "nest anti-assoc" $
prettyShowPortrayal
(Binop
"+"
(infixl_ 6)
(LitInt 2)
(Binop "+" (infixl_ 6) (LitInt 4) (LitInt 6))) @?=
"2 + (4 + 6)"
]
, testGroup "Tuple"
[ testCase "pair" $
prettyShowPortrayal (Tuple [LitInt 2, LitInt 4]) @?= "( 2, 4 )"
, testCase "triple" $
prettyShowPortrayal (Tuple [LitInt 2, LitInt 4, LitInt 6]) @?=
"( 2, 4, 6 )"
, testCase "line-break" $
prettyShowPortrayal
(Tuple [strAtom "222", strAtom (replicate 61 '2')]) @?=
"( 222\n\
\, 2222222222222222222222222222222222222222222222222222222222222\n\
\)"
]
, testGroup "List"
[ testCase "empty" $ prettyShowPortrayal (List []) @?= "[]"
, testCase "singleton" $ prettyShowPortrayal (List [LitInt 2]) @?=
"[ 2 ]"
]
, testGroup "LambdaCase"
[ testCase "empty" $ prettyShowPortrayal (LambdaCase []) @?= "\\case {}"
, testCase "singleton" $
prettyShowPortrayal (LambdaCase [(Tuple [], LitInt 2)]) @?=
"\\case { () -> 2 }"
, testCase "two" $
prettyShowPortrayal
(LambdaCase
[(Name "True", LitInt 2), (Name "False", LitInt 4)]) @?=
"\\case { True -> 2; False -> 4 }"
, testCase "line-break" $
prettyShowPortrayal
(LambdaCase
[ (Name "True", strAtom (replicate 25 '2'))
, (Name "False", strAtom (replicate 25 '4'))
]) @?=
"\\case\n\
\ { True -> 2222222222222222222222222\n\
\ ; False -> 4444444444444444444444444\n\
\ }"
, testCase "no-parens" $
prettyShowPortrayal
(LambdaCase
[( Apply (Name "Just") [LitInt 2]
, Apply (Name "Just") [LitInt 4]
)]) @?=
"\\case { Just 2 -> Just 4 }"
]
, testGroup "Record"
[ testCase "empty" $ prettyShowPortrayal (Record (Name "Nothing") []) @?=
"Nothing"
, testCase "singleton" $
prettyShowPortrayal
(Record (Name "Just") [FactorPortrayal "it" (LitInt 2)]) @?=
"Just { it = 2 }"
, testCase "two" $
prettyShowPortrayal
(Record (Name "These")
[ FactorPortrayal "l" (LitInt 2)
, FactorPortrayal "r" (LitInt 4)
]) @?=
"These { l = 2, r = 4 }"
, testCase "line-break" $
prettyShowPortrayal
(Record (Name "These")
[ FactorPortrayal "l" (portray @[Int] [0..10])
, FactorPortrayal "r" (portray @[Int] [0..10])
]) @?=
"These\n\
\ { l = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]\n\
\ , r = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]\n\
\ }"
, testCase "break-equals" $
prettyShowPortrayal
(Record (Name "These")
[ FactorPortrayal
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
(Name "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
]) @?=
"These\n\
\ { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n\
\ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
\ }"
]
, testGroup "TyApp"
[ testCase "con" $
prettyShowPortrayal (TyApp (Name "typeRep") (Name "Int")) @?=
"typeRep @Int"
, testCase "parens" $
prettyShowPortrayal
(TyApp (Name "typeRep") (Apply (Name "Maybe") [Name "Int"])) @?=
"typeRep @(Maybe Int)"
, testCase "line-break" $
prettyShowPortrayal
(TyApp
(strAtom $ replicate 50 'a')
(strAtom $ replicate 50 'a')) @?=
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
\ @aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
]
, testGroup "TySig"
[ testCase "con" $ prettyShowPortrayal (TySig (LitInt 2) (Name "Int")) @?=
"2 :: Int"
, testCase "no-parens" $
prettyShowPortrayal
(TySig
(Apply (Name "Just") [LitInt 2])
(Apply (Name "Maybe") [Name "Int"])) @?=
"Just 2 :: Maybe Int"
, testCase "line-break" $
prettyShowPortrayal
(TySig
(strAtom $ replicate 50 'a')
(strAtom $ replicate 50 'a')) @?=
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
\ :: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
, testCase "parens" $
prettyShowPortrayal
(Apply (Name "Just") [TySig (LitInt 2) (Name "Int")]) @?=
"Just (2 :: Int)"
]
]
| google/hs-portray | portray-pretty/test/Main.hs | apache-2.0 | 8,066 | 0 | 19 | 3,000 | 1,888 | 948 | 940 | 181 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextCharFormat.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QTextCharFormat (
VerticalAlignment, eAlignNormal, eAlignSuperScript, eAlignSubScript, eAlignMiddle
, UnderlineStyle, eNoUnderline, eSingleUnderline, eDashUnderline, eWaveUnderline, eSpellCheckUnderline
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CVerticalAlignment a = CVerticalAlignment a
type VerticalAlignment = QEnum(CVerticalAlignment Int)
ieVerticalAlignment :: Int -> VerticalAlignment
ieVerticalAlignment x = QEnum (CVerticalAlignment x)
instance QEnumC (CVerticalAlignment Int) where
qEnum_toInt (QEnum (CVerticalAlignment x)) = x
qEnum_fromInt x = QEnum (CVerticalAlignment x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> VerticalAlignment -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eAlignNormal :: VerticalAlignment
eAlignNormal
= ieVerticalAlignment $ 0
eAlignSuperScript :: VerticalAlignment
eAlignSuperScript
= ieVerticalAlignment $ 1
eAlignSubScript :: VerticalAlignment
eAlignSubScript
= ieVerticalAlignment $ 2
eAlignMiddle :: VerticalAlignment
eAlignMiddle
= ieVerticalAlignment $ 3
instance QeAlignTop VerticalAlignment where
eAlignTop
= ieVerticalAlignment $ 4
instance QeAlignBottom VerticalAlignment where
eAlignBottom
= ieVerticalAlignment $ 5
data CUnderlineStyle a = CUnderlineStyle a
type UnderlineStyle = QEnum(CUnderlineStyle Int)
ieUnderlineStyle :: Int -> UnderlineStyle
ieUnderlineStyle x = QEnum (CUnderlineStyle x)
instance QEnumC (CUnderlineStyle Int) where
qEnum_toInt (QEnum (CUnderlineStyle x)) = x
qEnum_fromInt x = QEnum (CUnderlineStyle x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> UnderlineStyle -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eNoUnderline :: UnderlineStyle
eNoUnderline
= ieUnderlineStyle $ 0
eSingleUnderline :: UnderlineStyle
eSingleUnderline
= ieUnderlineStyle $ 1
eDashUnderline :: UnderlineStyle
eDashUnderline
= ieUnderlineStyle $ 2
instance QeDotLine UnderlineStyle where
eDotLine
= ieUnderlineStyle $ 3
instance QeDashDotLine UnderlineStyle where
eDashDotLine
= ieUnderlineStyle $ 4
instance QeDashDotDotLine UnderlineStyle where
eDashDotDotLine
= ieUnderlineStyle $ 5
eWaveUnderline :: UnderlineStyle
eWaveUnderline
= ieUnderlineStyle $ 6
eSpellCheckUnderline :: UnderlineStyle
eSpellCheckUnderline
= ieUnderlineStyle $ 7
| keera-studios/hsQt | Qtc/Enums/Gui/QTextCharFormat.hs | bsd-2-clause | 5,172 | 0 | 18 | 1,056 | 1,284 | 649 | 635 | 126 | 1 |
module Main where
import System.Console.CmdArgs
import Application.MiscUtils.ProgType
import Application.MiscUtils.Command
main :: IO ()
main = do
putStrLn "misc-utils"
param <- cmdArgs mode
commandLineProcess param | wavewave/misc-utils | oldcode/exe/misc-utils.hs | bsd-2-clause | 227 | 0 | 8 | 35 | 59 | 31 | 28 | 9 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
module Text.OGDL.Parsec where
import Text.Parsec(Column, sourceColumn, (<?>), (<|>), getPosition, getState,
many, modifyState, runParser, try, unexpected, char, oneOf, satisfy, string,
between, choice, count, lookAhead, many1, noneOf, option, optional, sepEndBy, sepEndBy1)
import Data.Tree(Tree(Node))
import Control.Monad(when, unless, liftM, liftM2)
import Data.List(intercalate)
import Data.Maybe(Maybe(..), fromMaybe)
data IndentChar = Space | Tab deriving (Show,Eq)
data Indentation = I { iStack :: [Column], indentChar :: Maybe IndentChar}
deriving (Eq,Show)
emptyState = I [] Nothing
modifyStack f = modifyState (`modifyStack'` f)
where rec `modifyStack'` f = rec { iStack = f (iStack rec) }
withStack f = getState >>= return . (`withStack'` f)
where rec `withStack'` f = f (iStack rec)
pushStack c = modifyStack (c:)
popStack = do is <- getState >>= return . iStack
case is of
[] -> return Nothing
(x:_) -> modifyStack tail >> return (Just x)
topStack = do is <- getState >>= return . iStack
case is of
[] -> return Nothing
(x:_) -> return (Just x)
getIndentChar = liftM indentChar getState
setIndentChar c = modifyState (\x -> x { indentChar = Just c }) >> return c
indent = do cc <- getPosition >>= return . sourceColumn
pc <- liftM (fromMaybe 0) topStack
if cc > pc
then pushStack cc
else unexpected "end of block"
-- // # 5. Level 1: Tree grammar
-- // [1] char_word ::= [0x21-0xD7FF] | [0xE000-0xFFFD] | [0x10000-0x10FFFD]
-- // This range includes all Unicode characters, except characters below
-- // and including 0x20 (space), Unicode surrogate blocks, 0xfffe and
-- // 0xffff.
-- Since this actually differs from the characters that can appear
-- in words, I've renamed it.
isAllowedChar = flip (any . inRange) [ ('\x21','\xD7FF') , ('\xE000','\xFFFD') , ('\x10000','\x10FFFD') ]
where i `inRange` (m,n) = m <= i && i <= n
allowedChar = satisfy isAllowedChar
headWordChar = lookAhead (satisfy $ (`notElem` "\"'#(,)") ) >> (satisfy isAllowedChar)
tailWordChar = lookAhead (noneOf "\"#(,)") >> (satisfy isAllowedChar)
headPathChar = lookAhead (satisfy $ (`notElem` "\"'#.,()[]{}") ) >> (satisfy isAllowedChar)
tailPathChar = lookAhead (satisfy $ (`notElem` "\"#.,()[]{}") ) >> (satisfy isAllowedChar)
-- // [2] char_space ::= 0x20 | 0x09
isSpaceChar c = c == '\x20' || c == '\x09'
spaceChar = oneOf "\x20\x09"
spaceChars = many1 spaceChar
trimSpaces p = do r <- p
optional spaceChars
return r
indentTab = char '\x09' >> return Tab <?> "tab"
indentSpace = char '\x20' >> return Space <?> "space"
indentSpaceChar = indentSpace <|> indentTab
-- // [3] char_break ::= 0x0d | 0x0a
breakChar = oneOf "\x0d\x0a"
isBreakChar c = c == '\x0d' || c == '\x0a'
-- // [4] char_end ::= any_char - char_word - char_space - char_break
-- // This production states that any character that is not char\_word,
-- // char\_space or char\_break is considered the end of the OGDL
-- // stream, and makes the parser stop and return, without signaling an
-- // error.
endChar = satisfy (\c -> not (any ($c) [isAllowedChar,isSpaceChar,isBreakChar] ) )
-- // [5] word ::= ( char_word - ',' - '(' - ')' )+
-- for comments to work, either (a) '#' can't appear in words or
-- (b) it can't appear at the beginning of words and must be separated
-- by a space to start a comment. I'll go with option (a).
-- On a related note, why is char_word called that if it doesn't
-- actually specify the characters that can appear in words?
word = liftM2 (:) (try headWordChar) (option [] $ many1 (try tailWordChar))
pathString = liftM2 (:) (try headPathChar ) (option [] $ many1 (try tailPathChar))
-- // [6] break ::= 0x0a | 0x0d | (0x0d 0x0a)
lineBreak = (choice $ map (try . string) ["\x0d\x0a","\x0a","\x0d"]) <?> "line break"
-- // When parsing, breaks are normalized: standalone 0x0d characters and
-- // 0x0d 0x0a sequences are converted to 0x0a characters. The emitter
-- // should print breaks according to the particular operating system
-- // rules.
-- // [7] end ::= char_end | ( break "--" break )
end = choice [ endChar >> return (), between lineBreak lineBreak $ string "--" >> return ()]
-- // [8] space ::= char_space+
-- // [9] space(n) ::= char_space*n, where n is the equivalent number of spaces.
-- indentWhiteSpace
-- = do i <- liftM indentChar getState
-- maybe (do sc <- indentSpaceChar
-- modifyState (\x -> x { indentChar = Just sc } ) ) only i
-- optional indentWhiteSpace
-- optional (comment >> optional lineBreak >> whiteSpace)
-- where
-- only p = do { s <- indentSpaceChar ;
-- when (p /= s) (fail "mixing spaces and tabs is not permitted")
-- return ()
--
indentation = do cc <- liftM sourceColumn getPosition
unless (cc==1) (fail "indetation can only occur at the beginning of a line.")
m <- getIndentChar
ic <- case m of
Nothing -> lookAhead indentSpaceChar >>= setIndentChar
Just c -> return c
only ic
return ()
where only p = many ( do s <- indentSpaceChar
when (p /= s) (unexpected "mixing of space and tabs")
return () )
whiteSpace = optional $ many1 ( try comment <|> (spaceChars >> return ()) <|> (lineBreak >> return ()) ) >> return ()
-- // This is the indentation production. It corresponds to the
-- // equivalent number of spaces between the start of a line and the
-- // beginning of the first scalar node. For any two consecutive scalars
-- // preceded by indentation, the second is child of the first one if it
-- // is more indented. Intermixing of spaces and tabs is NOT allowed:
-- // either tabs or spaces should be used for indentation within a
-- // document.
-- // [10] single_quoted ::= "'" (char_word | char_space | break)* "'"
-- // A quote character that has to be included in the string should be
-- // preceded by '\\'. If the string contains line breaks, leading
-- // spaces on each new line are stripped off. The initial indentation
-- // is defined by the first line after a break. The indentation is
-- // decreased if word characters appear at a lower indentation, but it
-- // is never increased. Lines ending with '\\' are concatenaded. Escape
-- // sequences that are recognized are \\", \\' and \\\\. The character
-- // '\\' should be considered literal in other cases.
-- // [11] double_quoted ::= '"' (char_word | char_space | break)* '"'
-- // Same rule applies as for [10].
-- FIXME: I still need to handle the described indentation rule
quotedBy q = between qp (qp <?> "end of string") quotedText
where qp = char q
quotedText = many ( try escape <|> try stringCharacter )
stringCharacter = satisfy (\c -> (c/=q) && ( isAllowedChar c || isSpaceChar c) )
escape = do char '\\'
oneOf "\"'\\" <|> (lineBreak >> return ' ')
singleQuoted = quotedBy '\''
doubleQuoted = quotedBy '"'
quoted = (doubleQuoted <|> singleQuoted) <?> "string literal"
-- // [12] comment ::= '#' (char_word | char_space)+
comment = (char '#' >> many ( allowedChar <|> spaceChar ) >> lineBreak >> return ()) <?> "comment"
-- // [13] scalar ::= (word | single_quoted | double_quoted )
-- no quoted yet
scalar = (trimSpaces $ word <|> quoted) <?> "scalar"
-- // [14] block(n) ::= scalar '\' space? break (space(>n) (char_word | char_space)* break)+
-- // A block is a scalar leaf node, i.e., it cannot be parent of other
-- // nodes. It is to be used for holding a block of literal text. The
-- // only transformation that it undergoes is leading space stripping,
-- // according to the indentation rules. A block is child of the scalar
-- // that starts it.
block = do s <- scalar
char '\\' >> many spaceChar >> lineBreak
d <- liftM length (many spaceChar)
l <- many (allowedChar <|> spaceChar)
lineBreak
ls <- try (count d spaceChar >> many ( allowedChar <|> spaceChar )) `sepEndBy` lineBreak
let txt = intercalate "\n" (l:ls)
return $ [Node s [(Node txt [] )] ]
-- // [15] list ::= (scalar|group) ( (space? ',')? space? (scalar|group) )*
-- this doesn't seem accurate, or terribly useful, let me try:
-- [15.1] node ::= scalar ( (space* group) | (space+ node) )
--
-- [15.2] list ::= (node|group) ( (space* ',' ) (node|group) )*
comma = (trimSpaces $ char ',') <?> "comma"
parens p = between o c p
where o = trimSpaces $ char '('
c = trimSpaces $ char ')'
node = try block <|> trimSpaces
( do nodeLabel <- scalar
subNodes <- option [] $ try (node <|> group)
return [(Node nodeLabel subNodes) ]
)
-- the grammer doesn't seem to allow lists that end in commas, but
-- such lists appear in the examples.
list = (trimSpaces $ (node <|> group) `sepEndBy1` comma >>= return . concat) <?> "list"
-- // [16] group ::= '(' space? list? space? ')'
group = (trimSpaces $ parens (try list <|> return [])) <?> "group"
-- // [17] line(n) ::=
-- // space(n) (list|group)? space? comment? break |
-- // space? comment? break |
-- // space(n) block
-- In order to parse this structurally, I am going to parse a
-- line and all its children in one go, so my function will
-- be called 'tree' instead of 'line'
tree = do whiteSpace
indent <?> "correct indentation"
ts <- list
whiteSpace
sf <- many (try tree) >>= return . concat
popStack
case ts of
[] -> unexpected "lack of nodes"
((Node x ys):zs) -> return ((Node x (ys++sf)):zs)
-- // [18] graph ::= line* end
--ogdl = liftM (ogdlRoot . concat) $ tree `sepEndBy1` whiteSpace
-- where ogdlRoot xs = [Node "OGDL" xs]
ogdl = liftM (ogdlRoot . concat) $ tree `sepEndBy1` whiteSpace
where ogdlRoot xs = (Node "OGDL" xs)
parseOGDL filename source = runParser ogdl emptyState filename source
parseOGDLFromFile fname = do input <- readFile fname
return (runParser ogdl emptyState fname input)
-- // # 6. Level 2: Graph grammar
-- // [19] anchor ::= '-' '{' word '}'
-- // [20] reference ::= '+' '{' word '}'
-- // [21] path_reference ::= '=' '{' path '}'
-- // Path syntax should be according to the OGDL Path reference.
-- // # 7. Character encoding
-- // OGDL streams must parse well without explicit encoding information
-- // for all ASCII transparent encodings.
-- // All special characters used in OGDL that define structure and
-- // delimit tokens are part of the US-ASCII (ISO646-US) set. It is
-- // specified that, in unidentified 8-bit streams without a
-- // [Unicode BOM](http://www.unicode.org/unicode/faq/utf_bom.html),
-- // there can be no ASCII values that don't map to ASCII characters,
-- // i.e, should be ASCII transparent. This guarantees that tools that
-- // support only single byte streams will work on any 8-bit fixed or
-- // variable length encoded stream, particularly
-- // [UTF-8](ftp://ftp.rfc-editor.org/in-notes/rfc2279.txt) and most
-- // ISO8859 variants.
-- // When a Unicode BOM is present, then the parser should interpret the
-- // stream as Unicode and choose the right UTF transform.
-- // # 8. Meta-information
-- // The '\#?' character combination used as a top level node (not
-- // necessarily the first one) is reserved for comunication between the
-- // OGDL stream and the parser. It is not mandatory and allows for
-- // future enhancements of the standard. For example, some optional
-- // behavior could be switched on. Normally meta-information will not
-- // be part of the in-memory graph. Meta-information is written in
-- // OGDL, as can be seen in the following examples.
-- // #? ogdl 1.0
-- // #? ( ogdl 1.0, encoding iso-8859-1 )
-- // The meta-information keys that are currently reserved are: ogdl,
-- // encoding and schema.
-- // # 9. Round-tripping
-- // OGDL streams are guaranted to round-trip in the presence of a
-- // capable parser and emitter, while maintaining a simple in-memory
-- // structure of nested nodes. Such a parser includes meta-information
-- // but not comments. Depending on the precision of the parser-emitter
-- // chain, the resulting stream may differ from the original in format
-- // or not.
| thedward/haskell-ogdl | Text/OGDL/Parsec.hs | bsd-3-clause | 12,841 | 0 | 16 | 3,190 | 2,217 | 1,201 | 1,016 | 111 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.