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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
#! /usr/bin/env nix-shell
#! nix-shell ./shell.nix -i runghc
import Distribution.Simple
main = defaultMain
|
k0001/haskell-money
|
safe-money/Setup.hs
|
bsd-3-clause
| 107 | 0 | 4 | 13 | 13 | 8 | 5 | 2 | 1 |
{-# OPTIONS_GHC -Wall -Werror #-}
module ManySecond where
|
holzensp/ghc
|
testsuite/tests/driver/dynamic_flags_002/ManySecond.hs
|
bsd-3-clause
| 61 | 0 | 2 | 11 | 5 | 4 | 1 | 2 | 0 |
module Sudoku where
import Data.Maybe (catMaybes, fromJust, isJust, listToMaybe)
import Data.List ((\\), transpose)
type SudokuVal = Int -- The type representing Sudoku values
type EmptyPuzzle = [[ Maybe SudokuVal ]] -- A matrix where Nothing values represent unknowns.
-- The matrix is a list of rows, where each row is
-- a list of values.
type Puzzle = [[ SudokuVal ]] -- A matrix of final Int values. Stored as a list of
-- rows, where each row is a list of values.
-- | Solves a sudoku puzzle, receiving a matrix of Maybe values and returning a
-- matrix of final values
sudoku :: EmptyPuzzle -> Puzzle
sudoku puzzle
| isJust solvedPuzzle = map (map fromJust) $ fromJust solvedPuzzle
| otherwise = error "This puzzle has no solution!"
where solvedPuzzle = populatePuzzle (0, 0) puzzle
-- | Fills the given coordinate, with a valid number for the spot. If there are no
-- valid possibilities, return Nothing
populatePuzzle :: (Int, Int) -> EmptyPuzzle -> Maybe EmptyPuzzle
-- base case on last square in the puzzle
populatePuzzle (8,8) puzzle
| isJust elem = setAsJust elem
| null possible = Nothing
| otherwise = setAsJust (Just $ head possible)
where elem = getElem puzzle (8,8)
possible = getPossible puzzle (8,8)
setAsJust = Just . setElem puzzle (8,8)
-- recursive case for all other squares
populatePuzzle (i,j) puzzle
| isJust elem = setAndCall elem
| null possible = Nothing
| otherwise = if null nextPuzzles
then Nothing
else head nextPuzzles
where elem = getElem puzzle (i,j)
possible = getPossible puzzle (i,j)
setAndCall = populatePuzzle (nextCoord (i,j)) . setElem puzzle (i,j)
nextPuzzles = filter isJust [ setAndCall $ Just elem | elem <- possible ]
-- | Gets all possible values for the given coordinate
getPossible :: EmptyPuzzle -> (Int, Int) -> [Int]
getPossible puzzle (i,j) = (([1..9] \\ getRowVals) \\ getColVals) \\ getSquareVals
where getRowVals = catMaybes $ getRow puzzle i
getColVals = catMaybes $ getCol puzzle j
getSquareVals = catMaybes $ getSquare puzzle (i,j)
------------------------
----- PUZZLE UTILS -----
-- | Gets the row at the given index in the matrix
getRow :: [[a]] -> Int -> [a]
getRow matrix i = matrix !! i
-- | Gets the col at the given index in the matrix
getCol :: [[a]] -> Int -> [a]
getCol matrix j = (transpose matrix) !! j
-- | Gets the square that contains the given index in the matrix
getSquare :: [[a]] -> (Int, Int) -> [a]
getSquare matrix (i,j) = [getElem matrix (x,y) | x <- rows, y <- cols]
where rows = [ (getStart i) .. (getStart i)+2 ]
cols = [ (getStart j) .. (getStart j)+2 ]
getStart val = 3 * (val `quot` 3)
-- | Gets the element at the given coordinate in the matrix
getElem :: [[a]] -> (Int, Int) -> a
getElem matrix (i,j) = (getRow matrix i) !! j
-- | Sets the element at the given coordinate in the matrix
setElem :: [[a]] -> (Int, Int) -> a -> [[a]]
setElem matrix (i,j) val = let (prevRows, row:nextRows) = splitAt i matrix
(prevCols, _:nextCols) = splitAt j row
in prevRows ++ (prevCols ++ val : nextCols) : nextRows
-- | Gets the next coordinate to the given coordinate
nextCoord :: (Int, Int) -> (Int, Int)
nextCoord (i,8) = (i+1, 0)
nextCoord (i,j) = (i, j+1)
|
brandonchinn178/sudoku
|
src/Sudoku.hs
|
mit
| 3,674 | 0 | 11 | 1,091 | 1,044 | 577 | 467 | 52 | 2 |
module Test.Hspec.Core.Formatters.Pretty.Unicode (
ushow
, ushows
) where
import Prelude ()
import Test.Hspec.Core.Compat
import Data.Char
ushow :: String -> String
ushow xs = ushows xs ""
ushows :: String -> ShowS
ushows = uShowString
uShowString :: String -> ShowS
uShowString cs = showChar '"' . showLitString cs . showChar '"'
showLitString :: String -> ShowS
showLitString [] s = s
showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s)
showLitString (c : cs) s = uShowLitChar c (showLitString cs s)
uShowLitChar :: Char -> ShowS
uShowLitChar c
| isPrint c && not (isAscii c) = showChar c
| otherwise = showLitChar c
|
hspec/hspec
|
hspec-core/src/Test/Hspec/Core/Formatters/Pretty/Unicode.hs
|
mit
| 688 | 0 | 11 | 157 | 241 | 125 | 116 | 20 | 1 |
myTuple = (8, 11)
fst' = fst myTuple
snd' = snd myTuple
-- the zip function will merge two lists into tuples
zip' = zip [1,2,3,4,5] [5,5,5,5,5]
lazyZip = zip [1.. ] ["one", "two", "three", "four", "five"]
--triangles problem
triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ]
rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2]
rightTrianglesPerimeter x = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == x]
|
luisgepeto/HaskellLearning
|
02 Starting Out/06_tuples.hs
|
mit
| 500 | 0 | 11 | 107 | 333 | 188 | 145 | 8 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module IHaskell.Display.Widgets.Box.SelectionContainer.Tab
( -- * The Tab widget
TabWidget
-- * Constructor
, mkTab
) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (void)
import Data.Aeson
import Data.IORef (newIORef)
import qualified Data.Scientific as Sci
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
import IHaskell.Display.Widgets.Layout.LayoutWidget
-- | A 'TabWidget' represents a Tab widget from IPython.html.widgets.
type TabWidget = IPythonWidget 'TabType
-- | Create a new box
mkTab :: IO TabWidget
mkTab = do
-- Default properties, with a random uuid
wid <- U.random
layout <- mkLayout
let widgetState = WidgetState $ defaultSelectionContainerWidget "TabView" "TabModel" layout
stateIO <- newIORef widgetState
let box = IPythonWidget wid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen box $ toJSON widgetState
-- Return the widget
return box
instance IHaskellWidget TabWidget where
getCommUUID = uuid
comm widget val _ =
case nestedObjectLookup val ["state", "selected_index"] of
Just (Number num) -> do
void $ setField' widget SelectedIndex $ Just (Sci.coefficient num)
triggerChange widget
Just Null -> do
void $ setField' widget SelectedIndex Nothing
triggerChange widget
_ -> pure ()
|
gibiansky/IHaskell
|
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Box/SelectionContainer/Tab.hs
|
mit
| 1,810 | 0 | 15 | 420 | 340 | 184 | 156 | 41 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Either.Unwrap
-- Copyright : (c) Gregory Crosswhite
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Functions for probing and unwrapping values inside of Either.
--
-----------------------------------------------------------------------------
module Data.Either.Unwrap
( isLeft
, isRight
, fromLeft
, fromRight
, eitherM
, whenLeft
, whenRight
, unlessLeft
, unlessRight
) where
-- ---------------------------------------------------------------------------
-- Functions over Either
-- |The 'isLeft' function returns 'True' iff its argument is of the form @Left _@.
isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _ = False
-- |The 'isRight' function returns 'True' iff its argument is of the form @Right _@.
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
-- | The 'fromLeft' function extracts the element out of a 'Left' and
-- throws an error if its argument take the form @Right _@.
fromLeft :: Either a b -> a
fromLeft (Right _) = error "Either.Unwrap.fromLeft: Argument takes form 'Right _'" -- yuck
fromLeft (Left x) = x
-- | The 'fromRight' function extracts the element out of a 'Right' and
-- throws an error if its argument take the form @Left _@.
fromRight :: Either a b -> b
fromRight (Left _) = error "Either.Unwrap.fromRight: Argument takes form 'Left _'" -- yuck
fromRight (Right x) = x
-- | The 'eitherM' function takes an 'Either' value and two functions which return monads.
-- If the argument takes the form @Left _@ then the element within is passed to the first
-- function, otherwise the element within is passed to the second function.
eitherM :: Monad m => Either a b -> (a -> m c) -> (b -> m c) -> m c
eitherM (Left x) f _ = f x
eitherM (Right x) _ f = f x
-- | The 'whenLeft' function takes an 'Either' value and a function which returns a monad.
-- The monad is only executed when the given argument takes the form @Left _@, otherwise
-- it does nothing.
whenLeft :: Monad m => Either a b -> (a -> m ()) -> m ()
whenLeft (Left x) f = f x
whenLeft _ _ = return ()
-- | The 'whenLeft' function takes an 'Either' value and a function which returns a monad.
-- The monad is only executed when the given argument takes the form @Right _@, otherwise
-- it does nothing.
whenRight :: Monad m => Either a b -> (b -> m ()) -> m ()
whenRight (Right x) f = f x
whenRight _ _ = return ()
-- | A synonym of 'whenRight'.
unlessLeft :: Monad m => Either a b -> (b -> m ()) -> m ()
unlessLeft = whenRight
-- | A synonym of 'whenLeft'.
unlessRight :: Monad m => Either a b -> (a -> m ()) -> m ()
unlessRight = whenLeft
|
Spawek/HCPParse
|
src/Data/Either/Unwrap.hs
|
mit
| 2,954 | 0 | 11 | 711 | 572 | 301 | 271 | 35 | 1 |
-- Prints Hello World N Times
--
hello_worlds 0 = return()
hello_worlds n = do
putStrLn "Hello World"
hello_worlds (n-1)
-- Complete this function
-- This part is related to the Input/Output and can be used as it is
-- Do not modify it
main = do
n <- readLn :: IO Int
hello_worlds n
|
jmeline/secret-meme
|
hackerrank/functional_programming/haskell/hello_world_n.hs
|
mit
| 304 | 0 | 9 | 76 | 70 | 34 | 36 | 7 | 1 |
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
import Control.Applicative
import Control.Monad
import Control.Monad.Reader
import qualified GHCJS.Types as T
import qualified GHCJS.Foreign as F
import qualified GHCJS.Marshal as M
import WebGL
import Simple
fragmentShaderSrc = [src|
precision mediump float;
varying vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
|]
vertexShaderSrc = [src|
attribute vec3 aVertexPosition;
attribute vec4 aVertexColor;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
varying vec4 vColor;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vColor = aVertexColor;
}
|]
data GLInfo = GLInfo { glContext :: GL
, glWidth :: Int
, glHeight :: Int
}
data ColorShader = ColorShader { wsProgram :: ShaderProgram
, wsVertexP :: ShaderAttribute
, sVertexColor :: ShaderAttribute
, wsPMatrix :: ShaderUniform
, wsMVMatrix :: ShaderUniform
}
initGL :: Canvas -> IO GLInfo
initGL canvas = GLInfo <$> js_getContext canvas <*> js_getCanvasWidth canvas <*> js_getCanvasHeight canvas
-- We could use an extra type for a compiled shader... Maybe later.
makeShaders :: GLIO (Shader VertexShader, Shader FragmentShader)
makeShaders = do
fragmentShader <- makeShader fragmentShaderSrc createFragmentShader
vertexShader <- makeShader vertexShaderSrc createVertexShader
return (vertexShader, fragmentShader)
makeProgram :: (Shader VertexShader, Shader FragmentShader) -> GLIO ColorShader
makeProgram (vertexShader, fragmentShader) = do
program <- buildProgram vertexShader fragmentShader
useProgram program
vertexPosition <- getAttribLocation program $ glStr "aVertexPosition"
vertexColor <- getAttribLocation program $ glStr "aVertexColor"
pMatrixU <- getUniformLocation program (glStr "uPMatrix")
mvMatrixU <- getUniformLocation program (glStr "uMVMatrix")
enableVAA vertexPosition
enableVAA vertexColor
return $ ColorShader program vertexPosition vertexColor pMatrixU mvMatrixU
initBuffers :: GLIO (BufferInfo, BufferInfo, BufferInfo, BufferInfo)
initBuffers = do
triangle <- toBuffer $ V3L [ ( 0.0, 1.0, 0.0)
, (-1.0, -1.0, 0.0)
, (1.0, -1.0, 0.0)
]
square <- toBuffer $ V3L [ ( 1.0, 1.0, 0.0)
, (-1.0, 1.0, 0.0)
, ( 1.0, -1.0, 0.0)
, (-1.0, -1.0, 0.0)
]
triangleColors <- toBuffer $ V4L [ (1.0, 0.0, 0.0, 1.0)
, (0.0, 1.0, 0.0, 1.0)
, (0.0, 0.0, 1.0, 1.0)
]
squareColors <- toBuffer $ V4L $ replicate 4 (0.5, 0.5, 1.0, 1.0)
return (triangle, square, triangleColors, squareColors)
drawScene :: (Int, Int) -> ColorShader -> (BufferInfo, BufferInfo, BufferInfo, BufferInfo) -> GLIO ()
drawScene (width, height) shader (triangle, square, triangleColors, squareColors) = do
clear
viewport 0 0 width height
-- This will run without the call to viewport
moveMatrix <- mat4
positionMatrix <- mat4
mat4perspective 45 (fromIntegral width / fromIntegral height) 0.1 100.0 positionMatrix
mat4identity moveMatrix
-- move is a 3-element list...
-- Some of the types here are still quite loose.
let moveAndDraw move shape colors = do
mat4translate moveMatrix =<< glList move
bindBuffer arrayBuffer (buffer shape)
vertexAttribPointer (wsVertexP shader) (itemSize shape)
bindBuffer arrayBuffer (buffer colors)
vertexAttribPointer (sVertexColor shader) (itemSize colors)
uniformMatrix4fv (wsPMatrix shader) positionMatrix
uniformMatrix4fv (wsMVMatrix shader) moveMatrix
-- The original draws 'triangles' for the triangle and a strip for the square...
-- Probably for didactic reasons. We can refactor that out when we need to.
drawArrays drawTriangleStrip 0 (numItems shape)
moveAndDraw [-1.4, 0.0, -7.0] triangle triangleColors
moveAndDraw [3.0, 0.0, 0.0] square squareColors
main = runLesson1 =<< initGL =<< js_documentGetElementById "lesson01-canvas"
runLesson1 glInfo = flip runReaderT (glContext glInfo) $ do
clearColor 0.0 0.0 0.0 1.0
enableDepthTest
shaderProgram <- makeProgram =<< makeShaders
buffers <- initBuffers
drawScene (glWidth glInfo, glHeight glInfo) shaderProgram buffers
|
jmillikan/webgl-lessons-ghcjs
|
src/Lesson02.hs
|
mit
| 4,723 | 0 | 14 | 1,279 | 1,067 | 560 | 507 | 79 | 1 |
module Tach.Wavelet.Core where
import Tach.Wavelet.Core.Internal
|
smurphy8/tach
|
core-libs/tach-wavelet-core/src/Tach/Wavelet/Core.hs
|
mit
| 66 | 0 | 4 | 6 | 14 | 10 | 4 | 2 | 0 |
{-# LANGUAGE DeriveGeneric #-}
module Data.Monoid.Colorful.Term (
Term(..)
, getTerm
, hGetTerm
) where
import Data.List (isPrefixOf, isInfixOf)
import System.Environment (getEnv)
import System.IO (Handle, hIsTerminalDevice, stdout)
import GHC.Generics (Generic)
-- | Terminal type. For less capable terminals the color depth is automatically reduced.
data Term
= TermDumb -- ^ Dumb terminal - no color output
| Term8 -- ^ 8 colors supported
| Term256 -- ^ 256 colors supported
| TermRGB -- ^ True colors supported
| TermWin -- ^ Windows terminal. Will use emulation (Not yet implemented).
deriving (Eq, Ord, Show, Read, Enum, Bounded, Generic)
getTerm :: IO Term
getTerm = hGetTerm stdout
-- | The action @(hGetTerm handle)@ determines the terminal type of the file @handle@.
--
-- The terminal type is determined by checking if the file handle points to a device
-- and by looking at the @$TERM@ environment variable.
hGetTerm :: Handle -> IO Term
hGetTerm h = do
term <- hIsTerminalDevice h
if term
then envToTerm <$> getEnv "TERM"
else pure TermDumb
-- | Determine the terminal type from the value of the @$TERM@ environment variable.
-- TODO improve this
envToTerm :: String -> Term
envToTerm "dumb" = TermDumb
envToTerm term | any (`isPrefixOf` term) rgbTerminals = TermRGB
| "256" `isInfixOf` term = Term256
| otherwise = Term8
where rgbTerminals = ["xterm", "konsole", "gnome", "st", "linux"]
|
minad/colorful-monoids
|
src/Data/Monoid/Colorful/Term.hs
|
mit
| 1,476 | 0 | 9 | 297 | 290 | 167 | 123 | 30 | 2 |
module GearScript.AST where
data Type = Type
{ typeName :: String
, typeParent :: Maybe Type
}
deriving (Show, Eq)
data Typed a = Typed
{ typedType :: Maybe Type
, typedVal :: a
}
data TopStatement = FunctionDef
{ functionName :: String
, functionArguments :: [String]
, functionBody :: [Statement]
}
| TopPlainStatement Statement
deriving (Show, Eq)
data Statement = ExprStatement Expression
deriving (Show, Eq)
data Expression = Call
{ callObject :: Maybe Expression
, callFunctionName :: String
, callArguments :: [Expression]
}
| GlobalVariable String
| LocalVariable String
| StringLiteral String
| NumberLiteral Double
| Plus Expression Expression
| Minus Expression Expression
| Mult Expression Expression
| Div Expression Expression
| Mod Expression Expression
deriving (Show, Eq)
|
teozkr/GearScript
|
src/GearScript/AST.hs
|
mit
| 1,237 | 0 | 9 | 567 | 234 | 138 | 96 | 30 | 0 |
-- | Debugging functions.
module RWPAS.Debug
( logShow )
where
import Control.Concurrent
import System.IO
import System.IO.Unsafe
logLock :: MVar ()
logLock = unsafePerformIO $ newMVar ()
{-# NOINLINE logLock #-}
logShow :: Show a => a -> b -> b
logShow thing result = unsafePerformIO $ withMVar logLock $ \_ -> do
withFile "debug_log.txt" AppendMode $ \handle ->
hPrint handle thing
return result
|
Noeda/rwpas
|
src/RWPAS/Debug.hs
|
mit
| 415 | 0 | 11 | 80 | 127 | 66 | 61 | 13 | 1 |
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
{-
Copyright (C) 2013 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.JSON
Copyright : Copyright (C) 2013 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Functions for serializing the Pandoc AST to JSON and deserializing from JSON.
Example of use: The following script (@capitalize.hs@) reads
reads a JSON representation of a Pandoc document from stdin,
and writes a JSON representation of a Pandoc document to stdout.
It changes all regular text in the document to uppercase, without
affecting URLs, code, tags, etc. Run the script with
> pandoc -t json | runghc capitalize.hs | pandoc -f json
or (making capitalize.hs executable)
> pandoc --filter ./capitalize.hs
> #!/usr/bin/env runghc
> import Text.Pandoc.JSON
> import Data.Char (toUpper)
>
> main :: IO ()
> main = toJSONFilter capitalizeStrings
>
> capitalizeStrings :: Inline -> Inline
> capitalizeStrings (Str s) = Str $ map toUpper s
> capitalizeStrings x = x
-}
module Text.Pandoc.JSON ( module Text.Pandoc.Definition
, ToJSONFilter(..)
)
where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Text.Pandoc.Generic
import Data.Maybe (listToMaybe)
import Data.Data
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BL
import Data.Aeson
import System.Environment (getArgs)
-- | 'toJSONFilter' convert a function into a filter that reads pandoc's
-- JSON serialized output from stdin, transforms it by walking the AST
-- and applying the specified function, and serializes the result as JSON
-- to stdout.
--
-- For a straight transformation, use a function of type @a -> a@ or
-- @a -> IO a@ where @a@ = 'Block', 'Inline','Pandoc', 'Meta', or 'MetaValue'.
--
-- If your transformation needs to be sensitive to the script's arguments,
-- use a function of type @[String] -> a -> a@ (with @a@ constrained as above).
-- The @[String]@ will be populated with the script's arguments.
--
-- An alternative is to use the type @Maybe Format -> a -> a@.
-- This is appropriate when the first argument of the script (if present)
-- will be the target format, and allows scripts to behave differently
-- depending on the target format. The pandoc executable automatically
-- provides the target format as argument when scripts are called using
-- the `--filter` option.
class ToJSONFilter a where
toJSONFilter :: a -> IO ()
instance (Walkable a Pandoc) => ToJSONFilter (a -> a) where
toJSONFilter f = BL.getContents >>=
BL.putStr . encode . (walk f :: Pandoc -> Pandoc) . either error id .
eitherDecode'
instance (Walkable a Pandoc) => ToJSONFilter (a -> IO a) where
toJSONFilter f = BL.getContents >>=
(walkM f :: Pandoc -> IO Pandoc) . either error id . eitherDecode' >>=
BL.putStr . encode
instance Data a => ToJSONFilter (a -> [a]) where
toJSONFilter f = BL.getContents >>=
BL.putStr . encode . (bottomUp (concatMap f) :: Pandoc -> Pandoc) .
either error id . eitherDecode'
instance Data a => ToJSONFilter (a -> IO [a]) where
toJSONFilter f = BL.getContents >>=
(bottomUpM (fmap concat . mapM f) :: Pandoc -> IO Pandoc) .
either error id . eitherDecode' >>=
BL.putStr . encode
instance (ToJSONFilter a) => ToJSONFilter ([String] -> a) where
toJSONFilter f = getArgs >>= toJSONFilter . f
instance (ToJSONFilter a) => ToJSONFilter (Maybe Format -> a) where
toJSONFilter f = getArgs >>= toJSONFilter . f . fmap Format . listToMaybe
|
timtylin/scholdoc-types
|
Text/Pandoc/JSON.hs
|
gpl-2.0
| 4,328 | 45 | 10 | 835 | 538 | 309 | 229 | 35 | 0 |
{- |
Module : $Header$
Description : colimit of an arbitrary diagram in Set
Copyright : (c) 2005, Amr Sabry, Chung-chieh Shan, Oleg Kiselyov,
and Daniel P. Friedman
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Logic Monad Transformer: MonadPlusT with interleave, bindi, ifte and once
Definition and implementation of generic operations, in terms of msplit
-}
module Common.LogicT (
LogicT(..), bagofN, reflect
) where
import Control.Monad
import Control.Monad.Trans
class MonadTrans t => LogicT t where
msplit :: (Monad m, MonadPlus (t m)) => t m a -> t m (Maybe (a, t m a))
-- All other things are implemneted in terms of MonadPlus + msplit
-- All the functions below have generic implementations
-- fair disjunction
interleave :: (Monad m, MonadPlus (t m)) =>
t m a -> t m a -> t m a
-- Note the generic implementation below
-- The code is *verbatim* from Logic.hs
interleave sg1 sg2 =
do r <- msplit sg1
case r of
Nothing -> sg2
Just (sg11,sg12) -> (return sg11) `mplus`
(interleave sg2 sg12)
-- just conventional aliases
gsuccess:: (Monad m, MonadPlus (t m)) => a -> t m a
gsuccess = return
gfail :: (Monad m, MonadPlus (t m)) => t m a
gfail = mzero
-- standard `bind' is the conjunction
-- the following is a fair conjunction
-- Again, the old Logic.hs code works verbatim
bindi:: (Monad m, MonadPlus (t m)) =>
t m a -> (a -> t m b) -> t m b
bindi sg g = do r <- msplit sg
case r of
Nothing -> mzero
Just (sg1,sg2) -> interleave
(g sg1)
(bindi sg2 g)
-- Pruning things
-- Soft-cut (aka if-then-else)
-- ifte t th el = (or (and t th) (and (not t) el))
-- However, t is evaluated only once
ifte :: (Monad m, MonadPlus (t m)) =>
t m a -> (a -> t m b) -> t m b -> t m b
ifte t th el =
do r <- msplit t
case r of
Nothing -> el
Just (sg1,sg2) -> (th sg1) `mplus` (sg2 >>= th)
once :: (Monad m, MonadPlus (t m)) => t m a -> t m a
once m =
do r <- msplit m
case r of
Nothing -> mzero
Just (sg1,_) -> return sg1
{- A particular transformer must define
-- The inverse of `lift'. Hinze calls it `observe'. Others may call
-- it `down'. It gives the first answer (or fails if there aren't any)
observe :: (Monad m) => t m a -> m a
It can't be put into the LogicT class because of in teh case of SRReif,
the variable `r' will escape
-}
-- The following functions are not in the class LogicT
-- Their implementation is generic
-- Note: the following gives t m [a] answer. To get back `m [a]'
-- we should call ``observe''
-- This is similar to Hinze's `sol' (at the very end of Section
-- 4.3, only we can select the arbitrary number of answers
-- and do that even for non-stream-based monad)
bagofN :: (Monad m, LogicT t, MonadPlus (t m)) => Maybe Int -> t m a -> t m [a]
bagofN (Just n) _ | n <= 0 = return []
bagofN n m = msplit m >>= bagofN'
where bagofN' Nothing = return []
bagofN' (Just (a, m')) = bagofN (fmap ((-1) +) n) m'
>>= return . (a :)
-- This is like the opposite of `msplit'
-- The law is: msplit tm >>= reflect === tm
reflect :: (Monad m, LogicT t, MonadPlus (t m)) => Maybe (a, t m a) -> t m a
reflect r = case r of
Nothing -> mzero
Just (a,tmr) -> return a `mplus` tmr
|
nevrenato/Hets_Fork
|
Common/LogicT.hs
|
gpl-2.0
| 3,844 | 0 | 14 | 1,319 | 938 | 486 | 452 | 49 | 2 |
module Chap02.Exercise04.Test where
import Chap02.Exercise04 (insert)
import Chap02.Data.UnbalancedSet hiding (insert, member)
import Data.Foldable (toList)
prop_Ex4InsertBST :: Int -> UnbalancedSet Int -> Bool
prop_Ex4InsertBST n t = isSorted . toList $ insert n t
where
isSorted [] = True
isSorted [_] = True
isSorted (x:l@(y:_)) = x < y && isSorted l
|
stappit/okasaki-pfds
|
test/Chap02/Exercise04/Test.hs
|
gpl-3.0
| 405 | 0 | 12 | 102 | 140 | 77 | 63 | 9 | 3 |
module Parser where
import Movie
import Data.Function
import Data.List.Split
import Data.Maybe
import Text.Regex
import Text.Regex.Posix
import Prelude hiding (id)
-- | Parse a [String] to a Movie with a default rating of 0
parseMovie :: [String] -> Movie
parseMovie (id:title:date:url:genres) = Movie (read id) title date
(parseUrl url)
0
(parseGenres genres)
-- | Uses regex to find the year in brackets and remove it.
-- also removes any quotes `"`
parseUrl :: String -> String
parseUrl = filter (/= '\"') . head . splitRegex (mkRegex "\\(.*\\)")
-- | Parses a 1 to Just Genre and anything else to Nothing
-- Using the `Maybe` data type allows prevents us from getting a bad parse.
-- Anything it doesn't understand it will throw away as Nothing.
parseGenre :: (Num a, Eq a) => (Int, a) -> Maybe Genre
parseGenre (g, 1) = Just $ toGenre g
parseGenre _ = Nothing
parseGenres :: [String] -> [Genre]
parseGenres = catMaybes . map parseGenre . zip [1..18] . map read
parseRating :: String -> Rating
parseRating = parse . splitOn "\t"
where parse (uId:mId:rating:_) = Rating (read uId) (read mId) (read rating)
|
Jiggins/CS210
|
Parser.hs
|
gpl-3.0
| 1,265 | 0 | 11 | 343 | 336 | 183 | 153 | 23 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
module Snap.Snaplet.Sedna where
-------------------------------------------------------------------------------
import Control.Monad.IO.Control
import Control.Monad.State
import Database.SednaTypes
import Database.SednaBindings
import Database.Sedna as Sedna
import Snap.Snaplet
import Snap.Snaplet.Sedna.Types
-------------------------------------------------------------------------------
class (MonadControlIO m, ConnSrc s) => HasSedna m s | m -> s where
getConnSrc :: m (s SednaConnection)
-------------------------------------------------------------------------------
data SednaSnaplet s =
ConnSrc s => SednaSnaplet { connSrc :: s SednaConnection }
-------------------------------------------------------------------------------
instance MonadControlIO (Handler b v) where
liftControlIO f = liftIO (f return)
-------------------------------------------------------------------------------
sednaInit :: ConnSrc s => s SednaConnection -> SnapletInit b (SednaSnaplet s)
sednaInit src = makeSnaplet "sedna" "Sedna Database Connectivity" Nothing $
return $ SednaSnaplet src
-------------------------------------------------------------------------------
withSedna :: (MonadControlIO m, HasSedna m s) => (SednaConnection -> IO a) -> m a
withSedna f = do
src <- getConnSrc
liftIO $ withConn src (liftIO . f)
-------------------------------------------------------------------------------
withSedna' :: HasSedna m s => (SednaConnection -> a) -> m a
withSedna' f = do
src <- getConnSrc
liftIO $ withConn src (return . f)
-------------------------------------------------------------------------------
query :: HasSedna m s => Query -> m QueryResult
query xQuery =
withSedna (\conn -> withTransaction conn
(\conn' -> do
sednaExecute conn' xQuery
sednaGetResultString conn'))
-------------------------------------------------------------------------------
disconnect :: HasSedna m s => m ()
disconnect = withSedna sednaCloseConnection
-------------------------------------------------------------------------------
commit :: HasSedna m s => m ()
commit = withSedna sednaCommit
-------------------------------------------------------------------------------
rollback :: HasSedna m s => m ()
rollback = withSedna sednaRollBack
--------------------------------------------------------------------------------
loadXMLFile :: HasSedna m s => FilePath -> Document -> Collection -> m ()
loadXMLFile filepath doc coll = withSedna
(\conn' -> Sedna.loadXMLFile conn'
filepath
doc
coll)
|
ExternalReality/snaplet-sedna
|
src/Snap/Snaplet/Sedna.hs
|
gpl-3.0
| 3,091 | 0 | 13 | 725 | 574 | 298 | 276 | 47 | 1 |
module Data.Rhythm.RockBand.Lex.VenueRB3 where
import Data.Rhythm.RockBand.Common
import qualified Data.Rhythm.MIDI as MIDI
import Data.Rhythm.Event
import Data.Rhythm.Time
import Data.Rhythm.Interpret
import qualified Numeric.NonNegative.Class as NN
import Data.Char (toLower)
import qualified Sound.MIDI.File.Event as E
import qualified Sound.MIDI.File.Event.Meta as M
data Length
= SingAlong Instrument
| Spotlight Instrument
data CoopCamera
= AllFar
| All Distance
| Front Distance
| One Instrument Distance
| VoxCloseup
| HandCloseup Instrument
| HeadCloseup Instrument
| Two Instrument Instrument Distance
data Distance = Behind | Near
data Instrument = Drums | Vocals | Bass | Guitar | Keys
data Directed
= All
| AllCam
| AllLT
| AllYeah
| BRE
| BREJ
| NP Instrument
| Hit Instrument
| DrumsLT
| CamPR Instrument -- vox, gtr
| CamPT Instrument -- vox, gtr
| Cam Instrument -- keys, bass
| StageDive
| CrowdSurf
| Close Instrument
| DrumsPoint
| CrowdInteract -- gtr, bass
| DuoDrums
| Duo Instrument Instrument
| Crowd
data PostProcess
= ProFilmA
| ProFilmB
| VideoA
| Film16MM
| ShittyTV
| Bloom
| FilmSepiaInk
| FilmSilvertone
| FilmBW
| VideoBW
| ContrastA
| Photocopy
| FilmBlueFilter
| DesatBlue
| VideoSecurity
| Bright
| Posterize
| CleanTrails
| VideoTrails
| FlickerTrails
| DesatPosterizeTrails
| FilmContrast
| FilmContrastBlue
| FilmContrastGreen
| FilmContrastRed
| HorrorMovieSpecial
| PhotoNegative
| ProFilmMirrorA
| ProFilmPsychedelicBlueRed
| SpaceWoosh
|
mtolly/rhythm
|
src/Data/Rhythm/RockBand/Lex/VenueRB3.hs
|
gpl-3.0
| 1,606 | 0 | 6 | 338 | 350 | 230 | 120 | 76 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.MapsEngine.Layers.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Return metadata for a particular layer.
--
-- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.layers.get@.
module Network.Google.Resource.MapsEngine.Layers.Get
(
-- * REST Resource
LayersGetResource
-- * Creating a Request
, layersGet
, LayersGet
-- * Request Lenses
, lgVersion
, lgId
) where
import Network.Google.MapsEngine.Types
import Network.Google.Prelude
-- | A resource alias for @mapsengine.layers.get@ method which the
-- 'LayersGet' request conforms to.
type LayersGetResource =
"mapsengine" :>
"v1" :>
"layers" :>
Capture "id" Text :>
QueryParam "version" LayersGetVersion :>
QueryParam "alt" AltJSON :> Get '[JSON] Layer
-- | Return metadata for a particular layer.
--
-- /See:/ 'layersGet' smart constructor.
data LayersGet = LayersGet'
{ _lgVersion :: !(Maybe LayersGetVersion)
, _lgId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LayersGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lgVersion'
--
-- * 'lgId'
layersGet
:: Text -- ^ 'lgId'
-> LayersGet
layersGet pLgId_ =
LayersGet'
{ _lgVersion = Nothing
, _lgId = pLgId_
}
-- | Deprecated: The version parameter indicates which version of the layer
-- should be returned. When version is set to published, the published
-- version of the layer will be returned. Please use the
-- layers.getPublished endpoint instead.
lgVersion :: Lens' LayersGet (Maybe LayersGetVersion)
lgVersion
= lens _lgVersion (\ s a -> s{_lgVersion = a})
-- | The ID of the layer.
lgId :: Lens' LayersGet Text
lgId = lens _lgId (\ s a -> s{_lgId = a})
instance GoogleRequest LayersGet where
type Rs LayersGet = Layer
type Scopes LayersGet =
'["https://www.googleapis.com/auth/mapsengine",
"https://www.googleapis.com/auth/mapsengine.readonly"]
requestClient LayersGet'{..}
= go _lgId _lgVersion (Just AltJSON)
mapsEngineService
where go
= buildClient (Proxy :: Proxy LayersGetResource)
mempty
|
rueshyna/gogol
|
gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/Layers/Get.hs
|
mpl-2.0
| 3,082 | 0 | 13 | 730 | 388 | 234 | 154 | 59 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SWF.DescribeWorkflowExecution
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns information about the specified workflow execution including its type
-- and some statistics.
--
-- This operation is eventually consistent. The results are best effort and may
-- not exactly reflect recent updates and changes. Access Control
--
-- You can use IAM policies to control this action's access to Amazon SWF
-- resources as follows:
--
-- Use a 'Resource' element with the domain name to limit the action to only
-- specified domains. Use an 'Action' element to allow or deny permission to call
-- this action. You cannot use an IAM policy to constrain this action's
-- parameters. If the caller does not have sufficient permissions to invoke the
-- action, or the parameter values fall outside the specified constraints, the
-- action fails. The associated event attribute's cause parameter will be set to
-- OPERATION_NOT_PERMITTED. For details and example IAM policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAMto Manage Access to Amazon SWF Workflows>.
--
-- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_DescribeWorkflowExecution.html>
module Network.AWS.SWF.DescribeWorkflowExecution
(
-- * Request
DescribeWorkflowExecution
-- ** Request constructor
, describeWorkflowExecution
-- ** Request lenses
, dweDomain
, dweExecution
-- * Response
, DescribeWorkflowExecutionResponse
-- ** Response constructor
, describeWorkflowExecutionResponse
-- ** Response lenses
, dwerExecutionConfiguration
, dwerExecutionInfo
, dwerLatestActivityTaskTimestamp
, dwerLatestExecutionContext
, dwerOpenCounts
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SWF.Types
import qualified GHC.Exts
data DescribeWorkflowExecution = DescribeWorkflowExecution
{ _dweDomain :: Text
, _dweExecution :: WorkflowExecution
} deriving (Eq, Read, Show)
-- | 'DescribeWorkflowExecution' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dweDomain' @::@ 'Text'
--
-- * 'dweExecution' @::@ 'WorkflowExecution'
--
describeWorkflowExecution :: Text -- ^ 'dweDomain'
-> WorkflowExecution -- ^ 'dweExecution'
-> DescribeWorkflowExecution
describeWorkflowExecution p1 p2 = DescribeWorkflowExecution
{ _dweDomain = p1
, _dweExecution = p2
}
-- | The name of the domain containing the workflow execution.
dweDomain :: Lens' DescribeWorkflowExecution Text
dweDomain = lens _dweDomain (\s a -> s { _dweDomain = a })
-- | The workflow execution to describe.
dweExecution :: Lens' DescribeWorkflowExecution WorkflowExecution
dweExecution = lens _dweExecution (\s a -> s { _dweExecution = a })
data DescribeWorkflowExecutionResponse = DescribeWorkflowExecutionResponse
{ _dwerExecutionConfiguration :: WorkflowExecutionConfiguration
, _dwerExecutionInfo :: WorkflowExecutionInfo
, _dwerLatestActivityTaskTimestamp :: Maybe POSIX
, _dwerLatestExecutionContext :: Maybe Text
, _dwerOpenCounts :: WorkflowExecutionOpenCounts
} deriving (Eq, Read, Show)
-- | 'DescribeWorkflowExecutionResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dwerExecutionConfiguration' @::@ 'WorkflowExecutionConfiguration'
--
-- * 'dwerExecutionInfo' @::@ 'WorkflowExecutionInfo'
--
-- * 'dwerLatestActivityTaskTimestamp' @::@ 'Maybe' 'UTCTime'
--
-- * 'dwerLatestExecutionContext' @::@ 'Maybe' 'Text'
--
-- * 'dwerOpenCounts' @::@ 'WorkflowExecutionOpenCounts'
--
describeWorkflowExecutionResponse :: WorkflowExecutionInfo -- ^ 'dwerExecutionInfo'
-> WorkflowExecutionConfiguration -- ^ 'dwerExecutionConfiguration'
-> WorkflowExecutionOpenCounts -- ^ 'dwerOpenCounts'
-> DescribeWorkflowExecutionResponse
describeWorkflowExecutionResponse p1 p2 p3 = DescribeWorkflowExecutionResponse
{ _dwerExecutionInfo = p1
, _dwerExecutionConfiguration = p2
, _dwerOpenCounts = p3
, _dwerLatestActivityTaskTimestamp = Nothing
, _dwerLatestExecutionContext = Nothing
}
-- | The configuration settings for this workflow execution including timeout
-- values, tasklist etc.
dwerExecutionConfiguration :: Lens' DescribeWorkflowExecutionResponse WorkflowExecutionConfiguration
dwerExecutionConfiguration =
lens _dwerExecutionConfiguration
(\s a -> s { _dwerExecutionConfiguration = a })
-- | Information about the workflow execution.
dwerExecutionInfo :: Lens' DescribeWorkflowExecutionResponse WorkflowExecutionInfo
dwerExecutionInfo =
lens _dwerExecutionInfo (\s a -> s { _dwerExecutionInfo = a })
-- | The time when the last activity task was scheduled for this workflow
-- execution. You can use this information to determine if the workflow has not
-- made progress for an unusually long period of time and might require a
-- corrective action.
dwerLatestActivityTaskTimestamp :: Lens' DescribeWorkflowExecutionResponse (Maybe UTCTime)
dwerLatestActivityTaskTimestamp =
lens _dwerLatestActivityTaskTimestamp
(\s a -> s { _dwerLatestActivityTaskTimestamp = a })
. mapping _Time
-- | The latest executionContext provided by the decider for this workflow
-- execution. A decider can provide an executionContext (a free-form string)
-- when closing a decision task using 'RespondDecisionTaskCompleted'.
dwerLatestExecutionContext :: Lens' DescribeWorkflowExecutionResponse (Maybe Text)
dwerLatestExecutionContext =
lens _dwerLatestExecutionContext
(\s a -> s { _dwerLatestExecutionContext = a })
-- | The number of tasks for this workflow execution. This includes open and
-- closed tasks of all types.
dwerOpenCounts :: Lens' DescribeWorkflowExecutionResponse WorkflowExecutionOpenCounts
dwerOpenCounts = lens _dwerOpenCounts (\s a -> s { _dwerOpenCounts = a })
instance ToPath DescribeWorkflowExecution where
toPath = const "/"
instance ToQuery DescribeWorkflowExecution where
toQuery = const mempty
instance ToHeaders DescribeWorkflowExecution
instance ToJSON DescribeWorkflowExecution where
toJSON DescribeWorkflowExecution{..} = object
[ "domain" .= _dweDomain
, "execution" .= _dweExecution
]
instance AWSRequest DescribeWorkflowExecution where
type Sv DescribeWorkflowExecution = SWF
type Rs DescribeWorkflowExecution = DescribeWorkflowExecutionResponse
request = post "DescribeWorkflowExecution"
response = jsonResponse
instance FromJSON DescribeWorkflowExecutionResponse where
parseJSON = withObject "DescribeWorkflowExecutionResponse" $ \o -> DescribeWorkflowExecutionResponse
<$> o .: "executionConfiguration"
<*> o .: "executionInfo"
<*> o .:? "latestActivityTaskTimestamp"
<*> o .:? "latestExecutionContext"
<*> o .: "openCounts"
|
dysinger/amazonka
|
amazonka-swf/gen/Network/AWS/SWF/DescribeWorkflowExecution.hs
|
mpl-2.0
| 8,076 | 0 | 17 | 1,620 | 816 | 495 | 321 | 97 | 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.Logging.BillingAccounts.Sinks.Create
-- 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)
--
-- Creates a sink that exports specified log entries to a destination. The
-- export of newly-ingested log entries begins immediately, unless the
-- current time is outside the sink\'s start and end times or the sink\'s
-- writer_identity is not permitted to write to the destination. A sink can
-- export log entries only from the resource owning the sink.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Stackdriver Logging API Reference> for @logging.billingAccounts.sinks.create@.
module Network.Google.Resource.Logging.BillingAccounts.Sinks.Create
(
-- * REST Resource
BillingAccountsSinksCreateResource
-- * Creating a Request
, billingAccountsSinksCreate
, BillingAccountsSinksCreate
-- * Request Lenses
, bascParent
, bascXgafv
, bascUniqueWriterIdentity
, bascUploadProtocol
, bascPp
, bascAccessToken
, bascUploadType
, bascPayload
, bascBearerToken
, bascCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.billingAccounts.sinks.create@ method which the
-- 'BillingAccountsSinksCreate' request conforms to.
type BillingAccountsSinksCreateResource =
"v2" :>
Capture "parent" Text :>
"sinks" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "uniqueWriterIdentity" Bool :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] LogSink :> Post '[JSON] LogSink
-- | Creates a sink that exports specified log entries to a destination. The
-- export of newly-ingested log entries begins immediately, unless the
-- current time is outside the sink\'s start and end times or the sink\'s
-- writer_identity is not permitted to write to the destination. A sink can
-- export log entries only from the resource owning the sink.
--
-- /See:/ 'billingAccountsSinksCreate' smart constructor.
data BillingAccountsSinksCreate = BillingAccountsSinksCreate'
{ _bascParent :: !Text
, _bascXgafv :: !(Maybe Xgafv)
, _bascUniqueWriterIdentity :: !(Maybe Bool)
, _bascUploadProtocol :: !(Maybe Text)
, _bascPp :: !Bool
, _bascAccessToken :: !(Maybe Text)
, _bascUploadType :: !(Maybe Text)
, _bascPayload :: !LogSink
, _bascBearerToken :: !(Maybe Text)
, _bascCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'BillingAccountsSinksCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bascParent'
--
-- * 'bascXgafv'
--
-- * 'bascUniqueWriterIdentity'
--
-- * 'bascUploadProtocol'
--
-- * 'bascPp'
--
-- * 'bascAccessToken'
--
-- * 'bascUploadType'
--
-- * 'bascPayload'
--
-- * 'bascBearerToken'
--
-- * 'bascCallback'
billingAccountsSinksCreate
:: Text -- ^ 'bascParent'
-> LogSink -- ^ 'bascPayload'
-> BillingAccountsSinksCreate
billingAccountsSinksCreate pBascParent_ pBascPayload_ =
BillingAccountsSinksCreate'
{ _bascParent = pBascParent_
, _bascXgafv = Nothing
, _bascUniqueWriterIdentity = Nothing
, _bascUploadProtocol = Nothing
, _bascPp = True
, _bascAccessToken = Nothing
, _bascUploadType = Nothing
, _bascPayload = pBascPayload_
, _bascBearerToken = Nothing
, _bascCallback = Nothing
}
-- | Required. The resource in which to create the sink:
-- \"projects\/[PROJECT_ID]\" \"organizations\/[ORGANIZATION_ID]\"
-- Examples: \"projects\/my-logging-project\",
-- \"organizations\/123456789\".
bascParent :: Lens' BillingAccountsSinksCreate Text
bascParent
= lens _bascParent (\ s a -> s{_bascParent = a})
-- | V1 error format.
bascXgafv :: Lens' BillingAccountsSinksCreate (Maybe Xgafv)
bascXgafv
= lens _bascXgafv (\ s a -> s{_bascXgafv = a})
-- | Optional. Determines the kind of IAM identity returned as
-- writer_identity in the new sink. If this value is omitted or set to
-- false, and if the sink\'s parent is a project, then the value returned
-- as writer_identity is cloud-logs\'google.com, the same identity used
-- before the addition of writer identities to this API. The sink\'s
-- destination must be in the same project as the sink itself.If this field
-- is set to true, or if the sink is owned by a non-project resource such
-- as an organization, then the value of writer_identity will be a unique
-- service account used only for exports from the new sink. For more
-- information, see writer_identity in LogSink.
bascUniqueWriterIdentity :: Lens' BillingAccountsSinksCreate (Maybe Bool)
bascUniqueWriterIdentity
= lens _bascUniqueWriterIdentity
(\ s a -> s{_bascUniqueWriterIdentity = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
bascUploadProtocol :: Lens' BillingAccountsSinksCreate (Maybe Text)
bascUploadProtocol
= lens _bascUploadProtocol
(\ s a -> s{_bascUploadProtocol = a})
-- | Pretty-print response.
bascPp :: Lens' BillingAccountsSinksCreate Bool
bascPp = lens _bascPp (\ s a -> s{_bascPp = a})
-- | OAuth access token.
bascAccessToken :: Lens' BillingAccountsSinksCreate (Maybe Text)
bascAccessToken
= lens _bascAccessToken
(\ s a -> s{_bascAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
bascUploadType :: Lens' BillingAccountsSinksCreate (Maybe Text)
bascUploadType
= lens _bascUploadType
(\ s a -> s{_bascUploadType = a})
-- | Multipart request metadata.
bascPayload :: Lens' BillingAccountsSinksCreate LogSink
bascPayload
= lens _bascPayload (\ s a -> s{_bascPayload = a})
-- | OAuth bearer token.
bascBearerToken :: Lens' BillingAccountsSinksCreate (Maybe Text)
bascBearerToken
= lens _bascBearerToken
(\ s a -> s{_bascBearerToken = a})
-- | JSONP
bascCallback :: Lens' BillingAccountsSinksCreate (Maybe Text)
bascCallback
= lens _bascCallback (\ s a -> s{_bascCallback = a})
instance GoogleRequest BillingAccountsSinksCreate
where
type Rs BillingAccountsSinksCreate = LogSink
type Scopes BillingAccountsSinksCreate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/logging.admin"]
requestClient BillingAccountsSinksCreate'{..}
= go _bascParent _bascXgafv _bascUniqueWriterIdentity
_bascUploadProtocol
(Just _bascPp)
_bascAccessToken
_bascUploadType
_bascBearerToken
_bascCallback
(Just AltJSON)
_bascPayload
loggingService
where go
= buildClient
(Proxy :: Proxy BillingAccountsSinksCreateResource)
mempty
|
rueshyna/gogol
|
gogol-logging/gen/Network/Google/Resource/Logging/BillingAccounts/Sinks/Create.hs
|
mpl-2.0
| 7,962 | 0 | 20 | 1,834 | 1,036 | 608 | 428 | 145 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.RegionCommitments.Insert
-- 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)
--
-- Creates a commitment in the specified project using the data included in
-- the request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionCommitments.insert@.
module Network.Google.Resource.Compute.RegionCommitments.Insert
(
-- * REST Resource
RegionCommitmentsInsertResource
-- * Creating a Request
, regionCommitmentsInsert
, RegionCommitmentsInsert
-- * Request Lenses
, rciRequestId
, rciProject
, rciPayload
, rciRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.regionCommitments.insert@ method which the
-- 'RegionCommitmentsInsert' request conforms to.
type RegionCommitmentsInsertResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"commitments" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Commitment :> Post '[JSON] Operation
-- | Creates a commitment in the specified project using the data included in
-- the request.
--
-- /See:/ 'regionCommitmentsInsert' smart constructor.
data RegionCommitmentsInsert =
RegionCommitmentsInsert'
{ _rciRequestId :: !(Maybe Text)
, _rciProject :: !Text
, _rciPayload :: !Commitment
, _rciRegion :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegionCommitmentsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rciRequestId'
--
-- * 'rciProject'
--
-- * 'rciPayload'
--
-- * 'rciRegion'
regionCommitmentsInsert
:: Text -- ^ 'rciProject'
-> Commitment -- ^ 'rciPayload'
-> Text -- ^ 'rciRegion'
-> RegionCommitmentsInsert
regionCommitmentsInsert pRciProject_ pRciPayload_ pRciRegion_ =
RegionCommitmentsInsert'
{ _rciRequestId = Nothing
, _rciProject = pRciProject_
, _rciPayload = pRciPayload_
, _rciRegion = pRciRegion_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
rciRequestId :: Lens' RegionCommitmentsInsert (Maybe Text)
rciRequestId
= lens _rciRequestId (\ s a -> s{_rciRequestId = a})
-- | Project ID for this request.
rciProject :: Lens' RegionCommitmentsInsert Text
rciProject
= lens _rciProject (\ s a -> s{_rciProject = a})
-- | Multipart request metadata.
rciPayload :: Lens' RegionCommitmentsInsert Commitment
rciPayload
= lens _rciPayload (\ s a -> s{_rciPayload = a})
-- | Name of the region for this request.
rciRegion :: Lens' RegionCommitmentsInsert Text
rciRegion
= lens _rciRegion (\ s a -> s{_rciRegion = a})
instance GoogleRequest RegionCommitmentsInsert where
type Rs RegionCommitmentsInsert = Operation
type Scopes RegionCommitmentsInsert =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient RegionCommitmentsInsert'{..}
= go _rciProject _rciRegion _rciRequestId
(Just AltJSON)
_rciPayload
computeService
where go
= buildClient
(Proxy :: Proxy RegionCommitmentsInsertResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/RegionCommitments/Insert.hs
|
mpl-2.0
| 4,853 | 0 | 17 | 1,081 | 559 | 335 | 224 | 86 | 1 |
{- arch-tag: Generic Dict-Like Object Support
Copyright (C) 2005 John Goerzen <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-}
{- |
Module : Database.AnyDBM
Copyright : Copyright (C) 2005 John Goerzen
License : GNU LGPL, version 2.1 or above
Maintainer : John Goerzen <[email protected]>
Stability : provisional
Portability: portable
Written by John Goerzen, jgoerzen\@complete.org
This module provides a generic infrastructure for supporting storage of
hash-like items with String -> String mappings. It can be used for in-memory
or on-disk items.
-}
module Database.AnyDBM (-- * The AnyDBM class
AnyDBM(..),
-- * AnyDBM utilities
mapA,
strFromA, strToA
)
where
import Prelude hiding (lookup)
import System.IO
import Data.HashTable.IO
import Control.Exception
import Data.List.Utils(strFromAL, strToAL)
{- | The main class for items implementing this interface.
People implementing this class should provide methods for:
* 'closeA' (unless you have no persistent storage)
* 'flushA' (unless you have no persistent storage)
* 'insertA'
* 'deleteA'
* 'lookupA'
* either 'toListA' or 'keysA'
-}
class AnyDBM a where
{- | Close the object, writing out any unsaved data to disk if necessary.
If you implement this, make sure your implementation calls 'flushA'.
Note: if you have an object opened for writing, you MUST
call closeA on it when you are done. Implementations are not
required to preserve your data otherwise.
-}
closeA :: a -> IO ()
{- | Flush the object, saving any un-saved data to disk but not closing
it. Called automatically by 'closeA'. -}
flushA :: a -> IO ()
{- | Insert the given data into the map. Existing data with the same key
will be overwritten. -}
insertA :: a -- ^ AnyDBM object
-> String -- ^ Key
-> String -- ^ Value
-> IO ()
{- | Delete the data referenced by the given key. It is not an error
if the key does not exist. -}
deleteA :: a -> String -> IO ()
{- | True if the given key is present. -}
hasKeyA :: a -> String -> IO Bool
{- | Find the data referenced by the given key. -}
lookupA :: a -> String -> IO (Maybe String)
{- | Look up the data and raise an exception if the key does not exist.
The exception raised is PatternMatchFail, and the string accompanying
it is the key that was looked up.-}
forceLookupA :: a -> String -> IO String
{- | Call 'insertA' on each pair in the given association list, adding
them to the map. -}
insertListA :: a -> [(String, String)] -> IO ()
{- | Return a representation of the content of the map as a list. -}
toListA :: a -> IO [(String, String)]
{- | Returns a list of keys in the 'AnyDBM' object. -}
keysA :: a -> IO [String]
{- | Returns a list of values in the 'AnyDBM' object. -}
valuesA :: a -> IO [String]
valuesA h = do l <- toListA h
return $ map snd l
keysA h = do l <- toListA h
return $ map fst l
toListA h =
let conv k = do v <- forceLookupA h k
return (k, v)
in do k <- keysA h
mapM conv k
forceLookupA h key =
do x <- lookupA h key
case x of
Just y -> return y
Nothing -> throwIO $ PatternMatchFail key
insertListA h [] = return ()
insertListA h ((key, val):xs) = do insertA h key val
insertListA h xs
hasKeyA h k = do l <- lookupA h k
case l of
Nothing -> return False
Just _ -> return True
closeA h = flushA h
flushA h = return ()
{- | Similar to MapM, but for 'AnyDBM' objects. -}
mapA :: AnyDBM a => a -> ((String, String) -> IO b) -> IO [b]
mapA h func = do l <- toListA h
mapM func l
{- | Similar to 'Data.List.Utils.strToAL' -- load a string representation
into the AnyDBM. You must supply an existing AnyDBM object;
the items loaded from the string will be added to it. -}
strToA :: AnyDBM a => a -> String -> IO ()
strToA h s = insertListA h (strToAL s)
{- | Similar to 'Data.List.Utils.strFromAL' -- get a string representation of
the entire AnyDBM. -}
strFromA :: AnyDBM a => a -> IO String
strFromA h = do l <- toListA h
return (strFromAL l)
instance BasicHashTable String String ~ hashtable => AnyDBM hashtable where
insertA h k v = do delete h k
insert h k v
deleteA = delete
lookupA = lookup
toListA = toList
|
jgoerzen/anydbm
|
src/Database/AnyDBM.hs
|
lgpl-2.1
| 5,544 | 0 | 14 | 1,725 | 836 | 420 | 416 | -1 | -1 |
-- http://www.codewars.com/kata/5266876b8f4bf2da9b000362
module Likes where
likes :: [String] -> String
likes [] = "no one likes this"
likes (x:[]) = x++" likes this"
likes (x:y:[]) = x++" and "++y++" like this"
likes (x:y:z:[]) = x++", "++y++" and "++z++" like this"
likes (x:y:zs) = x++", "++y++" and "++show (length zs)++" others like this"
|
Bodigrim/katas
|
src/haskell/6-Who-likes-it.hs
|
bsd-2-clause
| 344 | 0 | 10 | 52 | 174 | 91 | 83 | 7 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QSplashScreen_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QSplashScreen_h (
QdrawContents_h(..)
) where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QSplashScreen ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QSplashScreen_unSetUserMethod" qtc_QSplashScreen_unSetUserMethod :: Ptr (TQSplashScreen a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QSplashScreenSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QSplashScreen ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QSplashScreenSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QSplashScreen ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QSplashScreenSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QSplashScreen_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QSplashScreen ()) (QSplashScreen x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setUserMethod" qtc_QSplashScreen_setUserMethod :: Ptr (TQSplashScreen a) -> CInt -> Ptr (Ptr (TQSplashScreen x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QSplashScreen :: (Ptr (TQSplashScreen x0) -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QSplashScreen_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QSplashScreenSc a) (QSplashScreen x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QSplashScreen ()) (QSplashScreen x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setUserMethodVariant" qtc_QSplashScreen_setUserMethodVariant :: Ptr (TQSplashScreen a) -> CInt -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QSplashScreen :: (Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QSplashScreen_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QSplashScreenSc a) (QSplashScreen x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QSplashScreen setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QSplashScreen_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QSplashScreen_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QSplashScreen ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QSplashScreen_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QSplashScreen_unSetHandler" qtc_QSplashScreen_unSetHandler :: Ptr (TQSplashScreen a) -> CWString -> IO (CBool)
instance QunSetHandler (QSplashScreenSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QSplashScreen_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QPainter t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler1" qtc_QSplashScreen_setHandler1 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen1 :: (Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QPainter t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQPainter t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QdrawContents_h x0 x1 where
drawContents_h :: x0 -> x1 -> IO ()
instance QdrawContents_h (QSplashScreen ()) ((QPainter t1)) where
drawContents_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_drawContents cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_drawContents" qtc_QSplashScreen_drawContents :: Ptr (TQSplashScreen a) -> Ptr (TQPainter t1) -> IO ()
instance QdrawContents_h (QSplashScreenSc a) ((QPainter t1)) where
drawContents_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_drawContents cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler2" qtc_QSplashScreen_setHandler2 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen2 :: (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QSplashScreen ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_event cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_event" qtc_QSplashScreen_event :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QSplashScreenSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_event cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler3" qtc_QSplashScreen_setHandler3 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen3 :: (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QmousePressEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mousePressEvent" qtc_QSplashScreen_mousePressEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mousePressEvent cobj_x0 cobj_x1
instance QactionEvent_h (QSplashScreen ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_actionEvent" qtc_QSplashScreen_actionEvent :: Ptr (TQSplashScreen a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QSplashScreenSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_actionEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QSplashScreen ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_changeEvent" qtc_QSplashScreen_changeEvent :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QSplashScreenSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_changeEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QSplashScreen ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_closeEvent" qtc_QSplashScreen_closeEvent :: Ptr (TQSplashScreen a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QSplashScreenSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QSplashScreen ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_contextMenuEvent" qtc_QSplashScreen_contextMenuEvent :: Ptr (TQSplashScreen a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QSplashScreenSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler4" qtc_QSplashScreen_setHandler4 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen4 :: (Ptr (TQSplashScreen x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QSplashScreen ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_devType cobj_x0
foreign import ccall "qtc_QSplashScreen_devType" qtc_QSplashScreen_devType :: Ptr (TQSplashScreen a) -> IO CInt
instance QdevType_h (QSplashScreenSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_devType cobj_x0
instance QdragEnterEvent_h (QSplashScreen ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dragEnterEvent" qtc_QSplashScreen_dragEnterEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QSplashScreenSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QSplashScreen ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dragLeaveEvent" qtc_QSplashScreen_dragLeaveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QSplashScreenSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QSplashScreen ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dragMoveEvent" qtc_QSplashScreen_dragMoveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QSplashScreenSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QSplashScreen ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_dropEvent" qtc_QSplashScreen_dropEvent :: Ptr (TQSplashScreen a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QSplashScreenSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QSplashScreen ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_enterEvent" qtc_QSplashScreen_enterEvent :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QSplashScreenSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_enterEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QSplashScreen ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_focusInEvent" qtc_QSplashScreen_focusInEvent :: Ptr (TQSplashScreen a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QSplashScreenSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QSplashScreen ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_focusOutEvent" qtc_QSplashScreen_focusOutEvent :: Ptr (TQSplashScreen a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QSplashScreenSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler5" qtc_QSplashScreen_setHandler5 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen5 :: (Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QSplashScreen ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QSplashScreen_heightForWidth" qtc_QSplashScreen_heightForWidth :: Ptr (TQSplashScreen a) -> CInt -> IO CInt
instance QheightForWidth_h (QSplashScreenSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QSplashScreen ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_hideEvent" qtc_QSplashScreen_hideEvent :: Ptr (TQSplashScreen a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QSplashScreenSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_hideEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler6" qtc_QSplashScreen_setHandler6 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen6 :: (Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QSplashScreen ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QSplashScreen_inputMethodQuery" qtc_QSplashScreen_inputMethodQuery :: Ptr (TQSplashScreen a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QSplashScreenSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent_h (QSplashScreen ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_keyPressEvent" qtc_QSplashScreen_keyPressEvent :: Ptr (TQSplashScreen a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QSplashScreenSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QSplashScreen ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_keyReleaseEvent" qtc_QSplashScreen_keyReleaseEvent :: Ptr (TQSplashScreen a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QSplashScreenSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QSplashScreen ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_leaveEvent" qtc_QSplashScreen_leaveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QSplashScreenSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_leaveEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler7" qtc_QSplashScreen_setHandler7 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen7 :: (Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QSplashScreen ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint cobj_x0
foreign import ccall "qtc_QSplashScreen_minimumSizeHint" qtc_QSplashScreen_minimumSizeHint :: Ptr (TQSplashScreen a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QSplashScreenSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QSplashScreen ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QSplashScreen_minimumSizeHint_qth" qtc_QSplashScreen_minimumSizeHint_qth :: Ptr (TQSplashScreen a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QSplashScreenSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QmouseDoubleClickEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mouseDoubleClickEvent" qtc_QSplashScreen_mouseDoubleClickEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mouseMoveEvent" qtc_QSplashScreen_mouseMoveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseMoveEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QSplashScreen ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_mouseReleaseEvent" qtc_QSplashScreen_mouseReleaseEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QSplashScreenSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_mouseReleaseEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QSplashScreen ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_moveEvent" qtc_QSplashScreen_moveEvent :: Ptr (TQSplashScreen a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QSplashScreenSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler8" qtc_QSplashScreen_setHandler8 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen8 :: (Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qSplashScreenFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QSplashScreen ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_paintEngine cobj_x0
foreign import ccall "qtc_QSplashScreen_paintEngine" qtc_QSplashScreen_paintEngine :: Ptr (TQSplashScreen a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QSplashScreenSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_paintEngine cobj_x0
instance QpaintEvent_h (QSplashScreen ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_paintEvent" qtc_QSplashScreen_paintEvent :: Ptr (TQSplashScreen a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QSplashScreenSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_paintEvent cobj_x0 cobj_x1
instance QresizeEvent_h (QSplashScreen ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_resizeEvent" qtc_QSplashScreen_resizeEvent :: Ptr (TQSplashScreen a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QSplashScreenSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler9" qtc_QSplashScreen_setHandler9 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen9 :: (Ptr (TQSplashScreen x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qSplashScreenFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QSplashScreen ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QSplashScreen_setVisible" qtc_QSplashScreen_setVisible :: Ptr (TQSplashScreen a) -> CBool -> IO ()
instance QsetVisible_h (QSplashScreenSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QSplashScreen ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_showEvent" qtc_QSplashScreen_showEvent :: Ptr (TQSplashScreen a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QSplashScreenSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_showEvent cobj_x0 cobj_x1
instance QqsizeHint_h (QSplashScreen ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint cobj_x0
foreign import ccall "qtc_QSplashScreen_sizeHint" qtc_QSplashScreen_sizeHint :: Ptr (TQSplashScreen a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QSplashScreenSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint cobj_x0
instance QsizeHint_h (QSplashScreen ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QSplashScreen_sizeHint_qth" qtc_QSplashScreen_sizeHint_qth :: Ptr (TQSplashScreen a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QSplashScreenSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QSplashScreen_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QtabletEvent_h (QSplashScreen ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_tabletEvent" qtc_QSplashScreen_tabletEvent :: Ptr (TQSplashScreen a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QSplashScreenSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_tabletEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QSplashScreen ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QSplashScreen_wheelEvent" qtc_QSplashScreen_wheelEvent :: Ptr (TQSplashScreen a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QSplashScreenSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QSplashScreen_wheelEvent cobj_x0 cobj_x1
instance QsetHandler (QSplashScreen ()) (QSplashScreen x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QSplashScreen_setHandler10" qtc_QSplashScreen_setHandler10 :: Ptr (TQSplashScreen a) -> CWString -> Ptr (Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen10 :: (Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QSplashScreen10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QSplashScreenSc a) (QSplashScreen x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QSplashScreen10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QSplashScreen10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QSplashScreen_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQSplashScreen x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qSplashScreenFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QSplashScreen ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QSplashScreen_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QSplashScreen_eventFilter" qtc_QSplashScreen_eventFilter :: Ptr (TQSplashScreen a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QSplashScreenSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QSplashScreen_eventFilter cobj_x0 cobj_x1 cobj_x2
|
keera-studios/hsQt
|
Qtc/Gui/QSplashScreen_h.hs
|
bsd-2-clause
| 62,301 | 0 | 18 | 13,107 | 20,098 | 9,685 | 10,413 | -1 | -1 |
--------------------------------------------------------------------------------
module WhatMorphism.Dump
( Dump (..)
) where
--------------------------------------------------------------------------------
import Coercion (Coercion)
import CoreSyn
import Data.List (intercalate)
import DataCon (DataCon)
import Literal (Literal)
import Name (Name)
import qualified Name as Name
import Module (Module)
import qualified Module as Module
import OccName (OccName)
import qualified OccName as OccName
import TyCon (TyCon)
import qualified TyCon as TyCon
import TypeRep (Type)
import Var (Var)
import qualified Var as Var
--------------------------------------------------------------------------------
class Dump a where
dump :: a -> String
--------------------------------------------------------------------------------
instance (Dump a, Dump b) => Dump (a, b) where
dump (x, y) = "(" ++ dump x ++ ", " ++ dump y ++ ")"
--------------------------------------------------------------------------------
instance (Dump a, Dump b, Dump c) => Dump (a, b, c) where
dump (x, y, z) = "(" ++ dump x ++ ", " ++ dump y ++ ", " ++ dump z ++ ")"
--------------------------------------------------------------------------------
instance Dump a => Dump [a] where
dump xs = "[" ++ intercalate ", " (map dump xs) ++ "]"
--------------------------------------------------------------------------------
instance Dump a => Dump (Maybe a) where
dump Nothing = "Nothing"
dump (Just x) = "(Just " ++ dump x ++ ")"
--------------------------------------------------------------------------------
instance Dump Name where
dump name = OccName.occNameString (Name.getOccName name) ++ "_" ++
show (Name.nameUnique name)
--------------------------------------------------------------------------------
instance Dump OccName where
dump = OccName.occNameString
--------------------------------------------------------------------------------
instance Dump Var where
dump = dump . Var.varName
--------------------------------------------------------------------------------
instance Dump DataCon where
dump = OccName.occNameString . Name.getOccName
--------------------------------------------------------------------------------
instance Dump TyCon where
dump tc = "@" ++ dump (TyCon.tyConName tc)
--------------------------------------------------------------------------------
instance Dump AltCon where
dump (DataAlt x) = dc "DataAlt" [dump x]
dump (LitAlt x) = dc "Literal" [dump x]
dump DEFAULT = dc "DEFAULT" []
--------------------------------------------------------------------------------
instance Dump Module where
dump = Module.moduleNameString . Module.moduleName
--------------------------------------------------------------------------------
instance Dump Literal where
dump _ = "<Literal>"
--------------------------------------------------------------------------------
instance Dump Coercion where
dump _ = "<Coercion>"
--------------------------------------------------------------------------------
instance Dump Type where
dump _ = "<Type>"
--------------------------------------------------------------------------------
instance Dump (Tickish a) where
dump _ = "<Tickish>"
--------------------------------------------------------------------------------
instance Dump b => Dump (Bind b) where
dump (NonRec x y) = dc "NonRec" [dump x, dump y]
dump (Rec x) = dc "Rec" [dump x]
--------------------------------------------------------------------------------
instance Dump b => Dump (Expr b) where
dump (Var x) = dc "Var" [dump x]
dump (Lit x) = dc "Lit" [dump x]
dump (App x y) = dc "App" [dump x, dump y]
dump (Lam x y) = dc "Lam" [dump x, dump y]
dump (Let x y) = dc "Let" [dump x, dump y]
dump (Case x y z w) = dc "Case" [dump x, dump y, dump z, dump w]
dump (Cast x y) = dc "Cast" [dump x, dump y]
dump (Tick x y) = dc "Tick" [dump x, dump y]
dump (Type x) = dc "Type" [dump x]
dump (Coercion x) = dc "Coercion" [dump x]
--------------------------------------------------------------------------------
dc :: String -> [String] -> String
dc constr [] = constr
dc constr args = "(" ++ constr ++ " " ++ intercalate " " args ++ ")"
|
jaspervdj/what-morphism
|
src/WhatMorphism/Dump.hs
|
bsd-3-clause
| 4,541 | 0 | 12 | 908 | 1,194 | 625 | 569 | 71 | 1 |
{-
BezCurve.hs (adapted from bezcurve.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2005 <[email protected]>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program uses evaluators to draw a Bezier curve.
-}
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
ctrlPoints :: [Vertex3 GLfloat]
ctrlPoints = [ Vertex3 (-4)(-4) 0, Vertex3 (-2) 4 0,
Vertex3 2 (-4) 0, Vertex3 4 4 0 ]
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
m <- newMap1 (0, 1) ctrlPoints
map1 $= Just (m :: GLmap1 Vertex3 GLfloat)
display :: DisplayCallback
display = do
clear [ ColorBuffer ]
-- resolve overloading, not needed in "real" programs
let color3f = color :: Color3 GLfloat -> IO ()
color3f (Color3 1 1 1)
renderPrimitive LineStrip $
mapM_ evalCoord1 [ i/30.0 :: GLfloat | i <- [0..30] ]
-- The following code displays the control points as dots.
pointSize $= 5
color3f (Color3 1 1 0)
renderPrimitive Points $
mapM_ vertex ctrlPoints
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
let wf = fromIntegral w
hf = fromIntegral h
if w <= h
then ortho (-5.0) 5.0 (-5.0*hf/wf) (5.0*hf/wf) (-5.0) 5.0
else ortho (-5.0*wf/hf) (5.0*wf/hf) (-5.0) 5.0 (-5.0) 5.0
matrixMode $= Modelview 0
loadIdentity
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 500 500
initialWindowPosition $= Position 100 100
createWindow progName
myInit
displayCallback $= display
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
|
FranklinChen/hugs98-plus-Sep2006
|
packages/GLUT/examples/RedBook/BezCurve.hs
|
bsd-3-clause
| 2,027 | 0 | 12 | 473 | 663 | 328 | 335 | 50 | 2 |
import Data.Char (isDigit)
data YorthData = YNil
| YInt Integer
| YOpAdd
| YOpSub
| YOpMul
| YOpDiv
| YError String
deriving (Show, Eq, Ord)
data Closure = DoneToken
| Closure [YorthData] Closure [(YorthData, [Closure])] Closure
deriving (Show, Eq, Ord)
empty_closure = (Closure [] empty_closure [] empty_closure)
parse :: Closure -> [String] -> Closure -> Closure
parse enclosure inputs caller = (Closure (stacks inputs) enclosure [] caller)
where stacks [] = []
stacks (input:is)
| foldl1 (&&) (map isDigit input) = (YInt (read input)):(stacks is)
| otherwise (case input of
"+" -> YOpAdd
"-" -> YOpSub
"*" -> YOpMul
"/" -> YOpDiv
"}" -> YNil
_ -> YError "Undefined token"
):(stacks is)
step :: Closure -> (YorthData, Closure)
step (Closure [] enclosure scope caller) = (YNil, DoneToken)
step (Closure (stack:ss) enclosure scope caller) = (YNil, empty_closure)
|
tricorder42/yorth
|
yorth.hs
|
bsd-3-clause
| 959 | 7 | 13 | 232 | 370 | 203 | 167 | -1 | -1 |
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FunctionalDependencies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Indexed.Traversable
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Indexed Traversable Functors
-----------------------------------------------------------------------------
module Indexed.Traversable
( ITraversable(..)
) where
import Control.Applicative
import Indexed.Functor
import Indexed.Foldable
-- | Indexed Traversable Functor
class (IFunctor t, IFoldable t) => ITraversable t where
itraverse :: Applicative f => (forall x. a x -> f (b x)) -> t a y -> f (t b y)
|
ekmett/indexed
|
src/Indexed/Traversable.hs
|
bsd-3-clause
| 904 | 0 | 14 | 138 | 131 | 77 | 54 | 12 | 0 |
import Data.Text (unpack)
import Data.List (sortOn)
import Lib
main :: IO ()
main = do
mod <- parseModuleFromFile "test/Test1.purs"
putStrLn ""
putStrLn $ show mod
putStrLn ""
putStrLn "% facts"
putStrLn . unpack . formatAtomsProlog . sortForProlog . factsFromModule $ mod
putStrLn ""
putStrLn "% rules"
putStrLn . unpack . formatRulesProlog $ definedInStar
-- putStrLn ""
-- putStrLn $ (formatDatomic . factsFromModule $ mod)
where
sortForProlog = sortOn (\(Pred name _) -> name)
|
epost/psc-query
|
test/Spec.hs
|
bsd-3-clause
| 540 | 0 | 11 | 132 | 156 | 74 | 82 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import System.Random
import System.Environment
import Debug.Trace
import Data.List
import Control.Monad.Par
import Control.DeepSeq
import Data.Map (Map)
import qualified Data.Map as Map
-- ----------------------------------------------------------------------------
-- <<Talk
newtype Talk = Talk Int
deriving (Eq,Ord)
instance NFData Talk
instance Show Talk where
show (Talk t) = show t
-- >>
-- <<Person
data Person = Person
{ name :: String
, talks :: [Talk]
}
deriving (Show)
-- >>
-- <<TimeTable
type TimeTable = [[Talk]]
-- >>
-- ----------------------------------------------------------------------------
-- The parallel skeleton
-- <<search_type
search :: ( partial -> Maybe solution ) -- <1>
-> ( partial -> [ partial ] ) -- <2>
-> partial -- <3>
-> [solution] -- <4>
-- >>
-- <<search
search finished refine emptysoln = generate emptysoln
where
generate partial
| Just soln <- finished partial = [soln]
| otherwise = concat (map generate (refine partial))
-- >>
-- <<parsearch
parsearch :: NFData solution
=> Int
-> ( partial -> Maybe solution ) -- finished?
-> ( partial -> [ partial ] ) -- refine a solution
-> partial -- initial solution
-> [solution]
parsearch maxdepth finished refine emptysoln
= runPar $ generate 0 emptysoln
where
generate d partial | d >= maxdepth -- <1>
= return (search finished refine partial)
generate d partial
| Just soln <- finished partial = return [soln]
| otherwise = do
solnss <- parMapM (generate (d+1)) (refine partial)
return (concat solnss)
-- >>
-- ----------------------------------------------------------------------------
-- <<Partial
type Partial = (Int, Int, [[Talk]], [Talk], [Talk], [Talk])
-- >>
-- <<timetable
timetable :: [Person] -> [Talk] -> Int -> Int -> [TimeTable]
timetable people allTalks maxTrack maxSlot =
parsearch 3 finished refine emptysoln
where
emptysoln = (0, 0, [], [], allTalks, allTalks)
finished (slotNo, trackNo, slots, slot, slotTalks, talks)
| slotNo == maxSlot = Just slots
| otherwise = Nothing
clashes :: Map Talk [Talk]
clashes = Map.fromListWith union
[ (t, ts)
| s <- people
, (t, ts) <- selects (talks s) ]
refine (slotNo, trackNo, slots, slot, slotTalks, talks)
| trackNo == maxTrack = [(slotNo+1, 0, slot:slots, [], talks, talks)]
| otherwise =
[ (slotNo, trackNo+1, slots, t:slot, slotTalks', talks')
| (t, ts) <- selects slotTalks
, let clashesWithT = Map.findWithDefault [] t clashes
, let slotTalks' = filter (`notElem` clashesWithT) ts
, let talks' = filter (/= t) talks
]
-- >>
-- ----------------------------------------------------------------------------
-- Utils
-- <<selects
selects :: [a] -> [(a,[a])]
selects xs0 = go [] xs0
where
go xs [] = []
go xs (y:ys) = (y,xs++ys) : go (y:xs) ys
-- >>
-- ----------------------------------------------------------------------------
-- Benchmarking / Testing
bench :: Int -> Int -> Int -> Int -> Int -> StdGen
-> ([Person],[Talk],[TimeTable])
bench nslots ntracks ntalks npersons c_per_s gen =
(persons,talks, timetable persons talks ntracks nslots)
where
total_talks = nslots * ntracks
talks = map Talk [1..total_talks]
persons = mkpersons npersons gen
mkpersons :: Int -> StdGen -> [Person]
mkpersons 0 g = []
mkpersons n g = Person ('P':show n) (take c_per_s cs) : rest
where
(g1,g2) = split g
rest = mkpersons (n-1) g2
cs = nub [ talks !! n | n <- randomRs (0,ntalks-1) g ]
main = do
[ a, b, c, d, e ] <- fmap (fmap read) getArgs
let g = mkStdGen 1001
let (ss,cs,ts) = bench a b c d e g
print ss
print (length ts)
-- [ a, b ] <- fmap (fmap read) getArgs
-- print (head (test2 a b))
test = timetable testPersons cs 2 2
where
cs@[c1,c2,c3,c4] = map Talk [1..4]
testPersons =
[ Person "P" [c1,c2]
, Person "Q" [c2,c3]
, Person "R" [c3,c4]
]
test2 n m = timetable testPersons cs m n
where
cs = map Talk [1 .. (n * m)]
testPersons =
[ Person "1" (take n cs)
]
|
mono0926/ParallelConcurrentHaskell
|
timetable3.hs
|
bsd-3-clause
| 4,343 | 9 | 13 | 1,131 | 1,522 | 826 | 696 | 96 | 2 |
----------------------
-- PARELM --
----------------------
module Parelm where
import LPPE
import Usage
-- This function removes global parameters that are never used.
parelm :: PSpecification -> PSpecification
parelm (lppe, initial, dataspec) = (lppeReduced, initial2, dataspec)
where
unused = [parNr | parNr <- [0..length (getLPPEPars lppe) - 1],
and [not (isUsedInSummand summand parNr (fst ((getLPPEPars lppe)!!parNr)) False) | summand <- (getPSummands lppe)]]
(lppeReduced,initial2,_) = removeParametersFromLPPE (lppe,initial,dataspec) unused
|
utwente-fmt/scoop
|
src/Parelm.hs
|
bsd-3-clause
| 607 | 0 | 19 | 125 | 172 | 97 | 75 | 8 | 1 |
{-# LANGUAGE TypeOperators #-}
module Data.Semigroupoid.Category where
import Data.Semigroupoid.Semigroupoid
class Semigroupoid (~>) => Category (~>) where
id ::
a ~> a
instance Category (->) where
id a =
a
|
tonymorris/type-class
|
src/Data/Semigroupoid/Category.hs
|
bsd-3-clause
| 222 | 0 | 7 | 44 | 62 | 36 | 26 | -1 | -1 |
module D18Spec (main, spec) where
import Test.Hspec
import D18Lib
import qualified Data.Vector as V
import qualified Text.Parsec as P
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "parsing" $ do
it "parses a row" $ do
let r = P.parse rowP "fixture" ".^\n"
r `shouldBe` Right (V.fromList [Safe, Trap])
describe "succRow" $ do
it "builds the next row" $ do
let r0 = V.fromList [Safe, Safe, Trap, Trap, Safe]
let r1 = V.fromList [Safe, Trap, Trap, Trap, Trap]
let r2 = V.fromList [Trap, Trap, Safe, Safe, Trap]
succRow r0 `shouldBe` r1
succRow r1 `shouldBe` r2
describe "nsafe" $ do
it "counts safe tiles" $ do
let r0 = V.fromList [Safe, Safe, Trap, Trap, Safe]
nsafe r0 3 `shouldBe` 6
|
wfleming/advent-of-code-2016
|
2016/test/D18Spec.hs
|
bsd-3-clause
| 862 | 0 | 18 | 278 | 326 | 171 | 155 | 24 | 1 |
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Sqlite (SqliteConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings(..), widgetFileNoReload,
widgetFileReload)
import Yesod.Default.Util (defaultTemplateLanguages)
import Yesod.Default.Util (TemplateLanguage(..))
import Yesod.Markdown (markdownToHtml, Markdown(..))
import Text.Shakespeare.Text (textFile, textFileReload)
import qualified Data.Text as T
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: SqliteConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Text
-- ^ Base for all generated URLs.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
, appPackageDBs :: [Text]
, appTrustedPkgs :: [String]
, appDistrustedPkgs :: [String]
, appDistribPort :: String
, appWSAddress :: Text
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .: "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
appPackageDBs <- o .:? "package-dbs" .!= []
appTrustedPkgs <- o .:? "trusted-packages" .!= []
appDistrustedPkgs <- o .:? "distrusted-packages" .!= []
appDistribPort <- (fmap (show :: Int -> String) <$> o .:? "distributed-port")
.!= ""
appWSAddress <- o .:? "websock-addr"
.!= T.replace "http" "ws" appRoot
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def { wfsLanguages = \hset -> defaultTemplateLanguages hset ++
[ TemplateLanguage True "md" markdownFile markdownFileReload
] }
markdownFile fs = [| markdownToHtml (Markdown $(textFile fs)) |]
markdownFileReload fs = [| markdownToHtml (Markdown $(textFileReload fs)) |]
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
{-
fayFile :: String -> Q Exp
fayFile fp =
let setting = (yesodFaySettings fp)
{yfsPackages = ["fay-base", "fay-ref", "fay-jquery", "fay-text", "fay-base"]
,yfsSeparateRuntime = Just ("static", ConE (mkName "StaticR"))}
in if appReloadTemplates compileTimeAppSettings
then fayFileReload setting
else fayFileProd setting
-}
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
|
konn/leport
|
leport-web/Settings.hs
|
bsd-3-clause
| 6,896 | 0 | 17 | 1,860 | 974 | 559 | 415 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
import Plots
import Network.Wreq
import Control.Lens
import Data.Csv hiding ((.=))
import Plots.Axis
import qualified Data.Vector as V
import Data.ByteString.Lazy (ByteString)
import Control.Arrow
import Control.Monad.State (MonadState, execStateT)
import Data.Foldable
import Control.Monad.IO.Class
import Data.Time.Clock.POSIX
-- import Plots.Axis
import Diagrams.Backend.Rasterific
import Data.Time
import Control.Monad
import Diagrams
import Data.Maybe
-- Incomplete example using mtl to perform IO in the axis do notation.
-- The axis show dates but currently the tick positions and the start of
-- the dates are not aligned properly. (the ticks might be 1.2 years
-- apart but the labels will just show the year, which is misleading)
parseStocks :: ByteString -> [(String, Double)]
parseStocks bs = toListOf (each . to (view _1 &&& view _7)) v
where
Right v = decode HasHeader bs :: Either String (V.Vector (String, Double, Double, Double, Double, Double, Double))
filterStocks :: [(String, Double)] -> [(Double, Double)]
filterStocks = mapMaybe f
where
f (s, d) = do
date <- s ^? timeFormat "%F"
start <- "2014" ^? timeFormat "%Y"
guard $ date > start
return $ (date ^. realUTC, d)
myaxis :: IO (Axis B V2 Double)
myaxis = execStateT ?? r2Axis $ do
goog <- liftIO $ get "http://ichart.yahoo.com/table.csv?s=GOOG"
appl <- liftIO $ get "http://ichart.yahoo.com/table.csv?s=AAPL"
for_ [goog, appl] $
linePlotOf (responseBody . to (filterStocks . parseStocks) . each)
axisTickLabels . _x . tickLabelFun .= autoTimeLabels
xAxisLabel .= "date"
yAxisLabel .= "closing (dollars)"
main :: IO ()
main = myaxis >>= make . renderAxis
make :: Diagram B -> IO ()
make = renderRasterific "examples/stocks.png" (mkWidth 600) . frame 30
------------------------------------------------------------------------
linePlotOf
:: (PointLike V2 n p, TypeableFloat n, MonadState (Axis b V2 n) m, Renderable (Path V2 n) b)
=> Fold s p -- ^ Fold over data
-> s -- ^ Data
-> m () -- ^ Monad action on axis
linePlotOf f s = addPlotable (Path [mkTrailOf f s])
------------------------------------------------------------------------
-- Time
------------------------------------------------------------------------
-- | Same as 'timeFormat' but with the option of choosing the
-- 'TimeLocale'.
localeTimeFormat
:: (ParseTime a, FormatTime a)
=> TimeLocale -> String -> Prism' String a
localeTimeFormat tl s = prism' (formatTime tl s) (parseTimeM False tl s)
{-# INLINE localeTimeFormat #-}
-- | A prism between a parse-able format and its string representation
-- from the given format string using the 'defaultTimeLocale'. See
-- 'formatTime' for a description of the format string.
--
-- @
-- >>> timeFormat "%F" # ModifiedJulianDay 91424
-- "2109-03-10"
--
-- >>> "2109-03-10" ^? timeFormat "%F" :: Maybe UTCTime
-- Just 2109-03-10 00:00:00 UTC
-- @
--
timeFormat
:: (ParseTime a, FormatTime a)
=> String -> Prism' String a
timeFormat = localeTimeFormat defaultTimeLocale
{-# INLINE timeFormat #-}
-- | Automatically choose a suitable time axis, based upon the time range
-- of data.
-- XXX: This is a terrible way to do it if the ticks aren't aligned
-- properly.
autoTimeLabels :: RealFloat n => [n] -> (n,n) -> [(n, String)]
autoTimeLabels ts (t0, t1)
| d < minute = fmt "%S%Q"
| d < hour = fmt "%M:%S"
| d < day = fmt "%H:%M"
| d < month = fmt "%F %H"
| d < year = fmt "%F"
| d < 2*year = fmt "%F"
| otherwise = fmt "%Y"
where
d = t1 - t0
fmt a = map (\n -> (n, formatTime defaultTimeLocale a (realToUTC n))) ts
minute = 60
hour = 60 * minute
day = 24 * hour
month = 30 * day
year = 365 * day
realToUTC :: Real a => a -> UTCTime
realToUTC = posixSecondsToUTCTime . realToFrac
realUTC :: (Real a, Fractional a) => Iso' UTCTime a
realUTC = iso (realToFrac . utcTimeToPOSIXSeconds) realToUTC
|
bergey/plots
|
examples/stocks.hs
|
bsd-3-clause
| 4,014 | 0 | 15 | 792 | 1,080 | 578 | 502 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.HcPkg
-- Copyright : Duncan Coutts 2009, 2013
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides an library interface to the @hc-pkg@ program.
-- Currently only GHC, GHCJS and LHC have hc-pkg programs.
module Distribution.Simple.Program.HcPkg (
HcPkgInfo(..),
init,
invoke,
register,
reregister,
unregister,
expose,
hide,
dump,
list,
-- * View operations
createView,
addPackageToView,
removePackageFromView,
-- * Program invocations
initInvocation,
registerInvocation,
reregisterInvocation,
unregisterInvocation,
exposeInvocation,
hideInvocation,
dumpInvocation,
listInvocation,
) where
import Prelude hiding (init)
import Distribution.Package
( PackageId, InstalledPackageId(..) )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo, InstalledPackageInfo_(..)
, showInstalledPackageInfo
, emptyInstalledPackageInfo, fieldsInstalledPackageInfo )
import Distribution.ParseUtils
import Distribution.Simple.Compiler
( PackageDB(..), PackageDBStack )
import Distribution.Simple.Program.Types
( ConfiguredProgram(programId) )
import Distribution.Simple.Program.Run
( ProgramInvocation(..), IOEncoding(..), programInvocation
, runProgramInvocation, getProgramInvocationOutput )
import Distribution.Text
( display, simpleParse )
import Distribution.Simple.Utils
( die )
import Distribution.Verbosity
( Verbosity, deafening, silent )
import Distribution.Compat.Exception
( catchExit )
import Control.Monad
( when )
import Data.Char
( isSpace )
import Data.List
( stripPrefix )
import qualified Data.List as List
import System.FilePath as FilePath
( (</>), splitPath, splitDirectories, joinPath, isPathSeparator )
import qualified System.FilePath.Posix as FilePath.Posix
-- | Information about the features and capabilities of an @hc-pkg@
-- program.
--
data HcPkgInfo = HcPkgInfo
{ hcPkgProgram :: ConfiguredProgram
, noPkgDbStack :: Bool -- ^ no package DB stack supported
, noVerboseFlag :: Bool -- ^ hc-pkg does not support verbosity flags
, flagPackageConf :: Bool -- ^ use package-conf option instead of package-db
, useSingleFileDb :: Bool -- ^ requires single file package database
, multInstEnabled :: Bool -- ^ ghc-pkg supports --enable-multi-instance
, supportsView :: Bool -- ^ views are supported.
}
-- | Call @hc-pkg@ to initialise a package database at the location {path}.
--
-- > hc-pkg init {path}
--
init :: HcPkgInfo -> Verbosity -> FilePath -> IO ()
init hpi verbosity path =
runProgramInvocation verbosity (initInvocation hpi verbosity path)
-- | Run @hc-pkg@ using a given package DB stack, directly forwarding the
-- provided command-line arguments to it.
invoke :: HcPkgInfo -> Verbosity -> PackageDBStack -> [String] -> IO ()
invoke hpi verbosity dbStack extraArgs =
runProgramInvocation verbosity invocation
where
args = packageDbStackOpts hpi dbStack ++ extraArgs
invocation = programInvocation (hcPkgProgram hpi) args
-- | Call @hc-pkg@ to register a package.
--
-- > hc-pkg register {filename | -} [--user | --global | --package-db]
--
register :: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath
InstalledPackageInfo
-> IO ()
register hpi verbosity packagedb pkgFile =
runProgramInvocation verbosity
(registerInvocation hpi verbosity packagedb pkgFile)
-- | Call @hc-pkg@ to re-register a package.
--
-- > hc-pkg register {filename | -} [--user | --global | --package-db]
--
reregister :: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath
InstalledPackageInfo
-> IO ()
reregister hpi verbosity packagedb pkgFile =
runProgramInvocation verbosity
(reregisterInvocation hpi verbosity packagedb pkgFile)
-- | Call @hc-pkg@ to unregister a package
--
-- > hc-pkg unregister [pkgid] [--user | --global | --package-db]
--
unregister :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
unregister hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(unregisterInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to expose a package.
--
-- > hc-pkg expose [pkgid] [--user | --global | --package-db]
--
expose :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
expose hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(exposeInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to hide a package.
--
-- > hc-pkg hide [pkgid] [--user | --global | --package-db]
--
hide :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId -> IO ()
hide hpi verbosity packagedb pkgid =
runProgramInvocation verbosity
(hideInvocation hpi verbosity packagedb pkgid)
-- | Call @hc-pkg@ to get all the details of all the packages in the given
-- package database.
--
dump :: HcPkgInfo -> Verbosity -> PackageDB -> IO [InstalledPackageInfo]
dump hpi verbosity packagedb = do
output <- getProgramInvocationOutput verbosity
(dumpInvocation hpi verbosity packagedb)
`catchExit` \_ -> die $ programId (hcPkgProgram hpi) ++ " dump failed"
case parsePackages output of
Left ok -> return ok
_ -> die $ "failed to parse output of '"
++ programId (hcPkgProgram hpi) ++ " dump'"
where
parsePackages str =
let parsed = map parseInstalledPackageInfo' (splitPkgs str)
in case [ msg | ParseFailed msg <- parsed ] of
[] -> Left [ setInstalledPackageId
. maybe id mungePackagePaths (pkgRoot pkg)
$ pkg
| ParseOk _ pkg <- parsed ]
msgs -> Right msgs
parseInstalledPackageInfo' =
parseFieldsFlat fieldsInstalledPackageInfo emptyInstalledPackageInfo
--TODO: this could be a lot faster. We're doing normaliseLineEndings twice
-- and converting back and forth with lines/unlines.
splitPkgs :: String -> [String]
splitPkgs = checkEmpty . map unlines . splitWith ("---" ==) . lines
where
-- Handle the case of there being no packages at all.
checkEmpty [s] | all isSpace s = []
checkEmpty ss = ss
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs = ys : case zs of
[] -> []
_:ws -> splitWith p ws
where (ys,zs) = break p xs
mungePackagePaths :: FilePath -> InstalledPackageInfo -> InstalledPackageInfo
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
mungePackagePaths pkgroot pkginfo =
pkginfo {
importDirs = mungePaths (importDirs pkginfo),
includeDirs = mungePaths (includeDirs pkginfo),
libraryDirs = mungePaths (libraryDirs pkginfo),
frameworkDirs = mungePaths (frameworkDirs pkginfo),
haddockInterfaces = mungePaths (haddockInterfaces pkginfo),
haddockHTMLs = mungeUrls (haddockHTMLs pkginfo)
}
where
mungePaths = map mungePath
mungeUrls = map mungeUrl
mungePath p = case stripVarPrefix "${pkgroot}" p of
Just p' -> pkgroot </> p'
Nothing -> p
mungeUrl p = case stripVarPrefix "${pkgrooturl}" p of
Just p' -> toUrlPath pkgroot p'
Nothing -> p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath (r : FilePath.splitDirectories p)
stripVarPrefix var p =
case splitPath p of
(root:path') -> case stripPrefix var root of
Just [sep] | isPathSeparator sep -> Just (joinPath path')
_ -> Nothing
_ -> Nothing
-- Older installed package info files did not have the installedPackageId
-- field, so if it is missing then we fill it as the source package ID.
setInstalledPackageId :: InstalledPackageInfo -> InstalledPackageInfo
setInstalledPackageId pkginfo@InstalledPackageInfo {
installedPackageId = InstalledPackageId "",
sourcePackageId = pkgid
}
= pkginfo {
--TODO use a proper named function for the conversion
-- from source package id to installed package id
installedPackageId = InstalledPackageId (display pkgid)
}
setInstalledPackageId pkginfo = pkginfo
-- | Call @hc-pkg@ to get the source package Id of all the packages in the
-- given package database.
--
-- This is much less information than with 'dump', but also rather quicker.
-- Note in particular that it does not include the 'InstalledPackageId', just
-- the source 'PackageId' which is not necessarily unique in any package db.
--
list :: HcPkgInfo -> Verbosity -> PackageDB
-> IO [PackageId]
list hpi verbosity packagedb = do
output <- getProgramInvocationOutput verbosity
(listInvocation hpi verbosity packagedb)
`catchExit` \_ -> die $ programId (hcPkgProgram hpi) ++ " list failed"
case parsePackageIds output of
Just ok -> return ok
_ -> die $ "failed to parse output of '"
++ programId (hcPkgProgram hpi) ++ " list'"
where
parsePackageIds = sequence . map simpleParse . words
-- Create a view from either name or symlink via filepath.
createView :: HcPkgInfo -> Verbosity -> Either String FilePath -> IO ()
createView hpi verbosity view =
when (supportsView hpi) $ runProgramInvocation verbosity invocation
where
invocation = programInvocation (hcPkgProgram hpi) args
args = ["view", "create", packageDbOpts hpi UserPackageDB] ++
case view of
Left name -> [name]
Right path -> ["--view-file", path]
-- | Adds a package to the given view.
addPackageToView :: HcPkgInfo -> Verbosity
-> String -> InstalledPackageId -> IO ()
addPackageToView hpi verbosity view ipid = do
removePackageFromView hpi verbosity view pkgid
when (supportsView hpi) $ runProgramInvocation verbosity invocation
where
invocation = programInvocation (hcPkgProgram hpi) args
args = ["view-modify",
view, "add-package",
"--ipid", display ipid,
packageDbOpts hpi UserPackageDB]
-- init clashes with this module's init.
pkgid = List.init . reverse . snd . (span (/= '-')) . reverse $
display ipid
-- | Removes a package from the given view. As only one instance of package can
-- be in a view we do not need ipid. TODO: Fourth argument type must be
-- PackageId but there is no suitable InstalledPackageId to PackageId function
-- now.
removePackageFromView :: HcPkgInfo -> Verbosity
-> String -> String -> IO ()
removePackageFromView hpi verbosity view packageId =
when (supportsView hpi) $ runProgramInvocation verbosity invocation
where
invocation = programInvocation (hcPkgProgram hpi) args
args = ["view-modify",
view,
"remove-package",
packageId,
packageDbOpts hpi UserPackageDB]
-- TODO:
-- getPackagesInView -- For GC
--------------------------
-- The program invocations
--
initInvocation :: HcPkgInfo -> Verbosity -> FilePath -> ProgramInvocation
initInvocation hpi verbosity path =
programInvocation (hcPkgProgram hpi) args
where
args = ["init", path]
++ verbosityOpts hpi verbosity
registerInvocation, reregisterInvocation
:: HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath InstalledPackageInfo
-> ProgramInvocation
registerInvocation = registerInvocation' "register"
reregisterInvocation = registerInvocation' "update"
registerInvocation' :: String -> HcPkgInfo -> Verbosity -> PackageDBStack
-> Either FilePath InstalledPackageInfo
-> ProgramInvocation
registerInvocation' cmdname hpi verbosity packagedbs (Left pkgFile) =
programInvocation (hcPkgProgram hpi) args
where
args' = [cmdname, pkgFile]
++ (if noPkgDbStack hpi
then [packageDbOpts hpi (last packagedbs)]
else packageDbStackOpts hpi packagedbs)
++ verbosityOpts hpi verbosity
args = (if multInstEnabled hpi
then args' ++ ["--enable-multi-instance"]
else args')
registerInvocation' cmdname hpi verbosity packagedbs (Right pkgInfo) =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeInput = Just (showInstalledPackageInfo pkgInfo),
progInvokeInputEncoding = IOEncodingUTF8
}
where
args' = [cmdname, "-"]
++ (if noPkgDbStack hpi
then [packageDbOpts hpi (last packagedbs)]
else packageDbStackOpts hpi packagedbs)
++ verbosityOpts hpi verbosity
args = (if multInstEnabled hpi
then args' ++ ["--enable-multi-instance"]
else args')
unregisterInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
unregisterInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["unregister", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
exposeInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
exposeInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["expose", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
hideInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> PackageId
-> ProgramInvocation
hideInvocation hpi verbosity packagedb pkgid =
programInvocation (hcPkgProgram hpi) $
["hide", packageDbOpts hpi packagedb, display pkgid]
++ verbosityOpts hpi verbosity
dumpInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> ProgramInvocation
dumpInvocation hpi _verbosity packagedb =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeOutputEncoding = IOEncodingUTF8
}
where
args = ["dump", packageDbOpts hpi packagedb]
++ verbosityOpts hpi silent
-- We use verbosity level 'silent' because it is important that we
-- do not contaminate the output with info/debug messages.
listInvocation :: HcPkgInfo -> Verbosity -> PackageDB -> ProgramInvocation
listInvocation hpi _verbosity packagedb =
(programInvocation (hcPkgProgram hpi) args) {
progInvokeOutputEncoding = IOEncodingUTF8
}
where
args = ["list", "--simple-output", packageDbOpts hpi packagedb]
++ verbosityOpts hpi silent
-- We use verbosity level 'silent' because it is important that we
-- do not contaminate the output with info/debug messages.
packageDbStackOpts :: HcPkgInfo -> PackageDBStack -> [String]
packageDbStackOpts hpi dbstack = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> "--global"
: "--user"
: map specific dbs
(GlobalPackageDB:dbs) -> "--global"
: ("--no-user-" ++ packageDbFlag hpi)
: map specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = "--" ++ packageDbFlag hpi ++ "=" ++ db
specific _ = ierror
ierror :: a
ierror = error ("internal error: unexpected package db stack: " ++ show dbstack)
packageDbFlag :: HcPkgInfo -> String
packageDbFlag hpi
| flagPackageConf hpi
= "package-conf"
| otherwise
= "package-db"
packageDbOpts :: HcPkgInfo -> PackageDB -> String
packageDbOpts _ GlobalPackageDB = "--global"
packageDbOpts _ UserPackageDB = "--user"
packageDbOpts hpi (SpecificPackageDB db) = "--" ++ packageDbFlag hpi ++ "=" ++ db
verbosityOpts :: HcPkgInfo -> Verbosity -> [String]
verbosityOpts hpi v
| noVerboseFlag hpi
= []
| v >= deafening = ["-v2"]
| v == silent = ["-v0"]
| otherwise = []
|
fugyk/cabal
|
Cabal/Distribution/Simple/Program/HcPkg.hs
|
bsd-3-clause
| 16,572 | 0 | 18 | 4,230 | 3,350 | 1,788 | 1,562 | 294 | 5 |
{-# LANGUAGE NoImplicitPrelude #-}
module Jetski.Foreign.Return (
Return(..)
, storableReturn
, withReturn
, retVoid
, retInt8
, retInt16
, retInt32
, retInt64
, retWord8
, retWord16
, retWord32
, retWord64
, retFloat
, retDouble
, retCChar
, retCUChar
, retCWchar
, retCInt
, retCUInt
, retCLong
, retCULong
, retCSize
, retCTime
, retPtr
, retFunPtr
, retByteString
, retByteStringCopy
) where
import Data.Word (Word8, Word16, Word32, Word64)
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import Foreign.Marshal (alloca)
import Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)
import Foreign.Storable (Storable(..))
import Foreign.C.Types (CChar, CUChar, CWchar)
import Foreign.C.Types (CInt, CUInt, CLong, CULong)
import Foreign.C.Types (CSize, CTime)
import Jetski.Foreign.Binding
import P
import System.IO (IO)
data Return a =
Return {
returnType :: !(Ptr CType)
, returnWith :: (Ptr CValue -> IO ()) -> IO a
}
instance Functor Return where
fmap f (Return typ withPoke) =
Return typ (fmap f . withPoke)
withReturn :: (a -> IO b) -> Return a -> Return b
withReturn f (Return typ withPoke) =
Return typ (withPoke >=> f)
storableReturn :: Storable a => Ptr CType -> Return a
storableReturn typ =
Return typ $ \write ->
alloca $ \ptr -> do
write (castPtr ptr)
peek ptr
retVoid :: Return ()
retVoid =
Return ffi_type_void $ \write -> do
write nullPtr
return ()
retInt8 :: Return Int8
retInt8 =
storableReturn ffi_type_sint8
retInt16 :: Return Int16
retInt16 =
storableReturn ffi_type_sint16
retInt32 :: Return Int32
retInt32 =
storableReturn ffi_type_sint32
retInt64 :: Return Int64
retInt64 =
storableReturn ffi_type_sint64
retWord8 :: Return Word8
retWord8 =
storableReturn ffi_type_uint8
retWord16 :: Return Word16
retWord16 =
storableReturn ffi_type_uint16
retWord32 :: Return Word32
retWord32 =
storableReturn ffi_type_uint32
retWord64 :: Return Word64
retWord64 =
storableReturn ffi_type_uint64
retFloat :: Return Float
retFloat =
storableReturn ffi_type_float
retDouble :: Return Double
retDouble =
storableReturn ffi_type_double
retCChar :: Return CChar
retCChar =
storableReturn ffi_type_schar
retCUChar :: Return CUChar
retCUChar =
storableReturn ffi_type_uchar
retCWchar :: Return CWchar
retCWchar =
storableReturn ffi_type_schar
retCInt :: Return CInt
retCInt =
storableReturn ffi_type_sint
retCUInt :: Return CUInt
retCUInt =
storableReturn ffi_type_uint
retCLong :: Return CLong
retCLong =
storableReturn ffi_type_slong
retCULong :: Return CULong
retCULong =
storableReturn ffi_type_ulong
retCSize :: Return CSize
retCSize =
storableReturn ffi_type_size
retCTime :: Return CTime
retCTime =
storableReturn ffi_type_time
retFunPtr :: Return a -> Return (FunPtr a)
retFunPtr _ =
storableReturn ffi_type_pointer
retPtr :: Return a -> Return (Ptr a)
retPtr _ =
storableReturn ffi_type_pointer
retByteString :: Return B.ByteString
retByteString =
withReturn B.packCString (retPtr retCChar)
retByteStringCopy :: Return B.ByteString
retByteStringCopy =
withReturn B.unsafePackMallocCString (retPtr retCChar)
|
ambiata/jetski
|
src/Jetski/Foreign/Return.hs
|
bsd-3-clause
| 3,333 | 0 | 13 | 702 | 929 | 498 | 431 | 133 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.SMT.SMT
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Abstraction of SMT solvers
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DefaultSignatures #-}
module Data.SBV.SMT.SMT where
import qualified Control.Exception as C
import Control.Concurrent (newEmptyMVar, takeMVar, putMVar, forkIO)
import Control.DeepSeq (NFData(..))
import Control.Monad (when, zipWithM)
import Data.Char (isSpace)
import Data.Int (Int8, Int16, Int32, Int64)
import Data.List (intercalate, isPrefixOf, isInfixOf)
import Data.Word (Word8, Word16, Word32, Word64)
import System.Directory (findExecutable)
import System.Process (runInteractiveProcess, waitForProcess, terminateProcess)
import System.Exit (ExitCode(..))
import System.IO (hClose, hFlush, hPutStr, hGetContents, hGetLine)
import qualified Data.Map as M
import Data.Typeable
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.Data
import Data.SBV.BitVectors.PrettyNum
import Data.SBV.Utils.Lib (joinArgs)
import Data.SBV.Utils.TDiff
-- | Extract the final configuration from a result
resultConfig :: SMTResult -> SMTConfig
resultConfig (Unsatisfiable c) = c
resultConfig (Satisfiable c _) = c
resultConfig (Unknown c _) = c
resultConfig (ProofError c _) = c
resultConfig (TimeOut c) = c
-- | A 'prove' call results in a 'ThmResult'
newtype ThmResult = ThmResult SMTResult
-- | A 'sat' call results in a 'SatResult'
-- The reason for having a separate 'SatResult' is to have a more meaningful 'Show' instance.
newtype SatResult = SatResult SMTResult
-- | An 'allSat' call results in a 'AllSatResult'. The boolean says whether
-- we should warn the user about prefix-existentials.
newtype AllSatResult = AllSatResult (Bool, [SMTResult])
-- | User friendly way of printing theorem results
instance Show ThmResult where
show (ThmResult r) = showSMTResult "Q.E.D."
"Unknown" "Unknown. Potential counter-example:\n"
"Falsifiable" "Falsifiable. Counter-example:\n" r
-- | User friendly way of printing satisfiablity results
instance Show SatResult where
show (SatResult r) = showSMTResult "Unsatisfiable"
"Unknown" "Unknown. Potential model:\n"
"Satisfiable" "Satisfiable. Model:\n" r
-- | The Show instance of AllSatResults. Note that we have to be careful in being lazy enough
-- as the typical use case is to pull results out as they become available.
instance Show AllSatResult where
show (AllSatResult (e, xs)) = go (0::Int) xs
where uniqueWarn | e = " (Unique up to prefix existentials.)"
| True = ""
go c (s:ss) = let c' = c+1
(ok, o) = sh c' s
in c' `seq` if ok then o ++ "\n" ++ go c' ss else o
go c [] = case c of
0 -> "No solutions found."
1 -> "This is the only solution." ++ uniqueWarn
_ -> "Found " ++ show c ++ " different solutions." ++ uniqueWarn
sh i c = (ok, showSMTResult "Unsatisfiable"
"Unknown" "Unknown. Potential model:\n"
("Solution #" ++ show i ++ ":\n[Backend solver returned no assignment to variables.]") ("Solution #" ++ show i ++ ":\n") c)
where ok = case c of
Satisfiable{} -> True
_ -> False
-- | The result of an 'sAssert' call
data SafeResult = SafeNeverFails
| SafeAlwaysFails String
| SafeFailsInModel String SMTConfig SMTModel
deriving Typeable
-- | The show instance for SafeResult. Note that this is for display purposes only,
-- user programs are likely to pattern match on the output and proceed accordingly.
instance Show SafeResult where
show SafeNeverFails = "No safety violations detected."
show (SafeAlwaysFails s) = intercalate "\n" ["Assertion failure: " ++ show s, "*** Fails in all assignments to inputs"]
show (SafeFailsInModel s cfg md) = intercalate "\n" ["Assertion failure: " ++ show s, showModel cfg md]
-- | If a 'prove' or 'sat' call comes accross an 'sAssert' call that fails, they will throw a 'SafeResult' as an exception.
instance C.Exception SafeResult
-- | Instances of 'SatModel' can be automatically extracted from models returned by the
-- solvers. The idea is that the sbv infrastructure provides a stream of 'CW''s (constant-words)
-- coming from the solver, and the type @a@ is interpreted based on these constants. Many typical
-- instances are already provided, so new instances can be declared with relative ease.
--
-- Minimum complete definition: 'parseCWs'
class SatModel a where
-- | Given a sequence of constant-words, extract one instance of the type @a@, returning
-- the remaining elements untouched. If the next element is not what's expected for this
-- type you should return 'Nothing'
parseCWs :: [CW] -> Maybe (a, [CW])
-- | Given a parsed model instance, transform it using @f@, and return the result.
-- The default definition for this method should be sufficient in most use cases.
cvtModel :: (a -> Maybe b) -> Maybe (a, [CW]) -> Maybe (b, [CW])
cvtModel f x = x >>= \(a, r) -> f a >>= \b -> return (b, r)
default parseCWs :: Read a => [CW] -> Maybe (a, [CW])
parseCWs (CW _ (CWUserSort (_, s)) : r) = Just (read s, r)
parseCWs _ = Nothing
-- | Parse a signed/sized value from a sequence of CWs
genParse :: Integral a => Kind -> [CW] -> Maybe (a, [CW])
genParse k (x@(CW _ (CWInteger i)):r) | kindOf x == k = Just (fromIntegral i, r)
genParse _ _ = Nothing
-- | Base case for 'SatModel' at unit type. Comes in handy if there are no real variables.
instance SatModel () where
parseCWs xs = return ((), xs)
-- | 'Bool' as extracted from a model
instance SatModel Bool where
parseCWs xs = do (x, r) <- genParse KBool xs
return ((x :: Integer) /= 0, r)
-- | 'Word8' as extracted from a model
instance SatModel Word8 where
parseCWs = genParse (KBounded False 8)
-- | 'Int8' as extracted from a model
instance SatModel Int8 where
parseCWs = genParse (KBounded True 8)
-- | 'Word16' as extracted from a model
instance SatModel Word16 where
parseCWs = genParse (KBounded False 16)
-- | 'Int16' as extracted from a model
instance SatModel Int16 where
parseCWs = genParse (KBounded True 16)
-- | 'Word32' as extracted from a model
instance SatModel Word32 where
parseCWs = genParse (KBounded False 32)
-- | 'Int32' as extracted from a model
instance SatModel Int32 where
parseCWs = genParse (KBounded True 32)
-- | 'Word64' as extracted from a model
instance SatModel Word64 where
parseCWs = genParse (KBounded False 64)
-- | 'Int64' as extracted from a model
instance SatModel Int64 where
parseCWs = genParse (KBounded True 64)
-- | 'Integer' as extracted from a model
instance SatModel Integer where
parseCWs = genParse KUnbounded
-- | 'AlgReal' as extracted from a model
instance SatModel AlgReal where
parseCWs (CW KReal (CWAlgReal i) : r) = Just (i, r)
parseCWs _ = Nothing
-- | 'Float' as extracted from a model
instance SatModel Float where
parseCWs (CW KFloat (CWFloat i) : r) = Just (i, r)
parseCWs _ = Nothing
-- | 'Double' as extracted from a model
instance SatModel Double where
parseCWs (CW KDouble (CWDouble i) : r) = Just (i, r)
parseCWs _ = Nothing
-- | 'CW' as extracted from a model; trivial definition
instance SatModel CW where
parseCWs (cw : r) = Just (cw, r)
parseCWs [] = Nothing
-- | A rounding mode, extracted from a model. (Default definition suffices)
instance SatModel RoundingMode
-- | A list of values as extracted from a model. When reading a list, we
-- go as long as we can (maximal-munch). Note that this never fails, as
-- we can always return the empty list!
instance SatModel a => SatModel [a] where
parseCWs [] = Just ([], [])
parseCWs xs = case parseCWs xs of
Just (a, ys) -> case parseCWs ys of
Just (as, zs) -> Just (a:as, zs)
Nothing -> Just ([], ys)
Nothing -> Just ([], xs)
-- | Tuples extracted from a model
instance (SatModel a, SatModel b) => SatModel (a, b) where
parseCWs as = do (a, bs) <- parseCWs as
(b, cs) <- parseCWs bs
return ((a, b), cs)
-- | 3-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c) => SatModel (a, b, c) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c), ds) <- parseCWs bs
return ((a, b, c), ds)
-- | 4-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d) => SatModel (a, b, c, d) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d), es) <- parseCWs bs
return ((a, b, c, d), es)
-- | 5-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d, SatModel e) => SatModel (a, b, c, d, e) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d, e), fs) <- parseCWs bs
return ((a, b, c, d, e), fs)
-- | 6-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d, SatModel e, SatModel f) => SatModel (a, b, c, d, e, f) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d, e, f), gs) <- parseCWs bs
return ((a, b, c, d, e, f), gs)
-- | 7-Tuples extracted from a model
instance (SatModel a, SatModel b, SatModel c, SatModel d, SatModel e, SatModel f, SatModel g) => SatModel (a, b, c, d, e, f, g) where
parseCWs as = do (a, bs) <- parseCWs as
((b, c, d, e, f, g), hs) <- parseCWs bs
return ((a, b, c, d, e, f, g), hs)
-- | Various SMT results that we can extract models out of.
class Modelable a where
-- | Is there a model?
modelExists :: a -> Bool
-- | Extract a model, the result is a tuple where the first argument (if True)
-- indicates whether the model was "probable". (i.e., if the solver returned unknown.)
getModel :: SatModel b => a -> Either String (Bool, b)
-- | Extract a model dictionary. Extract a dictionary mapping the variables to
-- their respective values as returned by the SMT solver. Also see `getModelDictionaries`.
getModelDictionary :: a -> M.Map String CW
-- | Extract a model value for a given element. Also see `getModelValues`.
getModelValue :: SymWord b => String -> a -> Maybe b
getModelValue v r = fromCW `fmap` (v `M.lookup` getModelDictionary r)
-- | Extract a representative name for the model value of an uninterpreted kind.
-- This is supposed to correspond to the value as computed internally by the
-- SMT solver; and is unportable from solver to solver. Also see `getModelUninterpretedValues`.
getModelUninterpretedValue :: String -> a -> Maybe String
getModelUninterpretedValue v r = case v `M.lookup` getModelDictionary r of
Just (CW _ (CWUserSort (_, s))) -> Just s
_ -> Nothing
-- | A simpler variant of 'getModel' to get a model out without the fuss.
extractModel :: SatModel b => a -> Maybe b
extractModel a = case getModel a of
Right (_, b) -> Just b
_ -> Nothing
-- | Return all the models from an 'allSat' call, similar to 'extractModel' but
-- is suitable for the case of multiple results.
extractModels :: SatModel a => AllSatResult -> [a]
extractModels (AllSatResult (_, xs)) = [ms | Right (_, ms) <- map getModel xs]
-- | Get dictionaries from an all-sat call. Similar to `getModelDictionary`.
getModelDictionaries :: AllSatResult -> [M.Map String CW]
getModelDictionaries (AllSatResult (_, xs)) = map getModelDictionary xs
-- | Extract value of a variable from an all-sat call. Similar to `getModelValue`.
getModelValues :: SymWord b => String -> AllSatResult -> [Maybe b]
getModelValues s (AllSatResult (_, xs)) = map (s `getModelValue`) xs
-- | Extract value of an uninterpreted variable from an all-sat call. Similar to `getModelUninterpretedValue`.
getModelUninterpretedValues :: String -> AllSatResult -> [Maybe String]
getModelUninterpretedValues s (AllSatResult (_, xs)) = map (s `getModelUninterpretedValue`) xs
-- | 'ThmResult' as a generic model provider
instance Modelable ThmResult where
getModel (ThmResult r) = getModel r
modelExists (ThmResult r) = modelExists r
getModelDictionary (ThmResult r) = getModelDictionary r
-- | 'SatResult' as a generic model provider
instance Modelable SatResult where
getModel (SatResult r) = getModel r
modelExists (SatResult r) = modelExists r
getModelDictionary (SatResult r) = getModelDictionary r
-- | 'SMTResult' as a generic model provider
instance Modelable SMTResult where
getModel (Unsatisfiable _) = Left "SBV.getModel: Unsatisfiable result"
getModel (Unknown _ m) = Right (True, parseModelOut m)
getModel (ProofError _ s) = error $ unlines $ "Backend solver complains: " : s
getModel (TimeOut _) = Left "Timeout"
getModel (Satisfiable _ m) = Right (False, parseModelOut m)
modelExists (Satisfiable{}) = True
modelExists (Unknown{}) = False -- don't risk it
modelExists _ = False
getModelDictionary (Unsatisfiable _) = M.empty
getModelDictionary (Unknown _ m) = M.fromList (modelAssocs m)
getModelDictionary (ProofError _ _) = M.empty
getModelDictionary (TimeOut _) = M.empty
getModelDictionary (Satisfiable _ m) = M.fromList (modelAssocs m)
-- | Extract a model out, will throw error if parsing is unsuccessful
parseModelOut :: SatModel a => SMTModel -> a
parseModelOut m = case parseCWs [c | (_, c) <- modelAssocs m] of
Just (x, []) -> x
Just (_, ys) -> error $ "SBV.getModel: Partially constructed model; remaining elements: " ++ show ys
Nothing -> error $ "SBV.getModel: Cannot construct a model from: " ++ show m
-- | Given an 'allSat' call, we typically want to iterate over it and print the results in sequence. The
-- 'displayModels' function automates this task by calling 'disp' on each result, consecutively. The first
-- 'Int' argument to 'disp' 'is the current model number. The second argument is a tuple, where the first
-- element indicates whether the model is alleged (i.e., if the solver is not sure, returing Unknown)
displayModels :: SatModel a => (Int -> (Bool, a) -> IO ()) -> AllSatResult -> IO Int
displayModels disp (AllSatResult (_, ms)) = do
inds <- zipWithM display [a | Right a <- map (getModel . SatResult) ms] [(1::Int)..]
return $ last (0:inds)
where display r i = disp i r >> return i
-- | Show an SMTResult; generic version
showSMTResult :: String -> String -> String -> String -> String -> SMTResult -> String
showSMTResult unsatMsg unkMsg unkMsgModel satMsg satMsgModel result = case result of
Unsatisfiable _ -> unsatMsg
Satisfiable _ (SMTModel [] [] []) -> satMsg
Satisfiable _ m -> satMsgModel ++ showModel cfg m
Unknown _ (SMTModel [] [] []) -> unkMsg
Unknown _ m -> unkMsgModel ++ showModel cfg m
ProofError _ [] -> "*** An error occurred. No additional information available. Try running in verbose mode"
ProofError _ ls -> "*** An error occurred.\n" ++ intercalate "\n" (map ("*** " ++) ls)
TimeOut _ -> "*** Timeout"
where cfg = resultConfig result
-- | Show a model in human readable form
showModel :: SMTConfig -> SMTModel -> String
showModel cfg m = intercalate "\n" (map shM assocs ++ concatMap shUI uninterps ++ concatMap shUA arrs)
where assocs = modelAssocs m
uninterps = modelUninterps m
arrs = modelArrays m
shM (s, v) = " " ++ s ++ " = " ++ shCW cfg v
-- | Show a constant value, in the user-specified base
shCW :: SMTConfig -> CW -> String
shCW = sh . printBase
where sh 2 = binS
sh 10 = show
sh 16 = hexS
sh n = \w -> show w ++ " -- Ignoring unsupported printBase " ++ show n ++ ", use 2, 10, or 16."
-- | Print uninterpreted function values from models. Very, very crude..
shUI :: (String, [String]) -> [String]
shUI (flong, cases) = (" -- uninterpreted: " ++ f) : map shC cases
where tf = dropWhile (/= '_') flong
f = if null tf then flong else tail tf
shC s = " " ++ s
-- | Print uninterpreted array values from models. Very, very crude..
shUA :: (String, [String]) -> [String]
shUA (f, cases) = (" -- array: " ++ f) : map shC cases
where shC s = " " ++ s
-- | Helper function to spin off to an SMT solver.
pipeProcess :: SMTConfig -> String -> [String] -> SMTScript -> (String -> String) -> IO (Either String [String])
pipeProcess cfg execName opts script cleanErrs = do
let nm = show (name (solver cfg))
mbExecPath <- findExecutable execName
case mbExecPath of
Nothing -> return $ Left $ "Unable to locate executable for " ++ nm
++ "\nExecutable specified: " ++ show execName
Just execPath ->
do solverResult <- dispatchSolver cfg execPath opts script
case solverResult of
Left s -> return $ Left s
Right (ec, contents, allErrors) ->
let errors = dropWhile isSpace (cleanErrs allErrors)
in case (null errors, xformExitCode (solver cfg) ec) of
(True, ExitSuccess) -> return $ Right $ map clean (filter (not . null) (lines contents))
(_, ec') -> let errors' = if null errors
then (if null (dropWhile isSpace contents)
then "(No error message printed on stderr by the executable.)"
else contents)
else errors
finalEC = case (ec', ec) of
(ExitFailure n, _) -> n
(_, ExitFailure n) -> n
_ -> 0 -- can happen if ExitSuccess but there is output on stderr
in return $ Left $ "Failed to complete the call to " ++ nm
++ "\nExecutable : " ++ show execPath
++ "\nOptions : " ++ joinArgs opts
++ "\nExit code : " ++ show finalEC
++ "\nSolver output: "
++ "\n" ++ line ++ "\n"
++ intercalate "\n" (filter (not . null) (lines errors'))
++ "\n" ++ line
++ "\nGiving up.."
where clean = reverse . dropWhile isSpace . reverse . dropWhile isSpace
line = replicate 78 '='
-- | A standard solver interface. If the solver is SMT-Lib compliant, then this function should suffice in
-- communicating with it.
standardSolver :: SMTConfig -> SMTScript -> (String -> String) -> ([String] -> a) -> ([String] -> a) -> IO a
standardSolver config script cleanErrs failure success = do
let msg = when (verbose config) . putStrLn . ("** " ++)
smtSolver= solver config
exec = executable smtSolver
opts = options smtSolver
isTiming = timing config
nmSolver = show (name smtSolver)
msg $ "Calling: " ++ show (unwords (exec:[joinArgs opts]))
case smtFile config of
Nothing -> return ()
Just f -> do msg $ "Saving the generated script in file: " ++ show f
writeFile f (scriptBody script)
contents <- timeIf isTiming nmSolver $ pipeProcess config exec opts script cleanErrs
msg $ nmSolver ++ " output:\n" ++ either id (intercalate "\n") contents
case contents of
Left e -> return $ failure (lines e)
Right xs -> return $ success (mergeSExpr xs)
-- | Wrap the solver call to protect against any exceptions
dispatchSolver :: SMTConfig -> FilePath -> [String] -> SMTScript -> IO (Either String (ExitCode, String, String))
dispatchSolver cfg execPath opts script = rnf script `seq` (Right `fmap` runSolver cfg execPath opts script) `C.catch` (\(e::C.SomeException) -> bad (show e))
where bad s = return $ Left $ unlines [ "Failed to start the external solver: " ++ s
, "Make sure you can start " ++ show execPath
, "from the command line without issues."
]
-- | A variant of 'readProcessWithExitCode'; except it knows about continuation strings
-- and can speak SMT-Lib2 (just a little).
runSolver :: SMTConfig -> FilePath -> [String] -> SMTScript -> IO (ExitCode, String, String)
runSolver cfg execPath opts script
= do (send, ask, cleanUp, pid) <- do
(inh, outh, errh, pid) <- runInteractiveProcess execPath opts Nothing Nothing
let send l = hPutStr inh (l ++ "\n") >> hFlush inh
recv = hGetLine outh
ask l = send l >> recv
cleanUp response
= do hClose inh
outMVar <- newEmptyMVar
out <- hGetContents outh
_ <- forkIO $ C.evaluate (length out) >> putMVar outMVar ()
err <- hGetContents errh
_ <- forkIO $ C.evaluate (length err) >> putMVar outMVar ()
takeMVar outMVar
takeMVar outMVar
hClose outh
hClose errh
ex <- waitForProcess pid
return $ case response of
Nothing -> (ex, out, err)
Just (r, vals) -> -- if the status is unknown, prepare for the possibility of not having a model
-- TBD: This is rather crude and potentially Z3 specific
let finalOut = intercalate "\n" (r : vals)
notAvail = "model is not available" `isInfixOf` (finalOut ++ out ++ err)
in if "unknown" `isPrefixOf` r && notAvail
then (ExitSuccess, "unknown" , "")
else (ex, finalOut ++ "\n" ++ out, err)
return (send, ask, cleanUp, pid)
let executeSolver = do mapM_ send (lines (scriptBody script))
response <- case scriptModel script of
Nothing -> do send $ satCmd cfg
return Nothing
Just ls -> do r <- ask $ satCmd cfg
vals <- if any (`isPrefixOf` r) ["sat", "unknown"]
then do let mls = lines ls
when (verbose cfg) $ do putStrLn "** Sending the following model extraction commands:"
mapM_ putStrLn mls
mapM ask mls
else return []
return $ Just (r, vals)
cleanUp response
executeSolver `C.onException` terminateProcess pid
-- | In case the SMT-Lib solver returns a response over multiple lines, compress them so we have
-- each S-Expression spanning only a single line. We'll ignore things line parentheses inside quotes
-- etc., as it should not be an issue
mergeSExpr :: [String] -> [String]
mergeSExpr [] = []
mergeSExpr (x:xs)
| d == 0 = x : mergeSExpr xs
| True = let (f, r) = grab d xs in unwords (x:f) : mergeSExpr r
where d = parenDiff x
parenDiff :: String -> Int
parenDiff = go 0
where go i "" = i
go i ('(':cs) = let i'= i+1 in i' `seq` go i' cs
go i (')':cs) = let i'= i-1 in i' `seq` go i' cs
go i (_ :cs) = go i cs
grab i ls
| i <= 0 = ([], ls)
grab _ [] = ([], [])
grab i (l:ls) = let (a, b) = grab (i+parenDiff l) ls in (l:a, b)
|
Copilot-Language/sbv-for-copilot
|
Data/SBV/SMT/SMT.hs
|
bsd-3-clause
| 26,491 | 0 | 38 | 9,209 | 6,396 | 3,353 | 3,043 | 344 | 8 |
{-
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0
Kubernetes API version: v1.9.12
Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
-}
{-|
Module : Kubernetes.OpenAPI.API.Events
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-}
module Kubernetes.OpenAPI.API.Events where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
-- * Operations
-- ** Events
-- *** getAPIGroup
-- | @GET \/apis\/events.k8s.io\/@
--
-- get information of a group
--
-- AuthMethod: 'AuthApiKeyBearerToken'
--
getAPIGroup
:: Accept accept -- ^ request accept ('MimeType')
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/events.k8s.io/"]
`_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken)
data GetAPIGroup
-- | @application/json@
instance Consumes GetAPIGroup MimeJSON
-- | @application/yaml@
instance Consumes GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Consumes GetAPIGroup MimeVndKubernetesProtobuf
-- | @application/json@
instance Produces GetAPIGroup MimeJSON
-- | @application/yaml@
instance Produces GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Produces GetAPIGroup MimeVndKubernetesProtobuf
|
denibertovic/haskell
|
kubernetes/lib/Kubernetes/OpenAPI/API/Events.hs
|
bsd-3-clause
| 2,712 | 0 | 8 | 331 | 484 | 333 | 151 | -1 | -1 |
module ELc.Arbitrary where
import Language.ELc
import Lc.Arbitrary
import Test.QuickCheck
--------------------------------------------------------------
-- QuickCheck - Arbitratry
--------------------------------------------------------------
instance Arbitrary ELc where
arbitrary = arbitraryELc
instance Arbitrary Let where
arbitrary = arbitraryLet
arbitraryELc :: Gen ELc
arbitraryELc = oneof [ELcLet <$> arbitraryLet, ELc <$> arbitrary]
arbitraryLet :: Gen Let
arbitraryLet = Let <$> string <*> arbitrary
|
d-dorazio/lc
|
test/ELc/Arbitrary.hs
|
bsd-3-clause
| 522 | 0 | 7 | 66 | 101 | 57 | 44 | 12 | 1 |
{-# LANGUAGE BangPatterns #-}
module Scrabble (makeDict,process,validHand,prettySC
,ScrabbleCommand(..),Sort(..),Dict,FilePath,Score) where
import Data.Array.Unboxed((!))
import Data.Ix(inRange)
import Data.List(group,sort)
import Data.Char(toUpper)
import Tiles(freqArray)
import Dict(Dict,build)
import Lookup(HandTiles(..),Hist(..),Score,lookupTiles,withTemplate,withTemplates)
--import Best(best)
import Control.OldException(catchJust,ioErrors)
import Data.List(sortBy)
hist :: [Int] -> Hist -- [(Int,Int)]
hist = Hist . map hist' . group . sort
where hist' xs = (head xs, length xs)
makeDict :: FilePath -> IO (Either String Dict)
makeDict file = catchJust ioErrors
(fmap (Right . build . lines) (readFile file))
(\e -> return (Left (show e)))
data Sort = Sort {iMethod :: Int, bReversed :: Bool} deriving Show
sortMethod :: Sort -> [(Score,String)] -> [(Score,String)]
sortMethod (Sort 1 False) = sortBy (flip compare)
sortMethod (Sort 1 True) = sort
sortMethod (Sort 2 False) = sortBy (flip compare `on` (length . snd))
sortMethod (Sort 2 True) = sortBy (compare `on` (length . snd))
sortMethod (Sort 3 False) = sortBy (compare `on` snd)
sortMethod (Sort 3 True) = sortBy (flip compare `on` snd)
sortMethod err = error $ "Scrabble.sortMethod failed "++show err
data ScrabbleCommand = LookupCommand {sTiles :: String, getSort :: Sort}
| TemplateCommand {sTiles :: String, sTemplate :: String, getSort :: Sort}
| TemplatesCommand {sTiles :: String, sTemplate :: String, getSort :: Sort}
deriving Show
prettySC :: ScrabbleCommand -> Score -> String
prettySC (LookupCommand {sTiles=hand}) bestScore = (show bestScore) ++ " " ++ hand
prettySC (TemplateCommand {sTiles=hand,sTemplate=template}) bestScore = (show bestScore) ++ " " ++ hand ++ " " ++ template
prettySC (TemplatesCommand {sTiles=hand,sTemplate=template}) bestScore = (show bestScore) ++ " " ++ hand ++ " " ++ template
parseTiles :: String -> HandTiles
--parseTiles :: String -> (Int, [(Int,Int)], Int)
parseTiles tiles = HandTiles wilds h (length tiles)
where wilds = length (filter (dot ==) tiles)
h = hist . map fromEnum . map toUpper . filter (dot /=) $ tiles
dot = '.'
-- Returns sorted (and perhaps limited) results
process :: Dict -> ScrabbleCommand -> [(Score,String)]
process t command = post . sortMethod (getSort command) $ results where
hand = parseTiles (sTiles command)
post | validHand hand = id
| otherwise = take 100
results = case command of
LookupCommand {} -> lookupTiles t hand
TemplateCommand {} -> withTemplate t hand (sTemplate command)
TemplatesCommand {} -> withTemplates t hand (sTemplate command)
on :: (b->b->c) -> (a->b) -> (a -> a -> c)
f `on` g = (\a b -> (g a) `f` (g b))
validHand :: HandTiles -> Bool
validHand (HandTiles wilds (Hist h) n) = inRange (0,2) wilds && inRange (1,7) n && and (map validCharFreq h)
where validCharFreq (c,f) = inRange (1,freqArray ! c) f
|
ChrisKuklewicz/XWords
|
src/Scrabble.hs
|
bsd-3-clause
| 3,074 | 0 | 12 | 632 | 1,208 | 664 | 544 | 55 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module CryptoTest (tests, cbTests) where
import System.IO
import System.IO.Temp
import System.Posix.IO
import Control.Monad (liftM, when)
import Control.Monad.Trans.Maybe
import Control.Monad.IO.Class
import Control.Monad.Catch
import Control.Concurrent
import Data.List (isInfixOf)
import Data.ByteString.Char8 ()
import Data.Maybe ( fromJust )
import qualified Data.ByteString as BS
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase)
import Test.Tasty.QuickCheck
import Test.HUnit hiding (assert)
import Test.QuickCheck.Monadic
import Crypto.Gpgme
import Crypto.Gpgme.Types ( GpgmeError (GpgmeError)
, SignMode ( Clear, Detach, Normal )
)
import TestUtil
tests :: TestTree
tests = testGroup "crypto"
[ testProperty "bob_encrypt_for_alice_decrypt_prompt_no_travis"
$ bob_encrypt_for_alice_decrypt False
, testProperty "bob_encrypt_sign_for_alice_decrypt_verify_prompt_no_travis"
$ bob_encrypt_sign_for_alice_decrypt_verify False
, testProperty "bob_encrypt_for_alice_decrypt_short_prompt_no_travis"
bob_encrypt_for_alice_decrypt_short
, testProperty "bob_encrypt_sign_for_alice_decrypt_verify_short_prompt_no_travis"
bob_encrypt_sign_for_alice_decrypt_verify_short
, testCase "decrypt_garbage" decrypt_garbage
, testCase "encrypt_wrong_key" encrypt_wrong_key
, testCase "bob_encrypt_symmetrically_prompt_no_travis" bob_encrypt_symmetrically
, testCase "bob_detach_sign_and_verify_specify_key_prompt_no_travis" bob_detach_sign_and_verify_specify_key_prompt
, testCase "bob_clear_sign_and_verify_specify_key_prompt_no_travis" bob_clear_sign_and_verify_specify_key_prompt
, testCase "bob_clear_sign_and_verify_default_key_prompt_no_travis" bob_clear_sign_and_verify_default_key_prompt
, testCase "bob_normal_sign_and_verify_specify_key_prompt_no_travis" bob_normal_sign_and_verify_specify_key_prompt
, testCase "bob_normal_sign_and_verify_default_key_prompt_no_travis" bob_normal_sign_and_verify_default_key_prompt
, testCase "encrypt_file_no_travis" encrypt_file
, testCase "encrypt_stream_no_travis" encrypt_stream
]
cbTests :: IO TestTree
cbTests = do
supported <- withCtx "test/bob" "C" OpenPGP $ \ctx ->
return $ isPassphraseCbSupported ctx
if supported
then return $ testGroup "passphrase-cb"
[ testProperty "bob_encrypt_for_alice_decrypt"
$ bob_encrypt_for_alice_decrypt True
, testProperty "bob_encrypt_sign_for_alice_decrypt_verify_with_passphrase_cb_prompt_no_travis"
$ bob_encrypt_sign_for_alice_decrypt_verify True
]
else return $ testGroup "passphrase-cb" []
hush :: Monad m => m (Either e a) -> MaybeT m a
hush = MaybeT . liftM (either (const Nothing) Just)
withPassphraseCb :: String -> Ctx -> IO ()
withPassphraseCb passphrase ctx = do
setPassphraseCallback ctx (Just callback)
where
callback _ _ _ = return (Just passphrase)
bob_encrypt_for_alice_decrypt :: Bool -> Plain -> Property
bob_encrypt_for_alice_decrypt passphrCb plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
Just enc <- withCtx "test/bob" "C" OpenPGP $ \bCtx -> runMaybeT $ do
aPubKey <- MaybeT $ getKey bCtx alice_pub_fpr NoSecret
hush $ encrypt bCtx [aPubKey] NoFlag plain
-- decrypt
dec <- withCtx "test/alice" "C" OpenPGP $ \aCtx -> do
when passphrCb $ withPassphraseCb "alice123" aCtx
decrypt aCtx enc
return $ fromRight dec
bob_encrypt_for_alice_decrypt_short :: Plain -> Property
bob_encrypt_for_alice_decrypt_short plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
enc <- encrypt' "test/bob" alice_pub_fpr plain
-- decrypt
dec <- decrypt' "test/alice" (fromRight enc)
return $ fromRight dec
bob_encrypt_sign_for_alice_decrypt_verify :: Bool -> Plain -> Property
bob_encrypt_sign_for_alice_decrypt_verify passphrCb plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
Just enc <- withCtx "test/bob" "C" OpenPGP $ \bCtx -> runMaybeT $ do
aPubKey <- MaybeT $ getKey bCtx alice_pub_fpr NoSecret
hush $ encryptSign bCtx [aPubKey] NoFlag plain
-- decrypt
dec <- withCtx "test/alice" "C" OpenPGP $ \aCtx -> do
when passphrCb $ withPassphraseCb "alice123" aCtx
decryptVerify aCtx enc
return $ fromRight dec
bob_encrypt_sign_for_alice_decrypt_verify_short :: Plain -> Property
bob_encrypt_sign_for_alice_decrypt_verify_short plain =
not (BS.null plain) ==> monadicIO $ do
dec <- run encr_and_decr
assert $ dec == plain
where encr_and_decr =
do -- encrypt
enc <- encryptSign' "test/bob" alice_pub_fpr plain
-- decrypt
dec <- decryptVerify' "test/alice" (fromRight enc)
return $ fromRight dec
encrypt_wrong_key :: Assertion
encrypt_wrong_key = do
res <- encrypt' "test/bob" "INEXISTENT" "plaintext"
assertBool "should fail" (isLeft res)
let err = fromLeft res
assertBool "should contain key" ("INEXISTENT" `isInfixOf` err)
decrypt_garbage :: Assertion
decrypt_garbage = do
val <- withCtx "test/bob" "C" OpenPGP $ \bCtx ->
decrypt bCtx (BS.pack [1,2,3,4,5,6])
isLeft val @? "should be left " ++ show val
bob_encrypt_symmetrically :: Assertion
bob_encrypt_symmetrically = do
-- encrypt
cipher <- fmap fromRight $
withCtx "test/bob" "C" OpenPGP $ \ctx ->
encrypt ctx [] NoFlag "plaintext"
assertBool "must not be plain" (cipher /= "plaintext")
-- decrypt
plain <- fmap fromRight $
withCtx "test/alice" "C" OpenPGP $ \ctx ->
decrypt ctx cipher
assertEqual "should decrypt to same" "plaintext" plain
bob_detach_sign_and_verify_specify_key_prompt :: Assertion
bob_detach_sign_and_verify_specify_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
key <- getKey ctx bob_pub_fpr NoSecret
let msgToSign = "Clear text message from bob!!"
resSign <-sign ctx [(fromJust key)] Detach msgToSign
verifyDetached ctx (fromRight resSign) msgToSign
assertBool "Could not verify bob's signature was correct" $ isVerifyDetachValid resVerify
bob_clear_sign_and_verify_specify_key_prompt :: Assertion
bob_clear_sign_and_verify_specify_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
key <- getKey ctx bob_pub_fpr NoSecret
resSign <- sign ctx [(fromJust key)] Clear "Clear text message from bob specifying signing key"
verifyPlain ctx (fromRight resSign) ""
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
bob_clear_sign_and_verify_default_key_prompt :: Assertion
bob_clear_sign_and_verify_default_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
resSign <- sign ctx [] Clear "Clear text message from bob with default key"
verifyPlain ctx (fromRight resSign) ""
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
bob_normal_sign_and_verify_specify_key_prompt :: Assertion
bob_normal_sign_and_verify_specify_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
key <- getKey ctx bob_pub_fpr NoSecret
resSign <- sign ctx [(fromJust key)] Normal "Normal text message from bob specifying signing key"
verify ctx (fromRight resSign)
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
bob_normal_sign_and_verify_default_key_prompt :: Assertion
bob_normal_sign_and_verify_default_key_prompt = do
resVerify <- withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
resSign <- sign ctx [] Normal "Normal text message from bob with default key"
verify ctx (fromRight resSign)
assertBool "Could not verify bob's signature was correct" $ isVerifyValid resVerify
encrypt_file :: Assertion
encrypt_file =
withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
withPassphraseCb "bob123" ctx
withTestTmpFiles $ \pp ph cp ch dp dh -> do
plainFd <- handleToFd ph
cipherFd <- handleToFd ch
decryptedFd <- handleToFd dh
key <- getKey ctx bob_pub_fpr NoSecret
-- Add plaintext content
writeFile pp "Plaintext contents. 1234go!"
-- Encrypt plaintext
resEnc <- encryptFd ctx [(fromJust key)] NoFlag plainFd cipherFd
if (resEnc == Right ())
then return ()
else assertFailure $ show resEnc
-- Recreate the cipher FD because it is closed (or something) from the encrypt command
cipherHandle' <- openFile cp ReadWriteMode
cipherFd' <- handleToFd cipherHandle'
-- Decrypt ciphertext
resDec <- decryptFd ctx cipherFd' decryptedFd
if (resDec == Right ())
then return ()
else assertFailure $ show resDec
-- Compare plaintext and decrypted text
plaintext <- readFile pp
decryptedtext <- readFile dp
plaintext @=? decryptedtext
-- Encrypt from FD pipe into a FD file
encrypt_stream :: Assertion
encrypt_stream =
withCtx "test/bob/" "C" OpenPGP $ \ctx -> do
withPassphraseCb "bob123" ctx
withTestTmpFiles $ \_ _ cp ch dp dh -> do
cipherFd <- handleToFd ch
decryptedFd <- handleToFd dh
-- Use bob's key
key <- getKey ctx bob_pub_fpr NoSecret
-- Create pipe
(pipeRead, pipeWrite) <- createPipe
-- Write to pipe
-- Add plaintext content
let testString = take (1000) $ repeat '.'
_ <- forkIO $ do
threadWaitWrite pipeWrite
_ <- fdWrite pipeWrite testString
closeFd pipeWrite
-- Start encrypting in thread
_ <- forkIO $ do
threadWaitRead pipeRead
_ <- encryptFd ctx [(fromJust key)] NoFlag pipeRead cipherFd
closeFd pipeRead
-- Wait a second for threads to finish
threadDelay (1000 * 1000 * 1)
-- Check result
-- Recreate the cipher FD because it is closed (or something) from the encrypt command
threadWaitRead cipherFd
ch' <- openFile cp ReadWriteMode
cipherFd' <- handleToFd ch'
-- Decrypt ciphertext
resDec <- decryptFd ctx cipherFd' decryptedFd
if (resDec == Right ())
then return ()
else assertFailure $ show resDec
-- Compare plaintext and decrypted text
decryptedtext <-readFile dp
testString @=? decryptedtext
withTestTmpFiles :: (MonadIO m, MonadMask m)
=> ( FilePath -> Handle -- Plaintext
-> FilePath -> Handle -- Ciphertext
-> FilePath -> Handle -- Decrypted text
-> m a)
-> m a
withTestTmpFiles f =
withSystemTempFile "plain" $ \pp ph ->
withSystemTempFile "cipher" $ \cp ch ->
withSystemTempFile "decrypt" $ \dp dh ->
f pp ph cp ch dp dh
-- Verify that the signature verification is successful
isVerifyValid :: Either t ([(GpgmeError, [SignatureSummary], t1)], t2) -> Bool
isVerifyValid (Right ((v:[]), _)) = (isVerifyValid' v)
isVerifyValid (Right ((v:vs), t)) = (isVerifyValid' v) && isVerifyValid (Right (vs,t))
isVerifyValid _ = False
isVerifyValid' :: (GpgmeError, [SignatureSummary], t) -> Bool
isVerifyValid' (GpgmeError 0, [Green,Valid], _) = True
isVerifyValid' _ = False
-- Verify that the signature verification is successful for verifyDetach
isVerifyDetachValid :: Either t [(GpgmeError, [SignatureSummary], t1)] -> Bool
isVerifyDetachValid (Right ((v:[]))) = (isVerifyDetachValid' v)
isVerifyDetachValid (Right ((v:vs))) = (isVerifyDetachValid' v) && isVerifyDetachValid (Right vs)
isVerifyDetachValid _ = False
isVerifyDetachValid' :: (GpgmeError, [SignatureSummary], t) -> Bool
isVerifyDetachValid' (GpgmeError 0, [Green,Valid], _) = True
isVerifyDetachValid' _ = False
|
mmhat/h-gpgme
|
test/CryptoTest.hs
|
mit
| 12,536 | 0 | 21 | 3,024 | 2,963 | 1,470 | 1,493 | 239 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE CPP #-}
module Network.Wai.Handler.Warp.HTTP2.Worker (
Respond
, response
, worker
) where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
#endif
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception (Exception, SomeException(..), AsyncException(..))
import qualified Control.Exception as E
import Control.Monad (void, when)
import Data.Typeable
import qualified Network.HTTP.Types as H
import Network.HTTP2
import Network.HTTP2.Priority
import Network.Wai
import Network.Wai.Handler.Warp.HTTP2.EncodeFrame
import Network.Wai.Handler.Warp.HTTP2.Manager
import Network.Wai.Handler.Warp.HTTP2.Types
import Network.Wai.Handler.Warp.IORef
import Network.Wai.HTTP2
( Chunk(..)
, HTTP2Application
, PushPromise
, Responder(runResponder)
, RespondFunc
)
import qualified Network.Wai.Handler.Warp.Settings as S
import qualified Network.Wai.Handler.Warp.Timeout as T
----------------------------------------------------------------
-- | An 'HTTP2Application' takes a function of status, headers, trailers, and
-- body; this type implements that by currying some internal arguments.
--
-- The token type of the RespondFunc is set to be (). This is a bit
-- anti-climactic, but the real benefit of the token type is that the
-- application is forced to call the responder, and making it a boring type
-- doesn't break that property.
--
-- This is the argument to a 'Responder'.
type Respond = IO () -> Stream -> RespondFunc ()
-- | This function is passed to workers. They also pass responses from
-- 'HTTP2Application's to this function. This function enqueues commands for
-- the HTTP/2 sender.
response :: Context -> Manager -> ThreadContinue -> Respond
response ctx mgr tconf tickle strm s h strmbdy = do
-- TODO(awpr) HEAD requests will still stream.
-- We must not exit this WAI application.
-- If the application exits, streaming would be also closed.
-- So, this work occupies this thread.
--
-- We need to increase the number of workers.
myThreadId >>= replaceWithAction mgr
-- After this work, this thread stops to decrease the number of workers.
setThreadContinue tconf False
runStream ctx OResponse tickle strm s h strmbdy
-- | Set up a waiter thread and run the stream body with functions to enqueue
-- 'Sequence's on the stream's queue.
runStream :: Context
-> (Stream -> H.Status -> H.ResponseHeaders -> Aux -> Output)
-> Respond
runStream Context{outputQ} mkOutput tickle strm s h strmbdy = do
-- Since 'Body' is loop, we cannot control it.
-- So, let's serialize 'Builder' with a designated queue.
sq <- newTBQueueIO 10 -- fixme: hard coding: 10
tvar <- newTVarIO SyncNone
let out = mkOutput strm s h (Persist sq tvar)
-- Since we must not enqueue an empty queue to the priority
-- queue, we spawn a thread to ensure that the designated
-- queue is not empty.
void $ forkIO $ waiter tvar sq strm outputQ
atomically $ writeTVar tvar (SyncNext out)
let write chunk = do
atomically $ writeTBQueue sq $ case chunk of
BuilderChunk b -> SBuilder b
FileChunk path part -> SFile path part
tickle
flush = atomically $ writeTBQueue sq SFlush
trailers <- strmbdy write flush
atomically $ writeTBQueue sq $ SFinish trailers
-- | Handle abnormal termination of a stream: mark it as closed, send a reset
-- frame, and call the user's 'settingsOnException' handler if applicable.
cleanupStream :: Context -> S.Settings -> Stream -> Maybe Request -> Maybe SomeException -> IO ()
cleanupStream ctx@Context{outputQ} set strm req me = do
closed strm Killed ctx
let sid = streamNumber strm
frame = resetFrame InternalError sid
enqueue outputQ sid controlPriority $ OFrame frame
case me of
Nothing -> return ()
Just e -> S.settingsOnException set req e
-- | Push the given 'Responder' to the client if the settings allow it
-- (specifically 'enablePush' and 'maxConcurrentStreams'). Returns 'True' if
-- the stream was actually pushed.
--
-- This is the push function given to an 'HTTP2Application'.
pushResponder :: Context -> S.Settings -> Stream -> PushPromise -> Responder -> IO Bool
pushResponder ctx set strm promise responder = do
let Context{ http2settings
, pushConcurrency
} = ctx
cnt <- readIORef pushConcurrency
settings <- readIORef http2settings
let enabled = enablePush settings
fits = maybe True (cnt <) $ maxConcurrentStreams settings
canPush = fits && enabled
if canPush then
actuallyPushResponder ctx set strm promise responder
else
return False
-- | Set up a pushed stream and run the 'Responder' in its own thread. Waits
-- for the sender thread to handle the push request. This can fail to push the
-- stream and return 'False' if the sender dequeued the push request after the
-- associated stream was closed.
actuallyPushResponder :: Context -> S.Settings -> Stream -> PushPromise -> Responder -> IO Bool
actuallyPushResponder ctx set strm promise responder = do
let Context{ http2settings
, nextPushStreamId
, pushConcurrency
, streamTable
} = ctx
-- Claim the next outgoing stream.
newSid <- atomicModifyIORef nextPushStreamId $ \sid -> (sid+2, sid)
ws <- initialWindowSize <$> readIORef http2settings
newStrm <- newStream pushConcurrency newSid ws
-- Section 5.3.5 of RFC 7540 defines the weight of push promise is 16.
-- But we need not to follow the spec. So, this value would change
-- if necessary.
writeIORef (streamPriority newStrm) $
defaultPriority { streamDependency = streamNumber strm }
opened newStrm
insert streamTable newSid newStrm
-- Set up a channel for the sender to report back whether it pushed the
-- stream.
mvar <- newEmptyMVar
let mkOutput = OPush strm promise mvar
tickle = return ()
respond = runStream ctx mkOutput
-- TODO(awpr): synthesize a Request for 'settingsOnException'?
_ <- forkIO $ runResponder responder (respond tickle newStrm) `E.catch`
(cleanupStream ctx set strm Nothing . Just)
takeMVar mvar
data Break = Break deriving (Show, Typeable)
instance Exception Break
worker :: Context
-> S.Settings
-> T.Manager
-> HTTP2Application
-> (ThreadContinue -> Respond)
-> IO ()
worker ctx@Context{inputQ} set tm app respond = do
tid <- myThreadId
sinfo <- newStreamInfo
tcont <- newThreadContinue
let setup = T.register tm $ E.throwTo tid Break
E.bracket setup T.cancel $ go sinfo tcont
where
go sinfo tcont th = do
setThreadContinue tcont True
ex <- E.try $ do
T.pause th
Input strm req <- atomically $ readTQueue inputQ
setStreamInfo sinfo strm req
T.resume th
T.tickle th
let responder = app req $ pushResponder ctx set strm
runResponder responder $ respond tcont (T.tickle th) strm
cont1 <- case ex of
Right () -> return True
Left e@(SomeException _)
| Just Break <- E.fromException e -> do
cleanup sinfo Nothing
return True
-- killed by the sender
| Just ThreadKilled <- E.fromException e -> do
cleanup sinfo Nothing
return False
| otherwise -> do
cleanup sinfo (Just e)
return True
cont2 <- getThreadContinue tcont
when (cont1 && cont2) $ go sinfo tcont th
cleanup sinfo me = do
m <- getStreamInfo sinfo
case m of
Nothing -> return ()
Just (strm,req) -> do
cleanupStream ctx set strm (Just req) me
clearStreamInfo sinfo
-- | A dedicated waiter thread to re-enqueue the stream in the priority tree
-- whenever output becomes available. When the sender drains the queue and
-- moves on to another stream, it drops a message in the 'TVar', and this
-- thread wakes up, waits for more output to become available, and re-enqueues
-- the stream.
waiter :: TVar Sync -> TBQueue Sequence -> Stream -> PriorityTree Output -> IO ()
waiter tvar sq strm outQ = do
-- waiting for actions other than SyncNone
mx <- atomically $ do
mout <- readTVar tvar
case mout of
SyncNone -> retry
SyncNext out -> do
writeTVar tvar SyncNone
return $ Just out
SyncFinish -> return Nothing
case mx of
Nothing -> return ()
Just out -> do
-- ensuring that the streaming queue is not empty.
atomically $ do
isEmpty <- isEmptyTBQueue sq
when isEmpty retry
-- ensuring that stream window is greater than 0.
enqueueWhenWindowIsOpen outQ out
waiter tvar sq strm outQ
----------------------------------------------------------------
-- | It would nice if responders could return values to workers.
-- Unfortunately, 'ResponseReceived' is already defined in WAI 2.0.
-- It is not wise to change this type.
-- So, a reference is shared by a 'Respond' and its worker.
-- The reference refers a value of this type as a return value.
-- If 'True', the worker continue to serve requests.
-- Otherwise, the worker get finished.
newtype ThreadContinue = ThreadContinue (IORef Bool)
newThreadContinue :: IO ThreadContinue
newThreadContinue = ThreadContinue <$> newIORef True
setThreadContinue :: ThreadContinue -> Bool -> IO ()
setThreadContinue (ThreadContinue ref) x = writeIORef ref x
getThreadContinue :: ThreadContinue -> IO Bool
getThreadContinue (ThreadContinue ref) = readIORef ref
----------------------------------------------------------------
-- | The type to store enough information for 'settingsOnException'.
newtype StreamInfo = StreamInfo (IORef (Maybe (Stream,Request)))
newStreamInfo :: IO StreamInfo
newStreamInfo = StreamInfo <$> newIORef Nothing
clearStreamInfo :: StreamInfo -> IO ()
clearStreamInfo (StreamInfo ref) = writeIORef ref Nothing
setStreamInfo :: StreamInfo -> Stream -> Request -> IO ()
setStreamInfo (StreamInfo ref) strm req = writeIORef ref $ Just (strm,req)
getStreamInfo :: StreamInfo -> IO (Maybe (Stream, Request))
getStreamInfo (StreamInfo ref) = readIORef ref
|
soenkehahn/wai
|
warp/Network/Wai/Handler/Warp/HTTP2/Worker.hs
|
mit
| 10,706 | 0 | 18 | 2,680 | 2,204 | 1,110 | 1,094 | 177 | 4 |
{-|
Types used in both Events and Effects.
-}
module Urbit.Arvo.Common
( KingId(..), ServId(..)
, Json, JsonNode(..)
, Desk(..), Mime(..)
, Port(..), Turf(..)
, HttpServerConf(..), PEM(..), Key, Cert
, HttpEvent(..), Method, Header(..), ResponseHeader(..)
, ReOrg(..), reorgThroughNoun
, AmesDest(..), Ipv4(..), Ipv6(..), Patp(..), Galaxy, AmesAddress(..)
) where
import Urbit.Prelude hiding (Term)
import qualified Network.HTTP.Types.Method as H
import qualified Urbit.Ob as Ob
-- Misc Types ------------------------------------------------------------------
{-|
Domain Name in TLD order:
["org", "urbit", "dns"] -> dns.urbit.org
-}
newtype Turf = Turf { unTurf :: [Cord] }
deriving newtype (Eq, Ord, Show, ToNoun, FromNoun)
newtype KingId = KingId { unKingId :: UV }
deriving newtype (Eq, Ord, Show, Num, Real, Enum, Integral, FromNoun, ToNoun)
newtype ServId = ServId { unServId :: UV }
deriving newtype (Eq, Ord, Show, Num, Enum, Integral, Real, FromNoun, ToNoun)
-- Http Common -----------------------------------------------------------------
data Header = Header Cord Bytes
deriving (Eq, Ord, Show)
data ResponseHeader = ResponseHeader
{ statusCode :: Word
, headers :: [Header]
}
deriving (Eq, Ord, Show)
data HttpEvent
= Start ResponseHeader (Maybe File) Bool
| Continue (Maybe File) Bool
| Cancel ()
deriving (Eq, Ord, Show)
deriveNoun ''ResponseHeader
deriveNoun ''Header
deriveNoun ''HttpEvent
-- Http Requests ---------------------------------------------------------------
type Method = H.StdMethod
-- TODO Hack! Don't write instances for library types. Write them for
-- our types instead.
instance ToNoun H.StdMethod where
toNoun = toNoun . MkBytes . H.renderStdMethod
instance FromNoun H.StdMethod where
parseNoun n = named "StdMethod" $ do
MkBytes bs <- parseNoun n
case H.parseMethod bs of
Left md -> fail ("Unexpected method: " <> unpack (decodeUtf8 md))
Right m -> pure m
-- Http Server Configuration ---------------------------------------------------
newtype PEM = PEM { unPEM :: Wain }
deriving newtype (Eq, Ord, Show, ToNoun, FromNoun)
type Key = PEM
type Cert = PEM
data HttpServerConf = HttpServerConf
{ hscSecure :: Maybe (Key, Cert)
, hscProxy :: Bool
, hscLog :: Bool
, hscRedirect :: Bool
}
deriving (Eq, Ord, Show)
deriveNoun ''HttpServerConf
-- Desk and Mime ---------------------------------------------------------------
newtype Desk = Desk { unDesk :: Cord }
deriving newtype (Eq, Ord, Show, ToNoun, FromNoun)
data Mime = Mime Path File
deriving (Eq, Ord, Show)
deriveNoun ''Mime
-- Json ------------------------------------------------------------------------
type Json = Nullable JsonNode
data JsonNode
= JNA [Json]
| JNB Bool
| JNO (HoonMap Cord Json)
| JNN Knot
| JNS Cord
deriving (Eq, Ord, Show)
deriveNoun ''JsonNode
-- Ames Destinations -------------------------------------------------
newtype Patp a = Patp { unPatp :: a }
deriving newtype (Eq, Ord, Enum, Real, Integral, Num, ToNoun, FromNoun)
-- Network Port
newtype Port = Port { unPort :: Word16 }
deriving newtype (Eq, Ord, Show, Enum, Real, Integral, Num, ToNoun, FromNoun)
-- @if
newtype Ipv4 = Ipv4 { unIpv4 :: Word32 }
deriving newtype (Eq, Ord, Show, Enum, Real, Integral, Num, ToNoun, FromNoun)
-- @is
newtype Ipv6 = Ipv6 { unIpv6 :: Word128 }
deriving newtype (Eq, Ord, Show, Enum, Real, Integral, Num, ToNoun, FromNoun)
type Galaxy = Patp Word8
instance Integral a => Show (Patp a) where
show = show . Ob.renderPatp . Ob.patp . fromIntegral . unPatp
data AmesAddress
= AAIpv4 Ipv4 Port
| AAVoid Void
deriving (Eq, Ord, Show)
deriveNoun ''AmesAddress
type AmesDest = Each Galaxy (Jammed AmesAddress)
-- Path+Tagged Restructuring ---------------------------------------------------
{-|
This reorganized events and effects to be easier to parse. This is
complicated and gross, and a better way should be found!
ReOrg takes in nouns with the following shape:
[[fst snd rest] [tag val]]
And turns that into:
ReOrg fst snd tag rest val
For example,
[//behn/5 %doze ~ 9999]
Becomes:
Reorg "" "behn" "doze" ["5"] 9999
This is convenient, since we can then use our head-tag based FromNoun
and ToNoun instances.
NOTE:
Also, in the wild, I ran into this event:
[//term/1 %init]
So, I rewrite atom-events as follows:
[x y=@] -> [x [y ~]]
Which rewrites the %init example to:
[//term/1 [%init ~]]
TODO The reverse translation is not done yet.
-}
data ReOrg = ReOrg Cord Cord Cord EvilPath Noun
instance FromNoun ReOrg where
parseNoun = named "ReOrg" . \case
A _ -> expected "got atom"
C (A _) _ -> expected "empty route"
C h (A a) -> parseNoun (C h (C (A a) (A 0)))
C (C _ (A _)) (C _ _) -> expected "route is too short"
C (C f (C s p)) (C t v) -> do
fst :: Cord <- named "first-route" $ parseNoun f
snd :: Cord <- named "second-route" $ parseNoun s
pax :: EvilPath <- named "rest-of-route" $ parseNoun p
tag :: Cord <- named "tag" $ parseNoun t
val :: Noun <- pure v
pure (ReOrg fst snd tag pax val)
where
expected got = fail ("expected route+tagged; " <> got)
instance ToNoun ReOrg where
toNoun (ReOrg fst snd tag pax val) =
toNoun ((fst, snd, pax), (tag, val))
{-|
Given something parsed from a ReOrg Noun, convert that back to
a ReOrg.
This code may crash, but only if the FromNoun/ToNoun instances for
the effects are incorrect.
-}
reorgThroughNoun :: ToNoun x => (Cord, x) -> ReOrg
reorgThroughNoun =
fromNounCrash . toNoun >>> \case
(f, s, t, p, v) -> ReOrg f s t p v
where
fromNounCrash :: FromNoun a => Noun -> a
fromNounCrash =
fromNounErr >>> \case
Left err -> error (show err)
Right vl -> vl
|
jfranklin9000/urbit
|
pkg/hs/urbit-king/lib/Urbit/Arvo/Common.hs
|
mit
| 6,142 | 0 | 17 | 1,512 | 1,704 | 931 | 773 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Glacier.ListJobs
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation lists jobs for a vault, including jobs that are
-- in-progress and jobs that have recently finished.
--
-- Amazon Glacier retains recently completed jobs for a period before
-- deleting them; however, it eventually removes completed jobs. The output
-- of completed jobs can be retrieved. Retaining completed jobs for a
-- period of time after they have completed enables you to get a job output
-- in the event you miss the job completion notification or your first
-- attempt to download it fails. For example, suppose you start an archive
-- retrieval job to download an archive. After the job completes, you start
-- to download the archive but encounter a network error. In this scenario,
-- you can retry and download the archive while the job exists.
--
-- To retrieve an archive or retrieve a vault inventory from Amazon
-- Glacier, you first initiate a job, and after the job completes, you
-- download the data. For an archive retrieval, the output is the archive
-- data, and for an inventory retrieval, it is the inventory list. The List
-- Job operation returns a list of these jobs sorted by job initiation
-- time.
--
-- This List Jobs operation supports pagination. By default, this operation
-- returns up to 1,000 jobs in the response. You should always check the
-- response for a 'marker' at which to continue the list; if there are no
-- more items the 'marker' is 'null'. To return a list of jobs that begins
-- at a specific job, set the 'marker' request parameter to the value you
-- obtained from a previous List Jobs request. You can also limit the
-- number of jobs returned in the response by specifying the 'limit'
-- parameter in the request.
--
-- Additionally, you can filter the jobs list returned by specifying an
-- optional 'statuscode' (InProgress, Succeeded, or Failed) and 'completed'
-- (true, false) parameter. The 'statuscode' allows you to specify that
-- only jobs that match a specified status are returned. The 'completed'
-- parameter allows you to specify that only jobs in a specific completion
-- state are returned.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don\'t have any
-- permissions by default. You must grant them explicit permission to
-- perform specific actions. For more information, see
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>.
--
-- For the underlying REST API, go to
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-jobs-get.html List Jobs>
--
-- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-ListJobs.html AWS API Reference> for ListJobs.
module Network.AWS.Glacier.ListJobs
(
-- * Creating a Request
listJobs
, ListJobs
-- * Request Lenses
, ljMarker
, ljCompleted
, ljLimit
, ljStatuscode
, ljAccountId
, ljVaultName
-- * Destructuring the Response
, listJobsResponse
, ListJobsResponse
-- * Response Lenses
, ljrsMarker
, ljrsJobList
, ljrsResponseStatus
) where
import Network.AWS.Glacier.Types
import Network.AWS.Glacier.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Provides options for retrieving a job list for an Amazon Glacier vault.
--
-- /See:/ 'listJobs' smart constructor.
data ListJobs = ListJobs'
{ _ljMarker :: !(Maybe Text)
, _ljCompleted :: !(Maybe Text)
, _ljLimit :: !(Maybe Text)
, _ljStatuscode :: !(Maybe Text)
, _ljAccountId :: !Text
, _ljVaultName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListJobs' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ljMarker'
--
-- * 'ljCompleted'
--
-- * 'ljLimit'
--
-- * 'ljStatuscode'
--
-- * 'ljAccountId'
--
-- * 'ljVaultName'
listJobs
:: Text -- ^ 'ljAccountId'
-> Text -- ^ 'ljVaultName'
-> ListJobs
listJobs pAccountId_ pVaultName_ =
ListJobs'
{ _ljMarker = Nothing
, _ljCompleted = Nothing
, _ljLimit = Nothing
, _ljStatuscode = Nothing
, _ljAccountId = pAccountId_
, _ljVaultName = pVaultName_
}
-- | An opaque string used for pagination. This value specifies the job at
-- which the listing of jobs should begin. Get the marker value from a
-- previous List Jobs response. You need only include the marker if you are
-- continuing the pagination of results started in a previous List Jobs
-- request.
ljMarker :: Lens' ListJobs (Maybe Text)
ljMarker = lens _ljMarker (\ s a -> s{_ljMarker = a});
-- | Specifies the state of the jobs to return. You can specify 'true' or
-- 'false'.
ljCompleted :: Lens' ListJobs (Maybe Text)
ljCompleted = lens _ljCompleted (\ s a -> s{_ljCompleted = a});
-- | Specifies that the response be limited to the specified number of items
-- or fewer. If not specified, the List Jobs operation returns up to 1,000
-- jobs.
ljLimit :: Lens' ListJobs (Maybe Text)
ljLimit = lens _ljLimit (\ s a -> s{_ljLimit = a});
-- | Specifies the type of job status to return. You can specify the
-- following values: \"InProgress\", \"Succeeded\", or \"Failed\".
ljStatuscode :: Lens' ListJobs (Maybe Text)
ljStatuscode = lens _ljStatuscode (\ s a -> s{_ljStatuscode = a});
-- | The 'AccountId' value is the AWS account ID of the account that owns the
-- vault. You can either specify an AWS account ID or optionally a single
-- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account
-- ID associated with the credentials used to sign the request. If you use
-- an account ID, do not include any hyphens (apos-apos) in the ID.
ljAccountId :: Lens' ListJobs Text
ljAccountId = lens _ljAccountId (\ s a -> s{_ljAccountId = a});
-- | The name of the vault.
ljVaultName :: Lens' ListJobs Text
ljVaultName = lens _ljVaultName (\ s a -> s{_ljVaultName = a});
instance AWSRequest ListJobs where
type Rs ListJobs = ListJobsResponse
request = get glacier
response
= receiveJSON
(\ s h x ->
ListJobsResponse' <$>
(x .?> "Marker") <*> (x .?> "JobList" .!@ mempty) <*>
(pure (fromEnum s)))
instance ToHeaders ListJobs where
toHeaders = const mempty
instance ToPath ListJobs where
toPath ListJobs'{..}
= mconcat
["/", toBS _ljAccountId, "/vaults/",
toBS _ljVaultName, "/jobs"]
instance ToQuery ListJobs where
toQuery ListJobs'{..}
= mconcat
["marker" =: _ljMarker, "completed" =: _ljCompleted,
"limit" =: _ljLimit, "statuscode" =: _ljStatuscode]
-- | Contains the Amazon Glacier response to your request.
--
-- /See:/ 'listJobsResponse' smart constructor.
data ListJobsResponse = ListJobsResponse'
{ _ljrsMarker :: !(Maybe Text)
, _ljrsJobList :: !(Maybe [GlacierJobDescription])
, _ljrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListJobsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ljrsMarker'
--
-- * 'ljrsJobList'
--
-- * 'ljrsResponseStatus'
listJobsResponse
:: Int -- ^ 'ljrsResponseStatus'
-> ListJobsResponse
listJobsResponse pResponseStatus_ =
ListJobsResponse'
{ _ljrsMarker = Nothing
, _ljrsJobList = Nothing
, _ljrsResponseStatus = pResponseStatus_
}
-- | An opaque string that represents where to continue pagination of the
-- results. You use this value in a new List Jobs request to obtain more
-- jobs in the list. If there are no more jobs, this value is 'null'.
ljrsMarker :: Lens' ListJobsResponse (Maybe Text)
ljrsMarker = lens _ljrsMarker (\ s a -> s{_ljrsMarker = a});
-- | A list of job objects. Each job object contains metadata describing the
-- job.
ljrsJobList :: Lens' ListJobsResponse [GlacierJobDescription]
ljrsJobList = lens _ljrsJobList (\ s a -> s{_ljrsJobList = a}) . _Default . _Coerce;
-- | The response status code.
ljrsResponseStatus :: Lens' ListJobsResponse Int
ljrsResponseStatus = lens _ljrsResponseStatus (\ s a -> s{_ljrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-glacier/gen/Network/AWS/Glacier/ListJobs.hs
|
mpl-2.0
| 9,094 | 0 | 13 | 1,863 | 1,072 | 658 | 414 | 118 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.KMS.PutKeyPolicy
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Attaches a policy to the specified key.
--
-- /See:/ <http://docs.aws.amazon.com/kms/latest/APIReference/API_PutKeyPolicy.html AWS API Reference> for PutKeyPolicy.
module Network.AWS.KMS.PutKeyPolicy
(
-- * Creating a Request
putKeyPolicy
, PutKeyPolicy
-- * Request Lenses
, pkpKeyId
, pkpPolicyName
, pkpPolicy
-- * Destructuring the Response
, putKeyPolicyResponse
, PutKeyPolicyResponse
) where
import Network.AWS.KMS.Types
import Network.AWS.KMS.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'putKeyPolicy' smart constructor.
data PutKeyPolicy = PutKeyPolicy'
{ _pkpKeyId :: !Text
, _pkpPolicyName :: !Text
, _pkpPolicy :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PutKeyPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pkpKeyId'
--
-- * 'pkpPolicyName'
--
-- * 'pkpPolicy'
putKeyPolicy
:: Text -- ^ 'pkpKeyId'
-> Text -- ^ 'pkpPolicyName'
-> Text -- ^ 'pkpPolicy'
-> PutKeyPolicy
putKeyPolicy pKeyId_ pPolicyName_ pPolicy_ =
PutKeyPolicy'
{ _pkpKeyId = pKeyId_
, _pkpPolicyName = pPolicyName_
, _pkpPolicy = pPolicy_
}
-- | A unique identifier for the customer master key. This value can be a
-- globally unique identifier or the fully specified ARN to a key.
--
-- - Key ARN Example -
-- arn:aws:kms:us-east-1:123456789012:key\/12345678-1234-1234-1234-123456789012
-- - Globally Unique Key ID Example -
-- 12345678-1234-1234-1234-123456789012
pkpKeyId :: Lens' PutKeyPolicy Text
pkpKeyId = lens _pkpKeyId (\ s a -> s{_pkpKeyId = a});
-- | Name of the policy to be attached. Currently, the only supported name is
-- \"default\".
pkpPolicyName :: Lens' PutKeyPolicy Text
pkpPolicyName = lens _pkpPolicyName (\ s a -> s{_pkpPolicyName = a});
-- | The policy, in JSON format, to be attached to the key.
pkpPolicy :: Lens' PutKeyPolicy Text
pkpPolicy = lens _pkpPolicy (\ s a -> s{_pkpPolicy = a});
instance AWSRequest PutKeyPolicy where
type Rs PutKeyPolicy = PutKeyPolicyResponse
request = postJSON kMS
response = receiveNull PutKeyPolicyResponse'
instance ToHeaders PutKeyPolicy where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("TrentService.PutKeyPolicy" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON PutKeyPolicy where
toJSON PutKeyPolicy'{..}
= object
(catMaybes
[Just ("KeyId" .= _pkpKeyId),
Just ("PolicyName" .= _pkpPolicyName),
Just ("Policy" .= _pkpPolicy)])
instance ToPath PutKeyPolicy where
toPath = const "/"
instance ToQuery PutKeyPolicy where
toQuery = const mempty
-- | /See:/ 'putKeyPolicyResponse' smart constructor.
data PutKeyPolicyResponse =
PutKeyPolicyResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PutKeyPolicyResponse' with the minimum fields required to make a request.
--
putKeyPolicyResponse
:: PutKeyPolicyResponse
putKeyPolicyResponse = PutKeyPolicyResponse'
|
fmapfmapfmap/amazonka
|
amazonka-kms/gen/Network/AWS/KMS/PutKeyPolicy.hs
|
mpl-2.0
| 4,075 | 0 | 12 | 939 | 563 | 338 | 225 | 78 | 1 |
-- | See "Control.Super.Monad.Functions".
module Control.Supermonad.Functions
( module Control.Super.Monad.Functions
) where
import Control.Super.Monad.Functions
|
jbracker/supermonad-plugin
|
src/Control/Supermonad/Functions.hs
|
bsd-3-clause
| 168 | 0 | 5 | 18 | 25 | 18 | 7 | 3 | 0 |
{-# LANGUAGE CPP #-}
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import Gigasecond (fromDay)
import Data.Time.Clock (UTCTime)
import System.Locale (iso8601DateFormat)
#if __GLASGOW_HASKELL__ >= 710
import Data.Time.Format (TimeLocale, ParseTime, parseTimeOrError, defaultTimeLocale)
readTime :: ParseTime t => TimeLocale -> String -> String -> t
readTime = parseTimeOrError True
#else
import System.Locale (defaultTimeLocale)
import Data.Time.Format (readTime)
#endif
dt :: String -> UTCTime
dt = readTime defaultTimeLocale (iso8601DateFormat (Just "%T%Z"))
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = exitProperly $ runTestTT $ TestList
[ TestList gigasecondTests ]
gigasecondTests :: [Test]
gigasecondTests =
[ testCase "from apr 25 2011" $
dt "2043-01-01T01:46:40Z" @=? fromDay (dt "2011-04-25T00:00:00Z")
, testCase "from jun 13 1977" $
dt "2009-02-19T01:46:40Z" @=? fromDay (dt "1977-06-13T00:00:00Z")
, testCase "from jul 19 1959" $
dt "1991-03-27T01:46:40Z" @=? fromDay (dt "1959-07-19T00:00:00Z")
-- customize this to test your birthday and find your gigasecond date:
]
|
stevejb71/xhaskell
|
gigasecond/gigasecond_test.hs
|
mit
| 1,429 | 0 | 12 | 228 | 392 | 210 | 182 | 27 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.AutoScaling.PutNotificationConfiguration
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Configures an Auto Scaling group to send notifications when specified events
-- take place. Subscribers to this topic can have messages for events delivered
-- to an endpoint such as a web server or email address.
--
-- For more information see <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/ASGettingNotifications.html Getting Notifications When Your Auto Scaling GroupChanges> in the /Auto Scaling Developer Guide/.
--
-- This configuration overwrites an existing configuration.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_PutNotificationConfiguration.html>
module Network.AWS.AutoScaling.PutNotificationConfiguration
(
-- * Request
PutNotificationConfiguration
-- ** Request constructor
, putNotificationConfiguration
-- ** Request lenses
, pncAutoScalingGroupName
, pncNotificationTypes
, pncTopicARN
-- * Response
, PutNotificationConfigurationResponse
-- ** Response constructor
, putNotificationConfigurationResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.AutoScaling.Types
import qualified GHC.Exts
data PutNotificationConfiguration = PutNotificationConfiguration
{ _pncAutoScalingGroupName :: Text
, _pncNotificationTypes :: List "member" Text
, _pncTopicARN :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'PutNotificationConfiguration' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pncAutoScalingGroupName' @::@ 'Text'
--
-- * 'pncNotificationTypes' @::@ ['Text']
--
-- * 'pncTopicARN' @::@ 'Text'
--
putNotificationConfiguration :: Text -- ^ 'pncAutoScalingGroupName'
-> Text -- ^ 'pncTopicARN'
-> PutNotificationConfiguration
putNotificationConfiguration p1 p2 = PutNotificationConfiguration
{ _pncAutoScalingGroupName = p1
, _pncTopicARN = p2
, _pncNotificationTypes = mempty
}
-- | The name of the Auto Scaling group.
pncAutoScalingGroupName :: Lens' PutNotificationConfiguration Text
pncAutoScalingGroupName =
lens _pncAutoScalingGroupName (\s a -> s { _pncAutoScalingGroupName = a })
-- | The type of event that will cause the notification to be sent. For details
-- about notification types supported by Auto Scaling, see 'DescribeAutoScalingNotificationTypes'.
pncNotificationTypes :: Lens' PutNotificationConfiguration [Text]
pncNotificationTypes =
lens _pncNotificationTypes (\s a -> s { _pncNotificationTypes = a })
. _List
-- | The Amazon Resource Name (ARN) of the Amazon Simple Notification Service
-- (SNS) topic.
pncTopicARN :: Lens' PutNotificationConfiguration Text
pncTopicARN = lens _pncTopicARN (\s a -> s { _pncTopicARN = a })
data PutNotificationConfigurationResponse = PutNotificationConfigurationResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'PutNotificationConfigurationResponse' constructor.
putNotificationConfigurationResponse :: PutNotificationConfigurationResponse
putNotificationConfigurationResponse = PutNotificationConfigurationResponse
instance ToPath PutNotificationConfiguration where
toPath = const "/"
instance ToQuery PutNotificationConfiguration where
toQuery PutNotificationConfiguration{..} = mconcat
[ "AutoScalingGroupName" =? _pncAutoScalingGroupName
, "NotificationTypes" =? _pncNotificationTypes
, "TopicARN" =? _pncTopicARN
]
instance ToHeaders PutNotificationConfiguration
instance AWSRequest PutNotificationConfiguration where
type Sv PutNotificationConfiguration = AutoScaling
type Rs PutNotificationConfiguration = PutNotificationConfigurationResponse
request = post "PutNotificationConfiguration"
response = nullResponse PutNotificationConfigurationResponse
|
romanb/amazonka
|
amazonka-autoscaling/gen/Network/AWS/AutoScaling/PutNotificationConfiguration.hs
|
mpl-2.0
| 4,899 | 0 | 10 | 952 | 476 | 292 | 184 | 61 | 1 |
{-| Cluster checker.
-}
{-
Copyright (C) 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Program.Hcheck
( main
, options
, arguments
) where
import Control.Monad
import qualified Data.IntMap as IntMap
import Data.List (transpose)
import System.Exit
import Text.Printf (printf)
import Ganeti.HTools.AlgorithmParams (fromCLIOptions)
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Cluster as Cluster
import qualified Ganeti.HTools.Cluster.Metrics as Metrics
import qualified Ganeti.HTools.Cluster.Utils as ClusterUtils
import qualified Ganeti.HTools.GlobalN1 as GlobalN1
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Program.Hbal as Hbal
import Ganeti.HTools.RedundancyLevel (redundancy)
import Ganeti.Common
import Ganeti.HTools.CLI
import Ganeti.HTools.ExtLoader
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import Ganeti.Utils
-- | Options list and functions.
options :: IO [OptType]
options = do
luxi <- oLuxiSocket
return
[ oDataFile
, oDiskMoves
, oAvoidDiskMoves
, oDynuFile
, oIgnoreDyn
, oEvacMode
, oExInst
, oExTags
, oIAllocSrc
, oInstMoves
, luxi
, oMachineReadable
, oMaxCpu
, oMaxSolLength
, oMinDisk
, oMinGain
, oMinGainLim
, oMinScore
, oIgnoreSoftErrors
, oNoSimulation
, oOfflineNode
, oQuiet
, oRapiMaster
, oSelInst
, oNoCapacityChecks
, oVerbose
]
-- | The list of arguments supported by the program.
arguments :: [ArgCompletion]
arguments = []
-- | Check phase - are we before (initial) or after rebalance.
data Phase = Initial
| Rebalanced
-- | Level of presented statistics.
data Level = GroupLvl String -- ^ Group level, with name
| ClusterLvl -- ^ Cluster level
-- | A type alias for a group index and node\/instance lists.
type GroupInfo = (Gdx, (Node.List, Instance.List))
-- | A type alias for group stats.
type GroupStats = ((Group.Group, Double, Int), [Int])
-- | Prefix for machine readable names.
htcPrefix :: String
htcPrefix = "HCHECK"
-- | Data showed both per group and per cluster.
commonData :: Options -> [(String, String)]
commonData opts =
[ ("N1_FAIL", "Nodes not N+1 happy")
, ("CONFLICT_TAGS", "Nodes with conflicting instances")
, ("OFFLINE_PRI", "Instances having the primary node offline")
, ("OFFLINE_SEC", "Instances having a secondary node offline")
]
++ [ ("GN1_FAIL", "Nodes not directly evacuateable") | optCapacity opts ]
-- | Data showed per group.
groupData :: Options -> [(String, String)]
groupData opts = commonData opts ++ [("SCORE", "Group score")]
++ [("REDUNDANCY", "Group redundancy level")]
-- | Data showed per cluster.
clusterData :: Options -> [(String, String)]
clusterData opts = commonData opts ++
[ ("REDUNDANCY", "Cluster redundancy level") ] ++
[ ("NEED_REBALANCE", "Cluster is not healthy") ]
-- | Phase-specific prefix for machine readable version.
phasePrefix :: Phase -> String
phasePrefix Initial = "INIT"
phasePrefix Rebalanced = "FINAL"
-- | Level-specific prefix for machine readable version.
levelPrefix :: Level -> String
levelPrefix GroupLvl {} = "GROUP"
levelPrefix ClusterLvl = "CLUSTER"
-- | Machine-readable keys to show depending on given level.
keysData :: Options -> Level -> [String]
keysData opts GroupLvl {} = map fst $ groupData opts
keysData opts ClusterLvl = map fst $ clusterData opts
-- | Description of phases for human readable version.
phaseDescr :: Phase -> String
phaseDescr Initial = "initially"
phaseDescr Rebalanced = "after rebalancing"
-- | Description to show depending on given level.
descrData :: Options -> Level -> [String]
descrData opts GroupLvl {} = map snd $ groupData opts
descrData opts ClusterLvl = map snd $ clusterData opts
-- | Human readable prefix for statistics.
phaseLevelDescr :: Phase -> Level -> String
phaseLevelDescr phase (GroupLvl name) =
printf "Statistics for group %s %s\n" name $ phaseDescr phase
phaseLevelDescr phase ClusterLvl =
printf "Cluster statistics %s\n" $ phaseDescr phase
-- | Format a list of key, value as a shell fragment.
printKeysHTC :: [(String, String)] -> IO ()
printKeysHTC = printKeys htcPrefix
-- | Prepare string from boolean value.
printBool :: Bool -- ^ Whether the result should be machine readable
-> Bool -- ^ Value to be converted to string
-> String
printBool True True = "1"
printBool True False = "0"
printBool False b = show b
-- | Print mapping from group idx to group uuid (only in machine
-- readable mode).
printGroupsMappings :: Group.List -> IO ()
printGroupsMappings gl = do
let extract_vals g = (printf "GROUP_UUID_%d" $ Group.idx g :: String,
Group.uuid g)
printpairs = map extract_vals (Container.elems gl)
printKeysHTC printpairs
-- | Prepare a single key given a certain level and phase of simulation.
prepareKey :: Level -> Phase -> String -> String
prepareKey level@ClusterLvl phase suffix =
printf "%s_%s_%s" (phasePrefix phase) (levelPrefix level) suffix
prepareKey level@(GroupLvl idx) phase suffix =
printf "%s_%s_%s_%s" (phasePrefix phase) (levelPrefix level) idx suffix
-- | Print all the statistics for given level and phase.
printStats :: Options
-> Bool -- ^ If the output should be machine readable
-> Level -- ^ Level on which we are printing
-> Phase -- ^ Current phase of simulation
-> [String] -- ^ Values to print
-> IO ()
printStats opts True level phase values = do
let keys = map (prepareKey level phase) (keysData opts level)
printKeysHTC $ zip keys values
printStats opts False level phase values = do
let prefix = phaseLevelDescr phase level
descr = descrData opts level
unless (optVerbose opts < 1) $ do
putStrLn ""
putStr prefix
mapM_ (uncurry (printf " %s: %s\n")) (zip descr values)
-- | Extract name or idx from group.
extractGroupData :: Bool -> Group.Group -> String
extractGroupData True grp = show $ Group.idx grp
extractGroupData False grp = Group.name grp
-- | Prepare values for group.
prepareGroupValues :: [Int] -> Double -> Int -> [String]
prepareGroupValues stats score redundancyLevel =
map show stats ++ [printf "%.8f" score] ++ [show redundancyLevel]
-- | Prepare values for cluster.
prepareClusterValues :: Bool -> [Int] -> [Bool] -> [String]
prepareClusterValues machineread stats bstats =
map show stats ++ map (printBool machineread) bstats
-- | Print all the statistics on a group level.
printGroupStats :: Options -> Bool -> Phase -> GroupStats -> IO ()
printGroupStats opts machineread phase
((grp, score, redundancyLevel), stats) = do
let values = prepareGroupValues stats score redundancyLevel
extradata = extractGroupData machineread grp
printStats opts machineread (GroupLvl extradata) phase values
-- | Print all the statistics on a cluster (global) level.
printClusterStats :: Options -> Bool -> Phase -> [Int] -> Bool -> Int -> IO ()
printClusterStats opts machineread phase stats needhbal gRed = do
let values = prepareClusterValues machineread (stats ++ [gRed]) [needhbal]
printStats opts machineread ClusterLvl phase values
-- | Check if any of cluster metrics is non-zero.
clusterNeedsRebalance :: [Int] -> Bool
clusterNeedsRebalance stats = sum stats > 0
{- | Check group for N+1 hapiness, conflicts of primaries on nodes and
instances residing on offline nodes.
-}
perGroupChecks :: Options -> Group.List -> GroupInfo -> GroupStats
perGroupChecks opts gl (gidx, (nl, il)) =
let grp = Container.find gidx gl
offnl = filter Node.offline (Container.elems nl)
n1violated = length . fst $ Cluster.computeBadItems nl il
gn1fail = length . filter (not . GlobalN1.canEvacuateNode (nl, il))
$ IntMap.elems nl
conflicttags = length $ filter (>0)
(map Node.conflictingPrimaries (Container.elems nl))
offline_pri = sum . map length $ map Node.pList offnl
offline_sec = length $ map Node.sList offnl
score = Metrics.compCV nl
redundancyLvl = redundancy (fromCLIOptions opts) nl il
groupstats = [ n1violated
, conflicttags
, offline_pri
, offline_sec
]
++ [ gn1fail | optCapacity opts ]
in ((grp, score, redundancyLvl), groupstats)
-- | Use Hbal's iterateDepth to simulate group rebalance.
executeSimulation :: Options -> Cluster.Table -> Double
-> Gdx -> Node.List -> Instance.List
-> IO GroupInfo
executeSimulation opts ini_tbl min_cv gidx nl il = do
let imlen = maximum . map (length . Instance.alias) $ Container.elems il
nmlen = maximum . map (length . Node.alias) $ Container.elems nl
(fin_tbl, _) <- Hbal.iterateDepth False (fromCLIOptions opts) ini_tbl
(optMaxLength opts)
nmlen imlen [] min_cv
let (Cluster.Table fin_nl fin_il _ _) = fin_tbl
return (gidx, (fin_nl, fin_il))
-- | Simulate group rebalance if group's score is not good
maybeSimulateGroupRebalance :: Options -> GroupInfo -> IO GroupInfo
maybeSimulateGroupRebalance opts (gidx, (nl, il)) = do
let ini_cv = Metrics.compCV nl
ini_tbl = Cluster.Table nl il ini_cv []
min_cv = optMinScore opts + Metrics.optimalCVScore nl
if ini_cv < min_cv
then return (gidx, (nl, il))
else executeSimulation opts ini_tbl min_cv gidx nl il
-- | Decide whether to simulate rebalance.
maybeSimulateRebalance :: Bool -- ^ Whether to simulate rebalance
-> Options -- ^ Command line options
-> [GroupInfo] -- ^ Group data
-> IO [GroupInfo]
maybeSimulateRebalance True opts cluster =
mapM (maybeSimulateGroupRebalance opts) cluster
maybeSimulateRebalance False _ cluster = return cluster
-- | Prints the final @OK@ marker in machine readable output.
printFinalHTC :: Bool -> IO ()
printFinalHTC = printFinal htcPrefix
-- | Main function.
main :: Options -> [String] -> IO ()
main opts args = do
unless (null args) $ exitErr "This program doesn't take any arguments."
let verbose = optVerbose opts
machineread = optMachineReadable opts
nosimulation = optNoSimulation opts
(ClusterData gl fixed_nl ilf _ _) <- loadExternalData opts
nlf <- setNodeStatus opts fixed_nl
let splitcluster = ClusterUtils.splitCluster nlf ilf
when machineread $ printGroupsMappings gl
let groupsstats = map (perGroupChecks opts gl) splitcluster
clusterstats = map sum . transpose . map snd $ groupsstats
globalRedundancy = minimum $ map (\((_, _, r), _) -> r) groupsstats
needrebalance = clusterNeedsRebalance clusterstats
unless (verbose < 1 || machineread) .
putStrLn $ if nosimulation
then "Running in no-simulation mode."
else if needrebalance
then "Cluster needs rebalancing."
else "No need to rebalance cluster, no problems found."
mapM_ (printGroupStats opts machineread Initial) groupsstats
printClusterStats opts machineread Initial clusterstats needrebalance
globalRedundancy
let exitOK = nosimulation || not needrebalance
simulate = not nosimulation && needrebalance
rebalancedcluster <- maybeSimulateRebalance simulate opts splitcluster
when (simulate || machineread) $ do
let newgroupstats = map (perGroupChecks opts gl) rebalancedcluster
newclusterstats = map sum . transpose . map snd $ newgroupstats
newGlobalRedundancy = minimum $ map (\((_, _, r), _) -> r)
newgroupstats
newneedrebalance = clusterNeedsRebalance clusterstats
mapM_ (printGroupStats opts machineread Rebalanced) newgroupstats
printClusterStats opts machineread Rebalanced newclusterstats
newneedrebalance newGlobalRedundancy
printFinalHTC machineread
unless exitOK . exitWith $ ExitFailure 1
|
andir/ganeti
|
src/Ganeti/HTools/Program/Hcheck.hs
|
bsd-2-clause
| 13,579 | 0 | 18 | 3,040 | 2,971 | 1,584 | 1,387 | 240 | 3 |
{-
(c) The University of Glasgow, 2004-2006
Module
~~~~~~~~~~
Simply the name of a module, represented as a FastString.
These are Uniquable, hence we can build Maps with Modules as
the keys.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RecordWildCards #-}
module Module
(
-- * The ModuleName type
ModuleName,
pprModuleName,
moduleNameFS,
moduleNameString,
moduleNameSlashes, moduleNameColons,
moduleStableString,
mkModuleName,
mkModuleNameFS,
stableModuleNameCmp,
-- * The UnitId type
UnitId,
fsToUnitId,
unitIdFS,
stringToUnitId,
unitIdString,
stableUnitIdCmp,
-- * Wired-in UnitIds
-- $wired_in_packages
primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
dphSeqUnitId,
dphParUnitId,
mainUnitId,
thisGhcUnitId,
holeUnitId, isHoleModule,
interactiveUnitId, isInteractiveModule,
wiredInUnitIds,
-- * The Module type
Module(Module),
moduleUnitId, moduleName,
pprModule,
mkModule,
stableModuleCmp,
HasModule(..),
ContainsModule(..),
-- * The ModuleLocation type
ModLocation(..),
addBootSuffix, addBootSuffix_maybe, addBootSuffixLocn,
-- * Module mappings
ModuleEnv,
elemModuleEnv, extendModuleEnv, extendModuleEnvList,
extendModuleEnvList_C, plusModuleEnv_C,
delModuleEnvList, delModuleEnv, plusModuleEnv, lookupModuleEnv,
lookupWithDefaultModuleEnv, mapModuleEnv, mkModuleEnv, emptyModuleEnv,
moduleEnvKeys, moduleEnvElts, moduleEnvToList,
unitModuleEnv, isEmptyModuleEnv,
foldModuleEnv, extendModuleEnvWith, filterModuleEnv,
-- * ModuleName mappings
ModuleNameEnv,
-- * Sets of Modules
ModuleSet,
emptyModuleSet, mkModuleSet, moduleSetElts, extendModuleSet, elemModuleSet
) where
import Config
import Outputable
import Unique
import UniqFM
import FastString
import Binary
import Util
import {-# SOURCE #-} Packages
import GHC.PackageDb (BinaryStringRep(..))
import Data.Data
import Data.Map (Map)
import qualified Data.Map as Map
import qualified FiniteMap as Map
import System.FilePath
{-
************************************************************************
* *
\subsection{Module locations}
* *
************************************************************************
-}
-- | Where a module lives on the file system: the actual locations
-- of the .hs, .hi and .o files, if we have them
data ModLocation
= ModLocation {
ml_hs_file :: Maybe FilePath,
-- The source file, if we have one. Package modules
-- probably don't have source files.
ml_hi_file :: FilePath,
-- Where the .hi file is, whether or not it exists
-- yet. Always of form foo.hi, even if there is an
-- hi-boot file (we add the -boot suffix later)
ml_obj_file :: FilePath
-- Where the .o file is, whether or not it exists yet.
-- (might not exist either because the module hasn't
-- been compiled yet, or because it is part of a
-- package with a .a file)
} deriving Show
instance Outputable ModLocation where
ppr = text . show
{-
For a module in another package, the hs_file and obj_file
components of ModLocation are undefined.
The locations specified by a ModLocation may or may not
correspond to actual files yet: for example, even if the object
file doesn't exist, the ModLocation still contains the path to
where the object file will reside if/when it is created.
-}
addBootSuffix :: FilePath -> FilePath
-- ^ Add the @-boot@ suffix to .hs, .hi and .o files
addBootSuffix path = path ++ "-boot"
addBootSuffix_maybe :: Bool -> FilePath -> FilePath
-- ^ Add the @-boot@ suffix if the @Bool@ argument is @True@
addBootSuffix_maybe is_boot path
| is_boot = addBootSuffix path
| otherwise = path
addBootSuffixLocn :: ModLocation -> ModLocation
-- ^ Add the @-boot@ suffix to all file paths associated with the module
addBootSuffixLocn locn
= locn { ml_hs_file = fmap addBootSuffix (ml_hs_file locn)
, ml_hi_file = addBootSuffix (ml_hi_file locn)
, ml_obj_file = addBootSuffix (ml_obj_file locn) }
{-
************************************************************************
* *
\subsection{The name of a module}
* *
************************************************************************
-}
-- | A ModuleName is essentially a simple string, e.g. @Data.List@.
newtype ModuleName = ModuleName FastString
deriving Typeable
instance Uniquable ModuleName where
getUnique (ModuleName nm) = getUnique nm
instance Eq ModuleName where
nm1 == nm2 = getUnique nm1 == getUnique nm2
-- Warning: gives an ordering relation based on the uniques of the
-- FastStrings which are the (encoded) module names. This is _not_
-- a lexicographical ordering.
instance Ord ModuleName where
nm1 `compare` nm2 = getUnique nm1 `compare` getUnique nm2
instance Outputable ModuleName where
ppr = pprModuleName
instance Binary ModuleName where
put_ bh (ModuleName fs) = put_ bh fs
get bh = do fs <- get bh; return (ModuleName fs)
instance BinaryStringRep ModuleName where
fromStringRep = mkModuleNameFS . mkFastStringByteString
toStringRep = fastStringToByteString . moduleNameFS
instance Data ModuleName where
-- don't traverse?
toConstr _ = abstractConstr "ModuleName"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "ModuleName"
stableModuleNameCmp :: ModuleName -> ModuleName -> Ordering
-- ^ Compares module names lexically, rather than by their 'Unique's
stableModuleNameCmp n1 n2 = moduleNameFS n1 `compare` moduleNameFS n2
pprModuleName :: ModuleName -> SDoc
pprModuleName (ModuleName nm) =
getPprStyle $ \ sty ->
if codeStyle sty
then ztext (zEncodeFS nm)
else ftext nm
moduleNameFS :: ModuleName -> FastString
moduleNameFS (ModuleName mod) = mod
moduleNameString :: ModuleName -> String
moduleNameString (ModuleName mod) = unpackFS mod
-- | Get a string representation of a 'Module' that's unique and stable
-- across recompilations.
-- eg. "$aeson_70dylHtv1FFGeai1IoxcQr$Data.Aeson.Types.Internal"
moduleStableString :: Module -> String
moduleStableString Module{..} =
"$" ++ unitIdString moduleUnitId ++ "$" ++ moduleNameString moduleName
mkModuleName :: String -> ModuleName
mkModuleName s = ModuleName (mkFastString s)
mkModuleNameFS :: FastString -> ModuleName
mkModuleNameFS s = ModuleName s
-- |Returns the string version of the module name, with dots replaced by slashes.
--
moduleNameSlashes :: ModuleName -> String
moduleNameSlashes = dots_to_slashes . moduleNameString
where dots_to_slashes = map (\c -> if c == '.' then pathSeparator else c)
-- |Returns the string version of the module name, with dots replaced by underscores.
--
moduleNameColons :: ModuleName -> String
moduleNameColons = dots_to_colons . moduleNameString
where dots_to_colons = map (\c -> if c == '.' then ':' else c)
{-
************************************************************************
* *
\subsection{A fully qualified module}
* *
************************************************************************
-}
-- | A Module is a pair of a 'UnitId' and a 'ModuleName'.
data Module = Module {
moduleUnitId :: !UnitId, -- pkg-1.0
moduleName :: !ModuleName -- A.B.C
}
deriving (Eq, Ord, Typeable)
instance Uniquable Module where
getUnique (Module p n) = getUnique (unitIdFS p `appendFS` moduleNameFS n)
instance Outputable Module where
ppr = pprModule
instance Binary Module where
put_ bh (Module p n) = put_ bh p >> put_ bh n
get bh = do p <- get bh; n <- get bh; return (Module p n)
instance Data Module where
-- don't traverse?
toConstr _ = abstractConstr "Module"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Module"
-- | This gives a stable ordering, as opposed to the Ord instance which
-- gives an ordering based on the 'Unique's of the components, which may
-- not be stable from run to run of the compiler.
stableModuleCmp :: Module -> Module -> Ordering
stableModuleCmp (Module p1 n1) (Module p2 n2)
= (p1 `stableUnitIdCmp` p2) `thenCmp`
(n1 `stableModuleNameCmp` n2)
mkModule :: UnitId -> ModuleName -> Module
mkModule = Module
pprModule :: Module -> SDoc
pprModule mod@(Module p n) =
pprPackagePrefix p mod <> pprModuleName n
pprPackagePrefix :: UnitId -> Module -> SDoc
pprPackagePrefix p mod = getPprStyle doc
where
doc sty
| codeStyle sty =
if p == mainUnitId
then empty -- never qualify the main package in code
else ztext (zEncodeFS (unitIdFS p)) <> char '_'
| qualModule sty mod = ppr (moduleUnitId mod) <> char ':'
-- the PrintUnqualified tells us which modules have to
-- be qualified with package names
| otherwise = empty
class ContainsModule t where
extractModule :: t -> Module
class HasModule m where
getModule :: m Module
{-
************************************************************************
* *
\subsection{UnitId}
* *
************************************************************************
-}
-- | A string which uniquely identifies a package. For wired-in packages,
-- it is just the package name, but for user compiled packages, it is a hash.
-- ToDo: when the key is a hash, we can do more clever things than store
-- the hex representation and hash-cons those strings.
newtype UnitId = PId FastString deriving( Eq, Typeable )
-- here to avoid module loops with PackageConfig
instance Uniquable UnitId where
getUnique pid = getUnique (unitIdFS pid)
-- Note: *not* a stable lexicographic ordering, a faster unique-based
-- ordering.
instance Ord UnitId where
nm1 `compare` nm2 = getUnique nm1 `compare` getUnique nm2
instance Data UnitId where
-- don't traverse?
toConstr _ = abstractConstr "UnitId"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "UnitId"
stableUnitIdCmp :: UnitId -> UnitId -> Ordering
-- ^ Compares package ids lexically, rather than by their 'Unique's
stableUnitIdCmp p1 p2 = unitIdFS p1 `compare` unitIdFS p2
instance Outputable UnitId where
ppr pk = getPprStyle $ \sty -> sdocWithDynFlags $ \dflags ->
case unitIdPackageIdString dflags pk of
Nothing -> ftext (unitIdFS pk)
Just pkg -> text pkg
-- Don't bother qualifying if it's wired in!
<> (if qualPackage sty pk && not (pk `elem` wiredInUnitIds)
then char '@' <> ftext (unitIdFS pk)
else empty)
instance Binary UnitId where
put_ bh pid = put_ bh (unitIdFS pid)
get bh = do { fs <- get bh; return (fsToUnitId fs) }
instance BinaryStringRep UnitId where
fromStringRep = fsToUnitId . mkFastStringByteString
toStringRep = fastStringToByteString . unitIdFS
fsToUnitId :: FastString -> UnitId
fsToUnitId = PId
unitIdFS :: UnitId -> FastString
unitIdFS (PId fs) = fs
stringToUnitId :: String -> UnitId
stringToUnitId = fsToUnitId . mkFastString
unitIdString :: UnitId -> String
unitIdString = unpackFS . unitIdFS
-- -----------------------------------------------------------------------------
-- $wired_in_packages
-- Certain packages are known to the compiler, in that we know about certain
-- entities that reside in these packages, and the compiler needs to
-- declare static Modules and Names that refer to these packages. Hence
-- the wired-in packages can't include version numbers, since we don't want
-- to bake the version numbers of these packages into GHC.
--
-- So here's the plan. Wired-in packages are still versioned as
-- normal in the packages database, and you can still have multiple
-- versions of them installed. However, for each invocation of GHC,
-- only a single instance of each wired-in package will be recognised
-- (the desired one is selected via @-package@\/@-hide-package@), and GHC
-- will use the unversioned 'UnitId' below when referring to it,
-- including in .hi files and object file symbols. Unselected
-- versions of wired-in packages will be ignored, as will any other
-- package that depends directly or indirectly on it (much as if you
-- had used @-ignore-package@).
-- Make sure you change 'Packages.findWiredInPackages' if you add an entry here
integerUnitId, primUnitId,
baseUnitId, rtsUnitId,
thUnitId, dphSeqUnitId, dphParUnitId,
mainUnitId, thisGhcUnitId, interactiveUnitId :: UnitId
primUnitId = fsToUnitId (fsLit "ghc-prim")
integerUnitId = fsToUnitId (fsLit n)
where
n = case cIntegerLibraryType of
IntegerGMP -> "integer-gmp"
IntegerSimple -> "integer-simple"
baseUnitId = fsToUnitId (fsLit "base")
rtsUnitId = fsToUnitId (fsLit "rts")
thUnitId = fsToUnitId (fsLit "template-haskell")
dphSeqUnitId = fsToUnitId (fsLit "dph-seq")
dphParUnitId = fsToUnitId (fsLit "dph-par")
thisGhcUnitId = fsToUnitId (fsLit "ghc")
interactiveUnitId = fsToUnitId (fsLit "interactive")
-- | This is the package Id for the current program. It is the default
-- package Id if you don't specify a package name. We don't add this prefix
-- to symbol names, since there can be only one main package per program.
mainUnitId = fsToUnitId (fsLit "main")
-- | This is a fake package id used to provide identities to any un-implemented
-- signatures. The set of hole identities is global over an entire compilation.
holeUnitId :: UnitId
holeUnitId = fsToUnitId (fsLit "hole")
isInteractiveModule :: Module -> Bool
isInteractiveModule mod = moduleUnitId mod == interactiveUnitId
isHoleModule :: Module -> Bool
isHoleModule mod = moduleUnitId mod == holeUnitId
wiredInUnitIds :: [UnitId]
wiredInUnitIds = [ primUnitId,
integerUnitId,
baseUnitId,
rtsUnitId,
thUnitId,
thisGhcUnitId,
dphSeqUnitId,
dphParUnitId ]
{-
************************************************************************
* *
\subsection{@ModuleEnv@s}
* *
************************************************************************
-}
-- | A map keyed off of 'Module's
newtype ModuleEnv elt = ModuleEnv (Map Module elt)
filterModuleEnv :: (Module -> a -> Bool) -> ModuleEnv a -> ModuleEnv a
filterModuleEnv f (ModuleEnv e) = ModuleEnv (Map.filterWithKey f e)
elemModuleEnv :: Module -> ModuleEnv a -> Bool
elemModuleEnv m (ModuleEnv e) = Map.member m e
extendModuleEnv :: ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv (ModuleEnv e) m x = ModuleEnv (Map.insert m x e)
extendModuleEnvWith :: (a -> a -> a) -> ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnvWith f (ModuleEnv e) m x = ModuleEnv (Map.insertWith f m x e)
extendModuleEnvList :: ModuleEnv a -> [(Module, a)] -> ModuleEnv a
extendModuleEnvList (ModuleEnv e) xs = ModuleEnv (Map.insertList xs e)
extendModuleEnvList_C :: (a -> a -> a) -> ModuleEnv a -> [(Module, a)]
-> ModuleEnv a
extendModuleEnvList_C f (ModuleEnv e) xs = ModuleEnv (Map.insertListWith f xs e)
plusModuleEnv_C :: (a -> a -> a) -> ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv_C f (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.unionWith f e1 e2)
delModuleEnvList :: ModuleEnv a -> [Module] -> ModuleEnv a
delModuleEnvList (ModuleEnv e) ms = ModuleEnv (Map.deleteList ms e)
delModuleEnv :: ModuleEnv a -> Module -> ModuleEnv a
delModuleEnv (ModuleEnv e) m = ModuleEnv (Map.delete m e)
plusModuleEnv :: ModuleEnv a -> ModuleEnv a -> ModuleEnv a
plusModuleEnv (ModuleEnv e1) (ModuleEnv e2) = ModuleEnv (Map.union e1 e2)
lookupModuleEnv :: ModuleEnv a -> Module -> Maybe a
lookupModuleEnv (ModuleEnv e) m = Map.lookup m e
lookupWithDefaultModuleEnv :: ModuleEnv a -> a -> Module -> a
lookupWithDefaultModuleEnv (ModuleEnv e) x m = Map.findWithDefault x m e
mapModuleEnv :: (a -> b) -> ModuleEnv a -> ModuleEnv b
mapModuleEnv f (ModuleEnv e) = ModuleEnv (Map.mapWithKey (\_ v -> f v) e)
mkModuleEnv :: [(Module, a)] -> ModuleEnv a
mkModuleEnv xs = ModuleEnv (Map.fromList xs)
emptyModuleEnv :: ModuleEnv a
emptyModuleEnv = ModuleEnv Map.empty
moduleEnvKeys :: ModuleEnv a -> [Module]
moduleEnvKeys (ModuleEnv e) = Map.keys e
moduleEnvElts :: ModuleEnv a -> [a]
moduleEnvElts (ModuleEnv e) = Map.elems e
moduleEnvToList :: ModuleEnv a -> [(Module, a)]
moduleEnvToList (ModuleEnv e) = Map.toList e
unitModuleEnv :: Module -> a -> ModuleEnv a
unitModuleEnv m x = ModuleEnv (Map.singleton m x)
isEmptyModuleEnv :: ModuleEnv a -> Bool
isEmptyModuleEnv (ModuleEnv e) = Map.null e
foldModuleEnv :: (a -> b -> b) -> b -> ModuleEnv a -> b
foldModuleEnv f x (ModuleEnv e) = Map.foldRightWithKey (\_ v -> f v) x e
-- | A set of 'Module's
type ModuleSet = Map Module ()
mkModuleSet :: [Module] -> ModuleSet
extendModuleSet :: ModuleSet -> Module -> ModuleSet
emptyModuleSet :: ModuleSet
moduleSetElts :: ModuleSet -> [Module]
elemModuleSet :: Module -> ModuleSet -> Bool
emptyModuleSet = Map.empty
mkModuleSet ms = Map.fromList [(m,()) | m <- ms ]
extendModuleSet s m = Map.insert m () s
moduleSetElts = Map.keys
elemModuleSet = Map.member
{-
A ModuleName has a Unique, so we can build mappings of these using
UniqFM.
-}
-- | A map keyed off of 'ModuleName's (actually, their 'Unique's)
type ModuleNameEnv elt = UniqFM elt
|
siddhanathan/ghc
|
compiler/basicTypes/Module.hs
|
bsd-3-clause
| 18,321 | 0 | 19 | 4,439 | 3,590 | 1,927 | 1,663 | 294 | 2 |
{-# LANGUAGE CPP, BangPatterns #-}
module Main where
import Control.Monad
import Data.Int
import Network.Socket
( AddrInfo, AddrInfoFlag (AI_PASSIVE), HostName, ServiceName, Socket
, SocketType (Stream), SocketOption (ReuseAddr)
, accept, addrAddress, addrFlags, addrFamily, bindSocket, defaultProtocol
, defaultHints
, getAddrInfo, listen, setSocketOption, socket, sClose, withSocketsDo )
import System.Environment (getArgs, withArgs)
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import System.IO (withFile, IOMode(..), hPutStrLn, Handle, stderr)
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar)
import qualified Network.Socket as N
import Debug.Trace
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack, unpack)
import qualified Data.ByteString as BS
import qualified Network.Socket.ByteString as NBS
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import Data.ByteString.Internal as BSI
import Foreign.Storable (pokeByteOff, peekByteOff)
import Foreign.C (CInt(..))
import Foreign.ForeignPtr (withForeignPtr)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
foreign import ccall unsafe "htonl" htonl :: CInt -> CInt
foreign import ccall unsafe "ntohl" ntohl :: CInt -> CInt
passive :: Maybe AddrInfo
passive = Just (defaultHints { addrFlags = [AI_PASSIVE] })
main = do
[pingsStr] <- getArgs
serverReady <- newEmptyMVar
clientDone <- newEmptyMVar
-- Start the server
forkIO $ do
-- Initialize the server
serverAddr:_ <- getAddrInfo passive Nothing (Just "8080")
sock <- socket (addrFamily serverAddr) Stream defaultProtocol
setSocketOption sock ReuseAddr 1
bindSocket sock (addrAddress serverAddr)
listen sock 1
-- Set up multiplexing channel
multiplexChannel <- newChan
-- Wait for incoming connections (pings from the client)
putMVar serverReady ()
(clientSock, pingAddr) <- accept sock
forkIO $ socketToChan clientSock multiplexChannel
-- Reply to the client
forever $ readChan multiplexChannel >>= send clientSock
-- Start the client
forkIO $ do
takeMVar serverReady
serverAddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just "8080")
clientSock <- socket (addrFamily serverAddr) Stream defaultProtocol
N.connect clientSock (addrAddress serverAddr)
ping clientSock (read pingsStr)
putMVar clientDone ()
-- Wait for the client to finish
takeMVar clientDone
socketToChan :: Socket -> Chan ByteString -> IO ()
socketToChan sock chan = go
where
go = do bs <- recv sock
when (BS.length bs > 0) $ do
writeChan chan bs
go
pingMessage :: ByteString
pingMessage = pack "ping123"
ping :: Socket -> Int -> IO ()
ping sock pings = go pings
where
go :: Int -> IO ()
go 0 = do
putStrLn $ "client did " ++ show pings ++ " pings"
go !i = do
before <- getCurrentTime
send sock pingMessage
bs <- recv sock
after <- getCurrentTime
-- putStrLn $ "client received " ++ unpack bs
let latency = (1e6 :: Double) * realToFrac (diffUTCTime after before)
hPutStrLn stderr $ show i ++ " " ++ show latency
go (i - 1)
-- | Receive a package
recv :: Socket -> IO ByteString
recv sock = do
header <- NBS.recv sock 4
length <- decodeLength header
NBS.recv sock (fromIntegral (length :: Int32))
-- | Send a package
send :: Socket -> ByteString -> IO ()
send sock bs = do
length <- encodeLength (fromIntegral (BS.length bs))
NBS.sendMany sock [length, bs]
-- | Encode length (manual for now)
encodeLength :: Int32 -> IO ByteString
encodeLength i32 =
BSI.create 4 $ \p ->
pokeByteOff p 0 (htonl (fromIntegral i32))
-- | Decode length (manual for now)
decodeLength :: ByteString -> IO Int32
decodeLength bs =
let (fp, _, _) = BSI.toForeignPtr bs in
withForeignPtr fp $ \p -> do
w32 <- peekByteOff p 0
return (fromIntegral (ntohl w32))
|
tweag/network-transport-zeromq
|
benchmarks/subparts/h-tcp-chan.hs
|
bsd-3-clause
| 4,012 | 0 | 15 | 818 | 1,222 | 636 | 586 | 94 | 2 |
module Infix4 (f) where
-- define an infix constructor and attempt to remove it...
data T1 a b = b :#: a
{- g :: T1 Int Int -> Int -}
{- g (x :$: y) = x + y -}
f x y = error
"g (x :$: y) no longer defined for T1 at line: 5"
|
kmate/HaRe
|
old/testing/removeCon/Infix4_TokOut.hs
|
bsd-3-clause
| 241 | 0 | 6 | 75 | 38 | 23 | 15 | 4 | 1 |
module ListSort () where
import Language.Haskell.Liquid.Prelude
{-@ type OList a = [a]<{\fld v -> (v >= fld)}> @-}
{-@ predicate Pr X Y = (((len Y) > 1) => ((len Y) < (len X))) @-}
{-@ split :: xs:[a]
-> ({v:[a] | (Pr xs v)}, {v:[a]|(Pr xs v)})
<{\x y -> ((len x) + (len y) = (len xs))}>
@-}
split :: [a] -> ([a], [a])
split (x:(y:zs)) = (x:xs, y:ys) where (xs, ys) = split zs
split xs = (xs, [])
{-@ Decrease merge 4 @-}
{-@ merge :: Ord a => xs:(OList a) -> ys:(OList a) -> d:{v:Int| v = (len xs) + (len ys)} -> {v:(OList a) | (len v) = d} @-}
merge :: Ord a => [a] -> [a] -> Int -> [a]
merge xs [] _ = xs
merge [] ys _ = ys
merge (x:xs) (y:ys) d
| x <= y
= x:(merge xs (y:ys) (d-1))
| otherwise
= y:(merge (x:xs) ys (d-1))
{-@ mergesort :: (Ord a) => xs:[a] -> {v:(OList a) | (len v) = (len xs)} @-}
mergesort :: Ord a => [a] -> [a]
mergesort [] = []
mergesort [x] = [x]
mergesort xs = merge (mergesort xs1) (mergesort xs2) d
where (xs1, xs2) = split xs
d = length xs
|
ssaavedra/liquidhaskell
|
tests/pos/ListMSort.hs
|
bsd-3-clause
| 1,062 | 0 | 10 | 303 | 375 | 205 | 170 | 19 | 1 |
module Conflict1 where
f :: Int -> Int
f x = x + 1
f1 :: Int -> Int
f1 x = x - 1
f3 :: Int -> (Int, Int)
f3 x y = (x + 1, y - 1)
|
kmate/HaRe
|
old/testing/merging/Conflict1_TokOut.hs
|
bsd-3-clause
| 133 | 0 | 6 | 45 | 85 | 47 | 38 | 7 | 1 |
{-# LANGUAGE RecordWildCards #-}
-- | See:
--
-- * \"The Probabilistic Relevance Framework: BM25 and Beyond\"
-- <www.soi.city.ac.uk/~ser/papers/foundations_bm25_review.pdf>
--
-- * \"An Introduction to Information Retrieval\"
-- <http://nlp.stanford.edu/IR-book/pdf/irbookonlinereading.pdf>
--
module Distribution.Server.Features.Search.BM25F (
Context(..),
FeatureFunction(..),
Doc(..),
score,
Explanation(..),
explain,
) where
import Data.Ix
data Context term field feature = Context {
numDocsTotal :: !Int,
avgFieldLength :: field -> Float,
numDocsWithTerm :: term -> Int,
paramK1 :: !Float,
paramB :: field -> Float,
-- consider minimum length to prevent massive B bonus?
fieldWeight :: field -> Float,
featureWeight :: feature -> Float,
featureFunction :: feature -> FeatureFunction
}
data Doc term field feature = Doc {
docFieldLength :: field -> Int,
docFieldTermFrequency :: field -> term -> Int,
docFeatureValue :: feature -> Float
}
-- | The BM25F score for a document for a given set of terms.
--
score :: (Ix field, Bounded field, Ix feature, Bounded feature) =>
Context term field feature ->
Doc term field feature -> [term] -> Float
score ctx doc terms =
sum (map (weightedTermScore ctx doc) terms)
+ sum (map (weightedNonTermScore ctx doc) features)
where
features = range (minBound, maxBound)
weightedTermScore :: (Ix field, Bounded field) =>
Context term field feature ->
Doc term field feature -> term -> Float
weightedTermScore ctx doc t =
weightIDF ctx t * tf'
/ (k1 + tf')
where
tf' = weightedDocTermFrequency ctx doc t
k1 = paramK1 ctx
weightIDF :: Context term field feature -> term -> Float
weightIDF ctx t =
log ((n - n_t + 0.5) / (n_t + 0.5))
where
n = fromIntegral (numDocsTotal ctx)
n_t = fromIntegral (numDocsWithTerm ctx t)
weightedDocTermFrequency :: (Ix field, Bounded field) =>
Context term field feature ->
Doc term field feature -> term -> Float
weightedDocTermFrequency ctx doc t =
sum [ w_f * tf_f / _B_f
| field <- range (minBound, maxBound)
, let w_f = fieldWeight ctx field
tf_f = fromIntegral (docFieldTermFrequency doc field t)
_B_f = lengthNorm ctx doc field
]
lengthNorm :: Context term field feature ->
Doc term field feature -> field -> Float
lengthNorm ctx doc field =
(1-b_f) + b_f * sl_f / avgsl_f
where
b_f = paramB ctx field
sl_f = fromIntegral (docFieldLength doc field)
avgsl_f = avgFieldLength ctx field
weightedNonTermScore :: (Ix feature, Bounded feature) =>
Context term field feature ->
Doc term field feature -> feature -> Float
weightedNonTermScore ctx doc feature =
w_f * _V_f f_f
where
w_f = featureWeight ctx feature
_V_f = applyFeatureFunction (featureFunction ctx feature)
f_f = docFeatureValue doc feature
data FeatureFunction
= LogarithmicFunction Float -- ^ @log (\lambda_i + f_i)@
| RationalFunction Float -- ^ @f_i / (\lambda_i + f_i)@
| SigmoidFunction Float Float -- ^ @1 / (\lambda + exp(-(\lambda' * f_i))@
applyFeatureFunction :: FeatureFunction -> (Float -> Float)
applyFeatureFunction (LogarithmicFunction p1) = \fi -> log (p1 + fi)
applyFeatureFunction (RationalFunction p1) = \fi -> fi / (p1 + fi)
applyFeatureFunction (SigmoidFunction p1 p2) = \fi -> 1 / (p1 + exp (-fi * p2))
------------------
-- Explanation
--
-- | A breakdown of the BM25F score, to explain somewhat how it relates to
-- the inputs, and so you can compare the scores of different documents.
--
data Explanation field feature term = Explanation {
-- | The overall score is the sum of the 'termScores', 'positionScore'
-- and 'nonTermScore'
overallScore :: Float,
-- | There is a score contribution from each query term. This is the
-- score for the term across all fields in the document (but see
-- 'termFieldScores').
termScores :: [(term, Float)],
{-
-- | There is a score contribution for positional information. Terms
-- appearing in the document close together give a bonus.
positionScore :: [(field, Float)],
-}
-- | The document can have an inate bonus score independent of the terms
-- in the query. For example this might be a popularity score.
nonTermScores :: [(feature, Float)],
-- | This does /not/ contribute to the 'overallScore'. It is an
-- indication of how the 'termScores' relates to per-field scores.
-- Note however that the term score for all fields is /not/ simply
-- sum of the per-field scores. The point of the BM25F scoring function
-- is that a linear combination of per-field scores is wrong, and BM25F
-- does a more cunning non-linear combination.
--
-- However, it is still useful as an indication to see scores for each
-- field for a term, to see how the compare.
--
termFieldScores :: [(term, [(field, Float)])]
}
deriving Show
instance Functor (Explanation field feature) where
fmap f e@Explanation{..} =
e {
termScores = [ (f t, s) | (t, s) <- termScores ],
termFieldScores = [ (f t, fs) | (t, fs) <- termFieldScores ]
}
explain :: (Ix field, Bounded field, Ix feature, Bounded feature) =>
Context term field feature ->
Doc term field feature -> [term] -> Explanation field feature term
explain ctx doc ts =
Explanation {..}
where
overallScore = sum (map snd termScores)
-- + sum (map snd positionScore)
+ sum (map snd nonTermScores)
termScores = [ (t, weightedTermScore ctx doc t) | t <- ts ]
-- positionScore = [ (f, 0) | f <- range (minBound, maxBound) ]
nonTermScores = [ (feature, weightedNonTermScore ctx doc feature)
| feature <- range (minBound, maxBound) ]
termFieldScores =
[ (t, fieldScores)
| t <- ts
, let fieldScores =
[ (f, weightedTermScore ctx' doc t)
| f <- range (minBound, maxBound)
, let ctx' = ctx { fieldWeight = fieldWeightOnly f }
]
]
fieldWeightOnly f f' | sameField f f' = fieldWeight ctx f'
| otherwise = 0
sameField f f' = index (minBound, maxBound) f
== index (minBound, maxBound) f'
|
ocharles/hackage-server
|
Distribution/Server/Features/Search/BM25F.hs
|
bsd-3-clause
| 6,758 | 0 | 19 | 1,991 | 1,540 | 846 | 694 | 110 | 1 |
{-# LANGUAGE TypeFamilies #-}
module B where
import A
data B
type instance F (B,b) = ()
b :: () -> F (B,b)
b = id
|
shlevy/ghc
|
testsuite/tests/driver/recomp017/B.hs
|
bsd-3-clause
| 114 | 0 | 7 | 26 | 54 | 33 | 21 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
-- A very bogus program (multiple errors) but
-- sent GHC 6.12 into a loop
module T3330a where
newtype Writer w a = Writer { runWriter :: (a, w) }
execWriter :: Writer w a -> w
execWriter m = snd (runWriter m)
data AnyF (s :: * -> *) = AnyF
class HFunctor (f :: (* -> *) -> * -> *)
type family PF (phi :: * -> *) :: (* -> *) -> * -> *
children :: s ix -> (PF s) r ix -> [AnyF s]
children p x = execWriter (hmapM p collect x)
{-
0 from instantiating hmap
2 from instantiating collect
(forall ixx. (phi0 ixx -> r0 ixx -> m0 (r'0 ixx) ~ s ix))
phi0 ix0 ~ s2 ix2 -> r2 ix2 -> Writer [AnyF s2] (r2 ix2)
f0 r0 ix0 ~ PF s r ix
m0 (f0 r'0 ix0) ~ Writer [AnyF s] a0
Hence ix0 := ix
r0 := r
f0 := PF s
phi0 := (->) s2 ix2
m0 := Writer [AnyF s]
a0 : = f0 r'0 ix0
(forall ixx. ((->) (s2 ix2 -> ixx) (r ixx -> Writer [AnyF s] (r'0 ixx)) ~ s ix))
s2 ix2 ix0 ~ (->) (s2 ix2) (r2 ix2 -> Writer [AnyF s2] (r2 ix2))
-}
collect :: HFunctor (PF s) => s ix -> r ix -> Writer [AnyF s] (r ix)
collect = error "collect"
hmapM :: (forall ix. phi ix -> r ix -> m (r' ix))
-> phi ix -> f r ix -> m (f r' ix)
hmapM _ = error "hmapM"
|
ezyang/ghc
|
testsuite/tests/indexed-types/should_fail/T3330a.hs
|
bsd-3-clause
| 1,260 | 0 | 12 | 341 | 333 | 176 | 157 | -1 | -1 |
{-# LANGUAGE BangPatterns, MagicHash, UnboxedTuples #-}
-- Test allocation of statically sized arrays. There's an optimization
-- that targets these and we want to make sure that the code generated
-- in the optimized case is correct.
--
-- The tests proceeds by allocating a bunch of arrays of different
-- sizes and reading elements from them, to try to provoke GC crashes,
-- which would be a symptom of the optimization not generating correct
-- code.
module Main where
import Control.Monad
import GHC.Exts
import GHC.IO
import Prelude hiding (read)
main :: IO ()
main = do
loop 1000
putStrLn "success"
where
loop :: Int -> IO ()
loop 0 = return ()
loop i = do
-- Sizes have been picked to match the triggering of the
-- optimization and to match boundary conditions. Sizes are
-- given explicitly as to not rely on other optimizations to
-- make the static size known to the compiler.
marr0 <- newArray 0
marr1 <- newArray 1
marr2 <- newArray 2
marr3 <- newArray 3
marr4 <- newArray 4
marr5 <- newArray 5
marr6 <- newArray 6
marr7 <- newArray 7
marr8 <- newArray 8
marr9 <- newArray 9
marr10 <- newArray 10
marr11 <- newArray 11
marr12 <- newArray 12
marr13 <- newArray 13
marr14 <- newArray 14
marr15 <- newArray 15
marr16 <- newArray 16
marr17 <- newArray 17
let marrs = [marr0, marr1, marr2, marr3, marr4, marr5, marr6, marr7,
marr8, marr9, marr10, marr11, marr12, marr13, marr14,
marr15, marr16, marr17]
total <- sumManyArrays marrs
unless (total == 153) $
putStrLn "incorrect sum"
loop (i-1)
sumManyArrays :: [MArray] -> IO Int
sumManyArrays = go 0
where
go !acc [] = return acc
go acc (marr:marrs) = do
n <- sumArray marr
go (acc+n) marrs
sumArray :: MArray -> IO Int
sumArray marr = go 0 0
where
go :: Int -> Int -> IO Int
go !acc i
| i < len = do
k <- read marr i
go (acc + k) (i+1)
| otherwise = return acc
len = lengthM marr
data MArray = MArray { unMArray :: !(MutableArray# RealWorld Int) }
newArray :: Int -> IO MArray
newArray (I# sz#) = IO $ \s -> case newArray# sz# 1 s of
(# s', marr #) -> (# s', MArray marr #)
{-# INLINE newArray #-} -- to make sure optimization triggers
lengthM :: MArray -> Int
lengthM marr = I# (sizeofMutableArray# (unMArray marr))
read :: MArray -> Int -> IO Int
read marr i@(I# i#)
| i < 0 || i >= len =
error $ "bounds error, offset " ++ show i ++ ", length " ++ show len
| otherwise = IO $ \ s -> readArray# (unMArray marr) i# s
where len = lengthM marr
|
urbanslug/ghc
|
testsuite/tests/codeGen/should_run/StaticArraySize.hs
|
bsd-3-clause
| 2,785 | 0 | 12 | 842 | 831 | 407 | 424 | 68 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Impl.MVar1 where
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import Control.Monad.Trans.Either
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as Map
import Data.Proxy
import Data.Time
import Network.Wai.Handler.Warp (run)
import Servant.API
import Servant.Server
import API
data Environment
= Environment
{ serverFortuneMap :: MVar (HashMap Email Fortune)
}
runApp :: IO ()
runApp = do
env <- createEnvironment
run 8080 $ serve (Proxy :: Proxy API)
( createPlayer env
:<|> tradeFortunes env)
createEnvironment :: IO Environment
createEnvironment = do
fm <- newMVar Map.empty
return $ Environment fm
createPlayer :: Environment -> NewPlayer -> EitherT ServantErr IO ()
createPlayer env player = do
now <- liftIO getCurrentTime
let f = Fortune (npFortune player) now
m <- liftIO $ takeMVar (serverFortuneMap env)
let m' = Map.insert (npEmail player) f m
liftIO $ putMVar (serverFortuneMap env) m'
tradeFortunes :: Environment -> Email -> Email -> EitherT ServantErr IO FortunePair
tradeFortunes env from to = do
m <- liftIO $ takeMVar (serverFortuneMap env)
let mgiven = Map.lookup from m
mreceived = Map.lookup to m
case (mgiven, mreceived) of
(Just given, Just received) -> do
let m' = Map.insert from received m
m'' = Map.insert to given m'
liftIO $ putMVar (serverFortuneMap env) m''
return $ FortunePair given received
_ -> left err404
|
AndrewRademacher/whimsy
|
src/Impl/MVar1.hs
|
mit
| 1,786 | 0 | 16 | 517 | 514 | 260 | 254 | 47 | 2 |
{-
- Comonad implementation of an infinite cellular automata grid, adapted with
- minor modifications from Kukuruku's implementation here:
- http://kukuruku.co/hub/haskell/cellular-automata-using-comonads
-
-}
module Universe where
import Control.Applicative (pure)
import Control.Comonad (Comonad(..))
-- Universe: a comonad/zipper infinite list
data Universe a = Universe [a] a [a]
-- Shift the zipper one element to the left or right
left, right :: Universe a -> Universe a
left (Universe (a:as) x bs) = Universe as a (x:bs)
right (Universe as x (b:bs)) = Universe (x:as) b bs
-- Create a new Universe given functions to create the infinite lists
makeUniverse :: (a -> a) -> (a -> a) -> a -> Universe a
makeUniverse fl fr x = Universe (tail $ iterate fl x) x (tail $ iterate fr x)
-- Build a Universe using a finite list and a default value
fromList :: a -> [a] -> Universe a
fromList def (x:xs) = Universe (repeat def) x (xs ++ repeat def)
instance Functor Universe where
fmap f (Universe as x bs) = Universe (fmap f as) (f x) (fmap f bs)
instance Comonad Universe where
duplicate = makeUniverse left right
extract (Universe _ x _) = x
-- Get the center item and the two adjacent items
nearest3 :: Universe a -> [a]
nearest3 u = map extract [left u, u, right u]
-- Return a range from the zipper using the lower and upper indicies, inclusive.
-- e.g., takeRange (-10, 10) will return the center element and 10 elements
-- from each side
takeRange :: (Int, Int) -> Universe a -> [a]
takeRange (a, b) u = take (b-a+1) x
where Universe _ _ x
| a < 0 = iterate left u !! (-a + 1)
| otherwise = iterate right u !! (a - 1)
-- Two-dimensional comonad/zipper
newtype Universe2D a = Universe2D { getUniverse2D :: Universe (Universe a) }
instance Functor Universe2D where
fmap f = Universe2D . (fmap . fmap) f . getUniverse2D
instance Comonad Universe2D where
extract = extract . extract . getUniverse2D
duplicate = fmap Universe2D . Universe2D . shifted . shifted . getUniverse2D
where shifted :: Universe (Universe a) -> Universe (Universe (Universe a))
shifted = makeUniverse (fmap left) (fmap right)
-- Build a Universe2D given a list of lists and a default value
fromList2D :: a -> [[a]] -> Universe2D a
fromList2D def = Universe2D . fromList udef . fmap (fromList def)
where udef = Universe (repeat def) def (repeat def)
-- Return a rectangle from the 2D zipper using a bounding box, inclusive.
takeRange2D :: (Int, Int) -> (Int, Int) -> Universe2D a -> [[a]]
takeRange2D (x0, y0) (x1, y1)
= takeRange (y0, y1) . fmap (takeRange (x0, x1)) . getUniverse2D
-- Get the 8 cells surrounding the center cell in a Universe2D
neighbors :: Universe2D a -> [a]
neighbors u =
[ nearest3 . extract . left -- 3 cells in row above
, pure . extract . left . extract -- cell to the left
, pure . extract . right . extract -- cell to the right
, nearest3 . extract . right -- 3 cells in row below
] >>= ($ getUniverse2D u)
|
billpmurphy/conway-combat
|
Universe.hs
|
mit
| 3,075 | 0 | 13 | 695 | 970 | 514 | 456 | 44 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Nauva.Product.Varna.Shared
( root
, batteryCard
) where
import qualified Data.Aeson as A
import Nauva.View
import Nauva.Service.Head
import Nauva.Product.Varna.Element.Card
import Prelude hiding (rem)
root :: HeadH -> Element
root = component_ rootComponent
rootComponent :: Component HeadH () () ()
rootComponent = createComponent $ \cId -> Component
{ componentId = cId
, componentDisplayName = "Root"
, initialComponentState = \p -> pure ((), [], [updateHead p])
, componentEventListeners = \_ -> []
, componentHooks = emptyHooks
, processLifecycleEvent = \_ _ s -> (s, [])
, receiveProps = \_ s -> pure (s, [], [])
, update = \_ p _ -> ((), [updateHead p])
, renderComponent = render
, componentSnapshot = \_ -> A.Null
, restoreComponent = \_ s -> Right (s, [])
}
where
updateHead :: HeadH -> IO (Maybe ())
updateHead headH = do
hReplace headH
[ style_ [str_ "*,*::before,*::after{box-sizing:inherit}body{margin:0;box-sizing:border-box}"]
, title_ [str_ "Varna"]
]
pure Nothing
render _ _ = div_ [style_ rootStyle] $
[ navbar
, batteries
[ batteryCard
[ batteryCardBodyParagraph True [str_ "This looks like a fresh battery. Congratulations on your purchase."]
, batteryCardBodyPrimaryButton "charge battery"
, batteryCardBodySecondaryButton "discharge battery"
]
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
, batteryCard []
]
]
where
rootStyle :: Style
rootStyle = mkStyle $ do
height (vh 100)
display flex
flexDirection column
fontFamily "museo-slab, serif"
navbar :: Element
navbar = div_ [style_ rootStyle]
[ div_ [style_ navbarItemStyle] [ str_ "Home" ]
, div_ [style_ navbarItemStyle] [ str_ "Create Battery" ]
, null_
, div_ [style_ navbarItemStyle] [ str_ "Account" ]
]
where
rootStyle :: Style
rootStyle = mkStyle $ do
display flex
flexDirection row
height (rem 3)
backgroundColor "rgb(126, 120, 3)"
color "rgb(228, 228, 238)"
fontSize (rem 1.8)
lineHeight (rem 3)
flexShrink "0"
navbarItemStyle :: Style
navbarItemStyle = mkStyle $ do
padding (rem 0) (rem 0.5)
cursor pointer
onHover $ do
backgroundColor "#999"
batteries :: [Element] -> Element
batteries = div_ [style_ rootStyle]
where
rootStyle = mkStyle $ do
marginTop (rem 1)
display flex
flexDirection row
flexWrap wrap
|
wereHamster/nauva
|
product/varna/shared/src/Nauva/Product/Varna/Shared.hs
|
mit
| 3,087 | 0 | 15 | 1,038 | 840 | 436 | 404 | 84 | 1 |
{-# LANGUAGE TupleSections, RecordWildCards, DeriveGeneric #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
------------------------------------------------------------------------------
-- |
-- Module : Mahjong.Kyoku
-- Copyright : (C) 2014 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This module provides a mahjong state machine @Machine@ with state
-- @Kyoku@.
------------------------------------------------------------------------------
module Mahjong.Kyoku
( -- * Types
InKyoku, Machine(..), MachineInput(..), Flag(..)
-- * Actions
, step
, dealGameEvent
, updatePlayerNick
, tellPlayerState
, maybeNextDeal
-- * Utility
, playerToKaze
, getShouts
, nextRound
, getValuedHand
, module Mahjong.Kyoku.Internal
) where
------------------------------------------------------------------------------
import Import
import Mahjong.Tiles
import Mahjong.Hand
import Mahjong.Configuration
------------------------------------------------------------------------------
import Mahjong.Kyoku.Flags
import Mahjong.Kyoku.Internal
------------------------------------------------------------------------------
import qualified Data.Map as Map
import Data.Monoid (Endo(..))
import qualified Data.List as L (delete, findIndex, (!!))
-- | Context of game and deal flow.
--
-- Don't use the state monad yourself! always use tellEvent
type InKyoku m =
( MonadState Kyoku m
, MonadWriter [GameEvent] m
, MonadError Text m
, Functor m
, Applicative m
, Monad m )
handOf :: Kaze -> Lens Kyoku Kyoku (Maybe Hand) (Maybe Hand)
handOf pk = sHands.at pk
----------------------------------------------------------------------------------------
-- * Logic
-- | Game automata
data Machine = KyokuNone -- ^ No tiles in the table atm
| KyokuStartIn Int -- ^ Number of seconds before kyoku starts. Tiles dealt.
| CheckEndConditionsAfterDiscard
| WaitingDraw Kaze Bool
| WaitingDiscard Kaze
| WaitingShouts (Set Kaze) [Int] [(Kaze, Shout)] Bool -- ^ set of players who could shout but have not (passed), index of now winning shout(s), flag: chankan? (to continue with discard)
| KyokuEnded KyokuResults
| HasEnded FinalPoints -- ^ This game has ended
deriving (Eq, Show, Read, Generic)
-- | @MachineInput@ consists of two parts: actions from clients a la
-- @GameAction@, and actions from the managing process i.e. advances to
-- next rounds and automatic advances after timeouts.
data MachineInput = InpAuto -- ^ Whatever the current state is, do an action that advances it to the next state
| InpTurnAction Kaze TurnAction -- ^ An action from player in turn
| InpShout Kaze Shout -- ^ A call
| InpPass Kaze -- ^ Ignore call
deriving (Show, Read)
-- | Remember to publish the turn action when successful
step :: InKyoku m => Machine -> MachineInput -> m Machine
step KyokuNone _ = return KyokuNone
step (KyokuStartIn _) InpAuto = sendDealStarts >> waitForDraw -- startDeal
step (WaitingDraw pk wanpai) InpAuto = draw pk wanpai >> askForTurnAction 15 >> return (WaitingDiscard pk) -- TODO hard-coded timeout
step (WaitingDraw pk wanpai) (InpTurnAction pk' (TurnTileDraw wanpai' _))
| wanpai /= wanpai' = throwError "You are not supposed to draw there"
| pk /= pk' = throwError $ "Not your (" ++ tshow pk' ++ ") turn, it's turn of " ++ tshow pk
| otherwise = draw pk wanpai >> askForTurnAction 15 >> return (WaitingDiscard pk) -- TODO hard-coded timeout
step (WaitingDiscard pk) InpAuto = autoDiscard pk
step (WaitingDiscard pk) (InpTurnAction pk' ta)
| pk /= pk' = throwError $ "Not your (" ++ tshow pk' ++ ") turn, it's turn of " ++ tshow pk
| TurnTileDiscard d <- ta = processDiscard pk d
| TurnAnkan t <- ta = processAnkan pk t
| TurnTsumo <- ta = endKyoku =<< endTsumo pk
| TurnShouminkan t <- ta = processShouminkan pk t
step (WaitingShouts _ winning shouts chankan) InpAuto
| null winning = proceedWithoutShoutsAfterDiscard chankan
| otherwise = processShouts (map (shouts L.!!) winning) chankan
step (WaitingShouts couldShout winning shouts chankan) (InpPass pk) = do
let couldShout' = deleteSet pk couldShout
p <- kazeToPlayer pk
tellEvent $ DealWaitForShout (p, pk, 0, [])
if' (null couldShout') (flip step InpAuto) return $ WaitingShouts couldShout' winning shouts chankan
step (WaitingShouts couldShout winning shouts chankan) (InpShout pk shout)
| pk `onotElem` couldShout, elemOf (each._1) pk shouts = throwError "You have already called on that tile"
| Just i <- L.findIndex (== (pk, shout)) shouts = do
res <- use pTurn >>= \tk -> case winning of
j:js -> case shoutPrecedence tk (shouts L.!! j) (pk, shout) of -- XXX: Would be prettier with a view-pattern
EQ -> return $ WaitingShouts (deleteSet pk couldShout) (i:j:js) shouts chankan -- new goes through with old ones
GT -> return $ WaitingShouts couldShout (j:js) shouts chankan -- old takes precedence (XXX: this branch should never even be reached
LT -> return $ WaitingShouts (deleteSet pk couldShout) [i] shouts chankan -- new takes precedence
[] -> return $ WaitingShouts (deleteSet pk couldShout) [i] shouts chankan
p <- kazeToPlayer pk
tellEvent $ DealWaitForShout (p, pk, 0, [])
case res of
WaitingShouts couldShout' _ _ _ | null couldShout' -> step res InpAuto
_ -> return res
| otherwise = throwError $ "Call '" ++ tshow shout ++ "' not possible (Your possible calls at the moment are: "
++ tshow (filter ((==pk).fst) shouts) ++ ")"
step CheckEndConditionsAfterDiscard InpAuto = checkEndConditions
step (KyokuEnded{}) InpAuto = do
k <- get
case maybeGameResults k of
Nothing -> return KyokuNone
Just res -> endGame res
step HasEnded{} _ = throwError "This game has ended!"
step st inp = throwError $ "Kyoku.step: Invalid input in state " <> tshow st <> ": " <> tshow inp
-- | chankan?
proceedWithoutShoutsAfterDiscard :: InKyoku m => Bool -> m Machine
proceedWithoutShoutsAfterDiscard chankan = if' chankan (WaitingDiscard <$> use pTurn) (return CheckEndConditionsAfterDiscard)
dealGameEvent :: GameEvent -> Kyoku -> Kyoku
dealGameEvent ev = appEndo . mconcat $ case ev of
DealTurnBegins p ->
[ Endo $ pTurn .~ p
, Endo $ sWaiting .~ Nothing ]
DealTurnAction p ta ->
[ dealTurnAction p ta ]
DealTurnShouted p _shout ->
[ Endo $ pTurn .~ p ]
-- TODO get rid these in favor of finer control?
DealPublicHandChanged _pk _hp -> [ ]
-- [ Endo $ sHands.ix pk.handPublic .~ hp ]
DealPrivateHandChanged _ pk h ->
[ Endo $ sHands.ix pk .~ h ]
DealEnded how ->
[ Endo $ pResults .~ Just how ]
DealNick pk player nick ->
[ Endo $ pPlayers . ix pk . _3 .~ nick
, Endo $ pPlayers . ix pk . _1 .~ player ]
-- player-private
DealStarts{} -> [ ]
DealWaitForShout ws ->
[ Endo $ sWaiting %~ Just . Right . maybe [ws] (either (const [ws]) (|> ws)) ]
DealWaitForTurnAction wt ->
[ Endo $ sWaiting .~ Just (Left wt) ]
DealRiichi _pk ->
[ Endo $ pRiichi +~ 1000 ]
DealFlipDora td -> [ Endo $ pDora %~ (|> td) ]
GamePoints pk ps ->
[ Endo $ pPlayers.ix pk._2 +~ ps ]
GameEnded _ -> []
dealTurnAction :: Kaze -> TurnAction -> Endo Kyoku
dealTurnAction p ta = mconcat $ case ta of
TurnTileDiscard dc ->
[ Endo $ sHands.ix p.handDiscards %~ (|> dc) ]
TurnTileDraw _w _ ->
[ Endo $ pWallTilesLeft -~ 1 ]
TurnAnkan _ ->
[ ]
-- [ Endo $ sHands.ix p.handCalled %~ (|> kantsu tile) ]
TurnShouminkan _ ->
[ ]
-- let isShoum m = mentsuKind m == Koutsu && mentsuTile m == t
-- in [ Endo $ sHands.ix p.handPublic.handCalled.each . filtered isShoum %~ promoteToKantsu ]
TurnTsumo ->
[] -- XXX: should something happen?
-- | Results are returned if west or higher round has just ended and
-- someone is winning (over 30000 points).
maybeGameResults :: Kyoku -> Maybe FinalPoints
maybeGameResults kyoku@Kyoku{..}
| minimumOf (traversed._2) _pPlayers < Just 0 = return score -- if anyone below zero end immediately
| otherwise = do
guard (nextRound kyoku ^. _1 > Nan) -- Don't end before *last* south deal
unless (nextRound kyoku ^. _1 > Shaa) $ -- Require point-difference, unless last deal of an extra-round ended
guard (maximumOf (traversed._2) _pPlayers > Just 30000)
return score
where
score = finalPoints $ mapFromList $ _pPlayers ^.. each.to (\(p,ps,_) -> (p, ps))
nextRound :: Kyoku -> Round
nextRound Kyoku{..} = case _pResults of
Just DealAbort{..} -> _pRound & _3 +~ 1
Just DealDraw{..} -> _pRound & if elemOf (each._1) Ton dTenpais then _3 +~ 1 else set _3 (_pRound^._3 + 1) . roundRotates
Just DealRon{..} -> _pRound & if elemOf (each._1) Ton dWinners then _3 +~ 1 else roundRotates
Just DealTsumo{..} -> _pRound & if elemOf (each._1) Ton dWinners then _3 +~ 1 else roundRotates
Nothing -> _pRound
where
roundRotates (k, 4, _) = (succCirc k, 1, 0)
roundRotates (k, r, _) = (k, r + 1, 0)
-- | Advance the game to next deal, or end it.
-- TODO move to Round.hs
maybeNextDeal :: Kyoku -> IO (Either FinalPoints Kyoku)
maybeNextDeal deal = maybe (Right <$> nextDeal deal) (return . Left) $ maybeGameResults deal
-- | TODO move to Round.hs. Everything but tile shuffling could be in
-- events.
nextDeal :: Kyoku -> IO Kyoku
nextDeal kyoku = do tiles <- shuffleTiles
return $ go $ dealTiles tiles kyoku
where
go = set pRound newRound
. set pTurn Ton
. set pHonba (newRound^._3)
. if' rotate (pOja .~ nextOja) id
. if' rotate (over pPlayers rotatePlayers) id
. if' riichiTransfers (pRiichi .~ 0) id
. set pResults Nothing
newRound = nextRound kyoku
rotate = newRound^._2 /= kyoku^.pRound._2
riichiTransfers = case kyoku^?!pResults of
Just DealAbort{} -> False
Just DealDraw{} -> False
_ -> True
nextOja = kyoku ^?! pPlayers.ix Nan . _1 :: Player
rotatePlayers :: Map Kaze a -> Map Kaze a
rotatePlayers = mapFromList . map (_1 %~ predCirc) . mapToList
nagashiOrDraw :: InKyoku m => m Machine
nagashiOrDraw = do
hands <- use sHands
wins <- iforM hands $ \pk hand -> if handInNagashi hand then return $ handWinsNagashi pk hand else return Nothing
let winners = map fst $ catMaybes $ map snd $ mapToList wins :: [Winner]
payers = map (\xs@((p,_):_) -> (p, sumOf (traversed._2) xs)) $ groupBy (equating fst) $ (concatMap snd $ catMaybes $ map snd $ mapToList wins) :: [Payer]
res <- if null winners then endDraw else return $ DealTsumo winners payers
endKyoku res
handWinsNagashi :: Kaze -> Hand -> Maybe (Winner, [Payer])
handWinsNagashi pk hand =
-- TODO perhaps this could be placed in YakuCheck too
let points = floor $ if' (pk == Ton) 1.5 1 * 8000
value = Value [Yaku 5 "Nagashi Mangan"] 0 5 0 (Just "Mangan")
winner = (pk, points, ValuedHand (hand^.handCalled) (hand^.handConcealed) value)
-- TODO fails when not four players
payers = map (\payer -> (payer, if' (payer == Ton) 2 1 * 2000)) $ L.delete pk [Ton .. Pei]
in Just (winner, payers)
processAnkan :: InKyoku m => Kaze -> Tile -> m Machine
processAnkan pk t = do
handOf' pk >>= ankanOn t >>= updateHand pk
otherHands <- use sHands <&> filter ((/=pk).fst) . Map.toList
let kokushiWins = filter ((== NotFuriten) . _handFuriten . snd) $
filter ((== Just (-1)) . shantenBy kokushiShanten . (handConcealed %~ cons t) . snd) otherHands
if null kokushiWins -- chankan on ankan only when kokushi could win from it
then return $ WaitingDraw pk True
else return $ WaitingShouts (setFromList $ map fst kokushiWins) [] (each._2 .~ Shout Chankan pk t [] $ kokushiWins) True
processShouminkan :: InKyoku m => Kaze -> Tile -> m Machine
processShouminkan pk t = do
handOf' pk >>= shouminkanOn t >>= updateHand pk
chankanShouts <- getShouts True t
if null chankanShouts then return (WaitingDraw pk True)
else do tellEvents . map DealWaitForShout =<< toWaitShouts chankanShouts
return (WaitingShouts (setFromList $ map fst chankanShouts) [] chankanShouts True)
checkEndConditions :: InKyoku m => m Machine
checkEndConditions = do
updateTempFuritens
tilesLeft <- use pWallTilesLeft
dora <- use pDora
everyoneRiichi <- use sHands <&> allOf (each.handRiichi) (/= NoRiichi)
firstDiscards <- use sHands <&> toListOf (each.handDiscards._head.dcTile)
let fourWindTiles = length firstDiscards == 4 && isKaze (headEx firstDiscards) && allSame firstDiscards
case () of
_ | length dora == 5 -> endKyoku $ DealAbort SuuKaikan -- TODO check that someone is not waiting for the yakuman
| tilesLeft == 0 -> nagashiOrDraw
| everyoneRiichi -> endKyoku $ DealAbort SuuchaRiichi
| fourWindTiles -> endKyoku $ DealAbort SuufonRenda
| otherwise -> advanceTurn <&> (`WaitingDraw` False)
where
allSame :: [Tile] -> Bool
allSame [] = True
allSame (x:xs) = all (x ==~) xs
-- ** Beginning
-- | Send the very first Kyoku events to everyone. Contains the game state.
sendDealStarts :: InKyoku m => m ()
sendDealStarts = do
deal <- get
imapM_ (\pk (player,_,_) -> tellEvent . DealStarts $ PlayerKyoku player pk deal) (deal^.pPlayers)
-- ** Drawing
-- | WaitingDraw, not wanpai
waitForDraw :: InKyoku m => m Machine
waitForDraw = do
pk <- use pTurn
h <- handOf' pk
updateHand pk $ h & handState .~ DrawFromWall
tellEvent $ DealTurnBegins pk
return $ WaitingDraw pk False
draw :: InKyoku m => Kaze -> Bool -> m ()
draw pk wanpai = do
firstRound <- use $ pFlags.to (member FirstRoundUninterrupted)
when firstRound $ do
allHandsInterrupted <- use sHands <&> allOf (each.handFlags) (notMember HandFirsRoundUninterrupted)
when allHandsInterrupted $ unsetFlag FirstRoundUninterrupted
updateHand pk =<< (if wanpai then drawDeadWall else drawWall) =<< handOf' pk
tellEvent $ DealTurnAction pk $ TurnTileDraw wanpai Nothing
drawWall :: InKyoku m => Hand -> m Hand
drawWall hand = do
wallHead <- preuse (sWall._head) >>= maybe (throwError "Wall is empty") return
sWall %= tailEx
wallHead `toHand` hand
drawDeadWall :: InKyoku m => Hand -> m Hand
drawDeadWall hand = do
lastTileInWall <- preuse (sWall._last) >>= maybe (throwError "Wall is empty") return
fromWanpai <- wanpaiGetSupplement lastTileInWall
flipNewDora -- TODO should it flip now or after the discard?
fromWanpai `toHandWanpai` hand
-- ** Discarding
processDiscard :: InKyoku m => Kaze -> Discard -> m Machine
processDiscard pk d' = do
let d = d' & dcTo .~ Nothing
when (d^.dcRiichi) $ doRiichi pk
updateHand pk =<< discard d =<< handOf' pk
shouts <- getShouts False (d^.dcTile)
waiting <- toWaitShouts shouts
tellEvents $ map DealWaitForShout waiting
return $ if null waiting
then CheckEndConditionsAfterDiscard
else WaitingShouts (setFromList $ map fst shouts) [] shouts False
doRiichi :: InKyoku m => Kaze -> m ()
doRiichi pk = do
pointsAfterRiichi <- use $ pPlayers.at pk.singular _Just._2.to (\a -> a - 1000)
when (pointsAfterRiichi < 0) $ throwError "Cannot riichi: not enough points"
tellEvents [DealRiichi pk, GamePoints pk (-1000)]
autoDiscard :: InKyoku m => Kaze -> m Machine
autoDiscard tk = processDiscard tk =<< handAutoDiscard =<< handOf' tk
-- | Update temporary furiten state of all players after a discard.
updateTempFuritens :: InKyoku m => m ()
updateTempFuritens = do
pk <- use pTurn
tile <- _dcTile . lastEx . _handDiscards <$> handOf' pk
handOf' pk >>= \h -> case h^.handFuriten of
NotFuriten | tile `elem` handGetAgari h -> updateHand pk $ h & handFuriten .~ TempFuriten
TempFuriten -> updateHand pk $ h & handFuriten .~ NotFuriten
_ -> return ()
forM_ (L.delete pk [Ton .. Pei]) $ \k -> handOf' k >>= \h -> case h^.handFuriten of
NotFuriten | tile `elem` handGetAgari h -> updateHand k $ h & handFuriten .~ TempFuriten
_ -> return ()
-- ** Turn-passing
-- | Next player who draws a tile
advanceTurn :: InKyoku m => m Kaze
advanceTurn = do
pk <- use pTurn <&> succCirc
updateHand pk . set handState DrawFromWall =<< handOf' pk
tellEvent $ DealTurnBegins pk
return pk
-- ** Wanpai
-- | Flip a new dora from wanpai. If the kyoku would end in suukaikan after
-- the next discard, set the @SuuKaikanAfterDiscard@ flag.
--
-- Note: does not check if the filp is valid.
flipNewDora :: InKyoku m => m ()
flipNewDora = tellEvent . DealFlipDora =<< wanpaiGetDora
-- | Reveals opened ura-dora from the wanpai. Toggles the @OpenedUraDora@
-- flag.
revealUraDora :: InKyoku m => m ()
revealUraDora = do
count <- use (pDora.to length)
ura <- use (sWanpai.wUraDora) <&> take count
tellEvent $ DealFlipDora ura
setFlag . OpenedUraDora $ map TileEq ura
-- | Get supplementary tile from wanpai. Argument must be a tile from
-- the wall to append to the wall.
wanpaiGetSupplement :: InKyoku m => Tile -> m Tile
wanpaiGetSupplement fromWall = preuse (sWanpai.wSupplement._Cons) >>= \case
Just (x, xs) -> do sWanpai.wSupplement .= xs
sWanpai.wBlank %= flip snoc fromWall
return x
Nothing -> throwError "Four kantsu already called"
wanpaiGetDora :: InKyoku m => m Tile
wanpaiGetDora = preuse (sWanpai.wDora._Cons) >>= \case
Just (x, xs) -> sWanpai.wDora .= xs >> return x
Nothing -> throwError "Internal error: no dora left in wanpai"
-- ** Waiting
-- | n seconds
askForTurnAction :: InKyoku m => Int -> m ()
askForTurnAction n = do
tk <- use pTurn
tp <- kazeToPlayer tk
rt <- handOf' tk <&> handCanRiichiWith
tellEvent $ DealWaitForTurnAction (tp, tk, n, rt)
-- | @processShout shouts chankan?@
--
-- Multiple shouts are allowed only when they go out
processShouts :: InKyoku m => [(Kaze, Shout)] -> Bool -> m Machine
processShouts [] _ = return $ CheckEndConditionsAfterDiscard
processShouts shouts@((fsk,fs):_) _chank = do
tk <- use pTurn
th <- handOf' tk
(th':_) <- forM shouts $ \(sk, s) -> do
sh <- handOf' sk
th' <- shoutFromHand sk s th
sh' <- if null (shoutTo s) then rons s sh else meldTo s sh -- if null then kokushi. can't use a mentsu 'cause mentsu have >=2 tiles
updateHand sk sh'
tellEvent $ DealTurnShouted sk s
return th'
updateHand tk th'
case () of
_ | shoutKind fs `elem` [Ron, Chankan] -> endRon (map fst shouts) tk >>= endKyoku
| shoutKind fs == Kan -> unsetFlag FirstRoundUninterrupted >> return (WaitingDraw fsk True)
| otherwise -> do
unsetFlag FirstRoundUninterrupted
tellEvent $ DealTurnBegins fsk
return (WaitingDiscard fsk)
-- ** Ending
endKyoku :: InKyoku m => KyokuResults -> m Machine
endKyoku res = return (KyokuEnded res)
endGame :: InKyoku m => FinalPoints -> m Machine
endGame points = do tellEvent $ GameEnded points
return $ HasEnded points
endTsumo :: InKyoku m => Kaze -> m KyokuResults
endTsumo winner = do
handOf' winner >>= updateHand winner . setAgariTsumo
vh <- getValuedHand winner
honba <- use pHonba
riichi <- use pRiichi
payers <- use pPlayers <&> tsumoPayers honba (vh^.vhValue.vaValue) . L.delete winner . map fst . itoList
let win = (winner, - sumOf (each._2) payers + riichi, vh)
dealEnds $ DealTsumo [win] payers
endDraw :: InKyoku m => m KyokuResults
endDraw = do
hands <- use sHands
let x@(tenpaiHands, nootenHands) = partition (tenpai.snd) (itoList hands) -- & both.each %~ fst
(receive, pay) | null tenpaiHands || null nootenHands = (0, 0)
| otherwise = x & both %~ div 3000.fromIntegral.length
dealEnds $ DealDraw (map (\(k,h) -> (k,receive,h^.handCalled,h^.handConcealed)) tenpaiHands) (map ((,-pay) . fst) nootenHands)
endRon :: InKyoku m => [Kaze] -> Kaze -> m KyokuResults
endRon winners payer = do
valuedHands <- mapM getValuedHand winners
honba <- use pHonba
riichi <- use pRiichi
let pointsFromPayer = zipWith valuedHandPointsForRon winners valuedHands
pointsRiichi = riichi
pointsHonba = honba * 300
Just extraGoesTo = payer ^.. iterated succCirc & find (`elem` winners) -- Iterate every kaze, so one must be an element. unless no one won.
winEntries = map (\x -> if x^._1 == extraGoesTo then x & _2 +~ pointsHonba + pointsRiichi else x) $ zip3 winners pointsFromPayer valuedHands
dealEnds $ DealRon winEntries [(payer, negate $ pointsHonba + sum pointsFromPayer)]
-- *** Helpers
valuedHandPointsForRon :: Kaze -> ValuedHand -> Points
valuedHandPointsForRon pk vh = roundKyokuPoints $ if' (pk == Ton) 6 4 * (vh^.vhValue.vaValue)
-- | Apply KyokuResults and pay points.
dealEnds :: InKyoku m => KyokuResults -> m KyokuResults
dealEnds results = do
tellEvents $ DealEnded results : payPoints results
return results
-- | Value the hand. If the hand would be valueless (no yaku, just extras),
-- raise an error.
getValuedHand :: InKyoku m => Kaze -> m ValuedHand
getValuedHand pk = do
revealUraDora -- TODO wrong place for this
vh <- valueHand pk <$> handOf' pk <*> use id
when (length (vh^..vhValue.vaYaku.each.filtered yakuNotExtra) == 0) $
throwError $ "Need at least one yaku that ain't dora to win.\nThe ValuedHand: " ++ tshow vh
return vh
-- ** Scoring
payPoints :: KyokuResults -> [GameEvent]
payPoints res = case res of
DealAbort{} -> []
DealDraw{..} -> map (uncurry GamePoints) $ map (\x -> (x^._1,x^._2)) dTenpais ++ dNooten
_ -> map f (dWinners res) ++ map (uncurry GamePoints) (dPayers res)
where f (p, v, _) = GamePoints p v
-- |
-- >>> roundKyokuPoints 150
-- 200
--
-- >>> roundKyokuPoints 500
-- 500
roundKyokuPoints :: Points -> Points
roundKyokuPoints x = case x `divMod` 100 of
(a, b) | b > 0 -> (a + 1) * 100
| otherwise -> a * 100
-- |
-- @tsumoPayers honba winner basicPoints payers@
--
-- >>> tsumoPayers 0 320 [Nan, Shaa, Pei]
-- [(Nan,-700),(Shaa,-700),(Pei,-700)]
--
-- >>> tsumoPayers 1 320 [Ton, Shaa, Pei]
-- [(Ton,-800),(Shaa,-500),(Pei,-500)]
--
tsumoPayers :: Int -> Points -> [Kaze] -> [Payer]
tsumoPayers honba basic payers
| Ton `elem` payers = map (\p -> (p, negate $ roundKyokuPoints $ basic * if' (p == Ton) 2 1 + honba * 100)) payers
| otherwise = map ( , negate $ roundKyokuPoints $ basic * 2 + honba * 100) payers
-- * Final scoring
-- |
-- >>> finalPoints (Map.fromList [(Player 0,25000), (Player 1,25000), (Player 2,25000), (Player 3,25000)])
-- FinalPoints (fromList [(Player 0,35),(Player 1,5),(Player 2,-15),(Player 3,-25)])
--
-- >>> finalPoints (Map.fromList [(Player 0, 35700), (Player 1, 32400), (Player 2, 22200), (Player 3, 9700)])
-- FinalPoints (fromList [(Player 0,46),(Player 1,12),(Player 2,-18),(Player 3,-40)])
finalPoints :: PointsStatus -> FinalPoints
finalPoints xs = final & _head._2 -~ sumOf (each._2) final -- fix sum to 0
& Map.fromList & FinalPoints
where
target = 30000 -- TODO configurable target score
oka = 5000 * 4 -- TODO could be something else
uma = [20, 10, -10, -20] -- TODO This too
final = Map.toList xs & sortBy (flip $ comparing snd)
& each._2 -~ target
& _head._2 +~ oka
& each._2 %~ roundFinalPoints
& zipWith (\s (p, s') -> (p, s + s')) uma
-- |
-- >>> roundFinalPoints 15000
-- 15
-- >>> roundFinalPoints (-5000)
-- -5
roundFinalPoints :: Int -> Int
roundFinalPoints x = case x `divMod` 1000 of
(r, b) | b >= 500 -> r + 1
| otherwise -> r
----------------------------------------------------------------------------------------
-- * Events
tellPlayerState :: InKyoku m => Player -> m ()
tellPlayerState p = do
pk <- playerToKaze p
deal <- get
tellEvent . DealStarts $ PlayerKyoku p pk deal
updatePlayerNick :: InKyoku m => Player -> Text -> m ()
updatePlayerNick p nick = playerToKaze p >>= \pk -> tellEvent (DealNick pk p nick)
-- | Set the hand of player
updateHand :: InKyoku m => Kaze -> Hand -> m ()
updateHand pk new = do
p <- kazeToPlayer pk
sHands.at pk .= Just new
tellEvent (DealPrivateHandChanged p pk new)
tellEvent (DealPublicHandChanged pk $ PlayerHand new)
tellEvent :: InKyoku m => GameEvent -> m ()
tellEvent ev = do
modify $ dealGameEvent ev
tell [ev]
tellEvents :: InKyoku m => [GameEvent] -> m ()
tellEvents = mapM_ tellEvent
----------------------------------------------------------------------------------------
-- * Query info
playerToKaze :: InKyoku m => Player -> m Kaze
playerToKaze player = do
mp <- use pPlayers <&> ifind (\_ x -> x^._1 == player)
maybe (throwError $ "Player `" ++ tshow player ++ "' not found") (return . fst) mp
kazeToPlayer :: InKyoku m => Kaze -> m Player
kazeToPlayer pk = do
rp <- use pPlayers <&> view (at pk)
maybe (throwError $ "Player `" ++ tshow pk ++ "' not found") (return . (^._1)) rp
handOf' :: InKyoku m => Kaze -> m Hand
handOf' p = use (handOf p) >>= maybe (throwError "handOf': Player not found") return
----------------------------------------------------------------------------------------
-- * Waiting
-- | Get all possible shouts from all players for a given tile.
filterCouldShout :: Tile -- ^ Tile to shout
-> Kaze -- ^ Whose tile
-> Map Kaze Hand -- ^ All hands
-> [(Kaze, Shout)] -- ^ Sorted in correct precedence (highest priority as head)
filterCouldShout dt np = sortBy (shoutPrecedence np)
. concatMap flatten . Map.toList
. Map.mapWithKey (shoutsOn np dt)
. Map.filter ((== NotFuriten) . _handFuriten) -- discard furiten
where flatten (k, xs) = map (k,) xs
-- | Flag for chankan.
getShouts :: InKyoku m => Bool -> Tile -> m [(Kaze, Shout)]
getShouts chankan dt = do
lastTile <- use pWallTilesLeft <&> (== 0)
shouts <- filterCouldShout dt <$> use pTurn <*> use sHands
filterM couldContainYaku $
if' chankan (over (each._2) toChankan . filter ((== Ron) . shoutKind.snd)) id $
if' lastTile (filter $ (== Ron) . shoutKind . snd) id -- when there are no tiles, only go-out shouts are allowed
shouts
yakuNotExtra :: Yaku -> Bool
yakuNotExtra Yaku{} = True
yakuNotExtra YakuExtra{} = False
toChankan :: Shout -> Shout
toChankan s = s { shoutKind = Chankan }
-- | The shout wouldn't result in a 0-yaku mahjong call
couldContainYaku :: InKyoku m => (Kaze, Shout) -> m Bool
couldContainYaku (k, s)
| Ron <- shoutKind s = do
h <- handOf' k
vh <- valueHand k <$> meldTo s h <*> get
return $ length (vh^..vhValue.vaYaku.each.filtered yakuNotExtra) /= 0
| otherwise = return True
toWaitShouts :: InKyoku m => [(Kaze, Shout)] -> m [WaitShout]
toWaitShouts shouts = do
let grouped = map (liftA2 (,) (^?!_head._1) (^..each._2)) $ groupBy ((==) `on` view _1) shouts
forM grouped $ \(k, s) -> do
player <- kazeToPlayer k
return (player, k, 15, s)
-- * Flags
unsetFlag, setFlag :: InKyoku m => Flag -> m ()
setFlag f = void $ pFlags %= insertSet f
unsetFlag f = void $ pFlags %= deleteSet f
|
SimSaladin/hajong
|
hajong-server/src/Mahjong/Kyoku.hs
|
mit
| 28,620 | 0 | 21 | 7,312 | 8,552 | 4,277 | 4,275 | -1 | -1 |
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE PolyKinds #-}
module QuickForm.Validation where
import Data.Default
import QuickForm.Form
import QuickForm.TypeLevel
-- | Validation functions
data Validator (q :: QuickForm) where
ValidatedVal :: (FormOutput q -> Either e a) -> Validator q -> Validator (Validated e a q)
FieldVal :: Validator (Field n a)
FieldsVal :: TList (Map Validator qs) -> Validator (Fields qs)
class ValidateForm q where
validateForm :: Validator q -> Form q -> Result q
instance FormOutput (Field n a) ~ ToForm (Field n a) => ValidateForm (Field n a) where
validateForm FieldVal (Form a) = Success a
{-# INLINE validateForm #-}
instance (JoinFields qs, ValidateFields qs)
=> ValidateForm (Fields qs) where
validateForm fs as = joinFields $ validateFields fs as
{-# INLINE validateForm #-}
instance (Default (FormError q), ValidateForm q)
=> ValidateForm (Validated e a q) where
validateForm (ValidatedVal f sub) (Form b)
= runValidated f $ validateForm sub $ Form b
{-# INLINE validateForm #-}
instance Default (Validator (Field n a)) where
def = FieldVal
instance Default (TList (Map Validator qs))
=> Default (Validator (Fields qs)) where
def = FieldsVal def
class ValidateFields qs where
validateFields
:: Validator (Fields qs) -> Form (Fields qs) -> TList (Map Result qs)
instance ValidateFields '[] where
validateFields (FieldsVal Nil) (Form Nil) = Nil
instance
( ValidateForm q, ValidateFields qs
) => ValidateFields (q ': qs) where
validateFields (FieldsVal (f :| fs)) (Form (a :| as)) =
validateForm f (Form a) :| validateFields @qs (FieldsVal fs) (Form as)
-- | Result of running a validation
data Result q
= Error (FormError q)
| Success (FormOutput q)
deriving instance (Eq (FormError q), Eq (FormOutput q)) => Eq (Result q)
deriving instance (Show (FormError q), Show (FormOutput q)) => Show (Result q)
class JoinFields qs where
joinFields :: TList (Map Result qs) -> Result (Fields qs)
instance JoinFields '[] where
joinFields Nil = Success Nil
instance
( Default (TList (Map FormError qs))
, Default (FormError q)
, JoinFields qs
) => JoinFields (q ': qs) where
joinFields (e :| es) = case (e, joinFields @qs es) of
(Error e', Error (FieldsError es')) -> Error $ FieldsError $ e' :| es'
(Error e', _) -> Error $ FieldsError $ e' :| def
(_, Error (FieldsError es')) -> Error $ FieldsError $ def :| es'
(Success a, Success as) -> Success $ a :| as
runValidated
:: (Default (FormError q))
=> (FormOutput q -> Either e a) -> Result q -> Result (Validated e a q)
runValidated f q = case q of
Error e -> Error $ ValidatedError Nothing e
Success hs -> case f hs of
Left e -> Error $ ValidatedError (Just e) def
Right a -> Success a
|
tomsmalley/quickform
|
src/QuickForm/Validation.hs
|
mit
| 3,284 | 0 | 14 | 642 | 1,158 | 588 | 570 | -1 | -1 |
-- | This module contains the algorithm for determining the best possible move
-- in a game of tic-tac-toe.
module Minimax (findOptimalMove) where
-------------------
-- Local Imports --
import Board
----------
-- Code --
-- | Accessing the third element in a 3-tuple.
thd :: (a, b, c) -> c
thd (_, _, c) = c
-- | Finding the maximum score of a move.
maxScore :: BoardState -> Int
maxScore X = -2
maxScore O = 2
maxScore Nil = 0
-- | Finding the distance between two numbers.
distance :: Num a => a -> a -> a
distance a b = abs $ a - b
-- | Finding the better of two (Int, Int, Point)s.
findBetter :: Int -> (Int, Int, Point) -> (Int, Int, Point) -> (Int, Int, Point)
findBetter target (m1, s1, p1) (m2, s2, p2)
| distance target s1 < distance target s2 = (m1, s1, p1)
| distance target s2 < distance target s1 = (m2, s2, p1)
| distance target s1 == distance target s2 =
if m1 < m2
then (m1, s1, p1)
else (m2, s2, p2)
-- | The back-end to finding an optimal move in a board.
findOptimalMove' :: Int -> Point -> BoardState -> Board -> (Int, Int, Point)
findOptimalMove' numMoves pnt move board
| isOver board = (numMoves, boardStateToInt $ findWinner board, pnt)
| otherwise =
foldl1 (findBetter (maxScore move)) $
map (\p -> findOptimalMove' (numMoves + 1) p (otherState move) (boardPush p move board)) moves
where moves = validMoves board
-- | Finding the optimal move in a board.
findOptimalMove :: BoardState -> Board -> Point
findOptimalMove Nil = const (-1, -1)
findOptimalMove s = thd . findOptimalMove' 0 (-1, -1) s
|
crockeo/tic-taskell
|
src/Minimax.hs
|
mit
| 1,584 | 0 | 12 | 348 | 535 | 292 | 243 | 28 | 2 |
{-|
Module : BreadU.Pages.Markup.Common.Header
Description : HTML markup for pages' top area.
Stability : experimental
Portability : POSIX
HTML markup for pages' top area.
Please don't confuse it with <head>-tag, it's defined in another module.
-}
module BreadU.Pages.Markup.Common.Header
( commonHeader
) where
import BreadU.Types ( LangCode(..), allLanguages )
import BreadU.Pages.Types ( HeaderContent(..) )
import BreadU.Pages.CSS.Names ( ClassName(..) )
import BreadU.API ( indexPageLink )
import BreadU.Pages.Markup.Common.Utils
import Prelude hiding ( div, span )
import TextShow ( showt )
import Data.Text ( toUpper )
import Data.List ( delete )
import Data.Monoid ( (<>) )
import Text.Blaze.Html5
import qualified Text.Blaze.Html5.Attributes as A
-- | Header for all pages.
commonHeader :: HeaderContent -> LangCode -> Html
commonHeader headerContent@HeaderContent{..} langCode = header $ do
row_ $ do
aboutModal headerContent
col_6 languageSwitcher
col_6 about
h1 $ toHtml siteName
where
-- All supported languages are here.
languageSwitcher =
div ! A.class_ "btn-group" $ do
button ! A.class_ (toValue $ "btn btn-outline-info btn-sm btn-rounded waves-effect dropdown-toggle "
<> showt LanguageSwitcher)
! A.type_ "button"
! dataAttribute "toggle" "dropdown"
! customAttribute "aria-haspopup" "true"
! customAttribute "aria-expanded" "false" $ toHtml $ showt langCode
div ! A.class_ "dropdown-menu" $
mapM_ (\lCode -> a ! A.class_ "dropdown-item"
! A.href (toValue $ indexPageLink lCode) $
toHtml . toUpper . showt $ lCode)
otherLanguages
otherLanguages = delete langCode allLanguages
about = div ! A.class_ "text-right" $
button ! A.type_ "button"
! A.class_ "btn btn-outline-info btn-sm btn-rounded waves-effect"
! A.title (toValue aboutTitle)
! dataAttribute "toggle" "modal"
! dataAttribute "target" "#aboutModal" $ toHtml aboutLabel
-- | Show modal window with info about the service.
aboutModal :: HeaderContent -> Html
aboutModal HeaderContent{..} =
div ! A.class_ "modal"
! A.id "aboutModal"
! A.tabindex "-1"
! customAttribute "role" "dialog"
! customAttribute "aria-labelledby" "aboutModalLabel"
! customAttribute "aria-hidden" "true" $
div ! A.class_ "modal-dialog modal-lg"
! customAttribute "role" "document" $
div ! A.class_ "modal-content" $ do
div ! A.class_ "modal-header" $ do
h3 ! A.class_ "modal-title w-100"
! A.id "aboutModalLabel" $ toHtml siteName
closeButton
div ! A.class_ (toValue $ "modal-body " <> showt AboutInfo) $ do
p $ toHtml briefDescription
p $ toHtml buDescription
h4 $ toHtml howToUseItTitle
p $ toHtml howToUseItFood
p $ toHtml howToUseItQuantity
p $ toHtml howToUseItAddFood
p $ toHtml howToUseItCalculate
h4 $ toHtml ossTitle
p $ preEscapedToHtml oss
h4 $ toHtml disclaimerTitle
p $ toHtml disclaimer
where
closeButton =
button ! A.type_ "button"
! A.class_ "close"
! dataAttribute "dismiss" "modal"
! customAttribute "aria-label" "Close" $
span ! customAttribute "aria-hidden" "true" $
preEscapedToHtml ("×" :: String)
|
denisshevchenko/breadu.info
|
src/lib/BreadU/Pages/Markup/Common/Header.hs
|
mit
| 4,202 | 0 | 22 | 1,632 | 847 | 418 | 429 | -1 | -1 |
module System.Flannel.BuilderTreeSpec
( spec
) where
import qualified System.Flannel.Argument as A
import System.Flannel.Command
import System.Flannel.CommandBuilder
import System.Flannel.BuilderTree
import Test.Hspec
spec :: Spec
spec = do
describe "define" $ do
context "when there is no previous definition" $ do
let expected =
[ (A.Optional, A.Flag "beta" ["-b", "--beta"] "beta flag")
, (A.Optional, A.Argument "alpha" "the first argument")
]
it "defines the CommandBuilder" $ do
let definition = runDsl $ do
define $ do
desc "description"
flag "beta" ["-b", "--beta"] "beta flag"
arg "alpha" "the first argument"
command $ do
run $ print "yay"
length definition `shouldBe` 1
case head definition of
Namespace _ _ -> False `shouldBe` True
Builder (BuilderState d a _) -> do
d `shouldBe` "description"
a `shouldBe` expected
context "when there is a previous definition" $ do
it "does not overide it" $ do
let definition = runDsl $ do
define $ do
desc "d1"
define $ do
desc "d2"
length definition `shouldBe` 1
case head definition of
Namespace _ _ -> False `shouldBe` True
Builder (BuilderState d _ _) -> do
d `shouldBe` "d1"
describe "namespace" $ do
it "wraps a new Dsl" $ do
let definition = runDsl $ do
namespace "new namespace" $ return ()
length definition `shouldBe` 1
case head definition of
Builder _ -> False `shouldBe` True
Namespace d _ ->
d `shouldBe` "new namespace"
|
nahiluhmot/flannel
|
spec/System/Flannel/BuilderTreeSpec.hs
|
mit
| 2,162 | 0 | 29 | 1,000 | 508 | 248 | 260 | 49 | 4 |
-- |
module Constraint.Term where
import qualified Syntax
constrain env term ty = case term of
Literal lit -> Literal.constrain env lit ty
|
cpehle/faust
|
src/Constraint/Term.hs
|
mit
| 153 | 0 | 9 | 37 | 45 | 24 | 21 | 4 | 1 |
{-# LANGUAGE OverloadedStrings,
RecordWildCards,
LambdaCase,
ViewPatterns,
ScopedTypeVariables,
NoMonomorphismRestriction #-}
module Network.AWS.Connection where
import qualified Prelude as P
import qualified Data.List as L
import System.Environment (getEnvironment)
import Network.AWS.Core
---------------------------------------------------------------------
-- AWS Type Classes
-- Abstracts some common capabilities of AWS-related types.
---------------------------------------------------------------------
-- | Class of things which contain AWS configuration.
class AwsCfg a where
getCon :: Str s => a s -> AwsConnection s
-- | The class of types from which we can generate CanonicalHeaders.
class AwsCfg a => Canonical a where
-- | Builds the canonical list of headers.
canonicalHeaders :: Str s => a s -> [(s, s)]
-- | Munges information from the command into a "canonical request".
canonicalRequest :: Str s => a s -> s
---------------------------------------------------------------------
-- Data types
-- The @str@ in these types must be a type that implements @Str@.
---------------------------------------------------------------------
-- | Stores the key id and secret key for an AWS transaction.
data AwsCredentials str = AwsCredentials
{ awsKeyId :: str
, awsSecretKey :: str
} deriving (Show)
-- | Configures commonly-used AWS options.
data AwsConfig str = AwsConfig
{ awsHostName :: str
, awsRegion :: str
, awsIsSecure :: Bool
, awsService :: str
, awsGivenCredentials :: CredentialSource str
} deriving (Show)
-- | Credentials can either be supplied directly, provided through a file,
-- or given in the environment.
data CredentialSource s = FromEnv
| FromFile s
| Directly (AwsCredentials s)
deriving (Show)
-- | Combines static config from the user with credentials which might be
-- determined at run-time.
data AwsConnection str = AwsConnection
{ awsConfig :: AwsConfig str
, awsCredentials :: AwsCredentials str
} deriving (Show)
instance AwsCfg AwsConnection where
getCon = id
-- | Various getters for AwsCfg types:
getCreds :: (AwsCfg aws, Str s) => aws s -> AwsCredentials s
getCreds = awsCredentials . getCon
getKeyId :: (AwsCfg aws, Str s) => aws s -> s
getKeyId = awsKeyId . getCreds
getSecretKey :: (AwsCfg aws, Str s) => aws s -> s
getSecretKey = awsSecretKey . getCreds
getConfig :: (AwsCfg aws, Str s) => aws s -> AwsConfig s
getConfig = awsConfig . getCon
getHostName :: (AwsCfg aws, Str s) => aws s -> s
getHostName = awsHostName . getConfig
getRegion :: (AwsCfg aws, Str s) => aws s -> s
getRegion = awsRegion . getConfig
getSecurity :: (AwsCfg aws, Str s) => aws s -> Bool
getSecurity = awsIsSecure . getConfig
getService :: (AwsCfg aws, Str s) => aws s -> s
getService = awsService . getConfig
---------------------------------------------------------------------
-- Loading configurations
---------------------------------------------------------------------
-- | The key (either in the env or in a config file) for the AWS access key.
accessIdKey :: P.String
accessIdKey = "AWS_ACCESS_KEY_ID"
-- | The key (either in the env or in a config file) for the AWS secret key.
secretKeyKey :: P.String
secretKeyKey = "AWS_SECRET_ACCESS_KEY"
-- | Creates an AwsConnection using a config.
createConnection :: (Functor io, MonadIO io, Str s)
=> AwsConfig s -> io (AwsConnection s)
createConnection cfg@AwsConfig{..} = AwsConnection cfg <$> creds where
creds = case awsGivenCredentials of
Directly creds -> return creds
FromFile file -> findCredentialsFromFile file >>= \case
Just creds -> return creds
Nothing -> error $ unlines [ "Couldn't get credentials from file "
<> show file <> "."
, "The file should use ConfigFile format, "
<> "and have the keys " <> show accessIdKey
<> " (access id) and " <> show secretKeyKey
<> " (secred access key)."]
FromEnv -> findCredentialsFromEnv >>= \case
Just creds -> return creds
Nothing -> error $ unlines [ "No credentials found in environment."
, "An access key id should be under the "
<> "variable " <> show accessIdKey <> "."
, "A secret access key should be under the "
<> "variable " <> show secretKeyKey <> "."]
-- | Chooses some reasonably sane defaults.
defaultConfig :: Str s => AwsConfig s
defaultConfig = AwsConfig { awsHostName = "s3.amazonaws.com"
, awsRegion = "us-east-1"
, awsService = "s3"
, awsIsSecure = False
, awsGivenCredentials = FromEnv }
-- | Uses the default config to create an AwsConnection.
defaultConnection :: (Functor io, MonadIO io, Str s) => io (AwsConnection s)
defaultConnection = createConnection defaultConfig
-- | Looks for credentials in the environment.
findCredentialsFromEnv :: (Functor io, MonadIO io, Str s)
=> io (Maybe (AwsCredentials s))
findCredentialsFromEnv = do
let getEnvKey s = liftIO $ fmap fromString . L.lookup s <$> getEnvironment
keyid <- getEnvKey accessIdKey
secret <- getEnvKey secretKeyKey
if isNothing keyid || isNothing secret then return Nothing
else return $ Just $ AwsCredentials (fromJust keyid) (fromJust secret)
-- | Looks for credentials in a config file.
findCredentialsFromFile :: (Functor io, MonadIO io, Str s)
=> s -> io (Maybe (AwsCredentials s))
findCredentialsFromFile (toString -> path) = P.undefined
---------------------------------------------------------------------
-- AWS Monad
---------------------------------------------------------------------
-- | Many operations take place in the context of some AWS connection. We can
-- put them in a monad transformer to simplify them.
type AwsT s = ReaderT (AwsConnection s)
-- | Runs a series of actions in the context of a single connection.
withConnection :: (Str s, MonadIO io, Functor io)
=> AwsConnection s -> AwsT s io a -> io a
withConnection con = flip runReaderT con
withDefaultConnection :: (Str s, MonadIO io, Functor io) => AwsT s io a -> io a
withDefaultConnection actions = do
con <- defaultConnection
withConnection con actions
|
thinkpad20/s3-streams
|
src/Network/AWS/Connection.hs
|
mit
| 6,597 | 0 | 21 | 1,632 | 1,337 | 712 | 625 | 104 | 5 |
-- A module with some code to explore theorems in the monadic lambda calculus
module TP where
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Foldable hiding (concat,any,all)
import Control.Monad.State
import DataTypes
import Control.Parallel (par, pseq)
debShow (LeftContext l lc f r,c) = show $ (LeftContext (map formula l) (map formula lc) (formula f) (map formula r), formula c)
debShow (RightContext l f rc r,c) = show $ (RightContext (map formula l) (formula f) (map formula rc) (map formula r), formula c)
debShow (ContextLess l f r,c) = show $ (ContextLess (map formula l) (formula f) (map formula r), formula c)
startState :: S
startState = S (-1) Map.empty
-- |Returns the current state integer and decrease the state by one.
getAndDec :: NonDeterministicState S Int
getAndDec = do
s <- get
i <- return $ counter s
modify (\x -> x{counter = (i-1)})
return i
-- |Takes a sequent of formulae and generates fresh variables for each formula, wrapping it in a non-deterministic state
toDecorated :: Sequent -> NonDeterministicState S DecoratedSequent
toDecorated (gamma,f) = do
aux <- return $ \x -> do
i <- getAndDec
j <- getAndDec
return $ DF i (V j) x
gamma' <- mapM aux gamma
f' <- aux f
return (gamma',f')
-- |Takes a decorated sequent and generates fresh variables for each formula, wrapping it in a non-deterministic state and returning a map from the new variables to the original constant terms
toDecoratedWithConstants :: ([(LambdaTerm,Formula)],Formula) -> NonDeterministicState S (DecoratedSequent,Map Int LambdaTerm)
toDecoratedWithConstants (gamma,f) = do
aux <- return $ \(c,x) -> do
i <- getAndDec
j <- getAndDec
return $ (DF i (V j) x,(i,c))
gamma' <- mapM aux gamma
f' <- do
i <- getAndDec
j <- getAndDec
return $ DF i (V j) f
return ((map fst gamma',f'),Map.fromList $ map snd gamma')
-- |Associates two formulae in the variable-formula binding map in the state
associate :: Formula -> Formula -> NonDeterministicState S ()
associate f g = do
s <- get
m <- return $ vars s
modify (\x -> x{vars = Map.insert f g m})
return ()
-- |Looks up the binding of a formula in the variable-formula binding map of the state
getBinding :: Formula -> NonDeterministicState S (Maybe Formula)
getBinding f = aux f [f] where
aux f vs = do
s <- get
m <- return $ vars s
res <- return $ Map.lookup f m
case res of
Nothing -> return Nothing
Just v@(Var _) -> case Data.List.elem v vs of
False -> aux v (v : vs)
True -> return $ Just f
Just f -> return $ Just f
-- |Tries to unify to formulae: returns 'True' in case of success (and associate the unified formulae) and 'False' otherwise (without changing the state)
unify :: Formula -> Formula -> NonDeterministicState S Bool
unify v1@(Var _) v2@(Var _) =
do
binding1 <- getBinding v1
binding2 <- getBinding v2
case binding1 of
Nothing -> do
associate v1 v2
return True
Just g -> case binding2 of
Nothing -> do
associate v2 v1
return True
Just f -> return $ f == g
unify v@(Var _) f =
do
binding <- getBinding v
case binding of
Nothing -> do
associate v f
return True
Just g -> return $ g == f
unify f v@(Var _) = unify v f
unify f g = return $ f == g
provable :: Sequent -> Bool
provable s = not $ null $ evaluateState m startState where
m = do
ds <- toDecorated s
proofs ds
-- |Returns all the proofs for a given sequent
proofs :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
proofs s@(gamma,f) =
every $ map (\r -> r s) [lIR,rIR,mR,tR] ++
map (\(r,foc) -> r foc) [ (r,(foc,f)) | r <- [i,mL,tL]
, foc <- createAllContextLessFocuses gamma] ++
map (\foc -> lIL foc) [(foc,f) | foc <- createAllLeftContextFocuses gamma] ++
map (\foc -> rIL foc) [(foc,f) | foc <- createAllRightContextFocuses gamma]
-- do
-- every $ map (\r -> r s) [iR,mR,tR] ++ map (\(r,g) -> r g (delete g gamma,f))
-- [(r,g) | r <- [i,iL,mL,tL]
-- , g <- gamma]
-- |The identity rule
i :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
i (f,a') = do
guard $ all null $ getContexts f
a <- return $ getFocus f
res <- unify (formula a) (formula a')
case res of
False -> failure
True -> do
i <- getAndDec
x <- return $ V i
return $ Leaf Id ([DF (identifier a) x (formula a)]
, DF (identifier a') x (formula a'))
-- |The left left-implication rule
-- Y => A X[B] => C
-- -----------------
-- X[(Y,A\B)] => C
lIL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
lIL (LeftContext bigXLeft bigY f@(DF _ _ (LI a b)) bigXRight,c) = do
a_id <- getAndDec
b_id <- getAndDec
t <- getAndDec >>= \i -> return $ V i
x <- getAndDec >>= \j -> return $ V j
l <- proofs (bigY,DF a_id t a)
r <- proofs (bigXLeft ++ [DF b_id x b] ++ bigXRight,c)
(l,r) <- return $ l `par` (r `pseq` (l,r))
(newBigY,a') <- return $ getVal l
(newBigX, c') <- return $ getVal r
b' <- return $ lookupFormula b_id newBigX
(newBigXLeft,newBigXRight) <- return $ deleteWithRemainders b' newBigX
y <- getAndDec >>= \i -> return $ V i
return $ Branch LImplL l (newBigXLeft ++ newBigY ++ [DF (identifier f) y (LI a b)] ++ newBigXRight ,DF (identifier c') (sub (App y (term a')) (term b') (term c')) (formula c')) r
lIL _ = failure
-- |The left right-implication rule
-- Y => A X[B] => C
-- -----------------
-- X[(B/A,Y)] => C
rIL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
rIL (RightContext bigXLeft f@(DF _ _ (RI a b)) bigY bigXRight,c) = do
a_id <- getAndDec
b_id <- getAndDec
t <- getAndDec >>= \i -> return $ V i
x <- getAndDec >>= \j -> return $ V j
l <- proofs (bigY,DF a_id t a)
r <- proofs (bigXLeft ++ [DF b_id x b] ++ bigXRight,c)
(l,r) <- return $ l `par` (r `pseq` (l,r))
(newBigY,a') <- return $ getVal l
((newBigX), c') <- return $ getVal r
b' <- return $ lookupFormula b_id newBigX
(newBigXLeft,newBigXRight) <- return $ deleteWithRemainders b' newBigX
y <- getAndDec >>= \i -> return $ V i
return $ Branch RImplL l (newBigXLeft ++ [DF (identifier f) y (RI a b)] ++ newBigY ++ newBigXRight ,DF (identifier c') (sub (App y (term a')) (term b') (term c')) (formula c')) r
rIL _ = failure
-- |The left diamond rule
-- X[A] => <>B
-- ----------------
-- X[<>A] => <> B
mL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
mL (ContextLess bigXLeft ma@(DF _ y (M t a)) bigXRight, f@(DF j _ (M t' b))) = do
guard (t == t')
id_a <- getAndDec
x <- getAndDec >>= \i -> return $ V i
c <- proofs (bigXLeft ++ [DF id_a x a] ++ bigXRight, f)
(gamma_and_a,mb) <- return $ getVal c
a <- return $ lookupFormula id_a gamma_and_a
(newBigXLeft,newBigXRight) <- return $ deleteWithRemainders a gamma_and_a
return $ Unary (MonL t) (newBigXLeft ++ [ma] ++ newBigXRight, DF j (Bind t y (Lambda (term a) (term mb))) (M t b)) c
mL _ = failure
-- |The left tensor rule
-- X[(A,B)] => C
-- -------------
-- X[A*B] => C
tL :: FocusedDecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
tL (ContextLess bigXLeft ab@(DF _ y (P a b)) bigXRight, c) = do
a_id <- getAndDec
b_id <- getAndDec
f <- getAndDec >>= \i -> return $ V i
g <- getAndDec >>= \i -> return $ V i
child <- proofs (bigXLeft ++ [DF a_id f a,DF b_id g b] ++ bigXRight,c)
(gamma_and_a_and_b,c') <- return $ getVal child
a <- return $ lookupFormula a_id gamma_and_a_and_b
b <- return $ lookupFormula b_id gamma_and_a_and_b
(newBigXLeft,tmp) <- return $ deleteWithRemainders a gamma_and_a_and_b
(_,newBigXRight) <- return $ deleteWithRemainders b tmp
return $ Unary TensL (newBigXLeft ++ [ab] ++ newBigXRight,
DF (identifier c)
(sub (FirstProjection y)
(term a)
(sub (SecondProjection y)
(term b)
(term c')))
(formula c)) child
tL _ = failure
-- |The right left-implication rule
-- (A,X) => B
-- ----------
-- X => A\B
lIR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
lIR (gamma, DF i _ f@(LI a b)) = do
a_id <- getAndDec
b_id <- getAndDec
x <- getAndDec >>= \i -> return $ V i
t <- getAndDec >>= \i -> return $ V i
c <- proofs (DF a_id x a : gamma, DF b_id t b)
(gamma_and_a,b) <- return $ getVal c
a <- return $ lookupFormula a_id gamma_and_a
gamma <- return $ delete a gamma_and_a
return $ Unary LImplR (gamma, DF i (Lambda (term a) (term b)) f) c
lIR _ = failure
-- |The right right-implication rule
-- (X,A) => B
-- ----------
-- X => B/A
rIR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
rIR (gamma, DF i _ f@(RI a b)) = do
a_id <- getAndDec
b_id <- getAndDec
x <- getAndDec >>= \i -> return $ V i
t <- getAndDec >>= \i -> return $ V i
c <- proofs (gamma ++ [DF a_id x a], DF b_id t b)
(gamma_and_a,b) <- return $ getVal c
a <- return $ lookupFormula a_id gamma_and_a
gamma <- return $ delete a gamma_and_a
return $ Unary RImplR (gamma, DF i (Lambda (term a) (term b)) f) c
rIR _ = failure
-- |The right diamond rule
mR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
mR (gamma,DF i _ ma@(M t a)) = do
a_id <- getAndDec
x <- getAndDec >>= \i -> return $ V i
c <- proofs (gamma,DF a_id x a)
(gamma,a) <- return $ getVal c
return $ Unary (MonR t) (gamma,DF i (Eta t (term a)) ma) c
mR _ = failure
-- |The right tensor rule
tR :: DecoratedSequent -> NonDeterministicState S (BinTree DecoratedSequent)
tR (gamma,DF i _ f@(P a b)) = do
a_id <- getAndDec
b_id <- getAndDec
t <- getAndDec >>= \i -> return $ V i
u <- getAndDec >>= \i -> return $ V i
splits <- return $ split gamma
proveChildren <- return $ \(g,g') -> do
l <- proofs (g,DF a_id t a)
r <- proofs (g',DF b_id u b)
return (l,r)
(l,r) <- every $ map proveChildren splits
(gamma,a) <- return $ getVal l
(delta,b) <- return $ getVal r
return $ Branch TensR l (gamma ++ delta, DF i (Pair (term a) (term b)) f) r
tR _ = failure
-- |This function searches for a formula in a list of formulae by comparing their unique ids.
-- It's meant to be used only by the left implication and left monad rules.
-- Raises an error if no formula with the given id is found
lookupFormula :: Int -> [DecoratedFormula] -> DecoratedFormula
lookupFormula _ [] = error "This will never be reached by the rules"
lookupFormula n (f : rest) | n == (identifier f) = f
| otherwise = lookupFormula n rest
-- |Substitute a term for another inside a third term (should be the substitution of a variable with a term)
sub :: LambdaTerm -> -- the new term
LambdaTerm -> -- the variable/old term
LambdaTerm -> -- the context
LambdaTerm -- the new term
sub _ _ c@(C _) = c
sub new old t@(V _) | t == old = new
| otherwise = t
sub new old t@(Lambda v b) | v == old = t
| otherwise = Lambda v $ sub new old b
sub new old (App f a) = App (sub new old f) (sub new old a)
sub new old (Eta t f) = Eta t (sub new old f)
sub new old (Bind t m k) = Bind t (sub new old m) (sub new old k)
sub new old (Pair a b) = Pair (sub new old a) (sub new old b)
sub new old (FirstProjection a) = FirstProjection $ sub new old a
sub new old (SecondProjection a) = SecondProjection $ sub new old a
-- |Collects all variables from a proof
collectVars :: BinTree DecoratedSequent -> Set LambdaTerm
collectVars t = Set.fromList $ foldMap aux t where
aux = concat . (map f) . (map term) . j
j (c,f) = f : c
f v@(V _) = [v]
f (C _) = []
f (Lambda v t) = f v ++ f t
f (App g a) = f g ++ f a
f (Eta _ x) = f x
f (Bind _ m k) = f m ++ f k
f (Pair a b) = f a ++ f b
f (FirstProjection a) = f a
f (SecondProjection a) = f a
-- |Changes all the negative indices used in the vars to contiguos positive integers
sanitizeVars :: BinTree DecoratedSequent -> BinTree DecoratedSequent
sanitizeVars t = fmap sanitize t where
sanitize (gamma,f) = (map deepSub gamma,deepSub f)
deepSub (DF i lt f) = DF i (zub lt) f
zub (V i) = V $ fromJust $ lookup i m
zub c@(C _) = c
zub (Lambda x t) = Lambda (zub x) (zub t)
zub (App f g) = App (zub f) (zub g)
zub (Eta t x) = Eta t (zub x)
zub (Bind t m k) = Bind t (zub m) (zub k)
zub (Pair a b) = Pair (zub a) (zub b)
zub (FirstProjection a) = FirstProjection $ zub a
zub (SecondProjection a) = SecondProjection $ zub a
m = zip (map (\(V i) -> i) $ Set.toList $ collectVars t) [0..]
replaceWithConstants :: BinTree DecoratedSequent -> (Map Int LambdaTerm) -> BinTree DecoratedSequent
replaceWithConstants t m = fmap (\n -> replaceWithConstantsInNode n m) t
replaceWithConstantsInNode :: DecoratedSequent -> (Map Int LambdaTerm) -> DecoratedSequent
replaceWithConstantsInNode (gamma,f) m = new where
new = (map fst gamma', deepSub f)
gamma' = map replace gamma
n = map fromJust $ filter isJust $ map snd gamma'
replace df@(DF i v f) = case Map.lookup i m of
Nothing -> (df,Nothing)
Just c -> (DF i c f,Just (v,c))
deepSub (DF i lt f) = (DF i (zub lt) f)
zub v@(V _) = case lookup v n of
Nothing -> v
Just c -> c
zub c@(C _) = c
zub (Lambda x t) = Lambda (zub x) (zub t)
zub (App f g) = App (zub f) (zub g)
zub (Eta t x) = Eta t (zub x)
zub (Bind t m k) = Bind t (zub m) (zub k)
zub (Pair a b) = Pair (zub a) (zub b)
zub (FirstProjection a) = FirstProjection $ zub a
zub (SecondProjection a) = SecondProjection $ zub a
alphaEquivalent :: LambdaTerm -> LambdaTerm -> Map Int Int -> Bool
alphaEquivalent c1@(C _) c2@(C _) _ = c1 == c2
alphaEquivalent (V i) (V j) m = case Map.lookup i m of
Just h -> j == h
Nothing -> i == j
alphaEquivalent (Lambda (V i) t) (Lambda (V j) u) m = alphaEquivalent t u (Map.insert i j m)
alphaEquivalent (App t s) (App d z) m = (alphaEquivalent t d m) && (alphaEquivalent s z m)
alphaEquivalent (Eta t x) (Eta t' y) m = t == t' && alphaEquivalent x y m
alphaEquivalent (Bind t x y) (Bind t' w z) m = t == t' && (alphaEquivalent x w m) && (alphaEquivalent y z m)
alphaEquivalent (Pair a b) (Pair a' b') m = alphaEquivalent a a' m && alphaEquivalent b b' m
alphaEquivalent (FirstProjection a) (FirstProjection b) m = alphaEquivalent a b m
alphaEquivalent (SecondProjection a) (SecondProjection b) m = alphaEquivalent a b m
alphaEquivalent _ _ _ = False
-- |This function works only under the assumption that all the formulae in the hypothesis are distinct, otherwise the answer is NO!
equivalentDecoratedSequent :: DecoratedSequent -> DecoratedSequent -> Bool
equivalentDecoratedSequent s1 s2 = f1 == f2 && hypEqual && noDuplicates && alphaEquivalent t1 t2 e where
noDuplicates = (length $ Set.toList $ Set.fromList (map formula hyp1)) == length hyp1 &&
(length $ Set.toList $ Set.fromList (map formula hyp2)) == length hyp2
hyp1 = fst s1
hyp2 = fst s2
hypEqual = (Set.fromList (map formula hyp1)) == (Set.fromList (map formula hyp2))
varId (V i) = i
varId _ = -1
m1 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp1
m2 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp2
e = mixMaps m1 m2
t1 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s1
t2 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s2
f1 = formula $ snd $ s1
f2 = formula $ snd $ s2
simplifiedEquivalentDecoratedSequent s1 s2 = alphaEquivalent t1 t2 e where
hyp1 = fst s1
hyp2 = fst s2
varId (V i) = i
varId _ = -1
m1 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp1
m2 = Map.fromList $ map (\x -> (formula x, varId $ term x)) hyp2
e = mixMaps m1 m2
t1 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s1
t2 = betaReduce $ monadReduce $ etaReduce $ term $ snd $ s2
mixMaps :: Map Formula Int -> Map Formula Int -> Map Int Int
mixMaps m n = Map.fromList $ aux (Map.toList m) where
aux [] = []
aux ((f,i) : rest) = (i,n Map.! f) : aux rest
etaReduce :: LambdaTerm -> LambdaTerm
etaReduce c@(C _) = c
etaReduce v@(V _) = v
etaReduce (App f g) = App (etaReduce f) (etaReduce g)
etaReduce (Eta t m) = Eta t $ etaReduce m
etaReduce (Bind t m k) = Bind t (etaReduce m) (etaReduce k)
etaReduce (Pair a b) = Pair (etaReduce a) (etaReduce b)
etaReduce (FirstProjection a) = FirstProjection $ etaReduce a
etaReduce (SecondProjection a) = SecondProjection $ etaReduce a
etaReduce (Lambda (V i) (App f (V j))) | i == j = etaReduce f
| otherwise = Lambda (V i) (App (etaReduce f) (V j))
etaReduce (Lambda x t) = let x' = etaReduce x
t' = etaReduce t
in if t == t' then
Lambda x' t'
else
etaReduce (Lambda x' t')
betaReduce :: LambdaTerm -> LambdaTerm
betaReduce t = aux t Map.empty where
aux c@(C _) _ = c
aux v@(V i) m = case Map.lookup i m of
Nothing -> v
Just t -> t
aux (App (Lambda (V i) body) x) m = aux body (Map.insert i x m)
aux (App f x) m = let f' = aux f m
in if f == f' then
(App f (aux x m))
else
aux (App f' x) m
aux (Lambda x b) m = Lambda (aux x m) (aux b m)
aux (Eta t x) m = Eta t $ aux x m
aux (Bind t n k) m = Bind t (aux n m) (aux k m)
aux (Pair a b) m = Pair (aux a m) (aux b m)
aux (FirstProjection a) m = FirstProjection $ aux a m
aux (SecondProjection a) m = SecondProjection $ aux a m
monadReduce :: LambdaTerm -> LambdaTerm
monadReduce (Bind _ (Eta _ t) u) = App (monadReduce u) (monadReduce t) -- here there should be a check on types...
monadReduce (Bind ty t (Lambda (V i) (Eta ty' (V j)))) | i == j = monadReduce t
| otherwise = Bind ty (monadReduce t) (Lambda (V i) (Eta ty' (V j)))
monadReduce v@(V _) = v
monadReduce c@(C _) = c
monadReduce (App t u) = App (monadReduce t) (monadReduce u)
monadReduce (Lambda x t) = Lambda (monadReduce x) (monadReduce t)
monadReduce (Eta t x) = Eta t $ monadReduce x
monadReduce (Pair a b) = Pair (monadReduce a) (monadReduce b)
monadReduce (FirstProjection a) = FirstProjection $ monadReduce a
monadReduce (SecondProjection a) = SecondProjection $ monadReduce a
monadReduce (Bind ty t u) = let t' = monadReduce t
u' = monadReduce u
in if t == t' && u == u' then
Bind ty t' u'
else
monadReduce (Bind ty t' u')
|
gianlucagiorgolo/lambek-monad
|
TP.hs
|
mit
| 19,668 | 0 | 18 | 5,615 | 8,316 | 4,143 | 4,173 | 382 | 12 |
module Main where
import Text.ParserCombinators.UU
import Text.ParserCombinators.UU.Utils
import Text.ParserCombinators.UU.BasicInstances hiding (Parser, input)
import System.Console.Haskeline
import System.Environment (getArgs)
type Parser a = P (Str Char String LineColPos) a
main :: IO ()
main = do
args <- getArgs
if null args then interactive
else putStrLn $ run timeExpr (unwords args)
interactive :: IO ()
interactive = runInputT defaultSettings loop
where
loop :: InputT IO ()
loop = do minput <- getInputLine "> "
case minput of
Nothing -> return ()
Just "quit" -> return ()
Just input -> do outputStrLn $ run timeExpr input
loop
run :: Parser String -> String -> String
run p inp = do let (a, errors) = parse ( (,) <$> p <*> pEnd) (createStr (LineColPos 0 0 0) inp)
if null errors then a
else "Error in expression"
timeExpr :: Parser String
timeExpr = format <$> expr
where format :: Double -> String
format x = let minutes :: Integer
seconds :: Integer
(minutes,secondsMultiplier) = properFraction x
seconds = round $ secondsMultiplier * 60
showSeconds s | s < 10 = "0" ++ show s
| otherwise = show s
in show minutes ++ ":" ++ showSeconds seconds
expr :: Parser Double
expr = foldr pChainl ( pDouble <|> pTime <|>pParens expr) (map same_prio operators)
where
operators = [[('+', (+)), ('-', (-))], [('*' , (*))], [('/' , (/))]]
same_prio ops = foldr (<|>) empty [ op <$ lexeme (pSym c) | (c, op) <- ops]
pTime :: Parser Double
pTime = lexeme pRawMinuteTime <|> lexeme pRawHourTime
pRawMinuteTime :: Parser Double
pRawMinuteTime = makeTime <$> pIntegerRaw <* pSym ':' <*> pIntegerRaw <?> "min:sec"
where makeTime x y = x + (y / 60.0)
pRawHourTime :: Parser Double
pRawHourTime = makeTime <$> pIntegerRaw <* pSym ':' <*> pIntegerRaw <* pSym ':' <*> pIntegerRaw <?> "hour:min:sec"
where makeTime x y z = x * 60 + y + z / 60.0
|
chriseidhof/TimeCalc
|
TimeCalc.hs
|
mit
| 2,186 | 0 | 15 | 665 | 751 | 392 | 359 | 47 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Defines what each type of server does upon receiving each type of message.
-- Thus, the consensus protocol is largely defined here.
-- Note that each message receipt will be in an atomic transaction.
module Hetcons.Receive () where
import Hetcons.Conflicting_2as ( conflicting_2as )
import Hetcons.Hetcons_Exception (Hetcons_Exception(Hetcons_Exception_Invalid_Proposal_1a))
import Hetcons.Hetcons_State
( Participant_State, Observer_State, Hetcons_State )
import Hetcons.Instances_1b_2a ( well_formed_2a )
import Hetcons.Instances_Proof_of_Consensus ( observers_proven )
import Hetcons.Receive_Message
( Sendable(send)
,Receivable
,receive
,Hetcons_Transaction
,update_state
,put_state
,get_state
,get_my_private_key
,get_my_crypto_id
,get_witness)
import Hetcons.Send ()
import Hetcons.Signed_Message
( Encodable
,Parsable
,Recursive_2a(Recursive_2a)
,Recursive_1b(Recursive_1b)
,recursive_1b_non_recursive
,recursive_1b_proposal
,recursive_1b_conflicting_phase2as
,Verified
,Recursive_1a
,Recursive_2b(Recursive_2b)
,Recursive(non_recursive)
,Recursive_Proof_of_Consensus(Recursive_Proof_of_Consensus)
,Monad_Verify(verify)
,signed
,sign
,original )
import Hetcons.Value
( Contains_Value(extract_value)
,Contains_1a(extract_1a)
,Contains_1bs(extract_1bs)
,extract_ballot
,Value
,valid
,conflicts
)
import Charlotte_Consts ( sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR )
import Charlotte_Types
( Signed_Message(signed_Message_signature)
,Phase_2a(phase_2a_phase_1bs)
,Signed_Hash(signed_Hash_crypto_id)
,Phase_1b(phase_1b_conflicting_phase2as, phase_1b_proposal)
,Phase_2b(phase_2b_phase_1bs)
,Proof_of_Consensus(proof_of_Consensus_phase_2bs)
,default_Proof_of_Consensus
,default_Phase_2b
,default_Phase_1b
,default_Invalid_Proposal_1a
,invalid_Proposal_1a_offending_witness
,invalid_Proposal_1a_offending_proposal
,invalid_Proposal_1a_explanation)
import Control.Monad ( mapM, mapM_ )
import Control.Monad.Except ( MonadError(throwError) )
import Crypto.Random ( drgNew )
import Data.Foldable ( maximum )
import Data.Hashable (Hashable)
import Data.HashSet ( HashSet, toList, member, insert, fromList, size )
import qualified Data.HashSet as HashSet ( map, filter, empty )
-- | Helper function which signs a message using the Crypto_ID and Private_Key provided by the Mondic environment.
sign_m :: (Value v, Encodable a, Hetcons_State s) => a -> Hetcons_Transaction s v Signed_Message
sign_m m = do
{ crypto_id <- get_my_crypto_id
; private_key <- get_my_private_key
; gen <- drgNew
; sign crypto_id private_key sUPPORTED_SIGNED_HASH_TYPE_DESCRIPTOR gen m}
--------------------------------------------------------------------------------
-- Participants --
--------------------------------------------------------------------------------
-- | Participant receives 1A
-- If we've seen anything with this Ballot number or higher before (featuring the same Quorums), then do nothing.
-- Otherwise, send a 1B.
instance (Value v, Eq v, Hashable v, Parsable (Hetcons_Transaction (Participant_State v) v v)) => Receivable (Participant_State v) v (Verified (Recursive_1a v)) where
receive r1a = do
{ let naive_1b = default_Phase_1b {phase_1b_proposal = signed r1a}
; let naive_r1b = Recursive_1b {recursive_1b_non_recursive = naive_1b
,recursive_1b_proposal = r1a
,recursive_1b_conflicting_phase2as = HashSet.empty}
; state <- get_state
-- TODO: non-pairwise conflicts
; let conflicting_ballots = HashSet.map extract_ballot $ HashSet.filter (conflicts . fromList . (:[naive_r1b]) . original ) state
-- If we've seen this 1a before, or we've seen one with a greater ballot that conflicts
; if ((member naive_r1b $ HashSet.map original state) || ((not (null conflicting_ballots)) && ((extract_ballot r1a) <= (maximum conflicting_ballots))))
then return ()
else do { witness <- get_witness
; validity_check <- valid witness r1a
; if validity_check -- Checking validity here may seem odd, since we receive values inside other stuff, like 1bs.
then return () -- However, the first time we receive a value, we always must end up here.
else throwError $ Hetcons_Exception_Invalid_Proposal_1a default_Invalid_Proposal_1a {
invalid_Proposal_1a_offending_proposal = non_recursive $ original r1a
,invalid_Proposal_1a_offending_witness = Just witness
,invalid_Proposal_1a_explanation = Just "This value is not itself considered valid."}
; conflicting <- mapM sign_m $ toList $ conflicting_2as state r1a
; send (naive_1b {phase_1b_conflicting_phase2as = fromList conflicting})}}
-- | Participant receives 1B
-- If we've received this 1B before, or one that conflicts but has a higher ballot number, do nothing.
-- Otherwise, we try to assemble a 2A out of all the 1Bs we've received for this ballot, and if we have enough (if that 2A is valid), we send it.
instance forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v)) =>
Receivable (Participant_State v) v (Verified (Recursive_1b v)) where
receive r1b = do
{ old_state <- get_state
-- TODO: non-pairwise conflicts
; let conflicting_ballots = HashSet.map extract_ballot $ HashSet.filter (conflicts . fromList . (:[r1b])) old_state
; if ((member r1b old_state) || -- If we've received this 1b before, or received something of greater ballot number (below)
((not (null conflicting_ballots)) &&
((extract_ballot r1b) < (maximum conflicting_ballots))))
then return ()
else do { my_crypto_id <- get_my_crypto_id
; if (Just my_crypto_id) == (signed_Hash_crypto_id $ signed_Message_signature $ signed r1b) -- if this 1b is from me
then return ()
else receive ((extract_1a r1b) :: Verified (Recursive_1a v)) -- ensure we've received the 1a for this message before we store any 1bs
; mapM_ receive ((extract_1bs $ original r1b) :: (HashSet (Verified (Recursive_1b v)))) -- receive all prior 1bs contained herein
; state <- update_state (\s -> let new_state = insert r1b s in (new_state, new_state))
; let potential_2a = Recursive_2a $
HashSet.filter ((((extract_1a r1b) :: Verified (Recursive_1a v)) ==) . extract_1a) $ -- all the 1bs with the same proposal
HashSet.filter ((((extract_value r1b) :: v) ==) . extract_value) state
; case well_formed_2a potential_2a of
(Right _)-> do { signed <- sign_m $ ((non_recursive potential_2a) :: Phase_2a)
; (v :: (Verified (Recursive_2a v))) <- verify signed
; send v}
(Left _) -> return ()
; send r1b}} -- echo the 1b
-- | Participant receives 2A
-- Upon receiving a 2A, send a corresponding 2B.
-- Note that the only way for a participant to receive a 2A is for that participant to itself send it.
-- It can't come in over the wire.
instance (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Participant_State v) v v)) => Receivable (Participant_State v) v (Verified (Recursive_2a v)) where
-- | Recall that there is no actual way to receive a 2a other than sending it to yourself.
-- Therefore, we can be assured that this 2a comes to us exactly once, and that all 1bs therein have been received.
receive r2a = send $ default_Phase_2b {phase_2b_phase_1bs = phase_2a_phase_1bs $ non_recursive $ original r2a}
--------------------------------------------------------------------------------
-- Observers --
--------------------------------------------------------------------------------
-- | Observer receives 2B
-- If we've received this 2b before, do nothing.
-- Otherwise, assemble all received 2Bs with the same proposal and value, and see if those form a valid Proof_of_Consensus
-- If they do, send that Proof_of_Consensus
instance forall v . (Value v, Hashable v, Eq v, Parsable (Hetcons_Transaction (Observer_State v) v v)) => Receivable (Observer_State v) v (Verified (Recursive_2b v)) where
receive r2b = do
{ old_state <- get_state
; if (member r2b old_state)
then return () -- Else, we make a Proof_of_Consensus using what we've received, and see if that's valid.
else do { let state = insert r2b old_state
; put_state state
; let potential_proof' =
HashSet.filter ((((extract_1a r2b) :: Verified (Recursive_1a v)) ==) . extract_1a) $ -- all the 2bs with the same proposal
HashSet.filter ((((extract_value r2b) :: v) ==) . extract_value) state -- all the 2bs with the same value
-- filter for only the longest 2bs from each sender
; let potential_proof = HashSet.filter(\v2b->let same_crypto_id = HashSet.filter (((signed_Hash_crypto_id $ signed_Message_signature $ signed v2b) ==) .
signed_Hash_crypto_id . signed_Message_signature . signed)
potential_proof'
in all (\x -> let (Recursive_2b y) = original x
(Recursive_2b r) = original v2b
in (size y) <= (size r))
same_crypto_id)
potential_proof'
; if (length (observers_proven potential_proof)) > 0
then do { signed <- sign_m (default_Proof_of_Consensus { proof_of_Consensus_phase_2bs = HashSet.map signed potential_proof})
; (v :: (Verified (Recursive_Proof_of_Consensus v))) <- verify signed
; send v}
else return ()
; send r2b}}
-- | Observer receives Proof_of_Consensus
-- Note that this can only be received if this Observer sends it to itself.
-- It cannot come in over the wire.
-- TODO: what do we do here? We have consensus (at least for some observers).
instance (Value v) => Receivable (Observer_State v) v (Verified (Recursive_Proof_of_Consensus v)) where
receive rpoc = return ()
|
isheff/hetcons
|
src/Hetcons/Receive.hs
|
mit
| 11,350 | 0 | 29 | 3,212 | 2,135 | 1,183 | 952 | 149 | 1 |
{-****************************************************************************
* Hamster Balls *
* Purpose: Rendering code for terrains in the game *
* Author: David, Harley, Alex, Matt *
* Copyright (c) Yale University, 2010 *
****************************************************************************-}
module Terrain where
import Vec3d
import Graphics.Rendering.OpenGL hiding (Texture)
import GHC.Float
import BoundingVolume
import Data.Maybe
import Render
{---------------------------------------------------------------------------------------------------------------
TO DO:
Add orientation and scale to definition of TerrainElement
Existential types for the bounding boxes
Apply transformations to bounding boxes
Restore colors (do not need this, for now)
Only allow compound terrains to have associated transforms
This ways is much cleaner, but either way should be fine.
MAYBE:
Generate commands instead of executing them (easier for textures). Then, in
renderTerrainElement, just generate commands and execute them.
---------------------------------------------------------------------------------------------------------------}
data Col = Col{cspecular :: Color4 GLfloat,
cdiffuse :: Color4 GLfloat,
cambient :: Color4 GLfloat,
cemissive :: Color4 GLfloat,
cshininess :: GLfloat}
deriving Show
data Transform = Transform{toffset :: Vec3d,
tscale :: Vec3d, -- Also let orientation be set
ttheta :: Float,
tphi :: Float}
deriving Show
data Surface = Color Col
| Texture TextureObject -- Has how to render as well
| Mirror -- Mirror and Transparent are essentially the same (get the framebuffer?)
| Transparent
| NoSurface
deriving Show
{-
-- Hmm lazy way: orphan instance
instance Show QuadricPrimitive where
show _ = "QuadricPrimitive"
instance Show QuadricStyle where
show _ = "QuadricStyle"
-}
-- Maybe not best form (only CompoundTerrain should have transform). But saves lots of work
data Geometry = GLUQuadric QuadricPrimitive QuadricStyle Transform
| Cube Height Transform
| Quad Vec3d Vec3d Vec3d Vec3d Transform
| Tri Vec3d Vec3d Vec3d Transform
| Plane -- For later
| Trimesh -- For later
-- deriving Show
data TerrainElement = SimpleTerrain Geometry Surface -- Is Flavour part of TerrainElement or of Geometry?
| CompoundTerrain Transform [TerrainElement]
-- deriving Show
instance Show TerrainElement where
show _ = "TerrainElement"
-- Restore surface color properties
restoreSurfaceColor :: IO()
restoreSurfaceColor = do
materialDiffuse FrontAndBack $= Color4 0.0 0.0 0.0 1.0 -- For now, always FrontAndBack
materialSpecular FrontAndBack $= Color4 0.0 0.0 0.0 1.0
materialAmbient FrontAndBack $= Color4 0.0 0.0 0.0 1.0
materialEmission FrontAndBack $= Color4 0.0 0.0 0.0 1.0
-- Execute commands while preserving surface characteristics
-- Still have issues for texturing
preservingSurface :: Surface -> IO() -> IO()
preservingSurface (Terrain.Color (Col{cspecular=spec, cdiffuse=diff, cambient=amb,cemissive=emis,cshininess=shin})) commands = do
-- clear [ColorBuffer]
{-
let curDiff = materialDiffuse FrontAndBack
curSpec = materialSpecular FrontAndBack
curAmb = materialAmbient FrontAndBack
curEmis = materialEmission FrontAndBack
-}
-- Store colors
materialDiffuse FrontAndBack $= diff -- For now, always FrontAndBack
materialSpecular FrontAndBack $= spec
materialAmbient FrontAndBack $= amb
materialEmission FrontAndBack $= emis
-- materialShininess FrontAndBack $= shin
commands -- Execute commands
restoreSurfaceColor
-- flush
-- clearColor $= Color4 0.0 0.0 0.0 0.0 -- Reset colors (not working right now)
preservingSurface (Terrain.Texture tex) commands = do
-- materialDiffuse FrontAndBack $= Color4 0.4 0.5 0.6 1
texture Texture2D $= Enabled
textureFunction $= Decal
textureBinding Texture2D $= Just tex
commands
texture Texture2D $= Disabled
-- return ()
preservingSurface NoSurface commands = do
commands
preservingSurface _ commands = do
print "Surface functionality not yet implemented"
commands
{-
preservingSurface (Terrain.Texture tex) commands = do
-- materialDiffuse FrontAndBack $= Color4 0.4 0.5 0.6 1
texture Texture2D $= Enabled
textureFunction $= Decal
textureBinding Texture2D $= Just tex
commands
texture Texture2D $= Disabled
-- return ()
-- Then
renderTerrainElement (SimpleTerrain (Quad p1 p2 p3 p4 transform) (Texture texObj) flav) = do
-- print "Rendering quad with texture"
loadIdentity
preservingMatrix $ do
preservingSurface (Texture texObj) $ do
--loadIdentity
applyTransform transform
displaySprite3D (Just texObj) (vertex3 p1) (vertex3 p2) (vertex3 p3) (vertex3 p4) (0,0) (1,1)
-- renderQuad (Just texObj) (vertex3 p1) (vertex3 p2) (vertex3 p3) (vertex3 p4)
-}
applyTransform :: Transform -> IO()
applyTransform Transform{toffset=offset, tscale=Vec3d(sx,sy,sz), ttheta = thetaAngle, tphi = phiAngle} = do
translate $ vector3 offset
Graphics.Rendering.OpenGL.scale sx sy sz
rotate thetaAngle $ vector3 (Vec3d(0.0, 0.0, 1.0))
rotate phiAngle $ vector3 (Vec3d(1.0, 0.0, 0.0))
applyTransform2 :: Transform -> Vec3d -> Vec3d
applyTransform2 Transform{toffset=Vec3d(dx,dy,dz), tscale=Vec3d(sx,sy,sz), ttheta = thetaAngle, tphi = phiAngle} (Vec3d (x,y,z)) =
Vec3d (sx*x + dx, sy*y + dy, sz*z + dz) -- Bounding boxes are axis aligned... but still may need to make slightly larger
renderTerrainElement :: TerrainElement -> IO()
renderTerrainElement t@(SimpleTerrain (GLUQuadric qprimitive qstyle transform) surf) = do
-- print "Rendering GLUQuadric"
preservingMatrix $ do
preservingSurface surf $ do
applyTransform transform
renderQuadric qstyle qprimitive
-- renderBoundingVolume $ getTerrainBounds t
renderTerrainElement (SimpleTerrain (Cube height transform) (Texture texObj)) = do
-- print "Rendering glutobject with texture"
-- loadIdentity
preservingMatrix $ do
preservingSurface (Texture texObj) $ do
-- loadIdentity
let h2 = (float height)/2
p1 = Vertex3 (h2) (h2) (h2)
p2 = Vertex3 (h2) (h2) (-h2)
p3 = Vertex3 (h2) (-h2) (-h2)
p4 = Vertex3 (h2) (-h2) (h2)
p5 = Vertex3 (-h2) (h2) (h2)
p6 = Vertex3 (-h2) (h2) (-h2)
p7 = Vertex3 (-h2) (-h2) (-h2)
p8 = Vertex3 (-h2) (-h2) (h2)
applyTransform transform
renderQuad (Just texObj) p1 p2 p3 p4
renderQuad (Just texObj) p1 p5 p8 p4
renderQuad (Just texObj) p5 p6 p7 p8
renderQuad (Just texObj) p6 p7 p3 p2
renderQuad (Just texObj) p1 p2 p6 p5
renderQuad (Just texObj) p3 p4 p8 p7
--handle texture
renderTerrainElement (SimpleTerrain (Quad p1 p2 p3 p4 transform) (Texture texObj)) = do
-- print "Rendering quad with texture"
-- loadIdentity
preservingMatrix $ do
preservingSurface (Texture texObj) $ do
--loadIdentity
applyTransform transform
renderQuad (Just texObj) (vertex3 p1) (vertex3 p2) (vertex3 p3) (vertex3 p4)
renderTerrainElement (SimpleTerrain (Quad p1 p2 p3 p4 transform) surf) = do
-- print "Rendering quad"
-- loadIdentity
preservingMatrix $ do
preservingSurface surf $ do
-- loadIdentity
applyTransform transform
renderPrimitive Quads $ do
clear [ColorBuffer]
-- color $ (Color3 (1.0::GLfloat) 0 0)
-- materialDiffuse FrontAndBack $= Color4 1.0 0.0 0.0 1.0
-- materialEmission FrontAndBack $= Color4 1.0 0.0 0.0 1.0
vertex $ vertex3 p1
vertex $ vertex3 p2
vertex $ vertex3 p3
vertex $ vertex3 p4
renderTerrainElement (SimpleTerrain (Tri p1 p2 p3 transform) surf) = do
-- print "Rendering quad"
-- loadIdentity
preservingMatrix $ do
preservingSurface surf $ do
-- loadIdentity
blend $= Enabled
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
applyTransform transform
renderPrimitive Triangles $ do
clear [ColorBuffer]
-- color $ (Color3 (1.0::GLfloat) 0 0)
-- materialDiffuse FrontAndBack $= Color4 1.0 0.0 0.0 1.0
-- materialEmission FrontAndBack $= Color4 1.0 0.0 0.0 1.0
vertex $ vertex3 p1
vertex $ vertex3 p2
vertex $ vertex3 p3
renderTerrainElement (SimpleTerrain (Trimesh) _) = do
print "Rendering trimesh terrain"
renderTerrainElement (CompoundTerrain transform telements) = do
-- print "Rendering compound terrain"
-- loadIdentity
preservingMatrix $ do
applyTransform transform
foldr (>>) (return ()) $ map renderTerrainElement telements
renderTerrainElement _ = error "Undefined terrain element"
-- Need to consider transforms
getTerrainBounds :: TerrainElement -> BoundingVolume
getTerrainBounds (SimpleTerrain (Cube height trans) _) =
BoundingBox (applyTransform2 trans (Vec3d (-h2,-h2,-h2))) (applyTransform2 trans (Vec3d (h2,h2,h2)))
where h2 = float height/2
getTerrainBounds (SimpleTerrain (GLUQuadric (Cylinder innerRad outerRad height _ _) _ trans) _) =
BoundingBox (applyTransform2 trans (Vec3d (-maxR,-maxR,0.0))) (applyTransform2 trans (Vec3d (maxR,maxR,h)))
where h = float height
maxR = max (float outerRad) (float innerRad)
{-
getTerrainBounds (SimpleTerrain (GLUTObject (Sphere' radius _ _) Transform{toffset=position}) _ _) =
BoundingEmpty
getTerrainBounds (SimpleTerrain (GLUTObject _ Transform{toffset=position}) _ _) = -- Other GLUT objects. Implement later
BoundingEmpty
-}
getTerrainBounds (CompoundTerrain trans telements) =
MultipleVolumes $ map (bvTransform (applyTransform2 trans) . getTerrainBounds) telements
getTerrainBounds (SimpleTerrain (Quad p1 p2 p3 p4 trans) _) =
BoundingBox (Vec3d (minx,miny,minz)) (Vec3d (maxx,maxy,maxz))
where ps = map (applyTransform2 trans) [p1,p2,p3,p4]
minx = minimum $ map getx ps
miny = minimum $ map gety ps
minz = minimum $ map getz ps
maxx = maximum $ map getx ps
maxy = maximum $ map gety ps
maxz = maximum $ map getz ps
getTerrainBounds _ = BoundingEmpty
{-
processSurface :: Surface -> IO()
processSurface (Terrain.Color (Col{cspecular=spec, cdiffuse=diff, cambient=amb,cemissive=emis,cshininess=shin})) = do
clearColor $= Color4 0.0 0.0 0.0 0.0
materialDiffuse FrontAndBack $= diff -- For now, always FrontAndBack
processSurface (Terrain.Texture) = do
print "Processing texture"
processSurface _ = do
print "Surface functionality not yet implemented"
materialDiffuse FrontAndBack $= Color4 1.0 1.0 1.0 1.0 -- Default to white
-}
{-
preservingTransform :: Transform -> IO() -> IO()
preservingTransform Transform{toffset=offset, tscale=Vec3d(sx,sy,sz), ttheta = thetaAngle, tphi = phiAngle} commands = do
translate $ vector3 offset
Graphics.Rendering.OpenGL.scale sx sy sz
preservingMatrix $ do
Graphics.Rendering.OpenGL.scale sx sy sz
translate $ vector3 offset
rotate thetaAngle $ vector3 (Vec3d(0.0, 0.0, 1.0))
rotate phiAngle $ vector3 (Vec3d(1.0, 0.0, 0.0))
commands
-}
-- For debugging purposes
{-
tempTex = (Texture (fromJust $ unsafePerformIO (getAndCreateTexture "bricks")))
renderBoundingVolume (BoundingBox v1 v2) = do
renderTerrainElement (SimpleTerrain (Cube 1.0 transform) tempTex)
print "Coordinates are:"
print v1
print v2
where height = (getz v2) ^-^ (getz v1)
transform = Transform{toffset=Vec3d(0.0,0.0,height/2),tscale=(v2 ^-^ v1), ttheta=0.0,tphi=0.0}
-}
|
harley/hamball
|
src/Terrain.hs
|
mit
| 11,981 | 0 | 18 | 2,732 | 2,224 | 1,150 | 1,074 | 146 | 1 |
{-# LANGUAGE NoMonomorphismRestriction, FlexibleInstances #-}
module FP.Arrow
( Arrow (..)
, parse_arrow
, name
)
where
import Autolib.TES.Identifier
import Autolib.TES.Term
import Autolib.TES.Position
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Size
import Data.Char ( isLower )
data Arrow at = Arrow { unArrow :: Term Identifier at }
deriving ( Eq, Ord )
instance Size ( Arrow at ) where size = size . unArrow
instance ( Symbol at ) => ToDoc ( Arrow at ) where
toDocPrec p ( Arrow ( Var v ) ) = toDoc v
toDocPrec p ( Arrow ( Node fun args ) ) = case ( show fun, args ) of
( "List", [arg] ) -> brackets $ toDoc $ Arrow arg
( "Arrow", [ from, to ] ) -> docParen ( p > 0 ) $
hsep [ toDocPrec 1 $ Arrow from
, text "->"
, toDocPrec 0 $ Arrow to
]
( "Tuple" , args ) -> parens
$ hsep $ punctuate comma $ map ( toDoc . Arrow ) args
_ -> docParen ( p > 1 && not ( null args ) )
$ toDoc fun <+> hsep ( map (toDocPrec 2 . Arrow) args )
instance Reader ( Arrow Identifier ) where
reader = parse_arrow []
parse_arrow vars = do
t <- arrow vars
return $ Arrow t
arrow vars = do
let parrow = do string "->" ; my_whiteSpace
xs <- Autolib.Reader.sepBy1 ( atomic vars ) parrow
let barrow from to = Node ( mkunary "Arrow" ) [ from, to ]
return $ foldr barrow ( last xs ) ( init xs )
atomic vars = tuple vars <|> list vars <|> application vars
tuple vars = my_parens $ do
args <- Autolib.Reader.sepBy ( arrow vars ) my_comma
return $ case args of
[ arg ] -> arg
_ -> Node ( mkunary "Tuple" ) args
list vars = my_brackets $ do
arg <- arrow vars
return $ Node ( mkunary "List" ) [ arg ]
application vars = do
fun <- bounded_name vars
args <- many ( basic vars )
mkapp vars fun args
mkapp vars fun args =
case ( fun `elem` vars, args ) of
( False, _ ) -> return $ Node fun args
( True, [] ) -> return $ Var fun
( True, _ ) -> fail "Typvariable mit Argument(en)"
basic vars = tuple vars
<|> do n <- bounded_name vars; mkapp vars n []
name = checked_name Nothing
bounded_name vars = checked_name ( Just vars )
checked_name mvars = do
c <- letter
cs <- many alphaNum
let n = mkunary $ c : cs
case ( isLower c, mvars ) of
( True , Just vars ) -> if elem n vars
then return ()
else fail $ show $ vcat
[ text "nicht gebundene Typvariable:"
, nest 4 $ toDoc n
, text "gebunden sind hier:"
, nest 4 $ toDoc vars
]
_ -> return ()
my_whiteSpace
return n
|
Erdwolf/autotool-bonn
|
src/FP/Arrow.hs
|
gpl-2.0
| 2,697 | 23 | 15 | 848 | 978 | 501 | 477 | 74 | 3 |
{-# LANGUAGE ImplicitParams,DoRec, PatternGuards #-}
module Fenfire.Main where
-- Copyright (c) 2006-2007, Benja Fallenstein, Tuukka Hastrup
-- This file is part of Fenfire.
--
-- Fenfire 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.
--
-- Fenfire 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 Fenfire; if not, write to the Free
-- Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
-- MA 02111-1307 USA
import Fenfire.Utils
import Fenfire.Cairo hiding (Path, rotate)
import Fenfire.Vobs
import qualified Fenfire.Raptor as Raptor
import Fenfire.URN5
import Fenfire.RDF
import Fenfire.VanishingView
import Fenfire
import Paths_fenfire (getDataFileName)
import Control.Exception hiding (Handler)
import Control.Monad
import Control.Monad.State
import Data.IORef
import Data.Maybe (fromJust)
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.Map as Map
--import Fenfire.GtkFixes
import Graphics.UI.Gtk hiding (Color, get, disconnect,
{-- GtkFixes overrides:
actionNew,
widgetGetStyle,
styleGetForeground, styleGetBackground,
styleGetLight, styleGetMiddle, styleGetDark,
styleGetText, styleGetBase,
styleGetAntiAliasing -})
import Graphics.UI.Gtk.ModelView as New
import Graphics.UI.Gtk.Gdk.Events as E
import qualified Network.URI
import System.Directory (canonicalizePath)
import System.Environment (getArgs, getProgName)
interpretNode :: (?graph :: Graph) => String -> Node
interpretNode str | "<" `List.isPrefixOf` str && ">" `List.isSuffixOf` str =
IRI $ tail $ init str
| isQname
, Just base <- Map.lookup ns (graphNamespaces ?graph) =
IRI $ base ++ local
| isQname = error $ "No such namespace: \""++ns++"\""
| otherwise = IRI str
where local = drop 1 $ dropWhile (/= ':') str
ns = takeWhile (/= ':') str
isQname = ns /= "" && (not $ any (`elem` local) [':', '/', '@'])
openFile :: (?vs :: ViewSettings) => FilePath ->
IO (Maybe (Graph, FilePath))
openFile fileName0 = do
dialog <- fileChooserDialogNew Nothing Nothing FileChooserActionOpen
[(stockCancel, ResponseCancel),
(stockOpen, ResponseAccept)]
when (fileName0 /= "") $ do fileChooserSetFilename dialog fileName0
return ()
response <- dialogRun dialog
widgetHide dialog
case response of
ResponseAccept -> do Just fileName <- fileChooserGetFilename dialog
graph <- loadGraph fileName
return $ Just (graph, fileName)
_ -> return Nothing
saveFile :: Graph -> FilePath -> Bool -> IO (FilePath,Bool)
saveFile graph fileName0 confirmSame = do
dialog <- fileChooserDialogNew Nothing Nothing FileChooserActionSave
[(stockCancel, ResponseCancel),
(stockSave, ResponseAccept)]
fileChooserSetDoOverwriteConfirmation dialog True
dialogSetDefaultResponse dialog ResponseAccept
when (fileName0 /= "") $ do fileChooserSetFilename dialog fileName0
return ()
onConfirmOverwrite dialog $ do
Just fileName <- fileChooserGetFilename dialog
if fileName == fileName0 && not confirmSame
then return FileChooserConfirmationAcceptFilename
else return FileChooserConfirmationConfirm
response <- dialogRun dialog
widgetHide dialog
case response of
ResponseAccept -> do Just fileName <- fileChooserGetFilename dialog
let fileName' = checkSuffix fileName
saveGraph graph fileName'
return (fileName', True)
_ -> return (fileName0, False)
checkSuffix :: FilePath -> FilePath
checkSuffix s | List.isSuffixOf ".turtle" s = s
| otherwise = s ++ ".turtle"
confirmSave :: (?vs :: ViewSettings, ?pw :: Window,
?views :: Views, ?uriMaker :: URIMaker) =>
Bool -> HandlerAction FenState ->
HandlerAction FenState
confirmSave False action = action
confirmSave True action = do
response <- liftIO $ do
dialog <- makeConfirmUnsavedDialog
response' <- dialogRun dialog
widgetHide dialog
return response'
case response of ResponseClose -> action
ResponseAccept -> do
handleAction "save"
saved <- get >>= return . not . fsGraphModified
when (saved) action
_ -> return ()
confirmFix :: (?vs :: ViewSettings, ?pw :: Window,
?views :: Views, ?uriMaker :: URIMaker) =>
String -> Bool -> HandlerAction FenState ->
HandlerAction FenState -> HandlerAction FenState
confirmFix _ False _ action = action
confirmFix title True fixaction action = do
response <- liftIO $ do
dialog <- makeDialog title
[(stockCancel, ResponseCancel),
(stockNo, ResponseReject),
(stockYes, ResponseAccept)]
ResponseAccept
response' <- dialogRun dialog
widgetHide dialog
return response'
case response of ResponseReject -> action
ResponseAccept -> action >> fixaction
_ -> return ()
confirmRevert :: (?vs :: ViewSettings, ?pw :: Window) =>
Bool -> HandlerAction FenState ->
HandlerAction FenState
confirmRevert False action = action
confirmRevert True action = do
response <- liftIO $ do
dialog <- makeConfirmRevertDialog
response' <- dialogRun dialog
widgetHide dialog
return response'
case response of ResponseClose -> action
_ -> return ()
confirmString :: (?vs :: ViewSettings, ?pw :: Window) =>
String -> String -> (String -> HandlerAction FenState) ->
HandlerAction FenState
confirmString title preset action = do
(response,text) <- liftIO $ do
dialog <- makeDialog title
[(stockCancel, ResponseCancel),
(stockApply, ResponseAccept)]
ResponseAccept
entry <- entryNew
set entry [ entryText := preset, entryActivatesDefault := True ]
widgetShow entry
vBox <- dialogGetUpper dialog
boxPackStart vBox entry PackNatural 0
response' <- dialogRun dialog
text' <- entryGetText entry
widgetHide dialog
return (response',text')
case response of ResponseAccept -> action text
_ -> return ()
handleEvent :: (?vs :: ViewSettings, ?pw :: Window, ?views :: Views,
?uriMaker :: URIMaker) => Handler Event FenState
handleEvent (Key { E.eventModifier=_mods, E.eventKeyName=key }) = do
state <- get; let graph = fsGraph state; fileName = fsFilePath state
case key of
x | x == "Up" || x == "i" -> handleAction "up"
x | x == "Down" || x == "comma" -> handleAction "down"
x | x == "Left" || x == "j" -> handleAction "left"
x | x == "Right" || x == "l" -> handleAction "right"
x | x == "Page_Up" -> handleAction "pageup"
x | x == "Page_Down" -> handleAction "pagedown"
x | x == "Home" -> handleAction "propup"
x | x == "End" -> handleAction "propdown"
"g" -> handleAction "goto"
"v" -> handleAction "chgview"
"p" -> handleAction "resetprop"
"O" -> handleAction "open"
"S" -> do (fp',saved) <- liftIO $ saveFile graph fileName False
let modified' = fsGraphModified state && not saved
put $ state { fsFilePath = fp', fsGraphModified = modified' }
_ -> unhandledEvent
handleEvent _ = unhandledEvent
handleAction :: (?vs :: ViewSettings, ?pw :: Window, ?views :: Views,
?uriMaker :: URIMaker) => Handler String FenState
handleAction action = do
state@(FenState { fsGraph = graph, fsPath = path, fsMark = mark,
fsFilePath = filepath, fsGraphModified = modified,
fsHasFocus=focus
}) <- get
let ?graph = graph in do
let rot@(Rotation node _) = fsRotation state
b f x = maybeDo (f rot x) $ \rot' -> do
putRotation rot'
modify $ \s -> s { fsGraphModified = modified }
n f x = do state' <- liftIO (f x state); put state'; setInterp True
o f x = do put (f x state); setInterp True
case action of
"up" -> b tryRotate (-1) ; "down" -> b tryRotate 1
"pageup"-> b tryRotate (-10); "pagedown" -> b tryRotate 10
"propup"-> b findChange (-1); "propdown" -> b findChange 1
"left" -> b tryMove Neg ; "right" -> b tryMove Pos
"nodel" -> n newNode Neg ; "noder" -> n newNode Pos
"connl" -> o connect Neg ; "connr" -> o connect Pos
"breakl"-> o disconnect Neg ; "breakr"-> o disconnect Pos
"rmlit" -> putGraph (delLit node graph)
"mark" -> putMark $ toggleMark node mark
"new" -> confirmSave modified $ do
(g', path') <- liftIO newGraph
put $ newState g' path' "" focus
"open" -> confirmSave modified $ do
result <- liftIO $ openFile filepath
maybeDo result $ \(g',fp') -> do
let g'' = mergeGraphs g' $ containsInfoTriples g'
put $ newState g'' (findStartPath Nothing g'') fp' focus
"loadIRI" -> case node of
IRI uri -> do
g <- liftIO $ loadGraph uri
let graph' = delete' (Any,Any,Any,node) graph
g' = mergeGraphs (mergeGraphs graph' g) $
containsInfoTriples g
s' = state {fsGraph=g',
fsUndo=(graph,path):fsUndo state,
fsRedo=[]}
put s'
_ -> unhandledEvent
"revert" | filepath /= "" -> confirmRevert modified $ do
g <- liftIO $ loadGraph filepath
let graph' = delete' (Any,Any,Any,Dft) graph
g' = mergeGraphs (mergeGraphs g graph') $
containsInfoTriples g
put $ newState g' (findStartPath Nothing g') filepath focus
"save" | filepath /= "" -> do
liftIO $ saveGraph graph filepath
modify $ \s -> s { fsGraphModified = False }
| otherwise -> handleAction "saveas"
"saveas"-> do
(fp',saved) <- liftIO $ saveFile graph filepath True
let modified' = modified && not saved
modify $ \s -> s { fsFilePath = fp', fsGraphModified = modified' }
"quit" -> do confirmSave modified $ liftIO mainQuit
"about" -> liftIO $ makeAboutDialog >>= widgetShow
"chgview" -> do put $ state { fsView = (fsView state + 1) `mod`
(length ?views) }
setInterp True
"addprop" -> do let uri = case node of IRI _ -> showNode
(graphNamespaces graph) node
_ -> ""
confirmString "Add property" uri $ \uri' ->
when (uri' /= "") $ do
let prop' = interpretNode uri'
props = fsProperties state
put $ state { fsProperty = prop',
fsProperties = Set.insert prop' props }
"resetprop" -> when (fsProperty state /= rdfs_seeAlso) $
put $ state { fsProperty = rdfs_seeAlso }
"changeIRI" -> case node of
IRI _ -> confirmString "New IRI" (showNode
(graphNamespaces graph) node) $ \uri' ->
put $ stateReplaceNode node
(interpretNode uri') state
_ -> unhandledEvent
"goto" -> confirmString "Go to node"
(showNode (graphNamespaces graph) node) $ \s -> do
let node' = interpretNode s
rot' = Rotation node' 0
noinfo = not $ iquery (node',Any,Any)
|| iquery (Any,Any,node')
confirmFix "Load info about node"
noinfo (handleAction "loadIRI")
$ putRotation rot'
"undo" | (graph',path'):undos <- fsUndo state -> do
put state {fsGraph=graph', fsPath=path',
fsUndo=undos, fsRedo=(graph,path):fsRedo state}
setInterp True
"redo" | (graph',path'):redos <- fsRedo state -> do
put state {fsGraph=graph', fsPath=path',
fsUndo=(graph,path):fsUndo state, fsRedo=redos}
setInterp True
_ -> do liftIO $ putStrLn $ "Unhandled action: " ++ action
unhandledEvent
where putGraph g = do modify $ \s ->
s { fsGraph=g, fsGraphModified=True,
fsUndo=(fsGraph s, fsPath s):fsUndo s,
fsRedo=[]}
setInterp True
putRotation rot = do modify $ \s -> s { fsPath = toPath' rot }
setInterp True
putMark mk = do modify $ \state -> state { fsMark=mk }
delLit n graph = delete' (n, rdfs_label, Any) graph
makeActions actionGroup = do
let actionentries =
[ ( "new" , "", stockNew , Nothing )
, ( "open" , "", stockOpen , Nothing )
, ( "save" , "", stockSave , Nothing )
, ( "saveas" , "", stockSaveAs , Just "<Ctl><Shift>S" )
, ( "revert" , "", stockRevertToSaved , Nothing )
, ( "quit" , "", stockQuit , Nothing )
, ( "about" , "", stockAbout , Nothing )
, ( "loadIRI", "_Load node's IRI",
stockGoForward , Just "<Ctl>L" )
, ( "undo" , "", stockUndo , Just "<Ctl>Z" )
, ( "redo" , "", stockRedo , Just "<Ctl><Shift>Z" )
]
forM actionentries $ \(name,label',stock,accel) -> do
action <- actionNew name label' Nothing (Just stock)
actionGroupAddActionWithAccel actionGroup action accel
-- actionSetAccelGroup action accelGroup
updateActions actionGroup stateRef = do
state <- readIORef stateRef
let readable = fsFilePath state /= ""
modified = fsGraphModified state
view = fst $ ?views !! (fsView state)
Just save <- actionGroupGetAction actionGroup "save"
actionSetSensitive save modified
Just revert <- actionGroupGetAction actionGroup "revert"
actionSetSensitive revert (modified && readable)
Just undo <- actionGroupGetAction actionGroup "undo"
actionSetSensitive undo (not $ null $ fsUndo state)
Just redo <- actionGroupGetAction actionGroup "redo"
actionSetSensitive redo (not $ null $ fsRedo state)
Just changeView <- actionGroupGetAction actionGroup view
toggleActionSetActive (castToToggleAction changeView) True
updatePropMenu propmenu actionGroup stateRef updateCanvas = do
state <- readIORef stateRef
Just addProp <- actionGroupGetAction actionGroup "addprop"
menu <- menuNew
forM (Set.toAscList $ fsProperties state) $ \prop -> do
item <- let ?graph = fsGraph state
in menuItemNewWithLabel $ getTextOrIRI prop
onActivateLeaf item $ do
modifyIORef stateRef $ \state' -> state' {fsProperty=prop}
updateCanvas False
menuShellAppend menu item
widgetShow item
sep <- separatorMenuItemNew
menuShellAppend menu sep
widgetShow sep
item <- actionCreateMenuItem addProp
menuShellAppend menu $ castToMenuItem item
menuItemSetSubmenu propmenu menu
makeBindings actionGroup = do
let bindingentries =
[ ("noder" , "_New node to right" ,
stockMediaForward , Just "n" )
, ("nodel" , "N_ew node to left" ,
stockMediaRewind , Just "<Shift>N" )
, ("breakr" , "_Break connection to right" ,
stockGotoLast , Just "b" )
, ("breakl" , "B_reak connection to left" ,
stockGotoFirst , Just "<Shift>B" )
, ("mark" , "Toggle _mark" ,
stockOk , Just "m" )
, ("connr" , "_Connect marked to right" ,
stockGoForward , Just "c" )
, ("connl" , "C_onnect marked to left" ,
stockGoBack , Just "<Shift>C" )
, ("rmlit" , "Remove _literal text" ,
stockStrikethrough , Just "<Alt>BackSpace" )
, ("addprop", "_Add property" ,
stockAdd , Just "<Ctl>P" )
, ("changeIRI", "Change node's _IRI" ,
stockRefresh , Just "u" )
, ( "goto" , "_Go to IRI" ,
stockJumpTo , Just "g" )
]
forM bindingentries $ \(name,label',stock,accel) -> do
action <- actionNew name label' Nothing (Just stock)
actionGroupAddActionWithAccel actionGroup action accel
-- actionSetAccelGroup action bindings
makeMenus actionGroup root propmenu = addAll root menu where
menu = [m "_File" [a "new", a "open", a "goto", a "loadIRI", sep,
a "save", a "saveas", a "revert", sep,
a "quit"],
m "_Edit" [a "undo", a "redo", sep,
return propmenu, sep,
a "noder", a "nodel", sep,
a "breakr", a "breakl", sep,
a "mark", a "connr", a "connl", sep,
a "changeIRI", a "rmlit"],
m "_View" (map (a . fst) ?views),
m "_Help" [a "about"]]
addAll parent items = mapM_ (menuShellAppend parent) =<< sequence items
m :: String -> [IO MenuItem] -> IO MenuItem
m name children = do item <- menuItemNewWithMnemonic name
menu' <- menuNew
addAll menu' children
menuItemSetSubmenu item menu'
return item
sep = liftM castToMenuItem separatorMenuItemNew
a name = do
actionM <- actionGroupGetAction actionGroup name
action <- case actionM of
Just action' -> return action'
Nothing -> error $ "Action: " ++ name ++ " does not exist."
item <- actionCreateMenuItem action
return (castToMenuItem item)
makeToolbarItems actionGroup toolbar = do
forM_ ["new", "open", "save", "", "undo", "redo",""] $ \name ->
if name == "" then do
item <- separatorToolItemNew
toolbarInsert toolbar item (-1)
else do
Just action <- actionGroupGetAction actionGroup name
item <- actionCreateToolItem action
toolbarInsert toolbar (castToToolItem item) (-1)
handleException :: Control.Exception.SomeException -> IO ()
handleException e = do
dialog <- makeMessageDialog "Exception in event" (show e)
dialogRun dialog
widgetHide dialog
main :: IO ()
main = do
uriMaker <- newURIMaker
-- initial state:
args <- initGUI
window <- windowNew
style <- widgetGetStyle window
bgColor <- styleGetBackground style StateSelected
blurBgColor <- styleGetBackground style StateActive
focusColor <- styleGetBase style StateSelected
blurColor <- styleGetBase style StateActive
textColor <- styleGetText style StateSelected
blurTextColor <- styleGetText style StateActive
canvasBgColor <- styleGetBackground style StateNormal
let alpha x (Color r g b a) = Color r g b (x*a)
let ?vs = ViewSettings { hiddenProps=[rdfs_label], maxCenter=3 }
?uriMaker = uriMaker in let
?views = [("Wheel view", vanishingView 20 30
(alpha 0.7 $ fromGtkColor bgColor)
(alpha 0.7 $ fromGtkColor blurBgColor)
(fromGtkColor focusColor) (fromGtkColor blurColor)
(fromGtkColor textColor) (fromGtkColor blurTextColor)),
("Presentation view", presentationView)] in do
let view s = snd (?views !! fsView s) s
stateRef <- case args of
[] -> do
(g, rot) <- newGraph
newIORef $ newState g rot "" False
xs -> do
let f x | List.isPrefixOf "http:" x = return x
| otherwise = canonicalizePath x
fileName:fileNames <- mapM f xs
g' <- loadGraph fileName
gs <- mapM loadGraph fileNames
let h x | List.isPrefixOf "http:" x = return x
| otherwise = Raptor.filenameToURI x
uri <- h fileName
let graph = foldl mergeGraphs g' (gs ++ map containsInfoTriples (g':gs))
newIORef $ newState graph (findStartPath (Just uri) graph) fileName False
-- start:
makeWindow window canvasBgColor view stateRef
widgetShowAll window
mainGUI
makeWindow window canvasBgColor view stateRef = do
-- main window:
let ?pw = window in do
rec
logo <- getDataFileName "data-files/icon16.png"
Control.Exception.catch (windowSetIconFromFile window logo)
(\e -> putStr ("Opening "++logo++" failed: ") >> print (e::Control.Exception.IOException))
windowSetTitle window "Fenfire"
windowSetDefaultSize window 800 550
-- textview for editing:
textView <- textViewNew
textViewSetAcceptsTab textView False
textViewSetWrapMode textView WrapWordChar
-- this needs to be called whenever the node or its text changes:
let stateChanged _ state@(FenState { fsPath=Path n _, fsGraph=g }) = do
buf <- textBufferNew Nothing
textBufferSetText buf (let ?graph=g in maybe "" id $ getText n)
afterBufferChanged buf $ do
start <- textBufferGetStartIter buf
end <- textBufferGetEndIter buf
text <- textBufferGetText buf start end True
s@(FenState { fsGraph = g' }) <- readIORef stateRef
let g'' = setText n text g' -- buf corresponds to n, not to n'
writeIORef stateRef $
s { fsGraph=g'', fsGraphModified=True, fsRedo=[],
fsUndo=(fsGraph s, fsPath s):(fsUndo s) }
updateActions actionGroup stateRef
updateCanvas True
textViewSetBuffer textView buf
updatePropMenu propmenu actionGroup stateRef updateCanvas
New.listStoreClear propList
forM_ (Set.toAscList $ fsProperties state) $ \prop ->
let ?graph = g in
New.listStoreAppend propList (prop, getTextOrIRI prop)
let activeIndex = List.elemIndex (fsProperty state)
(Set.toAscList $ fsProperties state)
maybe (return ()) (New.comboBoxSetActive combo) activeIndex
updateActions actionGroup stateRef
-- canvas for view:
(canvas, updateCanvas, canvasAction) <-
vobCanvas stateRef view handleEvent handleAction
stateChanged handleException (fromGtkColor canvasBgColor) 0.5
onFocusIn canvas $ \_event -> do
modifyIORef stateRef $ \s -> s { fsHasFocus = True }
forM_ bindingActions $ actionConnectAccelerator
updateCanvas True
return True
onFocusOut canvas $ \_event -> do
modifyIORef stateRef $ \s -> s { fsHasFocus = False }
forM_ bindingActions $ actionDisconnectAccelerator
updateCanvas True
return True
-- action widgets:
-- accelGroup <- accelGroupNew
-- windowAddAccelGroup window accelGroup
-- bindings are active only when the canvas has the focus:
-- bindings <- accelGroupNew
-- windowAddAccelGroup window bindings
-- fake bindings aren't used
-- fake <- accelGroupNew
actionGroup <- actionGroupNew "main"
bindingGroup <- actionGroupNew "bindings"
makeActions actionGroup -- accelGroup
makeBindings bindingGroup-- bindings
makeBindings actionGroup-- fake
actions <- actionGroupListActions actionGroup
bindingActions <- actionGroupListActions bindingGroup
forM_ (actions ++ bindingActions) $ \action -> do
name <- actionGetName action
onActionActivate action $ canvasAction name >> return ()
viewActs <- forM (zip [0..] ?views) $ \(index, (name, _view)) -> do
action <- radioActionNew name name Nothing Nothing index
actionGroupAddAction actionGroup action
onActionActivate action $ do
i <- radioActionGetCurrentValue action
state <- readIORef stateRef
when (i /= fsView state) $ do
writeIORef stateRef $ state { fsView = i }
updateCanvas True
return action
forM_ (tail viewActs) $ \x -> radioActionSetGroup x (head viewActs)
toggleActionSetActive (toToggleAction $ head viewActs) True
-- user interface widgets:
menubar <- menuBarNew
propmenu <- menuItemNewWithMnemonic "Set _property"
makeMenus actionGroup menubar propmenu
toolbar <- toolbarNew
makeToolbarItems actionGroup toolbar
propList <- New.listStoreNew []
combo <- New.comboBoxNew
set combo [-- New.comboBoxModel := Just propList
New.comboBoxFocusOnClick := False ]
renderer <- New.cellRendererTextNew
New.cellLayoutPackStart combo renderer True
New.cellLayoutSetAttributes combo renderer propList $ \row ->
[ New.cellText := snd row ]
New.onChanged combo $ do
active <- New.comboBoxGetActive combo
case active of
-1 -> return ()
i -> do
(prop,_name) <- listStoreGetValue propList i
state' <- readIORef stateRef
writeIORef stateRef $ state' {fsProperty=prop}
when (fsProperty state' /= prop) $ updateCanvas False
comboLabel <- labelNew (Just "Property: ")
comboVBox <- hBoxNew False 0
boxPackStart comboVBox comboLabel PackNatural 0
boxPackStart comboVBox combo PackNatural 0
comboAlign <- alignmentNew 0.5 0.5 1 0
containerAdd comboAlign comboVBox
combotool <- toolItemNew
containerAdd combotool comboAlign
toolbarInsert toolbar combotool (-1)
sepItem <- separatorToolItemNew
toolbarInsert toolbar sepItem (-1)
Just addpropAction <- actionGroupGetAction actionGroup "addprop"
addpropItem <- actionCreateToolItem addpropAction
toolbarInsert toolbar (castToToolItem addpropItem) (-1)
-- layout:
canvasFrame <- frameNew
set canvasFrame [ containerChild := canvas
, frameShadowType := ShadowIn
]
textViewFrame <- frameNew
set textViewFrame [ containerChild := textView
, frameShadowType := ShadowIn
]
paned <- vPanedNew
panedAdd1 paned canvasFrame
panedAdd2 paned textViewFrame
vBox <- vBoxNew False 0
boxPackStart vBox menubar PackNatural 0
boxPackStart vBox toolbar PackNatural 0
boxPackStart vBox paned PackGrow 0
containerSetFocusChain vBox [toWidget paned]
set paned [ panedPosition := 380, panedChildResize textViewFrame := False ]
set window [ containerChild := vBox ]
-- start:
startState <- readIORef stateRef
stateChanged (startState { fsProperties = Set.empty }) startState
widgetGrabFocus canvas
onDelete window $ \_event -> canvasAction "quit"
return window
makeAboutDialog :: (?pw :: Window) => IO AboutDialog
makeAboutDialog = do
dialog <- aboutDialogNew
{- pixbufNewFromFile has different signature on newer gtk2hs:
logoFilename <- getDataFileName "data-files/logo.svg"
pixbuf <- Control.Exception.catch (pixbufNewFromFile logoFilename)
(\e -> return $ Left (undefined, show e))
logo <- case pixbuf of Left (_,msg) -> do
putStr ("Opening "++logoFilename++" failed: ")
putStrLn msg
return Nothing
Right pixbuf' -> return . Just =<<
pixbufScaleSimple pixbuf'
200 (floor (200*(1.40::Double)))
InterpHyper
-} logo <- return Nothing
set dialog [ aboutDialogName := "Fenfire"
, aboutDialogVersion := "alpha version"
, aboutDialogCopyright := "Licensed under GNU GPL v2 or later"
, aboutDialogComments :=
"An application for notetaking and RDF graph browsing."
, aboutDialogLogo := logo
, aboutDialogWebsite := "http://fenfire.org"
, aboutDialogAuthors := ["Benja Fallenstein", "Tuukka Hastrup"]
, windowTransientFor := ?pw
]
onResponse dialog $ \_response -> widgetHide dialog
return dialog
makeDialog :: (?pw :: Window) => String -> [(String, ResponseId)] ->
ResponseId -> IO Dialog
makeDialog title buttons preset = do
dialog <- dialogNew
set dialog [ windowTitle := title
, windowTransientFor := ?pw
, windowModal := True
, windowDestroyWithParent := True
, dialogHasSeparator := False
]
mapM_ (uncurry $ dialogAddButton dialog) buttons
dialogSetDefaultResponse dialog preset
return dialog
makeConfirmUnsavedDialog :: (?pw :: Window) => IO Dialog
makeConfirmUnsavedDialog = do
makeDialog "Confirm unsaved changes"
[("_Discard changes", ResponseClose),
(stockCancel, ResponseCancel),
(stockSave, ResponseAccept)]
ResponseAccept
makeConfirmRevertDialog :: (?pw :: Window) => IO Dialog
makeConfirmRevertDialog = do
makeDialog "Confirm revert"
[(stockCancel, ResponseCancel),
(stockRevertToSaved,ResponseClose)]
ResponseCancel
makeMessageDialog primary secondary = do
dialog <- dialogNew
set dialog [ windowTitle := primary
, windowModal := True
, containerBorderWidth := 6
, dialogHasSeparator := False
]
image' <- imageNewFromStock stockDialogError IconSizeDialog
set image' [ miscYalign := 0.0 ]
label' <- labelNew $ Just $ "<span weight=\"bold\" size=\"larger\">"++
escapeMarkup primary++"</span>\n\n"++escapeMarkup secondary
set label' [ labelUseMarkup := True
, labelWrap := True
, labelSelectable := True
, miscYalign := 0.0
]
hBox <- hBoxNew False 0
set hBox [ boxSpacing := 12
, containerBorderWidth := 6
]
boxPackStart hBox image' PackNatural 0
boxPackStart hBox label' PackNatural 0
vBox <- dialogGetUpper dialog
set vBox [ boxSpacing := 12 ]
boxPackStart vBox hBox PackNatural 0
dialogAddButton dialog stockOk ResponseAccept
widgetShowAll hBox
return dialog
|
timthelion/fenfire
|
Fenfire/Main.hs
|
gpl-2.0
| 33,440 | 0 | 27 | 12,024 | 8,267 | 4,064 | 4,203 | -1 | -1 |
module Css.ShowCss where
import Css.CssTypes
import Data.List
showcss :: CssRule -> String
showcss (Sel sel, decls) = intercalate " " (map (concat . map showsel) sel) ++ " { " ++ intercalate " " (map showdecl decls) ++ " }"
showsel :: CssNodeSpec -> String
showsel (Elem n) = n
showsel (Class c) = "." ++ c
showsel (Id id) = "#" ++ id
showdecl :: CssDecl -> String
showdecl d = txt ++ ";"
where
txt = case d of
Display a -> "display: " ++ showdisplay a
TextAlign a -> "text-align: " ++ a
VerticalAlign a -> "vertical-align: " ++ a
FontSize sz -> "font-size: " ++ showsz sz
PaddingLeft sz -> "padding-left: " ++ showsz sz
PaddingRight sz -> "padding-right: " ++ showsz sz
PaddingTop sz -> "padding-top: " ++ showsz sz
PaddingBottom sz -> "padding-bottom: " ++ showsz sz
MarginLeft sz -> "margin-left: " ++ showsz sz
MarginRight sz -> "margin-right: " ++ showsz sz
MarginTop sz -> "margin-top: " ++ showsz sz
MarginBottom sz -> "margin-bottom: " ++ showsz sz
Width w -> "width: " ++ showsz w
Height w -> "height: " ++ showsz w
showsz (Px sz) = (show sz) ++ "px"
showsz (Em sz) = (show sz) ++ "em"
showsz (Pct sz) = (show sz) ++ "%"
showdisplay Block = "block"
showdisplay Inline = "inline"
showdisplay InlineBlock = "inline-block"
showdisplay None = "none"
|
pbevin/toycss
|
src/css/ShowCss.hs
|
gpl-2.0
| 1,351 | 0 | 13 | 327 | 503 | 242 | 261 | 33 | 14 |
-- Copyright (c) 2015-16 Nicola Bonelli <[email protected]>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
{-# LANGUAGE TupleSections #-}
module Lang.Parser
( defaultImports
, parseCode
, mkMainFunction
, mkImportList
) where
import Language.Haskell.Interpreter
-- import Data.List
import Control.Monad.Reader
import Options
import Data.Maybe
defaultImports :: [(ModuleName, Maybe String)]
defaultImports =
[ ("Prelude", Just "P")
, ("Data.Bits", Nothing)
, ("Data.Monoid", Nothing)
, ("Network.PFQ", Nothing)
, ("Network.PFQ.Lang", Nothing)
, ("Network.PFQ.Types", Nothing)
, ("Network.PFQ.Lang.Prelude", Nothing)
, ("Network.PFQ.Lang.Default", Nothing)
, ("Network.PFQ.Lang.Experimental", Nothing)
]
parseCode :: String -> (String, [(ModuleName, Maybe String)])
parseCode code = (unlines (map snd xs), mapMaybe fst xs)
where xs = map parseLine (lines code)
type Import = (ModuleName, Maybe String)
parseLine :: String -> (Maybe Import, String)
parseLine xs = case () of
_ | "import": "qualified": modname: "as": alias : ys <- ws -> (Just (modname, Just alias), unwords ys)
| "import": "qualified": modname : ys <- ws -> (Just (modname, Just modname), unwords ys)
| "import": modname : ys <- ws -> (Just (modname, Nothing), unwords ys)
| otherwise -> (Nothing, xs)
where ws = words xs
mkMainFunction :: String -> String
mkMainFunction code = "(let " ++ code ++ " in main)"
mkImportList :: (Monad m) => [(ModuleName, Maybe String)] -> OptionT m [(ModuleName, Maybe String)]
mkImportList xs = do
opt <- ask
return $ defaultImports ++ map (, Nothing) (modules opt) ++ xs
|
pfq/PFQ
|
user/pfq-lang/src/Lang/Parser.hs
|
gpl-2.0
| 2,419 | 0 | 16 | 529 | 570 | 323 | 247 | 38 | 1 |
module TransactionQb
(Transaction,
dummyNumber,
dummyAmount,
prototype,
createTransaction,
SalesDetail,
dateFromToday,
TransactionType,
allSales,
allPurchases,
allBankingTransactions,
salesRefund
)
where
import Data.Text (Text)
import Data.Time
import Data.Maybe
import Test.QuickCheck
data Date = UTCTime
deriving (Eq, Ord, Show, Read)
data Number = Double
deriving (Eq, Ord, Show, Read)
data SalesTaxType = TaxPayment | TaxAdjustment
deriving (Eq, Ord, Show,Read)
data Transaction = Transaction TransactionType Date Number Name Amount
deriving (Eq, Ord, Show, Read)
data TransactionType = Sales SalesDetail | Purchase PurchaseDetail | Banking BankingDetail
deriving (Eq, Ord, Show, Read)
data BankingDetail = SalesTax SalesTaxType | Check | CreditCard | JournalEntry | Deposit | CashExpense
deriving (Eq, Ord, Show, Read)
data SalesDetail = Refund | Estimate | SalesReceipt | CreditMemo | Invoice | Payment
deriving (Eq, Ord, Show, Read)
data PurchaseDetail = Expenses | Bill PaymentType | CashPurchase
deriving (Eq, Ord, Show, Read)
data PaymentType = CheckDetail Bank CheckNumber Amount | CreditCardDetail Card Amount
deriving (Eq, Ord, Show, Read)
type Name = String
type ABA = String
type AccountNumber = String
type InterestRate = Double
type CheckNumber = String
type Cash = Amount
type Amount = Double
data Card = Mastercard | Visa | AMEX
deriving (Eq, Ord, Show, Read)
data BankAccountType = CheckingAccount InterestRate | SavingsAccount InterestRate | MoneyMarket InterestRate
deriving (Eq, Ord, Show, Read)
data Bank = Bank Name ABA BankAccountType AccountNumber
deriving (Eq, Ord, Show, Read)
type Journal = [Maybe Transaction]
dateFromToday = read "2013-12-23"
dummyNumber = read "12.3"
dummyAmount = read "12.3"
prototype = "Prototype"
filterT :: Maybe Transaction -> Maybe Transaction -> Bool
filterT (Just (Transaction aType _ _ _ _ )) (Just(Transaction anotherType _ _ _ _)) =
aType == anotherType
filterT Nothing (Just t) = False
filterT (Just t) Nothing = False
allSales :: Journal -> Journal
allSales [] = []
allSales aList
= filter (filterT proto) aList
where proto = Just (Transaction (Sales Refund) dateFromToday dummyNumber prototype dummyAmount)
allPurchases:: Journal -> Journal
allPurchases [] = []
allPurchases aList = filter (filterT proto) aList
where proto = Just (Transaction (Purchase Expenses) dateFromToday dummyNumber prototype dummyAmount)
allBankingTransactions :: Journal -> Journal
allBankingTransactions [] = []
allBankingTransactions aList = filter (filterT proto) aList
where proto = Just (Transaction (Banking JournalEntry) dateFromToday dummyNumber prototype dummyAmount)
salesRefund = Sales Refund
createTransaction :: TransactionType -> Date -> Number -> Name -> Amount -> Transaction
createTransaction aType aDate aNumber aName anAmount = Transaction aType aDate aNumber aName anAmount
totalSales :: Journal -> Maybe Transaction
totalSales [] = Nothing
totalSales aJournal = foldr addTransaction Nothing sales
where sales = allSales aJournal
totalPurchases :: Journal -> Maybe Transaction
totalPurchases [] = Nothing
totalPurchases aJournal = foldr addTransaction Nothing purchases
where purchases = allPurchases aJournal
totalBankingTransactions :: Journal -> Maybe Transaction
totalBankingTransactions [] = Nothing
totalBankingTransactions aJournal = foldr addTransaction Nothing bankingTransactions
where bankingTransactions = allBankingTransactions aJournal
addTransaction:: Maybe Transaction -> Maybe Transaction -> Maybe Transaction
addTransaction Nothing Nothing = Nothing
addTransaction a Nothing = a
addTransaction Nothing a = a
-- The values a b and c are place holders..we are losing the date for the transaction in this
-- example. Not sure if this will work for long. The design has
-- quite a few issues: the number of functions seem to multiply with the type of transactions
-- we need to probably derive from Enum to limit the search functions??
addTransaction (Just (Transaction aType a b c anAmount)) (Just (Transaction anotherType _ _ _ anotherAmount))
| aType == anotherType = Just (Transaction aType a b c (anAmount + anotherAmount))
|
dservgun/haskell_test_code
|
src/TransactionQb.hs
|
gpl-2.0
| 4,301 | 0 | 11 | 770 | 1,222 | 649 | 573 | 92 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Brainfuck.Make
-- ( computer
-- , acceptor
-- )
where
-- $Id$
import Inter.Types
import Inter.Quiz
-- import Brainfuck.Property
import Brainfuck.Syntax.Data
import Brainfuck.Syntax.Parse
import qualified Brainfuck.Machine
import qualified Brainfuck.Example
-- import qualified Brainfuck.Config as TC
-- import qualified Machine.Acceptor.Type as A
-- import qualified Machine.Acceptor.Inter
-- import Language.Type
-- import Language.Inter
import qualified Machine.Numerical.Config as C
import qualified Machine.Numerical.Make as M
import qualified Machine.Numerical.Inter as I
import qualified Autolib.Reporter.Checker as R
import Machine.Vorrechnen
import Machine.Class
import Autolib.Set
import Autolib.ToDoc
import Autolib.Informed
import Autolib.Util.Zufall
import Autolib.Reporter
instance C.Check () Statement where
check () s = return ()
instance Container Statement () where { }
computer :: Make
computer = M.make $ C.Config
{ C.name = "Brainfuck-Maschine (als Computer)"
, C.conditions = []
, C.arity = 2
, C.op = read "x1 * x2"
, C.num_args = 10
, C.max_arg = 20
, C.cut = 1000
, C.checks = [ ] :: [ () ]
, C.start = Brainfuck.Example.student -- TODO
}
{-
----------------------------------------------------------------
acceptor :: Make
acceptor = quiz ( A.Acceptor "Brainfuck" ) TC.example
type Accept = A.Type ( Brainfuck Char Int ) String Property
instance Project A.Acceptor Accept Accept where
project _ i = i
instance Generator A.Acceptor TC.Config Accept where
generator _ config key = do
let l = inter $ TC.lang config
m = TC.max_num config
e = TC.max_length config
small = \ w -> length w <= e
yeah <- lift $ samples l m 0
noh <- lift $ anti_samples l m 0
return $ A.Make
{ A.machine_desc = text "Brainfuck-Maschine (als Akzeptor)"
, A.data_desc = info $ TC.lang config
, A.yeah = take m $ filter small yeah
, A.noh = take m $ filter small noh
, A.cut = TC.cut config
, A.properties = Sane : TC.properties config
, A.start = TC.start config
}
-}
|
Erdwolf/autotool-bonn
|
src/Brainfuck/Make.hs
|
gpl-2.0
| 2,316 | 0 | 9 | 610 | 280 | 178 | 102 | 33 | 1 |
-- type classes
-- class methods
class Geometry g where
area :: g -> Double
perim :: g -> Double
data Square = Square Double Double deriving Show
data Circle = Circle Double deriving Show
instance Geometry Square where
area (Square w h) = w * h
perim (Square w h) = 2 * w + 2 * h
instance Geometry Circle where
area (Circle r) = pi * r * r
perim (Circle r) = 2 * pi * r
measure :: (Geometry a, Show a) => a -> IO ()
measure g = do
print g
print $ area g
print $ perim g
main = do
let s = Square 3 4
let c = Circle 5
measure s
measure c
|
solvery/lang-features
|
haskell/typeclass_1.hs
|
gpl-2.0
| 596 | 0 | 10 | 184 | 270 | 132 | 138 | 21 | 1 |
{-# LANGUAGE TemplateHaskell, RankNTypes #-}
module Settings
( Settings
, fromOk
, strToCode, codeToStr, settingsFile, annotFile
, readSettings, writeUserSettings, getCode
, createSettings
, get_replicates, get_counts_file, get_counts_skip, get_user_settings
, get_info_columns, get_ec_column
, is_locked, get_csv_format
, get_js_user_settings, get_min_counts
) where
import Control.Applicative
import Data.Time
import Data.List
import Data.Maybe
import System.FilePath
import System.Directory (renameFile)
import Text.JSON
import Text.JSON.Types (set_field)
import qualified Data.ByteString.Lazy as BS
import Control.Lens
import Control.Monad (foldM)
import Utils
newtype Code = Code {codeToStr :: String} deriving (Eq,Show)
data Settings = Settings { code :: Code
, remote_addr :: String
, created :: String
, user_settings :: UserSettings
, locked :: Bool -- ^ True to allow a public example
} deriving Show
data UserSettings =
UserSettings { _skip :: Int -- ^ Number of rows to skip (not used frontend?)
, _csv_format :: Bool -- ^ True for CSV, False for TAB
, _ec_col :: Maybe String -- ^ Optional EC number column
, _info_cols :: [String] -- ^ Optional list of columns to include in display
, _link_col :: Maybe String -- ^ Optional gene-link column (used in link_url)
, _link_url :: Maybe String -- ^ Optional gene-link URL
-- Only used on the frontend
, _hide :: [String] -- ^ Used in the frontend to hide some columns
, _title :: String -- ^ Title to use in UI
, _fdr_threshold :: String -- ^ False Discovery Rate initial value on UI
, _fc_threshold :: String -- ^ (Log) Fold Change initial value on UI
, _analyze_server_side :: Bool -- ^ To be analysed server side?
-- Used for server-side analysis
, _init_select :: [String] -- ^ Replicates to initially select in UI
, _replicates :: [(String, [String])] -- ^ Definition of replicates
, _min_counts :: Maybe Int -- ^ Minimum number of reads across all replicates otherwise ignored
-- Used for data already analysed by user
, _fc_cols :: [String] -- ^ Columns containing FC info
, _primary :: String -- ^ Name for primary condition
, _avg_col :: String -- ^ Column name for average expression
, _fdr_col :: String -- ^ Column name for False Discovery Rate
} deriving Show
makeLenses ''UserSettings
defUserSettings :: UserSettings
defUserSettings = UserSettings { _ec_col = Nothing
, _link_col = Nothing
, _link_url = Nothing
, _info_cols = []
, _replicates = []
, _init_select = []
, _hide = []
, _csv_format = True
, _skip = 0
, _title = ""
, _fdr_threshold = "1"
, _fc_threshold = "0"
, _min_counts = Nothing
, _fc_cols = []
, _primary = ""
, _avg_col = ""
, _analyze_server_side = True
, _fdr_col = ""
}
instance JSON Settings where
-- readJSON :: JSValue -> Result Settings
readJSON (JSObject obj) = Settings <$> (strToCode <$> valFromObj "code" obj)
<*> valFromObj "remote_addr" obj
<*> valFromObj "created" obj
<*> valFromObj "user_settings" obj
<*> valFromObj "locked" obj
readJSON _ = Error "Expect object"
-- showJSON :: Settings -> JSValue
showJSON s = makeObj [("code", showJSON . codeToStr . code $ s)
,("remote_addr", showJSON $ remote_addr s)
,("created", showJSON $ created s)
,("user_settings",showJSON $ user_settings s)
,("locked",showJSON $ locked s)
]
instance JSON UserSettings where
readJSON (JSObject obj) = chkUserSettingsValid =<< foldM (\u (get,_) -> get u obj) defUserSettings user_settings_cols
readJSON _ = Error "Unable to read UserSettings"
showJSON u = JSObject $ foldl' (\obj (_,set) -> set u obj) (toJSObject []) user_settings_cols
chkUserSettingsValid :: UserSettings -> Result UserSettings
chkUserSettingsValid s = if any invalidChar allColumns
then Error "Invalid character in column name"
else return s
where
invalidChar :: String -> Bool
invalidChar str = not . null $ intersect "\\'\"\n" str
allColumns :: [String]
allColumns = (map fst $ s ^. replicates) ++ (concatMap snd $ s ^. replicates)
++ maybeToList (s ^. ec_col)
++ maybeToList (s ^. link_col)
++ s ^. info_cols
++ s ^. init_select
user_settings_cols :: [(UserSettings -> JSObject JSValue -> Result UserSettings
,UserSettings -> JSObject JSValue -> JSObject JSValue)]
user_settings_cols = [simple "info_columns" info_cols
,(get_simple_f "ec_column" ec_col id, set_maybe "ec_column" ec_col)
,(get_simple_f "link_column" link_col id, set_maybe "link_column" link_col)
,(get_simple_f "link_url" link_url id, set_maybe "link_url" link_url)
,simple "replicates" replicates
,simple "csv_format" csv_format
,simple "skip" skip
,simple_with_def "init_select" init_select []
,simple_with_def "hide_columns" hide []
,simple_with_def "name" title ""
,simple_with_def "fdrThreshold" fdr_threshold "1"
,simple_with_def "fcThreshold" fc_threshold "0"
,(get_simple_f "min_counts" min_counts id, set_maybe "min_counts" min_counts)
,simple_with_def "fc_columns" fc_cols []
,simple_with_def "primary_name" primary ""
,simple_with_def "avg_column" avg_col ""
,simple_with_def "analyze_server_side" analyze_server_side True
,simple_with_def "fdr_column" fdr_col ""
]
where
simple :: JSON a => String -> (Lens' UserSettings a)
-> (UserSettings -> JSObject JSValue -> Result UserSettings
,UserSettings -> JSObject JSValue -> JSObject JSValue)
simple name lens = (get_simple name lens, set_simple name lens)
get_simple name lens u obj = valFromObj name obj >>= \v -> return $ set lens v u
set_simple name lens u obj = set_field obj name (showJSON $ u ^. lens)
simple_with_def :: JSON a => String -> (Lens' UserSettings a) -> a
-> (UserSettings -> JSObject JSValue -> Result UserSettings
,UserSettings -> JSObject JSValue -> JSObject JSValue)
simple_with_def name lens def = (get_simple_f name lens (fromMaybe def), set_simple name lens)
-- | get_simple_f is like get_simple, but allows the user to specify what to do with a missing key
get_simple_f name lens f u obj = Ok $ case valFromObj name obj of
(Ok v) -> set lens (f $ Just v) u
_ -> set lens (f $ Nothing) u
-- | set_maybe is like set_simple, but Nothing will delete the key
set_maybe name lens u obj = case u ^. lens of
Nothing -> del_field obj name
Just v -> set_field obj name (showJSON v)
-- | Delete a field from a JSObject. To complement get_field and set_field
del_field :: JSObject a -> String -> JSObject a
del_field obj name = toJSObject . filter ((/=name).fst) $ fromJSObject obj
-- | Smart constructor for 'Code' to ensure it is a safe FilePath
strToCode :: String -> Code
strToCode s | badChars || null s = error $ "Bad code :"++s
| otherwise = Code s
where
badChars = length (intersect "/." s) > 0
codeToFilePath :: Code -> FilePath
codeToFilePath (Code s) = user_dir </> s
settingsFile,countsFile,annotFile :: Code -> String
settingsFile code = codeToFilePath code ++ "-settings.js"
countsFile code = codeToFilePath code ++ "-counts.csv"
annotFile code = codeToFilePath code ++ "-annot.csv"
user_dir :: FilePath
user_dir = "user-files"
-- globalSettings :: MVar Settings
-- globalSettings = unsafePerformIO $ newEmptyMVar
readSettings :: Code -> IO Settings
readSettings code = do
str <- Prelude.readFile $ settingsFile code
let ss = decode str
return $ fromOk ss
writeUserSettings :: Settings -> UserSettings -> IO ()
writeUserSettings settings userSettings = do
writeSettings (code settings) $ settings { user_settings = userSettings}
writeSettings :: Code -> Settings -> IO ()
writeSettings code settings
| not valid = error "Invalid settings"
| otherwise = do
Prelude.writeFile tmpFile $ encode settings
renameFile tmpFile (settingsFile code)
where
valid = True
tmpFile = settingsFile code++".tmp"
createSettings :: BS.ByteString -> String -> UTCTime -> IO Code
createSettings dat remote_ip now = do
(file, _) <- newRandFile user_dir
let code = strToCode (takeFileName file)
BS.writeFile (countsFile code) dat
writeSettings code $ (initSettings code) {remote_addr=remote_ip, created=show now}
return code
----------------------------------------------------------------------
getCode :: Settings -> Code
getCode settings = code settings
fromOk :: Show t => Result t -> t
fromOk (Ok r) = r
fromOk x = error $ "json parse failure : "++show x
----------------------------------------------------------------------
initSettings :: Code -> Settings
initSettings code = Settings { code = code
, remote_addr = ""
, created = error "Must set created"
, user_settings = defUserSettings
, locked = False
}
get_ec_column :: Settings -> Maybe String
get_ec_column settings = user_settings settings ^. ec_col
get_info_columns :: Settings -> [String]
get_info_columns settings = user_settings settings ^. info_cols
get_replicates :: Settings -> [(String,[String])]
get_replicates settings = user_settings settings ^. replicates
is_locked :: Settings -> Bool
is_locked settings = locked settings
get_csv_format :: Settings -> String
get_csv_format settings = if user_settings settings ^. csv_format then "CSV" else "TAB"
get_counts_file :: Settings -> FilePath
get_counts_file s = countsFile $ getCode s
get_counts_skip :: Settings -> Int
get_counts_skip s = user_settings s ^. skip
get_min_counts :: Settings -> Int
get_min_counts s = fromMaybe 0 (user_settings s ^. min_counts)
get_user_settings :: Settings -> UserSettings
get_user_settings s = user_settings s
-- | Turn the user settings into JS. Mostly just 'encode' but adds the 'locked' field from
-- the outer object
get_js_user_settings :: Settings -> String
get_js_user_settings s = -- encode $ get_user_settings s
case showJSON $ get_user_settings s of
JSObject obj -> encode $ set_field obj "locked" (showJSON $ is_locked s)
_ -> error "Unable to read user settings"
|
Victorian-Bioinformatics-Consortium/degust
|
app/backend/Settings.hs
|
gpl-3.0
| 11,987 | 0 | 17 | 3,890 | 2,641 | 1,406 | 1,235 | 205 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Ship where
import Prelude hiding ((.), id)
import Control.Category
import Control.Concurrent
import Data.Aeson
import Data.Data
import Data.Function hiding ((.), id)
import Data.IxSet as IxSet
import Data.Lens
import Data.Lens.Template
import Data.Ord
import Data.Text (Text)
data ShipColor =
ShipColor
{ _colorR :: !Int
, _colorG :: !Int
, _colorB :: !Int
}
deriving (Data, Typeable)
instance ToJSON ShipColor where
toJSON (ShipColor r g b) =
object ["r" .= r, "g" .= g, "b" .= b]
data ShipPosition =
ShipPosition
{ _posX :: Double
, _posY :: Double
, _posHeading :: Double
}
deriving (Data, Typeable)
instance ToJSON ShipPosition where
toJSON (ShipPosition x y heading) =
object ["x" .= x, "y" .= y, "heading" .= heading]
data ShipStatus =
ShipStatus
{ _statusEnergy :: !Double
, _statusHealth :: !Double
}
deriving (Data, Typeable)
instance ToJSON ShipStatus where
toJSON (ShipStatus energy health) =
object ["energy" .= energy, "health" .= health]
data ShipState =
ShipState
{ _stateShields :: !Bool
, _stateBoost :: !Bool
}
deriving (Data, Typeable)
instance ToJSON ShipState where
toJSON (ShipState shields boost) =
object ["shields" .= shields, "boost" .= boost]
newtype ShipId =
ShipId
{ unShipId :: Integer
}
deriving (Eq, Ord, Num, Data, Typeable)
instance ToJSON ShipId where
toJSON = toJSON . unShipId
data Ship =
Ship
{ shipId :: !ShipId
, shipThreadId :: !ThreadId
, shipName :: !Text
, _shipColor :: !ShipColor
, _shipStatus :: !ShipStatus
, _shipPosition :: !ShipPosition
, _shipState :: !ShipState
}
deriving (Data, Typeable)
instance Eq Ship where
(==) = (==) `on` shipId
instance Ord Ship where
compare = comparing shipId
data Ships =
Ships
{ _ships :: IxSet Ship
, _shipsNextId :: ShipId
}
instance ToJSON Ship where
toJSON (Ship sid _ name color status position state) =
object
[ "id" .= sid
, "name" .= name
, "color" .= color
, "status" .= status
, "position" .= position
, "state" .= state
]
instance Indexable Ship where
empty =
ixSet
[ ixFun $ return . shipId
, ixFun $ return . shipName
]
makeLenses
[ ''ShipColor
, ''ShipPosition
, ''ShipStatus
, ''ShipState
, ''Ship
, ''Ships
]
shipR :: Lens Ship Int
shipR = colorR . shipColor
shipG :: Lens Ship Int
shipG = colorG . shipColor
shipB :: Lens Ship Int
shipB = colorB . shipColor
shipX :: Lens Ship Double
shipX = posX . shipPosition
shipY :: Lens Ship Double
shipY = posY . shipPosition
shipHeading :: Lens Ship Double
shipHeading = posHeading . shipPosition
shipEnergy :: Lens Ship Double
shipEnergy = statusEnergy . shipStatus
shipHealth :: Lens Ship Double
shipHealth = statusHealth . shipStatus
shipShields :: Lens Ship Bool
shipShields = stateShields . shipState
shipBoost :: Lens Ship Bool
shipBoost = stateBoost . shipState
|
dflemstr/ship
|
Ship.hs
|
gpl-3.0
| 3,079 | 0 | 9 | 673 | 948 | 527 | 421 | 143 | 1 |
module Event.Default where
import State
import Types
import Graphics.X11
import Graphics.X11.Xlib.Extras
type EventHandler = Event -> X11State ()
defaultHandler :: EventHandler
defaultHandler _ = return ()
|
ktvoelker/argon
|
src/Event/Default.hs
|
gpl-3.0
| 212 | 0 | 7 | 32 | 57 | 33 | 24 | 8 | 1 |
module Main where
import Monitoring.Shinken.Configuration
import Monitoring.Shinken.Parser
import Monitoring.Shinken.Print
import Data.Either
import Data.List hiding (find)
import System.Directory
import System.Environment
import System.FilePath.Find
import System.IO
import Text.Parsec
pattern = "*.cfg"
main = do
dir <- getCurrentDirectory
files <- search dir
content <- mapM readFile files
let normalisedContent = map normaliseComments content
parseResults = zipWith (\ x y -> (x, parseConfigFile x y)) files normalisedContent
errors = filter (\ (_,x) -> isLeft x) parseResults
objects = concat . rights . map snd $ parseResults
mapM_ printErrors errors
putStrLn $ printDotGraph objects
putStrLn "* Stats"
putStr " * Files found: "
print $ length files
putStr " * Objects found: "
print $ length objects
putStr " * Files with errors: "
print $ length errors
search = find always (fileName ~~? pattern
&&? fileName /~? "shinken.cfg"
&&? directory /~? "**resource.d")
normaliseComments :: String -> String
normaliseComments = map (\ x -> if x == ';' then '#' else x)
printErrors :: (FilePath, Either ParseError [Object]) -> IO ()
printErrors (filepath, object) = do
putStr "***** File: "
putStrLn filepath
print object
putStrLn ""
|
Taeradan/shinken-config-graph
|
src/Main.hs
|
gpl-3.0
| 1,565 | 0 | 14 | 513 | 408 | 205 | 203 | 40 | 2 |
module WebParsing.ArtSciParser
(parseArtSci, getDeptList, fasCalendarURL) where
import Data.Either (either)
import Data.List (elemIndex)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Text as T
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Text.Parsec (count, many, parse, (<|>))
import Text.Parsec.Text (Parser)
import qualified Text.Parsec.Char as P
import WebParsing.ParsecCombinators (text)
import Network.HTTP.Simple (parseRequest, getResponseBody, httpLBS)
import qualified Text.HTML.TagSoup as TS
import Text.HTML.TagSoup (Tag)
import Text.HTML.TagSoup.Match (tagOpenAttrLit, tagOpenAttrNameLit)
import Database.Persist.Sqlite (runSqlite, SqlPersistM)
import Database.Persist (insertUnique)
import Database.CourseInsertion (insertCourse)
import Database.Tables (Courses(..), Department(..))
import WebParsing.ReqParser (parseReqs)
import Config (databasePath)
import WebParsing.PostParser (addPostToDatabase)
-- | The URLs of the Faculty of Arts & Science calendar.
fasCalendarURL :: String
fasCalendarURL = "https://fas.calendar.utoronto.ca/"
programsURL :: String
programsURL = "https://fas.calendar.utoronto.ca/listing-program-subject-areas"
-- | Parses the entire Arts & Science Course Calendar and inserts courses
-- into the database.
parseArtSci :: IO ()
parseArtSci = do
bodyTags <- httpBodyTags programsURL
let deptInfo = getDeptList bodyTags
runSqlite databasePath $ do
liftIO $ putStrLn "Inserting departments"
insertDepts $ map snd deptInfo
mapM_ parseDepartment deptInfo
-- | Converts the processed main page and extracts a list of department html pages
-- and department names
getDeptList :: [Tag T.Text] -> [(T.Text, T.Text)]
getDeptList tags =
let tables = TS.partitions (TS.isTagOpenName "table") tags -- every partition is a table
tables' = map (takeWhile (not . TS.isTagCloseName "table")) tables
depts = concatMap extractDepartments tables'
in depts
where
extractDepartments :: [Tag T.Text] -> [(T.Text, T.Text)]
extractDepartments tableTags =
-- Each aTag consists of a start tag, text, and end tag
let aTags = TS.partitions (tagOpenAttrNameLit "a" "href" (const True)) tableTags
depts = map (\t -> (TS.fromAttrib "href" $ head t,
T.replace "\8203" " " $ T.replace "\160" " " $ T.strip $ TS.innerText t)) aTags
in
filter (\t -> (not . T.null $ fst t) && (not . T.null $ snd t)) depts
-- | Insert department names to database
insertDepts :: [T.Text] -> SqlPersistM ()
insertDepts = mapM_ (print >> (insertUnique . Department))
-- | Takes the URL and name of a department name for parsing.
parseDepartment :: (T.Text, T.Text) -> SqlPersistM ()
parseDepartment (relativeURL, _) = do
bodyTags <- liftIO $ httpBodyTags $ fasCalendarURL ++ T.unpack relativeURL
let contentTags = dropWhile (not . tagOpenAttrLit "div" ("id", "block-system-main")) bodyTags
contentTags' = takeWhile (not . tagOpenAttrLit "p" ("class", "rteright")) contentTags
programs = dropWhile (not . tagOpenAttrNameLit "div" "class" (T.isInfixOf "view-id-section")) contentTags'
programs' = takeWhile (not . tagOpenAttrNameLit "div" "class" (T.isInfixOf "view-id-course_group_view")) programs
courseTags = dropWhile (not . tagOpenAttrNameLit "div" "class" (T.isInfixOf "view-id-courses")) contentTags'
parsePrograms programs'
let courseList = parseCourses courseTags
mapM_ insertCourse courseList
-- | Parse the section of the course calendar listing the programs offered by a department.
parsePrograms :: [Tag T.Text] -> SqlPersistM ()
parsePrograms programs = do
let elems = TS.partitions isPost programs
mapM_ addPostToDatabase elems
where
isPost tag = tagOpenAttrNameLit "h3" "class" (T.isInfixOf "programs_view") tag
-- | Parse the section of the course calendar listing the courses offered by a department.
parseCourses :: [Tag T.Text] -> [(Courses, T.Text, T.Text)]
parseCourses tags =
let elems = drop 1 $ TS.partitions (TS.isTagOpenName "h3") tags -- Remove the first one, which is the header
courses = map parseCourse elems
in
courses
where
parseCourse :: [Tag T.Text] -> (Courses, T.Text, T.Text)
parseCourse courseTags =
let courseHeader = T.strip . TS.innerText $ takeWhile (not . TS.isTagCloseName "h3") courseTags
(code, title) = either (error . show) id $ parse parseCourseTitle "course title" courseHeader
spans = TS.partitions (TS.isTagOpenName "span") courseTags
courseContents = map (T.strip . T.replace "\160" " " . TS.innerText) spans
i1 = elemIndex "Hours:" courseContents
-- TODO: add the number of contact hours to the database
(_, description) = maybe ("", "") (\i -> either (error . show) id $ parse parseHours "course hours" $ courseContents !! (i+1)) i1
prereqString = fmap ((courseContents!!) . (+1)) $ elemIndex "Prerequisite:" courseContents
coreq = fmap ((courseContents!!) . (+1)) $ elemIndex "Corequisite:" courseContents
-- TODO: add a "recommended preparation" field to the database
-- prep = maybe "" ((courseContents!!) . (+1)) $ elemIndex "Recommended Preparation:" courseContents
exclusion = fmap ((courseContents!!) . (+1)) $ elemIndex "Exclusion:" courseContents
distribution = maybe "" ((courseContents!!) . (+1)) $ elemIndex "Distribution Requirements:" courseContents
breadth = maybe "" ((courseContents!!) . (+1)) $ elemIndex "Breadth Requirements:" courseContents
in
(Courses code
(Just title)
(Just description)
Nothing
Nothing
(fmap (T.pack . show . parseReqs . T.unpack) prereqString)
exclusion
Nothing
Nothing
prereqString
coreq
[],
breadth, distribution)
-- | Parse a course's code and title.
parseCourseTitle :: Parser (T.Text, T.Text)
parseCourseTitle = do
dept <- count 3 P.letter
num <- count 3 P.digit
session <- P.letter
campus <- P.digit
_ <- text " - "
title <- many P.anyChar
return (T.pack $ dept ++ num ++ [session, campus], T.pack title)
-- | Parse a course's number of contact hours and description.
parseHours :: Parser (T.Text, T.Text)
parseHours = do
hours <- many (P.alphaNum <|> P.char '/')
_ <- many P.space
description <- many P.anyChar
return (T.pack hours, T.pack description)
-- | Make an HTTP(S) request and convert the body into a list of Tags.
httpBodyTags :: String -> IO [Tag T.Text]
httpBodyTags url = do
req <- parseRequest url
response <- httpLBS req
return . TS.parseTags . toStrict . decodeUtf8 . getResponseBody $ response
|
hermish/courseography
|
app/WebParsing/ArtSciParser.hs
|
gpl-3.0
| 7,169 | 0 | 19 | 1,762 | 1,904 | 1,006 | 898 | 116 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DataFusion.Projects.Locations.Instances.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 a single Date Fusion instance.
--
-- /See:/ <https://cloud.google.com/data-fusion/docs Cloud Data Fusion API Reference> for @datafusion.projects.locations.instances.delete@.
module Network.Google.Resource.DataFusion.Projects.Locations.Instances.Delete
(
-- * REST Resource
ProjectsLocationsInstancesDeleteResource
-- * Creating a Request
, projectsLocationsInstancesDelete
, ProjectsLocationsInstancesDelete
-- * Request Lenses
, plidXgafv
, plidUploadProtocol
, plidAccessToken
, plidUploadType
, plidName
, plidCallback
) where
import Network.Google.DataFusion.Types
import Network.Google.Prelude
-- | A resource alias for @datafusion.projects.locations.instances.delete@ method which the
-- 'ProjectsLocationsInstancesDelete' request conforms to.
type ProjectsLocationsInstancesDeleteResource =
"v1" :>
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] Operation
-- | Deletes a single Date Fusion instance.
--
-- /See:/ 'projectsLocationsInstancesDelete' smart constructor.
data ProjectsLocationsInstancesDelete =
ProjectsLocationsInstancesDelete'
{ _plidXgafv :: !(Maybe Xgafv)
, _plidUploadProtocol :: !(Maybe Text)
, _plidAccessToken :: !(Maybe Text)
, _plidUploadType :: !(Maybe Text)
, _plidName :: !Text
, _plidCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsInstancesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plidXgafv'
--
-- * 'plidUploadProtocol'
--
-- * 'plidAccessToken'
--
-- * 'plidUploadType'
--
-- * 'plidName'
--
-- * 'plidCallback'
projectsLocationsInstancesDelete
:: Text -- ^ 'plidName'
-> ProjectsLocationsInstancesDelete
projectsLocationsInstancesDelete pPlidName_ =
ProjectsLocationsInstancesDelete'
{ _plidXgafv = Nothing
, _plidUploadProtocol = Nothing
, _plidAccessToken = Nothing
, _plidUploadType = Nothing
, _plidName = pPlidName_
, _plidCallback = Nothing
}
-- | V1 error format.
plidXgafv :: Lens' ProjectsLocationsInstancesDelete (Maybe Xgafv)
plidXgafv
= lens _plidXgafv (\ s a -> s{_plidXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plidUploadProtocol :: Lens' ProjectsLocationsInstancesDelete (Maybe Text)
plidUploadProtocol
= lens _plidUploadProtocol
(\ s a -> s{_plidUploadProtocol = a})
-- | OAuth access token.
plidAccessToken :: Lens' ProjectsLocationsInstancesDelete (Maybe Text)
plidAccessToken
= lens _plidAccessToken
(\ s a -> s{_plidAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plidUploadType :: Lens' ProjectsLocationsInstancesDelete (Maybe Text)
plidUploadType
= lens _plidUploadType
(\ s a -> s{_plidUploadType = a})
-- | The instance resource name in the format
-- projects\/{project}\/locations\/{location}\/instances\/{instance}
plidName :: Lens' ProjectsLocationsInstancesDelete Text
plidName = lens _plidName (\ s a -> s{_plidName = a})
-- | JSONP
plidCallback :: Lens' ProjectsLocationsInstancesDelete (Maybe Text)
plidCallback
= lens _plidCallback (\ s a -> s{_plidCallback = a})
instance GoogleRequest
ProjectsLocationsInstancesDelete
where
type Rs ProjectsLocationsInstancesDelete = Operation
type Scopes ProjectsLocationsInstancesDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsInstancesDelete'{..}
= go _plidName _plidXgafv _plidUploadProtocol
_plidAccessToken
_plidUploadType
_plidCallback
(Just AltJSON)
dataFusionService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsInstancesDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-datafusion/gen/Network/Google/Resource/DataFusion/Projects/Locations/Instances/Delete.hs
|
mpl-2.0
| 5,039 | 0 | 15 | 1,075 | 697 | 408 | 289 | 103 | 1 |
-- This file is part of purebred
-- Copyright (C) 2017-2020 Fraser Tweedale and Róman Joost
--
-- purebred is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero 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 Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE OverloadedStrings #-}
-- | Utility functions for UI
module Purebred.UI.Utils
( titleize
, Titleize
) where
import Data.Text (Text, pack)
import Purebred.Types
-- | Show a descriptive name
--
class Titleize a where
titleize :: a -> Text
instance Titleize Name where
titleize ListOfMails = "List of Mails"
titleize ListOfThreads = "List of Threads"
titleize ManageThreadTagsEditor = "Edit Labels of Threads"
titleize ManageMailTagsEditor = "Edit Labels of Mails"
titleize SearchThreadsEditor = "Search Editor"
titleize ScrollingMailView = "Mail Viewer"
titleize ComposeTo = "Editor to Compose a new Mail"
titleize ComposeFrom = "Editor to Compose a new Mail"
titleize ComposeSubject = "Editor to Compose a new Mail"
titleize ListOfFiles = "Directory Listing"
titleize ComposeListOfAttachments = "Attachments"
titleize ManageFileBrowserSearchPath = "Filepath for Directory Listing"
titleize MailAttachmentOpenWithEditor = "Open With Editor"
titleize MailAttachmentPipeToEditor = "Pipe to Editor"
titleize m = pack $ show m
instance Titleize ViewName where
titleize a = pack $ show a
|
purebred-mua/purebred
|
src/Purebred/UI/Utils.hs
|
agpl-3.0
| 1,900 | 0 | 7 | 333 | 228 | 127 | 101 | 26 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
, makeLogWare
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr,
pgPoolSize, runSqlPool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai (Middleware)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.Profile
import Handler.User
import Handler.GuestForm
import Handler.HostForm
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and returns a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
-- The App {..} syntax is an example of record wild cards. For more
-- information, see:
-- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applying some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- makeLogWare foundation
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
makeLogWare :: App -> IO Middleware
makeLogWare foundation =
mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadYamlSettings ["config/secret.yml", configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadYamlSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
|
Lasokki/omanet
|
Application.hs
|
agpl-3.0
| 7,053 | 0 | 13 | 1,792 | 1,071 | 575 | 496 | -1 | -1 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func :: ((a))
|
lspitzner/brittany
|
data/Test361.hs
|
agpl-3.0
| 128 | 0 | 6 | 14 | 13 | 8 | 5 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
module Main where
import Control.Concurrent (threadDelay)
import Control.Monad.Random ()
import Control.Monad.Trans.Maybe
import Data.BotConfig
import Data.ByteString.Char8 (ByteString)
import Data.Maybe
import Data.Monoid
import Data.Response
import Network.IRC
import Pipes
import Pipes.Network
import qualified Pipes.Prelude as P
import qualified Data.ByteString.Char8 as B
import Network.HTTP.Client (newManager)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Commands.Admin
import Commands.Quote
import Commands.Interject
import Commands.Wolfram
import Commands.Github
import Commands.Reddit
import Commands.Crypto
import Commands.RotCipher
import Commands.Markov
import Commands.CIA
import Commands.Distrowatch
import Commands.Autokick
import Options.Applicative
data Options = Options
{ configPath :: Maybe FilePath
}
optParser :: Parser Options
optParser = Options
<$> optional
(strOption ( long "config"
<> metavar "FILE"
<> help "Config File Location" ))
optInfo :: ParserInfo Options
optInfo = info (helper <*> optParser)
( fullDesc
<> progDesc "An IRC Bot"
<> header "lmrbot - A spambot" )
response :: Monad m => Response m -> Pipe Message ByteString m ()
response rsp =
P.mapM (respond rsp) >-> filterJust >-> P.map (encode . filterLong)
where
filterLong t
| [c, m] <- msg_params t
, B.length m >= 448 = t {msg_params = [c, longMsg]}
| otherwise = t
longMsg = "Nah, too much work. You're on your own"
bootstrap :: MonadIO m
=> BotConfig
-> Producer ByteString m ()
-> Consumer ByteString m ()
-> Effect m ()
bootstrap conf up down = do
let encSend = P.map encode >-> P.tee (outbound conf) >-> down
up >-> P.take 2 >-> inbound conf
register conf >-> encSend
-- wait for and respond to initial ping
up >-> P.tee (inbound conf) >-> parseIRC >-> P.dropWhile (not . isPing)
>-> P.take 1 >-> response pingR >-> P.tee (outbound conf) >-> down
-- drain until nickserv notice
up >-> P.tee (inbound conf) >-> parseIRC >-> P.dropWhile (not . isNSNotice)
>-> P.take 1 >-> P.drain
-- do nickserv auth and modes, then wait 1s before joining
auth conf >-> encSend
modes conf >-> encSend
liftIO (threadDelay 1000000)
joins conf >-> encSend
main :: IO ()
main = do
opts <- execParser optInfo
conf <-
fmap (fromMaybe defaultConfig) . runMaybeT $ do
p <- MaybeT . return $ configPath opts
MaybeT $ readConfig p
h <- network conf
man <- newManager tlsManagerSettings
let up = fromHandleLine h
down = toHandleLine h
runEffect $ bootstrap conf up down
cooldown <- emptyCooldown
comms' <-
mappend (akicks conf) . mconcat <$> sequence (comms conf cooldown man)
-- bot loop
runEffect $
up >-> P.tee (inbound conf) >-> parseIRC >->
response (userIgnore conf comms') >->
P.tee (outbound conf) >->
down
where
akicks opts = mconcat $ map (\(u,t) -> autokick t u) (autokicks opts)
comms c ulim man =
[ return pingR
, return $ inviteR c
, return ctcpVersion
, return $ joinCmd c
, return $ leaveCmd c
, return $ nickCmd c
, return $ modeCmd c
, return $ say c
, return source
, userLimit' c ulim rotCmd
, userLimit' c ulim rmsfact
, userLimit' c ulim rms
, userLimit' c ulim linus
, userLimit' c ulim theo
, userLimit' c ulim catv
, userLimit' c ulim arch
, userLimit' c ulim =<< startrek man
, userLimit' c ulim =<< wcgw man
, userLimit' c ulim =<< meme man
, userLimit' c ulim =<< wallpaper man
, userLimit' c ulim nlab
, userLimit' c ulim trump
, userLimit' c ulim marxov
, userLimit' c ulim stirner
, userLimit' c ulim trek
, userLimit' c ulim interject
, userLimit' c ulim cia
, userLimit' c ulim fbi
, userLimit' c ulim fiveeyes
, userLimit' c ulim (distrowatch man)
, return $ wolfram man (wolframAPI c)
, return $ github man
, return $ crypto man
]
|
tsahyt/lmrbot
|
src/Main.hs
|
agpl-3.0
| 4,349 | 0 | 16 | 1,238 | 1,364 | 683 | 681 | 124 | 1 |
module Data.Geo.OSM.Xapi.Lens.NoteL where
import Data.Lens.Common
import Data.Geo.OSM.Xapi.Note
class NoteL a where
noteL :: Lens a Note
|
liesen/osm-xapi
|
src/Data/Geo/OSM/Xapi/Lens/NoteL.hs
|
lgpl-3.0
| 141 | 0 | 7 | 20 | 43 | 27 | 16 | 5 | 0 |
{-# LANGUAGE ExistentialQuantification,
TypeFamilies,
GADTs,
RankNTypes,
ScopedTypeVariables,
DeriveDataTypeable,
StandaloneDeriving,
MultiParamTypeClasses,
FlexibleInstances #-}
{-# LANGUAGE DeriveFunctor #-}
-- Based on "The Haxl Project at Facebook (slides from my talk at ZuriHac)"
-- https://github.com/meiersi/HaskellerZ/blob/master/meetups/20130829-FPAfternoon_The_Haxl_Project_at_Facebook/The%20Haxl%20Project%20at%20Facebook.pdf?raw=true
-- http://www.reddit.com/r/haskell/comments/1le4y5/the_haxl_project_at_facebook_slides_from_my_talk/
----------------------------------------------------------
import Control.Applicative
import Control.Concurrent.MVar
import Control.Monad hiding (mapM, filterM)
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Free -- from the `free` package
import Data.Hashable
import Data.Hashable.Extras
import Data.Maybe
import Data.Monoid (Monoid(..))
import qualified Data.Sequence as S -- Queue with O(1) head and tail operations
import Data.Text (Text)
import Data.Traversable hiding (mapM)
import Data.Typeable
import Prelude hiding (mapM)
main = putStrLn "hello"
newtype Haxl a = Haxl { unHaxl :: IO (Result a) }
deriving (Functor)
data Result a = Done a
| Blocked (Haxl a)
deriving (Functor)
instance Monad Haxl where
return a = Haxl (return (Done a))
m >>= k = Haxl $ do
a <- unHaxl m
case a of
Done a' -> unHaxl (k a')
Blocked r -> return (Blocked (r >>= k))
{-
-- ++AZ++ initial simple version, generalised to a DataSource req
-- later
-- The only side effects happen here
dataFetch :: Request a -> Haxl a
dataFetch r = do
addRequest r
Haxl (return (Blocked (Haxl (getResult r))))
-}
instance Applicative Haxl where
pure = return
Haxl f <*> Haxl a = Haxl $ do
r <- f
case r of
Done f' -> do
ra <- a
case ra of
Done a' -> return (Done (f' a'))
Blocked a' -> return (Blocked (f' <$> a'))
Blocked f' -> do
ra <- a
case ra of
Done a' -> return (Blocked (f' <*> return a'))
Blocked a' -> return (Blocked (f' <*> a'))
-- mapM :: Monad m => (a -> m b) -> [a] -> m [b]
-- class (Functor t, Data.Foldable.Foldable t) => Traversable t where
-- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
-- mapM :: (a -> Haxl b) -> [a] -> Haxl [b]
-- mapM :: (a -> Haxl b) -> [a] -> Haxl [b]
mapM = traverse
-- Prelude.sequence :: Monad m => [m a] -> m [a]
-- Data.Traversable.sequence :: (Monad m, Traversable t) => t (m a) -> m (t a)
-- class (Functor t, Data.Foldable.Foldable t) => Traversable t where
-- Data.Traversable.sequence :: Monad m => t (m a) -> m (t a)
-- class (Functor t, Data.Foldable.Foldable t) => Traversable t where
-- sequenceA :: Applicative f => t (f a) -> f (t a)
-- sequence = sequenceA
-- ---------------------------------------------------------------------
-- filterM that batches the data fetches correctly
-- filterM :: (Applicative f, Monad f) => (a -> f Bool) -> [a] -> f [a]
filterM :: (a -> Haxl Bool) -> [a] -> Haxl [a]
filterM pred xs = do
bools <- mapM pred xs
return [ x | (x,True) <- zip xs bools ]
-- ---------------------------------------------------------------------
-- Examples in use
--
-- Return the names of all the friends of the user that are
-- members of the Functional Programming group.
--
fpFriends :: Id -> Haxl [Text]
fpFriends id = do
fs <- friendsOf id
fp <- filterM (memberOfGroup functionalProgramming) fs
mapM getName fp
-- ---------------------------------------------------------------------
-- Written another way
nameOfFPFriend :: Id -> Haxl (Maybe Text)
nameOfFPFriend id = do
b <- memberOfGroup functionalProgramming id
if b then Just <$> getName id
else return Nothing
fpFriends2 :: Id -> Haxl [Text]
fpFriends2 id = do
fs <- friendsOf id
name_maybes <- mapM nameOfFPFriend fs
return (catMaybes name_maybes)
------------------------------------------------------------------------
newtype HaxlQuery a = HaxlQuery { query :: Haxl [a] }
-- basically ListT Haxl, but ListT doesn’t work!
-- instances of Monad, MonadPlus
selectFrom :: Haxl [a] -> HaxlQuery a
selectFrom = HaxlQuery
liftH :: Haxl a -> HaxlQuery a
liftH m = HaxlQuery (return <$> m)
suchThat :: Haxl Bool -> HaxlQuery ()
suchThat m = liftH m >>= guard
-- ---------------------------------------------------------------------
fpFriends3 :: Id -> Haxl [Text]
fpFriends3 id =
query $ head [ name | f <- [selectFrom (friendsOf id)],
_ <- [suchThat (memberOfFPGroup f)],
name <- [liftH (getName id)] ]
-- ---------------------------------------------------------------------
-- DSL tricks
instance Num a => Num (Haxl a) where
(+) = liftA2 (+)
(-) = liftA2 (-)
(*) = liftA2 (*)
abs = liftA abs
signum = liftA signum
fromInteger = fromInteger
-- ---------------------------------------------------------------------
simonFriends :: Id -> Haxl [Id]
simonFriends id =
filterM (isCalled "Simon") =<< friendsOf id
numCoolFriends :: Id -> Haxl Int
numCoolFriends id =
(length <$> fpFriends id) + (length <$> simonFriends id)
-- NOTE: each side of the '+' above does duplicate data fetching
-- =====================================================================
-- Implementation
-- An example GADT
data ExampleReq a where
CountAardvarks :: String -> ExampleReq Int
ListWombats :: Id -> ExampleReq [Id]
deriving Typeable
------------------------------------------------------------------------
-- Data Source / core
class (Typeable1 req, Hashable1 req, Eq1 req) => DataSource req where
data DataState req -- ^ Internal state, stored by core on behalf of
-- the DataSource
fetch :: DataState req -> [BlockedFetch req] -> IO ()
-- AZ: I think this stores the original request (hence Eq1) and the
-- MVar the result will eventually be written to when the IO
-- completes.
data BlockedFetch req = forall a . BlockedFetch (req a) (MVar a)
-- Question: how does a BlockedFetch come into existence? Can only be
-- through the dataFetch call interacting with the core.
-- It is Core’s job to keep track of requests submitted via dataFetch
-- When the computation is blocked, we have to fetch the batch of
-- requests from the data source
-- Core has a single way to issue a request
-- The only side effects happen here
-- Note: I think this should be putting stuff in the scheduler
dataFetch :: DataSource req => req a -> Haxl a
dataFetch r = do
addRequest r
Haxl (return (Blocked (Haxl (getResult r))))
-- Three ways that a data source interacts with core:
-- * issuing a data fetch request [addRequest?]
-- * persistent state [via DataState req]
-- * fetching the data [via fetch...getResult]
-- AZ new guess: addRequest/getResult belong in roundRobin, to manage
-- the state properly.
-- AZ Guess: Pass the request to the data source, store the state that
-- changes pertaining to the data source, as well as keep track of the
-- fact of the request in a BlockedFetch item.
addRequest :: DataSource req => req a -> Haxl a
addRequest = undefined
-- AZ guess: should end up calling fetch on the given datasource.
getResult :: DataSource req => req a -> IO (Result a)
getResult = undefined
-- fetch s []
-- ---------------------------------------------------------------------
-- Friends data source -------------------------------------
-- First define FriendsReq
data FriendsReq a where
FriendsOf :: Id -> FriendsReq [Id]
-- Then define a Friends DataSource
instance DataSource FriendsReq where
data DataState FriendsReq = Ss
-- fetch :: DataState req -> [BlockedFetch req] -> IO ()
fetch = fetchFriendsDs
fetchFriendsDs :: DataState FriendsReq -> [BlockedFetch FriendsReq] -> IO ()
fetchFriendsDs s bfs = do
mapM_ fetchOne bfs
return ()
-- AZ: this only makes sense if we write to the MVar here. Else no
-- other return path
fetchOne :: BlockedFetch FriendsReq -> IO ()
fetchOne (BlockedFetch (FriendsOf id) mvar) = do
-- NOTE: calculating v could make use of external IO, and could be
-- blocked in which case the put to the MVar would not occur
let v = [id,Id "foo"] -- Friends with self :)
putMVar mvar v
return ()
-- ---------------------------------------------------------------------
-- Admin stuff
class Eq1 req where
eq1 :: req a -> req a -> Bool
instance Eq1 FriendsReq where
eq1 (FriendsOf x) (FriendsOf y) = x == y
instance Hashable1 FriendsReq where
hashWithSalt1 m (FriendsOf x) = hashWithSalt m x
-- instance Typeable1 FriendsReq where
-- typeOf1 (FriendsOf x) =
deriving instance Typeable1 FriendsReq
------------------------------------------------------------------------
-- Simplistic core by AZ
-- testCore :: IO ()
testCore = do
runCore $ friendsOf (Id "Alan")
return ()
runCore :: Haxl a -> Haxl ()
runCore q = roundRobin (core q)
core :: Haxl a -> Thread Haxl a
core q = do
lift q
-- --------------------------------------------------------------------
friendsOf :: Id -> Haxl [Id]
friendsOf id = do
let req = FriendsOf id
dataFetch req
-- ---------------------------------------------------------------------
thread1 :: Thread Haxl [Id]
thread1 = do
r <- lift $ friendsOf (Id "Simon")
return r
------------------------------------------------------------------------
-- ++AZ++ missing definitions ---------------------------
-- newtype HaxlQuery a = HaxlQuery { query :: Haxl [a] }
instance Monoid (HaxlQuery a) where
mempty = HaxlQuery $ return []
(HaxlQuery x) `mappend` (HaxlQuery y) = HaxlQuery ((++) <$> x <*> y)
instance MonadPlus HaxlQuery where
mzero = mempty
mplus = mappend
instance Monad HaxlQuery where
return a = HaxlQuery $ return [a]
-- (>>=) :: Monad m => m a -> (a -> m b) -> m b
-- (>>=) :: HaxlQuery a -> (a -> HaxlQuery b) -> HaxlQuery b
-- so a :: Haxl [t]
-- b :: Haxl [u]
m >>= k = do
a <- m
(k a)
-- ---------------------------------------------------------------------
memberOfGroup = undefined
functionalProgramming = undefined
memberOfFPGroup = undefined
getName :: Id -> Haxl Text
getName = undefined
isCalled = undefined
data Id = Id String
deriving (Eq,Show,Ord)
instance Hashable Id where
hashWithSalt m (Id a) = hashWithSalt m a
{-
Need
fmap :: (a -> b) -> f a -> f b
fmap id = id
fmap (p . q) = (fmap p) . (fmap q)
-}
-- ------------------------------------------------------------------------
transpose :: [[a]] -> [[a]]
transpose [] = repeat []
transpose (xs:xss) = zipWith (:) xs (transpose xss)
t = transpose [[1,2,3],[4,5,6]]
-- -----------------------------------------------------------------------
-- understanding the class definition for DataSource
class Foo a where
data FooState a
fooOp :: a -> Int
instance Foo String where
data FooState String = Baz String | Buz | Biz
fooOp str = length str
blorp:: FooState String -> Int
blorp Buz = 0
blorp Biz = 0
blorp (Baz str) = fooOp str
-- ---------------------------------------------------------------------
-- Threading model, based on
-- http://www.haskellforall.com/2013/06/from-zero-to-cooperative-threads-in-33.html
data ThreadF next = Fork next next
| Yield next
| ThreadDone
deriving (Functor)
type Thread = FreeT ThreadF
yield :: (Monad m) => Thread m ()
yield = liftF (Yield ())
done :: (Monad m) => Thread m r
done = liftF ThreadDone
cFork :: (Monad m) => Thread m Bool
cFork = liftF (Fork False True)
fork :: (Monad m) => Thread m a -> Thread m ()
fork thread = do
child <- cFork
when child $ do
thread
done
roundRobin :: (Monad m) => Thread m a -> m ()
roundRobin t = go (S.singleton t) -- Begin with a single thread
where
go ts = case (S.viewl ts) of
-- The queue is empty: we're done!
S.EmptyL -> return ()
-- The queue is non-empty: Process the first thread
t S.:< ts' -> do
x <- runFreeT t -- Run this thread's effects
case x of
-- New threads go to the back of the queue
Free (Fork t1 t2) -> go (t1 S.<| (ts' S.|> t2))
-- Yielding threads go to the back of the queue
Free (Yield t') -> go (ts' S.|> t')
-- Thread done: Remove the thread from the queue
Free ThreadDone -> go ts'
Pure _ -> go ts'
-- ---------------------------------------------------------------------
-- EOF
|
alanz/haxl-play
|
src/main.hs
|
unlicense
| 12,779 | 11 | 21 | 2,849 | 2,765 | 1,443 | 1,322 | 214 | 5 |
{-
- Module to parse Lisp
-
-
- Copyright 2013 -- name removed for blind review, all rights reserved! Please push a git request to receive author's name! --
- 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.
-}
{-# OPTIONS_GHC -Wall #-}
module LispParser (pGetLisp,parse,LispTree(..),LispPrimitive(..),SourcePos) where
import Text.ParserCombinators.Parsec (getPosition,SourcePos,parse,space,spaces,many,string,(<|>),Parser,noneOf,anyChar,unexpected,oneOf,digit,(<?>),eof)
import Data.Char (toUpper)
data LispTree = LispCons SourcePos LispTree LispTree | LispTreePrimitive SourcePos LispPrimitive deriving (Show)
data LispPrimitive = LispInt Int | LispString String | LispSymbol String deriving (Eq,Show)
pGetLisp :: Parser [LispTree]
pGetLisp
= do spaces
e<-many lispTree
_<-eof
return (e)
where
lispTree :: Parser LispTree
lispTree
= do { pos<-getPosition ;
do{_<-string "(";spaces;lts<-innerLispTree pos;_<-string ")";spaces;return lts} <|>
do{_<-string "'";spaces;lt<-lispTree;spaces;return$ LispCons pos (LispTreePrimitive pos$ LispSymbol "QUOTE") (LispCons pos lt $ LispTreePrimitive pos $ LispSymbol "NIL")} <|>
do{p<-lispPrimitive;spaces;return$ LispTreePrimitive pos p} <?> "LISP expression"
}
innerLispTree pos = do{_<-string ".";_<-space <?> "space. Symbols starting with . should be enclosed in ||'s";spaces;lt<-lispTree;spaces;return lt}
<|> do{lt <- lispTree;spaces;rt<-innerLispTree pos;spaces;return$ LispCons pos lt rt} <|> (return$ LispTreePrimitive pos$LispSymbol "NIL")
lispPrimitive :: Parser LispPrimitive
lispPrimitive
= do{_<-string "\""; str<-lp "\""; return$ LispString str} <|>
-- note: we are a bit stricter on digits: any symbol starting with a digit, should be an integer
do{d<-digit; s<-many digit; return (LispInt (read$ d:s))} <|>
-- we also fail on any of these:
do{_<-oneOf "-;#\\.`"; unexpected "character. Symbols starting with . - ; \\ ` or # should be enclosed in ||'s"} <|>
do{s<-symb; return$LispSymbol s}
where lp s = do{_<-string s; return ""} <|> do{_<-string "\\"; c<-anyChar; r<-lp s; return (c:r)} <|> do{c<-anyChar; r<-lp s; return (c:r)} <?> "end of "++s++"-delimited string"
symb :: Parser String
symb = do{_<-string "|"; p<-lp "|"; r<-symb <|> (return ""); return$ p++r} <|>
do{c<-noneOf " \t\r\n()|;#"; r<-symb <|> (return ""); return$ (toUpper c):r}
|
DatePaper616/code
|
lispParser.hs
|
apache-2.0
| 3,029 | 0 | 19 | 611 | 909 | 470 | 439 | 30 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module Lycopene.Web.Api where
import Servant
import Lycopene.Application (AppEngine)
import Lycopene.Web.Trans (lyco)
import Lycopene.Web.Request
import qualified Lycopene.Core as Core
type LycopeneApi
= "ping" :> Get '[JSON] String
:<|> "projects" :> ProjectApi
:<|> Raw
type ProjectApi
= Get '[JSON] [Core.Project]
:<|> Capture "name" Core.Name :> Get '[JSON] Core.Project
:<|> ReqBody '[JSON] String :> Post '[JSON] Core.Project
:<|> Capture "name" Core.Name :> DeleteNoContent '[JSON] NoContent
:<|> Capture "name" Core.Name :> "sprints" :> SprintApi
type SprintApi
= Get '[JSON] [Core.Sprint]
:<|> Capture "name" Core.Name :> Get '[JSON] Core.Sprint
:<|> Capture "name" Core.Name :> "issues" :> IssueApi
type IssueApi
= QueryParam "status" Core.IssueStatus :> Get '[JSON] [Core.Issue]
:<|> Capture "id" Core.IssueId :> Get '[JSON] Core.Issue
:<|> ReqBody '[JSON] String :> Post '[JSON] Core.Issue
:<|> Capture "id" Core.IssueId :> DeleteNoContent '[JSON] NoContent
api :: Proxy LycopeneApi
api = Proxy
server :: FilePath -> AppEngine -> Server LycopeneApi
server dir engine
= ping
:<|> projectServer engine
:<|> serveDirectory dir
where
ping = return "pong"
projectServer :: AppEngine -> Server ProjectApi
projectServer engine
= allProjects
:<|> fetchByName
:<|> newProject
:<|> removeProject
:<|> sprintHandler
where
allProjects = lyco engine $ Core.AllProject
fetchByName n = lyco engine $ (Core.FetchProject n)
newProject n = lyco engine $ Core.NewProject n Nothing
removeProject n = NoContent <$ (lyco engine $ Core.RemoveProject n)
sprintHandler pj = sprintServer pj engine
sprintServer :: Core.Name -> AppEngine -> Server SprintApi
sprintServer pj engine
= fetchSprints
:<|> fetchSprint
:<|> issueHandler
where
fetchSprints = lyco engine $ (Core.FetchProjectSprint pj)
fetchSprint sp = lyco engine $ (Core.FetchSprint pj sp)
issueHandler sp = issueServer pj sp engine
issueServer :: Core.Name -> Core.Name -> AppEngine -> Server IssueApi
issueServer pj sp engine
= fetchIssues
:<|> fetchIssue
:<|> newIssue
:<|> removeIssue
where
fetchIssues (Just st) = lyco engine $ (Core.FetchIssues pj sp st)
fetchIssues Nothing = lyco engine $ (Core.FetchIssues pj sp Core.IssueOpen)
newIssue t = lyco engine $ Core.NewIssue pj sp t
fetchIssue issueId = lyco engine $ Core.FetchIssue issueId
removeIssue issueId = NoContent <$ (lyco engine $ Core.RemoveIssue issueId)
|
utky/lycopene
|
src/Lycopene/Web/Api.hs
|
apache-2.0
| 2,660 | 0 | 14 | 540 | 864 | 435 | 429 | 67 | 2 |
-- |
-- Common Data Types
--
-- <https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf saml-core-2.0-os> §1.3
module SAML2.Core.Datatypes where
import Prelude hiding (String)
import qualified SAML2.XML.Schema.Datatypes as XS
-- |§1.3.1
type XString = XS.String
-- |§1.3.2
type AnyURI = XS.AnyURI
-- |§1.3.3
type DateTime = XS.DateTime
-- |§1.3.4
type ID = XS.ID
-- |§1.3.4
type NCName = XS.NCName
|
dylex/hsaml2
|
SAML2/Core/Datatypes.hs
|
apache-2.0
| 420 | 0 | 5 | 56 | 75 | 53 | 22 | 8 | 0 |
{-# LANGUAGE TemplateHaskell, DeriveFunctor #-}
{-| Some common Ganeti types.
This holds types common to both core work, and to htools. Types that
are very core specific (e.g. configuration objects) should go in
'Ganeti.Objects', while types that are specific to htools in-memory
representation should go into 'Ganeti.HTools.Types'.
-}
{-
Copyright (C) 2012, 2013, 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Types
( AllocPolicy(..)
, allocPolicyFromRaw
, allocPolicyToRaw
, InstanceStatus(..)
, instanceStatusFromRaw
, instanceStatusToRaw
, DiskTemplate(..)
, diskTemplateToRaw
, diskTemplateFromRaw
, TagKind(..)
, tagKindToRaw
, tagKindFromRaw
, NonNegative
, fromNonNegative
, mkNonNegative
, Positive
, fromPositive
, mkPositive
, Negative
, fromNegative
, mkNegative
, NonEmpty
, fromNonEmpty
, mkNonEmpty
, NonEmptyString
, QueryResultCode
, IPv4Address
, mkIPv4Address
, IPv4Network
, mkIPv4Network
, IPv6Address
, mkIPv6Address
, IPv6Network
, mkIPv6Network
, MigrationMode(..)
, migrationModeToRaw
, VerifyOptionalChecks(..)
, verifyOptionalChecksToRaw
, DdmSimple(..)
, DdmFull(..)
, ddmFullToRaw
, CVErrorCode(..)
, cVErrorCodeToRaw
, Hypervisor(..)
, hypervisorFromRaw
, hypervisorToRaw
, OobCommand(..)
, oobCommandToRaw
, OobStatus(..)
, oobStatusToRaw
, StorageType(..)
, storageTypeToRaw
, EvacMode(..)
, evacModeToRaw
, FileDriver(..)
, fileDriverToRaw
, InstCreateMode(..)
, instCreateModeToRaw
, RebootType(..)
, rebootTypeToRaw
, ExportMode(..)
, exportModeToRaw
, IAllocatorTestDir(..)
, iAllocatorTestDirToRaw
, IAllocatorMode(..)
, iAllocatorModeToRaw
, NICMode(..)
, nICModeToRaw
, JobStatus(..)
, jobStatusToRaw
, jobStatusFromRaw
, FinalizedJobStatus(..)
, finalizedJobStatusToRaw
, JobId
, fromJobId
, makeJobId
, makeJobIdS
, RelativeJobId
, JobIdDep(..)
, JobDependency(..)
, absoluteJobDependency
, getJobIdFromDependency
, OpSubmitPriority(..)
, opSubmitPriorityToRaw
, parseSubmitPriority
, fmtSubmitPriority
, OpStatus(..)
, opStatusToRaw
, opStatusFromRaw
, ELogType(..)
, eLogTypeToRaw
, ReasonElem
, ReasonTrail
, StorageUnit(..)
, StorageUnitRaw(..)
, StorageKey
, addParamsToStorageUnit
, diskTemplateToStorageType
, VType(..)
, vTypeFromRaw
, vTypeToRaw
, NodeRole(..)
, nodeRoleToRaw
, roleDescription
, DiskMode(..)
, diskModeToRaw
, BlockDriver(..)
, blockDriverToRaw
, AdminState(..)
, adminStateFromRaw
, adminStateToRaw
, AdminStateSource(..)
, adminStateSourceFromRaw
, adminStateSourceToRaw
, StorageField(..)
, storageFieldToRaw
, DiskAccessMode(..)
, diskAccessModeToRaw
, LocalDiskStatus(..)
, localDiskStatusFromRaw
, localDiskStatusToRaw
, localDiskStatusName
, ReplaceDisksMode(..)
, replaceDisksModeToRaw
, RpcTimeout(..)
, rpcTimeoutFromRaw -- FIXME: no used anywhere
, rpcTimeoutToRaw
, HotplugTarget(..)
, hotplugTargetToRaw
, HotplugAction(..)
, hotplugActionToRaw
, Private(..)
, showPrivateJSObject
, HvParams
, OsParams
, OsParamsPrivate
, TimeStampObject(..)
, UuidObject(..)
, SerialNoObject(..)
, TagsObject(..)
) where
import Control.Applicative
import Control.Monad (liftM)
import qualified Text.JSON as JSON
import Text.JSON (JSON, readJSON, showJSON)
import Data.Ratio (numerator, denominator)
import qualified Data.Set as Set
import System.Time (ClockTime)
import qualified Ganeti.ConstantUtils as ConstantUtils
import Ganeti.JSON
import qualified Ganeti.THH as THH
import Ganeti.Utils
-- * Generic types
-- | Type that holds a non-negative value.
newtype NonNegative a = NonNegative { fromNonNegative :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'NonNegative'.
mkNonNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (NonNegative a)
mkNonNegative i | i >= 0 = return (NonNegative i)
| otherwise = fail $ "Invalid value for non-negative type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (NonNegative a) where
showJSON = JSON.showJSON . fromNonNegative
readJSON v = JSON.readJSON v >>= mkNonNegative
-- | Type that holds a positive value.
newtype Positive a = Positive { fromPositive :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'Positive'.
mkPositive :: (Monad m, Num a, Ord a, Show a) => a -> m (Positive a)
mkPositive i | i > 0 = return (Positive i)
| otherwise = fail $ "Invalid value for positive type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Positive a) where
showJSON = JSON.showJSON . fromPositive
readJSON v = JSON.readJSON v >>= mkPositive
-- | Type that holds a negative value.
newtype Negative a = Negative { fromNegative :: a }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'Negative'.
mkNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (Negative a)
mkNegative i | i < 0 = return (Negative i)
| otherwise = fail $ "Invalid value for negative type '" ++
show i ++ "'"
instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Negative a) where
showJSON = JSON.showJSON . fromNegative
readJSON v = JSON.readJSON v >>= mkNegative
-- | Type that holds a non-null list.
newtype NonEmpty a = NonEmpty { fromNonEmpty :: [a] }
deriving (Show, Eq, Ord)
-- | Smart constructor for 'NonEmpty'.
mkNonEmpty :: (Monad m) => [a] -> m (NonEmpty a)
mkNonEmpty [] = fail "Received empty value for non-empty list"
mkNonEmpty xs = return (NonEmpty xs)
instance (JSON.JSON a) => JSON.JSON (NonEmpty a) where
showJSON = JSON.showJSON . fromNonEmpty
readJSON v = JSON.readJSON v >>= mkNonEmpty
-- | A simple type alias for non-empty strings.
type NonEmptyString = NonEmpty Char
type QueryResultCode = Int
newtype IPv4Address = IPv4Address { fromIPv4Address :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv4Address :: Monad m => String -> m IPv4Address
mkIPv4Address address =
return IPv4Address { fromIPv4Address = address }
instance JSON.JSON IPv4Address where
showJSON = JSON.showJSON . fromIPv4Address
readJSON v = JSON.readJSON v >>= mkIPv4Address
newtype IPv4Network = IPv4Network { fromIPv4Network :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv4Network :: Monad m => String -> m IPv4Network
mkIPv4Network address =
return IPv4Network { fromIPv4Network = address }
instance JSON.JSON IPv4Network where
showJSON = JSON.showJSON . fromIPv4Network
readJSON v = JSON.readJSON v >>= mkIPv4Network
newtype IPv6Address = IPv6Address { fromIPv6Address :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv6Address :: Monad m => String -> m IPv6Address
mkIPv6Address address =
return IPv6Address { fromIPv6Address = address }
instance JSON.JSON IPv6Address where
showJSON = JSON.showJSON . fromIPv6Address
readJSON v = JSON.readJSON v >>= mkIPv6Address
newtype IPv6Network = IPv6Network { fromIPv6Network :: String }
deriving (Show, Eq, Ord)
-- FIXME: this should check that 'address' is a valid ip
mkIPv6Network :: Monad m => String -> m IPv6Network
mkIPv6Network address =
return IPv6Network { fromIPv6Network = address }
instance JSON.JSON IPv6Network where
showJSON = JSON.showJSON . fromIPv6Network
readJSON v = JSON.readJSON v >>= mkIPv6Network
-- * Ganeti types
-- | Instance disk template type. The disk template is a name for the
-- constructor of the disk configuration 'DiskLogicalId' used for
-- serialization, configuration values, etc.
$(THH.declareLADT ''String "DiskTemplate"
[ ("DTDiskless", "diskless")
, ("DTFile", "file")
, ("DTSharedFile", "sharedfile")
, ("DTPlain", "plain")
, ("DTBlock", "blockdev")
, ("DTDrbd8", "drbd")
, ("DTRbd", "rbd")
, ("DTExt", "ext")
, ("DTGluster", "gluster")
])
$(THH.makeJSONInstance ''DiskTemplate)
instance THH.PyValue DiskTemplate where
showValue = show . diskTemplateToRaw
instance HasStringRepr DiskTemplate where
fromStringRepr = diskTemplateFromRaw
toStringRepr = diskTemplateToRaw
-- | Data type representing what items the tag operations apply to.
$(THH.declareLADT ''String "TagKind"
[ ("TagKindInstance", "instance")
, ("TagKindNode", "node")
, ("TagKindGroup", "nodegroup")
, ("TagKindCluster", "cluster")
, ("TagKindNetwork", "network")
])
$(THH.makeJSONInstance ''TagKind)
-- | The Group allocation policy type.
--
-- Note that the order of constructors is important as the automatic
-- Ord instance will order them in the order they are defined, so when
-- changing this data type be careful about the interaction with the
-- desired sorting order.
$(THH.declareLADT ''String "AllocPolicy"
[ ("AllocPreferred", "preferred")
, ("AllocLastResort", "last_resort")
, ("AllocUnallocable", "unallocable")
])
$(THH.makeJSONInstance ''AllocPolicy)
-- | The Instance real state type.
$(THH.declareLADT ''String "InstanceStatus"
[ ("StatusDown", "ADMIN_down")
, ("StatusOffline", "ADMIN_offline")
, ("ErrorDown", "ERROR_down")
, ("ErrorUp", "ERROR_up")
, ("NodeDown", "ERROR_nodedown")
, ("NodeOffline", "ERROR_nodeoffline")
, ("Running", "running")
, ("UserDown", "USER_down")
, ("WrongNode", "ERROR_wrongnode")
])
$(THH.makeJSONInstance ''InstanceStatus)
-- | Migration mode.
$(THH.declareLADT ''String "MigrationMode"
[ ("MigrationLive", "live")
, ("MigrationNonLive", "non-live")
])
$(THH.makeJSONInstance ''MigrationMode)
-- | Verify optional checks.
$(THH.declareLADT ''String "VerifyOptionalChecks"
[ ("VerifyNPlusOneMem", "nplusone_mem")
])
$(THH.makeJSONInstance ''VerifyOptionalChecks)
-- | Cluster verify error codes.
$(THH.declareLADT ''String "CVErrorCode"
[ ("CvECLUSTERCFG", "ECLUSTERCFG")
, ("CvECLUSTERCERT", "ECLUSTERCERT")
, ("CvECLUSTERCLIENTCERT", "ECLUSTERCLIENTCERT")
, ("CvECLUSTERFILECHECK", "ECLUSTERFILECHECK")
, ("CvECLUSTERDANGLINGNODES", "ECLUSTERDANGLINGNODES")
, ("CvECLUSTERDANGLINGINST", "ECLUSTERDANGLINGINST")
, ("CvEINSTANCEBADNODE", "EINSTANCEBADNODE")
, ("CvEINSTANCEDOWN", "EINSTANCEDOWN")
, ("CvEINSTANCELAYOUT", "EINSTANCELAYOUT")
, ("CvEINSTANCEMISSINGDISK", "EINSTANCEMISSINGDISK")
, ("CvEINSTANCEFAULTYDISK", "EINSTANCEFAULTYDISK")
, ("CvEINSTANCEWRONGNODE", "EINSTANCEWRONGNODE")
, ("CvEINSTANCESPLITGROUPS", "EINSTANCESPLITGROUPS")
, ("CvEINSTANCEPOLICY", "EINSTANCEPOLICY")
, ("CvEINSTANCEUNSUITABLENODE", "EINSTANCEUNSUITABLENODE")
, ("CvEINSTANCEMISSINGCFGPARAMETER", "EINSTANCEMISSINGCFGPARAMETER")
, ("CvENODEDRBD", "ENODEDRBD")
, ("CvENODEDRBDVERSION", "ENODEDRBDVERSION")
, ("CvENODEDRBDHELPER", "ENODEDRBDHELPER")
, ("CvENODEFILECHECK", "ENODEFILECHECK")
, ("CvENODEHOOKS", "ENODEHOOKS")
, ("CvENODEHV", "ENODEHV")
, ("CvENODELVM", "ENODELVM")
, ("CvENODEN1", "ENODEN1")
, ("CvENODENET", "ENODENET")
, ("CvENODEOS", "ENODEOS")
, ("CvENODEORPHANINSTANCE", "ENODEORPHANINSTANCE")
, ("CvENODEORPHANLV", "ENODEORPHANLV")
, ("CvENODERPC", "ENODERPC")
, ("CvENODESSH", "ENODESSH")
, ("CvENODEVERSION", "ENODEVERSION")
, ("CvENODESETUP", "ENODESETUP")
, ("CvENODETIME", "ENODETIME")
, ("CvENODEOOBPATH", "ENODEOOBPATH")
, ("CvENODEUSERSCRIPTS", "ENODEUSERSCRIPTS")
, ("CvENODEFILESTORAGEPATHS", "ENODEFILESTORAGEPATHS")
, ("CvENODEFILESTORAGEPATHUNUSABLE", "ENODEFILESTORAGEPATHUNUSABLE")
, ("CvENODESHAREDFILESTORAGEPATHUNUSABLE",
"ENODESHAREDFILESTORAGEPATHUNUSABLE")
, ("CvENODEGLUSTERSTORAGEPATHUNUSABLE",
"ENODEGLUSTERSTORAGEPATHUNUSABLE")
, ("CvEGROUPDIFFERENTPVSIZE", "EGROUPDIFFERENTPVSIZE")
])
$(THH.makeJSONInstance ''CVErrorCode)
-- | Dynamic device modification, just add/remove version.
$(THH.declareLADT ''String "DdmSimple"
[ ("DdmSimpleAdd", "add")
, ("DdmSimpleRemove", "remove")
])
$(THH.makeJSONInstance ''DdmSimple)
-- | Dynamic device modification, all operations version.
--
-- TODO: DDM_SWAP, DDM_MOVE?
$(THH.declareLADT ''String "DdmFull"
[ ("DdmFullAdd", "add")
, ("DdmFullRemove", "remove")
, ("DdmFullModify", "modify")
])
$(THH.makeJSONInstance ''DdmFull)
-- | Hypervisor type definitions.
$(THH.declareLADT ''String "Hypervisor"
[ ("Kvm", "kvm")
, ("XenPvm", "xen-pvm")
, ("Chroot", "chroot")
, ("XenHvm", "xen-hvm")
, ("Lxc", "lxc")
, ("Fake", "fake")
])
$(THH.makeJSONInstance ''Hypervisor)
instance THH.PyValue Hypervisor where
showValue = show . hypervisorToRaw
instance HasStringRepr Hypervisor where
fromStringRepr = hypervisorFromRaw
toStringRepr = hypervisorToRaw
-- | Oob command type.
$(THH.declareLADT ''String "OobCommand"
[ ("OobHealth", "health")
, ("OobPowerCycle", "power-cycle")
, ("OobPowerOff", "power-off")
, ("OobPowerOn", "power-on")
, ("OobPowerStatus", "power-status")
])
$(THH.makeJSONInstance ''OobCommand)
-- | Oob command status
$(THH.declareLADT ''String "OobStatus"
[ ("OobStatusCritical", "CRITICAL")
, ("OobStatusOk", "OK")
, ("OobStatusUnknown", "UNKNOWN")
, ("OobStatusWarning", "WARNING")
])
$(THH.makeJSONInstance ''OobStatus)
-- | Storage type.
$(THH.declareLADT ''String "StorageType"
[ ("StorageFile", "file")
, ("StorageSharedFile", "sharedfile")
, ("StorageGluster", "gluster")
, ("StorageLvmPv", "lvm-pv")
, ("StorageLvmVg", "lvm-vg")
, ("StorageDiskless", "diskless")
, ("StorageBlock", "blockdev")
, ("StorageRados", "rados")
, ("StorageExt", "ext")
])
$(THH.makeJSONInstance ''StorageType)
-- | Storage keys are identifiers for storage units. Their content varies
-- depending on the storage type, for example a storage key for LVM storage
-- is the volume group name.
type StorageKey = String
-- | Storage parameters
type SPExclusiveStorage = Bool
-- | Storage units without storage-type-specific parameters
data StorageUnitRaw = SURaw StorageType StorageKey
-- | Full storage unit with storage-type-specific parameters
data StorageUnit = SUFile StorageKey
| SUSharedFile StorageKey
| SUGluster StorageKey
| SULvmPv StorageKey SPExclusiveStorage
| SULvmVg StorageKey SPExclusiveStorage
| SUDiskless StorageKey
| SUBlock StorageKey
| SURados StorageKey
| SUExt StorageKey
deriving (Eq)
instance Show StorageUnit where
show (SUFile key) = showSUSimple StorageFile key
show (SUSharedFile key) = showSUSimple StorageSharedFile key
show (SUGluster key) = showSUSimple StorageGluster key
show (SULvmPv key es) = showSULvm StorageLvmPv key es
show (SULvmVg key es) = showSULvm StorageLvmVg key es
show (SUDiskless key) = showSUSimple StorageDiskless key
show (SUBlock key) = showSUSimple StorageBlock key
show (SURados key) = showSUSimple StorageRados key
show (SUExt key) = showSUSimple StorageExt key
instance JSON StorageUnit where
showJSON (SUFile key) = showJSON (StorageFile, key, []::[String])
showJSON (SUSharedFile key) = showJSON (StorageSharedFile, key, []::[String])
showJSON (SUGluster key) = showJSON (StorageGluster, key, []::[String])
showJSON (SULvmPv key es) = showJSON (StorageLvmPv, key, [es])
showJSON (SULvmVg key es) = showJSON (StorageLvmVg, key, [es])
showJSON (SUDiskless key) = showJSON (StorageDiskless, key, []::[String])
showJSON (SUBlock key) = showJSON (StorageBlock, key, []::[String])
showJSON (SURados key) = showJSON (StorageRados, key, []::[String])
showJSON (SUExt key) = showJSON (StorageExt, key, []::[String])
-- FIXME: add readJSON implementation
readJSON = fail "Not implemented"
-- | Composes a string representation of storage types without
-- storage parameters
showSUSimple :: StorageType -> StorageKey -> String
showSUSimple st sk = show (storageTypeToRaw st, sk, []::[String])
-- | Composes a string representation of the LVM storage types
showSULvm :: StorageType -> StorageKey -> SPExclusiveStorage -> String
showSULvm st sk es = show (storageTypeToRaw st, sk, [es])
-- | Mapping from disk templates to storage types.
diskTemplateToStorageType :: DiskTemplate -> StorageType
diskTemplateToStorageType DTExt = StorageExt
diskTemplateToStorageType DTFile = StorageFile
diskTemplateToStorageType DTSharedFile = StorageSharedFile
diskTemplateToStorageType DTDrbd8 = StorageLvmVg
diskTemplateToStorageType DTPlain = StorageLvmVg
diskTemplateToStorageType DTRbd = StorageRados
diskTemplateToStorageType DTDiskless = StorageDiskless
diskTemplateToStorageType DTBlock = StorageBlock
diskTemplateToStorageType DTGluster = StorageGluster
-- | Equips a raw storage unit with its parameters
addParamsToStorageUnit :: SPExclusiveStorage -> StorageUnitRaw -> StorageUnit
addParamsToStorageUnit _ (SURaw StorageBlock key) = SUBlock key
addParamsToStorageUnit _ (SURaw StorageDiskless key) = SUDiskless key
addParamsToStorageUnit _ (SURaw StorageExt key) = SUExt key
addParamsToStorageUnit _ (SURaw StorageFile key) = SUFile key
addParamsToStorageUnit _ (SURaw StorageSharedFile key) = SUSharedFile key
addParamsToStorageUnit _ (SURaw StorageGluster key) = SUGluster key
addParamsToStorageUnit es (SURaw StorageLvmPv key) = SULvmPv key es
addParamsToStorageUnit es (SURaw StorageLvmVg key) = SULvmVg key es
addParamsToStorageUnit _ (SURaw StorageRados key) = SURados key
-- | Node evac modes.
--
-- This is part of the 'IAllocator' interface and it is used, for
-- example, in 'Ganeti.HTools.Loader.RqType'. However, it must reside
-- in this module, and not in 'Ganeti.HTools.Types', because it is
-- also used by 'Ganeti.Constants'.
$(THH.declareLADT ''String "EvacMode"
[ ("ChangePrimary", "primary-only")
, ("ChangeSecondary", "secondary-only")
, ("ChangeAll", "all")
])
$(THH.makeJSONInstance ''EvacMode)
-- | The file driver type.
$(THH.declareLADT ''String "FileDriver"
[ ("FileLoop", "loop")
, ("FileBlktap", "blktap")
, ("FileBlktap2", "blktap2")
])
$(THH.makeJSONInstance ''FileDriver)
-- | The instance create mode.
$(THH.declareLADT ''String "InstCreateMode"
[ ("InstCreate", "create")
, ("InstImport", "import")
, ("InstRemoteImport", "remote-import")
])
$(THH.makeJSONInstance ''InstCreateMode)
-- | Reboot type.
$(THH.declareLADT ''String "RebootType"
[ ("RebootSoft", "soft")
, ("RebootHard", "hard")
, ("RebootFull", "full")
])
$(THH.makeJSONInstance ''RebootType)
-- | Export modes.
$(THH.declareLADT ''String "ExportMode"
[ ("ExportModeLocal", "local")
, ("ExportModeRemote", "remote")
])
$(THH.makeJSONInstance ''ExportMode)
-- | IAllocator run types (OpTestIAllocator).
$(THH.declareLADT ''String "IAllocatorTestDir"
[ ("IAllocatorDirIn", "in")
, ("IAllocatorDirOut", "out")
])
$(THH.makeJSONInstance ''IAllocatorTestDir)
-- | IAllocator mode. FIXME: use this in "HTools.Backend.IAlloc".
$(THH.declareLADT ''String "IAllocatorMode"
[ ("IAllocatorAlloc", "allocate")
, ("IAllocatorMultiAlloc", "multi-allocate")
, ("IAllocatorReloc", "relocate")
, ("IAllocatorNodeEvac", "node-evacuate")
, ("IAllocatorChangeGroup", "change-group")
])
$(THH.makeJSONInstance ''IAllocatorMode)
-- | Network mode.
$(THH.declareLADT ''String "NICMode"
[ ("NMBridged", "bridged")
, ("NMRouted", "routed")
, ("NMOvs", "openvswitch")
, ("NMPool", "pool")
])
$(THH.makeJSONInstance ''NICMode)
-- | The JobStatus data type. Note that this is ordered especially
-- such that greater\/lesser comparison on values of this type makes
-- sense.
$(THH.declareLADT ''String "JobStatus"
[ ("JOB_STATUS_QUEUED", "queued")
, ("JOB_STATUS_WAITING", "waiting")
, ("JOB_STATUS_CANCELING", "canceling")
, ("JOB_STATUS_RUNNING", "running")
, ("JOB_STATUS_CANCELED", "canceled")
, ("JOB_STATUS_SUCCESS", "success")
, ("JOB_STATUS_ERROR", "error")
])
$(THH.makeJSONInstance ''JobStatus)
-- | Finalized job status.
$(THH.declareLADT ''String "FinalizedJobStatus"
[ ("JobStatusCanceled", "canceled")
, ("JobStatusSuccessful", "success")
, ("JobStatusFailed", "error")
])
$(THH.makeJSONInstance ''FinalizedJobStatus)
-- | The Ganeti job type.
newtype JobId = JobId { fromJobId :: Int }
deriving (Show, Eq, Ord)
-- | Builds a job ID.
makeJobId :: (Monad m) => Int -> m JobId
makeJobId i | i >= 0 = return $ JobId i
| otherwise = fail $ "Invalid value for job ID ' " ++ show i ++ "'"
-- | Builds a job ID from a string.
makeJobIdS :: (Monad m) => String -> m JobId
makeJobIdS s = tryRead "parsing job id" s >>= makeJobId
-- | Parses a job ID.
parseJobId :: (Monad m) => JSON.JSValue -> m JobId
parseJobId (JSON.JSString x) = makeJobIdS $ JSON.fromJSString x
parseJobId (JSON.JSRational _ x) =
if denominator x /= 1
then fail $ "Got fractional job ID from master daemon?! Value:" ++ show x
-- FIXME: potential integer overflow here on 32-bit platforms
else makeJobId . fromIntegral . numerator $ x
parseJobId x = fail $ "Wrong type/value for job id: " ++ show x
instance JSON.JSON JobId where
showJSON = JSON.showJSON . fromJobId
readJSON = parseJobId
-- | Relative job ID type alias.
type RelativeJobId = Negative Int
-- | Job ID dependency.
data JobIdDep = JobDepRelative RelativeJobId
| JobDepAbsolute JobId
deriving (Show, Eq, Ord)
instance JSON.JSON JobIdDep where
showJSON (JobDepRelative i) = showJSON i
showJSON (JobDepAbsolute i) = showJSON i
readJSON v =
case JSON.readJSON v::JSON.Result (Negative Int) of
-- first try relative dependency, usually most common
JSON.Ok r -> return $ JobDepRelative r
JSON.Error _ -> liftM JobDepAbsolute (parseJobId v)
-- | From job ID dependency and job ID, compute the absolute dependency.
absoluteJobIdDep :: (Monad m) => JobIdDep -> JobId -> m JobIdDep
absoluteJobIdDep (JobDepAbsolute jid) _ = return $ JobDepAbsolute jid
absoluteJobIdDep (JobDepRelative rjid) jid =
liftM JobDepAbsolute . makeJobId $ fromJobId jid + fromNegative rjid
-- | Job Dependency type.
data JobDependency = JobDependency JobIdDep [FinalizedJobStatus]
deriving (Show, Eq, Ord)
instance JSON JobDependency where
showJSON (JobDependency dep status) = showJSON (dep, status)
readJSON = liftM (uncurry JobDependency) . readJSON
-- | From job dependency and job id compute an absolute job dependency.
absoluteJobDependency :: (Monad m) => JobDependency -> JobId -> m JobDependency
absoluteJobDependency (JobDependency jdep fstats) jid =
liftM (flip JobDependency fstats) $ absoluteJobIdDep jdep jid
-- | From a job dependency get the absolute job id it depends on,
-- if given absolutely.
getJobIdFromDependency :: JobDependency -> [JobId]
getJobIdFromDependency (JobDependency (JobDepAbsolute jid) _) = [jid]
getJobIdFromDependency _ = []
-- | Valid opcode priorities for submit.
$(THH.declareIADT "OpSubmitPriority"
[ ("OpPrioLow", 'ConstantUtils.priorityLow)
, ("OpPrioNormal", 'ConstantUtils.priorityNormal)
, ("OpPrioHigh", 'ConstantUtils.priorityHigh)
])
$(THH.makeJSONInstance ''OpSubmitPriority)
-- | Parse submit priorities from a string.
parseSubmitPriority :: (Monad m) => String -> m OpSubmitPriority
parseSubmitPriority "low" = return OpPrioLow
parseSubmitPriority "normal" = return OpPrioNormal
parseSubmitPriority "high" = return OpPrioHigh
parseSubmitPriority str = fail $ "Unknown priority '" ++ str ++ "'"
-- | Format a submit priority as string.
fmtSubmitPriority :: OpSubmitPriority -> String
fmtSubmitPriority OpPrioLow = "low"
fmtSubmitPriority OpPrioNormal = "normal"
fmtSubmitPriority OpPrioHigh = "high"
-- | Our ADT for the OpCode status at runtime (while in a job).
$(THH.declareLADT ''String "OpStatus"
[ ("OP_STATUS_QUEUED", "queued")
, ("OP_STATUS_WAITING", "waiting")
, ("OP_STATUS_CANCELING", "canceling")
, ("OP_STATUS_RUNNING", "running")
, ("OP_STATUS_CANCELED", "canceled")
, ("OP_STATUS_SUCCESS", "success")
, ("OP_STATUS_ERROR", "error")
])
$(THH.makeJSONInstance ''OpStatus)
-- | Type for the job message type.
$(THH.declareLADT ''String "ELogType"
[ ("ELogMessage", "message")
, ("ELogRemoteImport", "remote-import")
, ("ELogJqueueTest", "jqueue-test")
, ("ELogDelayTest", "delay-test")
])
$(THH.makeJSONInstance ''ELogType)
-- | Type of one element of a reason trail, of form
-- @(source, reason, timestamp)@.
type ReasonElem = (String, String, Integer)
-- | Type representing a reason trail.
type ReasonTrail = [ReasonElem]
-- | The VTYPES, a mini-type system in Python.
$(THH.declareLADT ''String "VType"
[ ("VTypeString", "string")
, ("VTypeMaybeString", "maybe-string")
, ("VTypeBool", "bool")
, ("VTypeSize", "size")
, ("VTypeInt", "int")
, ("VTypeFloat", "float")
])
$(THH.makeJSONInstance ''VType)
instance THH.PyValue VType where
showValue = THH.showValue . vTypeToRaw
-- * Node role type
$(THH.declareLADT ''String "NodeRole"
[ ("NROffline", "O")
, ("NRDrained", "D")
, ("NRRegular", "R")
, ("NRCandidate", "C")
, ("NRMaster", "M")
])
$(THH.makeJSONInstance ''NodeRole)
-- | The description of the node role.
roleDescription :: NodeRole -> String
roleDescription NROffline = "offline"
roleDescription NRDrained = "drained"
roleDescription NRRegular = "regular"
roleDescription NRCandidate = "master candidate"
roleDescription NRMaster = "master"
-- * Disk types
$(THH.declareLADT ''String "DiskMode"
[ ("DiskRdOnly", "ro")
, ("DiskRdWr", "rw")
])
$(THH.makeJSONInstance ''DiskMode)
-- | The persistent block driver type. Currently only one type is allowed.
$(THH.declareLADT ''String "BlockDriver"
[ ("BlockDrvManual", "manual")
])
$(THH.makeJSONInstance ''BlockDriver)
-- * Instance types
$(THH.declareLADT ''String "AdminState"
[ ("AdminOffline", "offline")
, ("AdminDown", "down")
, ("AdminUp", "up")
])
$(THH.makeJSONInstance ''AdminState)
$(THH.declareLADT ''String "AdminStateSource"
[ ("AdminSource", "admin")
, ("UserSource", "user")
])
$(THH.makeJSONInstance ''AdminStateSource)
instance THH.PyValue AdminStateSource where
showValue = THH.showValue . adminStateSourceToRaw
-- * Storage field type
$(THH.declareLADT ''String "StorageField"
[ ( "SFUsed", "used")
, ( "SFName", "name")
, ( "SFAllocatable", "allocatable")
, ( "SFFree", "free")
, ( "SFSize", "size")
])
$(THH.makeJSONInstance ''StorageField)
-- * Disk access protocol
$(THH.declareLADT ''String "DiskAccessMode"
[ ( "DiskUserspace", "userspace")
, ( "DiskKernelspace", "kernelspace")
])
$(THH.makeJSONInstance ''DiskAccessMode)
-- | Local disk status
--
-- Python code depends on:
-- DiskStatusOk < DiskStatusUnknown < DiskStatusFaulty
$(THH.declareILADT "LocalDiskStatus"
[ ("DiskStatusFaulty", 3)
, ("DiskStatusOk", 1)
, ("DiskStatusUnknown", 2)
])
localDiskStatusName :: LocalDiskStatus -> String
localDiskStatusName DiskStatusFaulty = "faulty"
localDiskStatusName DiskStatusOk = "ok"
localDiskStatusName DiskStatusUnknown = "unknown"
-- | Replace disks type.
$(THH.declareLADT ''String "ReplaceDisksMode"
[ -- Replace disks on primary
("ReplaceOnPrimary", "replace_on_primary")
-- Replace disks on secondary
, ("ReplaceOnSecondary", "replace_on_secondary")
-- Change secondary node
, ("ReplaceNewSecondary", "replace_new_secondary")
, ("ReplaceAuto", "replace_auto")
])
$(THH.makeJSONInstance ''ReplaceDisksMode)
-- | Basic timeouts for RPC calls.
$(THH.declareILADT "RpcTimeout"
[ ("Urgent", 60) -- 1 minute
, ("Fast", 5 * 60) -- 5 minutes
, ("Normal", 15 * 60) -- 15 minutes
, ("Slow", 3600) -- 1 hour
, ("FourHours", 4 * 3600) -- 4 hours
, ("OneDay", 86400) -- 1 day
])
-- | Hotplug action.
$(THH.declareLADT ''String "HotplugAction"
[ ("HAAdd", "hotadd")
, ("HARemove", "hotremove")
, ("HAMod", "hotmod")
])
$(THH.makeJSONInstance ''HotplugAction)
-- | Hotplug Device Target.
$(THH.declareLADT ''String "HotplugTarget"
[ ("HTDisk", "hotdisk")
, ("HTNic", "hotnic")
])
$(THH.makeJSONInstance ''HotplugTarget)
-- * Private type and instances
-- | A container for values that should be happy to be manipulated yet
-- refuses to be shown unless explicitly requested.
newtype Private a = Private { getPrivate :: a }
deriving (Eq, Ord, Functor)
instance (Show a, JSON.JSON a) => JSON.JSON (Private a) where
readJSON = liftM Private . JSON.readJSON
showJSON (Private x) = JSON.showJSON x
-- | "Show" the value of the field.
--
-- It would be better not to implement this at all.
-- Alas, Show OpCode requires Show Private.
instance Show a => Show (Private a) where
show _ = "<redacted>"
instance THH.PyValue a => THH.PyValue (Private a) where
showValue (Private x) = "Private(" ++ THH.showValue x ++ ")"
instance Applicative Private where
pure = Private
Private f <*> Private x = Private (f x)
instance Monad Private where
(Private x) >>= f = f x
return = Private
showPrivateJSObject :: (JSON.JSON a) =>
[(String, a)] -> JSON.JSObject (Private JSON.JSValue)
showPrivateJSObject value = JSON.toJSObject $ map f value
where f (k, v) = (k, Private $ JSON.showJSON v)
-- | The hypervisor parameter type. This is currently a simple map,
-- without type checking on key/value pairs.
type HvParams = Container JSON.JSValue
-- | The OS parameters type. This is, and will remain, a string
-- container, since the keys are dynamically declared by the OSes, and
-- the values are always strings.
type OsParams = Container String
type OsParamsPrivate = Container (Private String)
-- | Class of objects that have timestamps.
class TimeStampObject a where
cTimeOf :: a -> ClockTime
mTimeOf :: a -> ClockTime
-- | Class of objects that have an UUID.
class UuidObject a where
uuidOf :: a -> String
-- | Class of object that have a serial number.
class SerialNoObject a where
serialOf :: a -> Int
-- | Class of objects that have tags.
class TagsObject a where
tagsOf :: a -> Set.Set String
|
ganeti-github-testing/ganeti-test-1
|
src/Ganeti/Types.hs
|
bsd-2-clause
| 32,269 | 0 | 11 | 6,330 | 7,437 | 4,189 | 3,248 | 659 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionFrameV2.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:21
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionFrameV2 (
QqStyleOptionFrameV2(..)
,QqStyleOptionFrameV2_nf(..)
,qStyleOptionFrameV2_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QStyleOptionFrameV2
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionFrameV2 x1 where
qStyleOptionFrameV2 :: x1 -> IO (QStyleOptionFrameV2 ())
instance QqStyleOptionFrameV2 (()) where
qStyleOptionFrameV2 ()
= withQStyleOptionFrameV2Result $
qtc_QStyleOptionFrameV2
foreign import ccall "qtc_QStyleOptionFrameV2" qtc_QStyleOptionFrameV2 :: IO (Ptr (TQStyleOptionFrameV2 ()))
instance QqStyleOptionFrameV2 ((QStyleOptionFrameV2 t1)) where
qStyleOptionFrameV2 (x1)
= withQStyleOptionFrameV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV21 cobj_x1
foreign import ccall "qtc_QStyleOptionFrameV21" qtc_QStyleOptionFrameV21 :: Ptr (TQStyleOptionFrameV2 t1) -> IO (Ptr (TQStyleOptionFrameV2 ()))
instance QqStyleOptionFrameV2 ((QStyleOptionFrame t1)) where
qStyleOptionFrameV2 (x1)
= withQStyleOptionFrameV2Result $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV22 cobj_x1
foreign import ccall "qtc_QStyleOptionFrameV22" qtc_QStyleOptionFrameV22 :: Ptr (TQStyleOptionFrame t1) -> IO (Ptr (TQStyleOptionFrameV2 ()))
class QqStyleOptionFrameV2_nf x1 where
qStyleOptionFrameV2_nf :: x1 -> IO (QStyleOptionFrameV2 ())
instance QqStyleOptionFrameV2_nf (()) where
qStyleOptionFrameV2_nf ()
= withObjectRefResult $
qtc_QStyleOptionFrameV2
instance QqStyleOptionFrameV2_nf ((QStyleOptionFrameV2 t1)) where
qStyleOptionFrameV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV21 cobj_x1
instance QqStyleOptionFrameV2_nf ((QStyleOptionFrame t1)) where
qStyleOptionFrameV2_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionFrameV22 cobj_x1
instance Qfeatures (QStyleOptionFrameV2 a) (()) (IO (FrameFeatures)) where
features x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionFrameV2_features cobj_x0
foreign import ccall "qtc_QStyleOptionFrameV2_features" qtc_QStyleOptionFrameV2_features :: Ptr (TQStyleOptionFrameV2 a) -> IO CLong
instance QsetFeatures (QStyleOptionFrameV2 a) ((FrameFeatures)) where
setFeatures x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionFrameV2_setFeatures cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QStyleOptionFrameV2_setFeatures" qtc_QStyleOptionFrameV2_setFeatures :: Ptr (TQStyleOptionFrameV2 a) -> CLong -> IO ()
qStyleOptionFrameV2_delete :: QStyleOptionFrameV2 a -> IO ()
qStyleOptionFrameV2_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionFrameV2_delete cobj_x0
foreign import ccall "qtc_QStyleOptionFrameV2_delete" qtc_QStyleOptionFrameV2_delete :: Ptr (TQStyleOptionFrameV2 a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QStyleOptionFrameV2.hs
|
bsd-2-clause
| 3,434 | 0 | 12 | 463 | 761 | 401 | 360 | -1 | -1 |
{-# LANGUAGE RankNTypes, DeriveTraversable #-}
-- |
-- Module : Data.Map.Justified.Tutorial
-- Copyright : (c) Matt Noonan 2017
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : portable
--
-- = Description
--
-- The examples below demonstrate how to use the types and functions in "Data.Map.Justified".
--
-- You should be able to simply load this module in @ghci@ to play along.
-- The import list is:
--
-- @
-- import Prelude hiding (lookup)
--
-- import Data.Map.Justified
--
-- import qualified Data.Map as M
--
-- import Data.Traversable (for)
-- import Data.Char (toUpper)
-- import Control.Monad (forM_)
-- @
module Data.Map.Justified.Tutorial where
import Prelude hiding (lookup)
import Data.Map.Justified
import qualified Data.Map as M
import Data.Char (toUpper)
import Control.Monad (forM_)
import Data.Type.Coercion
-- | A simple "Data.Map" value used in several examples below.
--
-- @
-- test_table = M.fromList [ (1, "hello"), (2, "world") ]
-- @
test_table :: M.Map Int String
test_table = M.fromList [ (1, "hello"), (2, "world") ]
-- | This example shows how the @'Data.Map.Justified.member'@
-- function can be used to obtain a key whose type has been
-- augmented by a proof that the key is present in maps of a
-- certain type.
--
-- Where "Data.Map" may use a @'Maybe'@ type to ensure that
-- the user handles missing keys when performing a lookup,
-- here we use the @'Maybe'@ type to either tell the user
-- that a key is missing (by returning @'Nothing'@), or
-- actually give back evidence of the key's presence
-- (by returning @Just known_key@)
--
-- The @'Data.Map.Justified.withMap'@ function is used to
-- plumb a "Data.Map" @'Data.Map.Map'@ into a function that
-- expects a "Data.Map.Justified" @'Data.Map.Justified.Map'@.
-- In the code below, you can think of @table@ as @test_table@,
-- enhanced with the ability to use verified keys.
--
-- You can get from @table@ back to @test_table@ using the
-- function @'Data.Map.Justified.theMap'@.
--
-- @
-- example1 = withMap test_table $ \\table -> do
--
-- putStrLn "Is 1 a valid key?"
-- case member 1 table of
-- Nothing -> putStrLn " No, it was not found."
-- Just key -> putStrLn $ " Yes, found key: " ++ show key
--
-- putStrLn "Is 5 a valid key?"
-- case member 5 table of
-- Nothing -> putStrLn " No, it was not found."
-- Just key -> putStrLn $ " Yes, found key: " ++ show key
-- @
-- Output:
--
-- @
-- Is 1 a valid key?
-- Yes, found key: Key 1
-- Is 5 a valid key?
-- No, it was not found.
-- @
example1 :: IO ()
example1 = withMap test_table $ \table -> do
putStrLn "Is 1 a valid key?"
case member 1 table of
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
putStrLn "Is 5 a valid key?"
case member 5 table of
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
-- | Once you have obtained a verified key, how do you use it?
--
-- "Data.Map.Justified" has several functions that are similar
-- to ones found in "Data.Map" that operate over verified keys.
-- In this example, notice that we can extract values directly
-- from the map using @'Data.Map.Justified.lookup'@; since we already
-- proved that the key is present when we obtained a @Key ph k@
-- value, @'Data.Map.Justified.lookup'@ does not need to return a
-- @'Maybe'@ value.
--
-- @
-- example2 = withMap test_table $ \\table -> do
--
-- case member 1 table of
-- Nothing -> putStrLn "Sorry, I couldn't prove that the key is present."
-- Just key -> do
-- -- In this do-block, \'key\' represents the key 1, but carries type-level
-- -- evidence that the key is present. Lookups and updates can now proceed
-- -- without the possibility of error.
-- putStrLn ("Found key: " ++ show key)
--
-- -- Note that lookup returns a value directly, not a \'Maybe\'!
-- putStrLn ("Value for key: " ++ lookup key table)
--
-- -- If you update an already-mapped value, the set of valid keys does
-- -- not change. So the evidence that \'key\' could be found in \'table\'
-- -- is still sufficient to ensure that \'key\' can be found in the updated
-- -- table as well.
-- let table' = reinsert key "howdy" table
-- putStrLn ("Value for key in updated map: " ++ lookup key table')
-- @
-- Output:
--
-- @
-- Found key: Key 1
-- Value for key: hello
-- Value for key in updated map: howdy
-- @
example2 :: IO ()
example2 = withMap test_table $ \table -> do
case member 1 table of
Nothing -> putStrLn "Sorry, I couldn't prove that the key is present."
Just key -> do
-- In this do-block, 'key' represents the key 1, but carries type-level
-- evidence that the key is present. Lookups and updates can now proceed
-- without the possibility of error.
putStrLn ("Found key " ++ show key)
-- Note that lookup returns a value directly, not a 'Maybe'!
putStrLn ("Value for key: " ++ lookup key table)
-- If you update an already-mapped value, the set of valid keys does
-- not change. So the evidence that 'key' could be found in 'table'
-- is still sufficient to ensure that 'key' can be found in the updated
-- table as well.
let table' = reinsert key "howdy" table
putStrLn ("Value for key in updated map: " ++ lookup key table')
-- | It is a bit surprising to realize that a key of type @Key ph k@ can
-- be used to safely look up values in /any/ map of type @Map ph k v@,
-- not only the map that they key was originally found in!
--
-- This example makes use of that property to look up corresponding
-- elements of two /different/ (but related) tables, using the same
-- key evidence.
--
-- @
-- example3 = withMap test_table $ \\table -> do
--
-- let uppercase = map toUpper
-- updated_table = fmap (reverse . uppercase) table
--
-- for (keys table) $ \\key -> do
-- -- Although we are iterating over keys from the original table, they
-- -- can also be used to safely lookup values in the fmapped table.
-- -- Unlike (!) from Data.Map, Data.Map.Justified's (!) can not fail at runtime.
-- putStrLn ("In original table, " ++ show key ++ " maps to " ++ table ! key)
-- putStrLn ("In updated table, " ++ show key ++ " maps to " ++ updated_table ! key)
--
-- return ()
-- @
-- Output:
--
-- @
-- In original table, Key 1 maps to hello
-- In updated table, Key 1 maps to OLLEH
-- In original table, Key 2 maps to world
-- In updated table, Key 2 maps to DLROW
-- @
example3 :: IO ()
example3 = withMap test_table $ \table -> do
let uppercase = map toUpper
updated_table = fmap (reverse . uppercase) table
forM_ (keys table) $ \key -> do
-- Although we are iterating over keys from the original table, they
-- can also be used to safely lookup values in the fmapped table.
-- Unlike (!) from Data.Map, Data.Map.Justified's (!) can not fail at runtime.
putStrLn ("In original table, " ++ show key ++ " maps to " ++ table ! key)
putStrLn ("In updated table, " ++ show key ++ " maps to " ++ updated_table ! key)
return ()
-- | What if your set of keys can change over time?
--
-- If you were to insert a new key into a map, evidence that a key
-- exists is in the old map is no longer equivalent to evidence that
-- a key exists in the new map.
--
-- On the other hand, we know that if some @key@ exists in the old map,
-- then @key@ must still exist in the new map. So there should be a
-- way of "upgrading" evidence from the old map to the new. Furthermore,
-- we know that the key we just added must be in the new map.
--
-- The @'Data.Map.Justified.inserting'@ function inserts a value into a map
-- and feeds the new map into a continuation, along with the "upgrade" and
-- "new key" data.
--
-- @
-- example4 = withMap test_table $ \\table -> do
-- inserting 3 "NEW" table $ \\(newKey, upgrade, table') -> do
-- forM_ (keys table) $ \\key -> do
-- putStrLn (show key ++ " maps to " ++ table ! key ++ " in the old table.")
-- putStrLn (show key ++ " maps to " ++ table' ! (upgrade key) ++ " in the new table.")
-- putStrLn ("Also, the new table maps " ++ show newKey ++ " to " ++ table' ! newKey)
-- @
-- Output:
--
-- @
-- Key 1 maps to hello in the old table.
-- Key 1 maps to hello in the new table.
-- Key 2 maps to world in the old table.
-- Key 2 maps to world in the new table.
-- Also, the new table maps Key 3 to NEW
-- @
example4 :: IO ()
example4 = withMap test_table $ \table -> do
inserting 3 "NEW" table $ \(newKey, upgrade, table') -> do
forM_ (keys table) $ \key -> do
putStrLn (show key ++ " maps to " ++ table ! key ++ " in the old table.")
putStrLn (show key ++ " maps to " ++ table' ! (upgrade key) ++ " in the new table.")
putStrLn ("Also, the new table maps " ++ show newKey ++ " to " ++ table' ! newKey)
-- | The next example uses a directed graph, defined by this adjacency list.
--
-- @
-- adjacencies = M.fromList [ (1, [2,3]), (2, [1,5,3]), (3, [4]), (4, [3, 1]), (5, []) ]
-- @
adjacencies :: M.Map Int [Int]
adjacencies = M.fromList [ (1, [2,3]), (2, [1,5,3]), (3, [4]), (4, [3, 1]), (5, []) ]
-- | Sometimes, the values in a map may include references back to keys
-- in the map. A canonical example of this is the adjacency map representation of
-- a directed graph, where each node maps to its list of immediate successors.
-- The type would look something like
--
-- @
-- type Digraphy node = M.Map node [node]
-- @
--
-- If you want to do a computation with a @Digraphy node@, you probably want each
-- of the neighbor nodes to have keys in the @Digraphy node@ map. That is, you
-- may really want
--
-- @
-- type Digraph ph node = Map ph node [Key ph node]
-- \/\\ \/\\
-- | |
-- +-----+------+
-- |
-- (each neighbor should carry a proof that they are also in the map)
-- @
-- You can do this via @'Data.Map.Justified.withRecMap'@, which converts each
-- key reference of type @k@ in your map to a verified key of type @'Key' ph k@.
--
-- But what if a referenced key really is missing from the map? @'Data.Map.Justified.withRecMap'@
-- returns an @'Either'@ value to represent failure; if a key is missing, then the
-- result will be a value of the form @'Left' problems@, where @problems@ is an explanation
-- of where the missing keys are.
--
-- @
-- example5 = do
-- -- Print out the nodes in a graph
-- putStrLn ("Finding nodes in the directed graph " ++ show adjacencies)
-- trial adjacencies
--
-- -- Now add the (non-present) node 6 as a target of an edge from node 4 and try again:
-- let adjacencies' = M.adjust (6:) 4 adjacencies
-- putStrLn ("Finding nodes in the directed graph " ++ show adjacencies')
-- trial adjacencies'
--
-- where
-- trial adj = either showComplaint showNodes (withRecMap adj (map theKey . keys))
--
-- showNodes nodes = putStrLn (" Nodes: " ++ show nodes)
--
-- showComplaint problems = do
-- putStrLn " The following edges are missing targets:"
-- let badPairs = concatMap (\\(src, tgts) -> [ (src,tgt) | (tgt, Missing) <- tgts ]) problems
-- forM_ badPairs $ \\(src,tgt) -> putStrLn (" " ++ show src ++ " -> " ++ show tgt)
-- @
-- Output:
--
-- @
-- Finding nodes in the directed graph fromList [(1,[2,3]),(2,[1,5,3]),(3,[4]),(4,[3,1]),(5,[])]
-- Nodes: [1,2,3,4,5]
-- Finding nodes in the directed graph fromList [(1,[2,3]),(2,[1,5,3]),(3,[4]),(4,[6,3,1]),(5,[])]
-- The following edges are missing targets:
-- 4 -> 6
-- @
example5 :: IO ()
example5 = do
-- Print out the nodes in a graph
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies)
trial adjacencies
-- Now add the (non-present) node 6 as a target of an edge from node 4 and try again:
let adjacencies' = M.adjust (6:) 4 adjacencies
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies')
trial adjacencies'
where
trial adj = either showComplaint showNodes (withRecMap adj (map theKey . keys))
showNodes nodes = putStrLn (" Nodes: " ++ show nodes)
showComplaint problems = do
putStrLn " The following edges are missing targets:"
let badPairs = concatMap (\(src, tgts) -> [ (src,tgt) | (tgt, Missing) <- tgts ]) problems
forM_ badPairs $ \(src,tgt) -> putStrLn (" " ++ show src ++ " -> " ++ show tgt)
|
matt-noonan/justified-containers
|
src/Data/Map/Justified/Tutorial.hs
|
bsd-2-clause
| 12,739 | 0 | 23 | 3,078 | 1,244 | 752 | 492 | 59 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.